github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/flushable.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bitalosdb
    16  
    17  import (
    18  	"fmt"
    19  	"sync/atomic"
    20  
    21  	"github.com/zuoyebang/bitalosdb/internal/base"
    22  )
    23  
    24  type flushable interface {
    25  	get(k []byte) ([]byte, bool, base.InternalKeyKind)
    26  	newIter(o *IterOptions) internalIterator
    27  	newFlushIter(o *IterOptions, bytesFlushed *uint64) internalIterator
    28  	inuseBytes() uint64
    29  	totalBytes() uint64
    30  	empty() bool
    31  	readyForFlush() bool
    32  }
    33  
    34  type flushableEntry struct {
    35  	flushable
    36  	flushed              chan struct{}
    37  	flushForced          bool
    38  	logNum               FileNum
    39  	logSize              uint64
    40  	logSeqNum            uint64
    41  	readerRefs           atomic.Int32
    42  	releaseMemAccounting func()
    43  }
    44  
    45  func (e *flushableEntry) readerRef() {
    46  	e.readerRefs.Add(1)
    47  }
    48  
    49  func (e *flushableEntry) readerUnref() {
    50  	switch v := e.readerRefs.Add(-1); {
    51  	case v == 0:
    52  		if e.releaseMemAccounting == nil {
    53  			fmt.Println("panic: flushableEntry readerUnref reservation already released")
    54  			return
    55  		}
    56  		e.releaseMemAccounting()
    57  		e.releaseMemAccounting = nil
    58  	case v < 0:
    59  		fmt.Printf("panic: flushableEntry readerUnref logNum:%d count:%d\n", e.logNum, v)
    60  	}
    61  }
    62  
    63  type flushableList []*flushableEntry
    64  
    65  func newFlushableEntry(f flushable, logNum FileNum, logSeqNum uint64) *flushableEntry {
    66  	entry := &flushableEntry{
    67  		flushable: f,
    68  		flushed:   make(chan struct{}),
    69  		logNum:    logNum,
    70  		logSeqNum: logSeqNum,
    71  	}
    72  	entry.readerRefs.Store(1)
    73  	return entry
    74  }