Documentation
¶
Overview ¶
Copyright 2021 hardcore-os Project Authors
Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- Variables
- func AssertTrue(b bool)
- func AssertTruef(b bool, format string, args ...interface{})
- func BloomBitsPerKey(numEntries int, fp float64) int
- func BytesToU32(b []byte) uint32
- func BytesToU32Slice(b []byte) []uint32
- func BytesToU64(b []byte) uint64
- func CalculateChecksum(data []byte) uint64
- func CompareKeys(key1, key2 []byte) int
- func CondPanic(condition bool, err error)
- func Copy(a []byte) []byte
- func CreateSyncedFile(filename string, sync bool) (*os.File, error)
- func DiscardEntry(e, vs *Entry) bool
- func Err(err error) error
- func EstimateWalCodecSize(e *Entry) int
- func FID(name string) uint64
- func FastRand() uint32
- func FileNameSSTable(dir string, id uint64) string
- func Float64() float64
- func Hash(b []byte) uint32
- func Int63n(n int64) int64
- func IsDeletedOrExpired(meta byte, expiresAt uint64) bool
- func IsValuePtr(e *Entry) bool
- func KeyWithTs(key []byte, ts uint64) []byte
- func LoadIDMap(dir string) map[uint64]struct{}
- func MemHash(data []byte) uint64
- func MemHashString(str string) uint64
- func NewCurVersion() uint64
- func Panic(err error)
- func Panic2(_ interface{}, err error)
- func ParseKey(key []byte) []byte
- func ParseTs(key []byte) uint64
- func RandN(n int) int
- func RemoveDir(dir string)
- func RunCallback(cb func())
- func SafeCopy(a, src []byte) []byte
- func SameKey(src, dst []byte) bool
- func SyncDir(dir string) error
- func U32SliceToBytes(u32s []uint32) []byte
- func U32ToBytes(v uint32) []byte
- func U64ToBytes(v uint64) []byte
- func ValuePtrCodec(vp *ValuePtr) []byte
- func ValueSize(value []byte) int64
- func VerifyChecksum(data []byte, expected []byte) error
- func VlogFilePath(dirPath string, fid uint32) string
- func WalCodec(buf *bytes.Buffer, e *Entry) int
- func WarpErr(format string, err error) error
- type Arena
- type Closer
- type CoreMap
- type Entry
- func (e *Entry) EncodedSize() uint32
- func (e *Entry) Entry() *Entry
- func (e *Entry) EstimateSize(threshold int) int
- func (e *Entry) IsDeletedOrExpired() bool
- func (e *Entry) IsZero() bool
- func (e *Entry) LogHeaderLen() int
- func (e *Entry) LogOffset() uint32
- func (e *Entry) WithTTL(dur time.Duration) *Entry
- type Filter
- type HashReader
- type Header
- type Item
- type Iterator
- type LogEntry
- type Options
- type SkipListIterator
- func (s *SkipListIterator) Close() error
- func (s *SkipListIterator) Item() Item
- func (s *SkipListIterator) Key() []byte
- func (s *SkipListIterator) Next()
- func (s *SkipListIterator) Prev()
- func (s *SkipListIterator) Rewind()
- func (s *SkipListIterator) Seek(target []byte)
- func (s *SkipListIterator) SeekForPrev(target []byte)
- func (s *SkipListIterator) SeekToFirst()
- func (s *SkipListIterator) SeekToLast()
- func (s *SkipListIterator) Valid() bool
- func (s *SkipListIterator) Value() ValueStruct
- func (s *SkipListIterator) ValueUint64() uint64
- type Skiplist
- type Slice
- type Throttle
- type UniIterator
- type ValuePtr
- type ValueStruct
- type WalHeader
Constants ¶
const ( // MaxLevelNum _ MaxLevelNum = 7 // DefaultValueThreshold _ DefaultValueThreshold = 1024 )
const ( ManifestFilename = "MANIFEST" ManifestRewriteFilename = "REWRITEMANIFEST" ManifestDeletionsRewriteThreshold = 10000 ManifestDeletionsRatio = 10 DefaultFileFlag = os.O_RDWR | os.O_CREATE | os.O_APPEND DefaultFileMode = 0666 MaxValueLogSize = 10 << 20 // 基于可变长编码,其最可能的编码 MaxHeaderSize = 21 VlogHeaderSize = 0 MaxVlogFileSize uint32 = math.MaxUint32 Mi int64 = 1 << 20 KVWriteChCapacity = 1000 )
file
const ( BitDelete byte = 1 << 0 // Set if the key has been deleted. BitValuePointer byte = 1 << 1 // Set if the value is NOT stored directly next to key. )
meta
const (
MaxNodeSize = int(unsafe.Sizeof(node{}))
)
const ( // size of vlog header. // +----------------+------------------+ // | keyID(8 bytes) | baseIV(12 bytes)| // +----------------+------------------+ ValueLogHeaderSize = 20 )
Variables ¶
var ( MagicText = [4]byte{'H', 'A', 'R', 'D'} MagicVersion = uint32(1) // CastagnoliCrcTable is a CRC32 polynomial table CastagnoliCrcTable = crc32.MakeTable(crc32.Castagnoli) )
codec
var ( // ErrKeyNotFound is returned when key isn't found on a txn.Get. ErrKeyNotFound = errors.New("Key not found") // ErrEmptyKey is returned if an empty key is passed on an update function. ErrEmptyKey = errors.New("Key cannot be empty") // ErrReWriteFailure reWrite failure ErrReWriteFailure = errors.New("reWrite failure") // ErrBadMagic bad magic ErrBadMagic = errors.New("bad magic") // ErrBadChecksum bad check sum ErrBadChecksum = errors.New("bad check sum") // ErrChecksumMismatch is returned at checksum mismatch. ErrChecksumMismatch = errors.New("checksum mismatch") ErrTruncate = errors.New("Do truncate") ErrStop = errors.New("Stop") // compact ErrFillTables = errors.New("Unable to fill tables") ErrBlockedWrites = errors.New("Writes are blocked, possibly due to DropAll or Close") ErrTxnTooBig = errors.New("Txn is too big to fit into one request") ErrDeleteVlogFile = errors.New("Delete vlog file") ErrNoRoom = errors.New("No room for write") // ErrInvalidRequest is returned if the user request is invalid. ErrInvalidRequest = errors.New("Invalid request") // ErrNoRewrite is returned if a call for value log GC doesn't result in a log file rewrite. ErrNoRewrite = errors.New("Value log GC attempt didn't result in any cleanup") // ErrRejected is returned if a value log GC is called either while another GC is running, or // after DB::Close has been called. ErrRejected = errors.New("Value log GC request rejected") )
NotFoundKey 找不到key
Functions ¶
func AssertTrue ¶
func AssertTrue(b bool)
AssertTrue asserts that b is true. Otherwise, it would log fatal.
func AssertTruef ¶
AssertTruef is AssertTrue with extra info.
func BloomBitsPerKey ¶
BloomBitsPerKey returns the bits per key required by bloomfilter based on the false positive rate.
func BytesToU32 ¶
BytesToU32 converts the given byte slice to uint32
func BytesToU32Slice ¶
BytesToU32Slice converts the given byte slice to uint32 slice
func CompareKeys ¶
CompareKeys checks the key without timestamp and checks the timestamp if keyNoTs is same. a<timestamp> would be sorted higher than aa<timestamp> if we use bytes.compare All keys should have timestamp.
func CreateSyncedFile ¶
CreateSyncedFile creates a new file (using O_EXCL), errors if it already existed.
func DiscardEntry ¶
func EstimateWalCodecSize ¶
EstimateWalCodecSize 预估当前kv 写入wal文件占用的空间大小
func IsDeletedOrExpired ¶
func IsValuePtr ¶
func MemHash ¶
MemHash is the hash function used by go map, it utilizes available hardware instructions(behaves as aeshash if aes instruction is available). NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
func MemHashString ¶
MemHashString is the hash function used by go map, it utilizes available hardware instructions (behaves as aeshash if aes instruction is available). NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
func NewCurVersion ¶
func NewCurVersion() uint64
func SyncDir ¶
SyncDir When you create or delete a file, you have to ensure the directory entry for the file is synced in order to guarantee the file is visible (if the system crashes). (See the man page for fsync, or see https://github.com/coreos/etcd/issues/6368 for an example.)
func U32SliceToBytes ¶
U32SliceToBytes converts the given Uint32 slice to byte slice
func VlogFilePath ¶
Types ¶
type Arena ¶
type Arena struct {
// contains filtered or unexported fields
}
Arena should be lock-free.
type Closer ¶
type Closer struct { CloseSignal chan struct{} // contains filtered or unexported fields }
Closer _用于资源回收的信号控制
type Entry ¶
type Entry struct { Key []byte Value []byte ExpiresAt uint64 Meta byte Version uint64 Offset uint32 Hlen int // Length of the header. ValThreshold int64 }
Entry _ 最外层写入的结构体
func (*Entry) EncodedSize ¶
EncodedSize is the size of the ValueStruct when encoded
func (*Entry) IsDeletedOrExpired ¶
type Filter ¶
type Filter []byte
Filter is an encoded set of []byte keys.
func NewFilter ¶
NewFilter returns a new Bloom filter that encodes a set of []byte keys with the given number of bits per key, approximately.
A good bitsPerKey value is 10, which yields a filter with ~ 1% false positive rate.
func (Filter) MayContain ¶
MayContain returns whether the filter may contain given key. False positives are possible, where it returns true for keys not in the original set.
type HashReader ¶
func NewHashReader ¶
func NewHashReader(r io.Reader) *HashReader
func (*HashReader) Read ¶
func (t *HashReader) Read(p []byte) (int, error)
Read reads len(p) bytes from the reader. Returns the number of bytes read, error on failure.
func (*HashReader) ReadByte ¶
func (t *HashReader) ReadByte() (byte, error)
ReadByte reads exactly one byte from the reader. Returns error on failure.
func (*HashReader) Sum32 ¶
func (t *HashReader) Sum32() uint32
Sum32 returns the sum32 of the underlying hash.
type Header ¶
header 对象 header is used in value log as a header before Entry.
func (*Header) Decode ¶
Decode decodes the given header from the provided byte slice. Returns the number of bytes read.
func (*Header) DecodeFrom ¶
func (h *Header) DecodeFrom(reader *HashReader) (int, error)
DecodeFrom reads the header from the hashReader. Returns the number of bytes read.
type SkipListIterator ¶
type SkipListIterator struct {
// contains filtered or unexported fields
}
Iterator is an iterator over skiplist object. For new objects, you just need to initialize Iterator.list.
func (*SkipListIterator) Close ¶
func (s *SkipListIterator) Close() error
Close frees the resources held by the iterator
func (*SkipListIterator) Item ¶
func (s *SkipListIterator) Item() Item
func (*SkipListIterator) Key ¶
func (s *SkipListIterator) Key() []byte
Key returns the key at the current position.
func (*SkipListIterator) Next ¶
func (s *SkipListIterator) Next()
Next advances to the next position.
func (*SkipListIterator) Prev ¶
func (s *SkipListIterator) Prev()
Prev advances to the previous position.
func (*SkipListIterator) Rewind ¶
func (s *SkipListIterator) Rewind()
func (*SkipListIterator) Seek ¶
func (s *SkipListIterator) Seek(target []byte)
Seek advances to the first entry with a key >= target.
func (*SkipListIterator) SeekForPrev ¶
func (s *SkipListIterator) SeekForPrev(target []byte)
SeekForPrev finds an entry with key <= target.
func (*SkipListIterator) SeekToFirst ¶
func (s *SkipListIterator) SeekToFirst()
SeekToFirst seeks position at the first entry in list. Final state of iterator is Valid() iff list is not empty.
func (*SkipListIterator) SeekToLast ¶
func (s *SkipListIterator) SeekToLast()
SeekToLast seeks position at the last entry in list. Final state of iterator is Valid() iff list is not empty.
func (*SkipListIterator) Valid ¶
func (s *SkipListIterator) Valid() bool
Valid returns true iff the iterator is positioned at a valid node.
func (*SkipListIterator) Value ¶
func (s *SkipListIterator) Value() ValueStruct
Value returns value.
func (*SkipListIterator) ValueUint64 ¶
func (s *SkipListIterator) ValueUint64() uint64
ValueUint64 returns the uint64 value of the current node.
type Skiplist ¶
type Skiplist struct { OnClose func() // contains filtered or unexported fields }
func NewSkiplist ¶
NewSkiplist makes a new empty skiplist, with a given arena size
func (*Skiplist) DecrRef ¶
func (s *Skiplist) DecrRef()
DecrRef decrements the refcount, deallocating the Skiplist when done using it
func (*Skiplist) MemSize ¶
MemSize returns the size of the Skiplist in terms of how much memory is used within its internal arena.
func (*Skiplist) NewSkipListIterator ¶
NewIterator returns a skiplist iterator. You have to Close() the iterator.
func (*Skiplist) Search ¶
func (s *Skiplist) Search(key []byte) ValueStruct
Get gets the value associated with the key. It returns a valid value if it finds equal or earlier version of the same key.
type Slice ¶
type Slice struct {
// contains filtered or unexported fields
}
Slice holds a reusable buf, will reallocate if you request a larger size than ever before. One problem is with n distinct sizes in random order it'll reallocate log(n) times.
type Throttle ¶
type Throttle struct {
// contains filtered or unexported fields
}
Throttle allows a limited number of workers to run at a time. It also provides a mechanism to check for errors encountered by workers and wait for them to finish.
func NewThrottle ¶
NewThrottle creates a new throttle with a max number of workers.
func (*Throttle) Do ¶
Do should be called by workers before they start working. It blocks if there are already maximum number of workers working. If it detects an error from previously Done workers, it would return it.
func (*Throttle) Done ¶
Done should be called by workers when they finish working. They can also pass the error status of work done.
type UniIterator ¶
type UniIterator struct {
// contains filtered or unexported fields
}
UniIterator is a unidirectional memtable iterator. It is a thin wrapper around Iterator. We like to keep Iterator as before, because it is more powerful and we might support bidirectional iterators in the future.
type ValuePtr ¶
type ValueStruct ¶
type ValueStruct struct { Meta byte Value []byte ExpiresAt uint64 Version uint64 // This field is not serialized. Only for internal usage. }
func (*ValueStruct) EncodeValue ¶
func (vs *ValueStruct) EncodeValue(b []byte) uint32
对value进行编码,并将编码后的字节写入byte 这里将过期时间和value的值一起编码
func (*ValueStruct) EncodedSize ¶
func (vs *ValueStruct) EncodedSize() uint32
value只持久化具体的value值和过期时间