xixi_kv

package module
v0.0.0-...-6bb8025 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2025 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

xixi-kv-logo.jpg
GitHub top language Go Reference LICENSE GitHub stars GitHub forks Go Report CardGitHub go.mod Go version (subdirectory of monorepo)GitHub contributors

English | 简体中文

xixi-kv is a lightweight key-logRecord storage engine based on the Bitcask model, featuring low-latency read/write operations, high throughput, and the ability to store data volumes exceeding available memory.

Features

  • Supports multiple idx implementations including B-Tree, persistent B+ Tree, and adaptive radix tree, allowing users to balance operational efficiency with storage capacity based on their needs.
  • Implements batch transaction writes with atomicity and isolation through global locking and database startup identification mechanisms.
  • Features a custom log record format with variable-length fields and self-implemented encoders/decoders to optimize storage efficiency.
  • Employs the iterator pattern with unified interfaces at both idx and database layers for ordered traversal and extended operations on log records.
  • Utilizes memory-mapped (MMap) IO management to accelerate idx building, improving startup speed when data volume is within available memory limits.

Quick Start

For a complete example, see: basic_operation.go

Installation

Install Go and run the go get command:

$ go get -u github.com/primeovercoa/xixi-kv

Opening the Database

The core object in xixi-kv is DB. Use the Open method to create or open a database:

package main

import (
	kv "github.com/primeovercoa/xixi-kv"
	"log"
)

// Usage example
func main() {
	// Use default options, default path is system temp directory
	opts := kv.DefaultOptions
	db, err := kv.Open(opts)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	// ...
}

Basic Operations

// Put
err = db.Put(key, logRecord)

// Get
val, err := db.Get(key)

// Delete
err = db.Delete(key)

Single-Thread Benchmark

MacOS system with default configuration

Operation QPS (os.File) Latency (os.File) QPS (mmap) Latency (mmap)
Put 53703 27745 855710 1725
Get 323540 3731 1767753 716.7
Delete 415341 2921 2121006 627.7

Known Issues

When running on Windows systems, ensure all open DB instances and files are explicitly closed before deletion. Otherwise, you may encounter errors like The process cannot access the file because it is being used by another process.

It is recommended to run on Mac or Linux environments, or manually delete generated files when testing on Windows.

Contributions

This project is still under development, and contributions are very welcome! Feel free to submit issues and pull requests—I will respond as quickly as possible!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKeyIsEmpty             = errors.New("the key is empty")
	ErrIndexUpdateFailed      = errors.New("failed to update index")
	ErrKeyNotFound            = errors.New("key not found in database")
	ErrDataFileNotFound       = errors.New("datafile file is not found")
	ErrDataDirectoryCorrupted = errors.New("the database directory maybe corrupted")
	ErrExceedMaxBatchNum      = errors.New("exceed the max batch num")
	ErrMergeIsProgress        = errors.New("merge is in progress, try again later")
	ErrDatabaseIsUsing        = errors.New("the database directory is used by another process")
	ErrMergeRatioUnreached    = errors.New("the merge ratio do not reach the option")
	ErrNoEnoughSpaceForMerge  = errors.New("no enough disk space for merge")
)
View Source
var DefaultIteratorOptions = IteratorOptions{
	Prefix:  nil,
	Reverse: false,
}

DefaultIteratorOptions 默认迭代器Options, 供测试使用

View Source
var DefaultOptions = Options{
	DirPath:               os.TempDir(),
	DataFileSize:          512 * 1024 * 1024,
	SyncStrategy:          No,
	BytesPerSync:          1024 * 1024,
	EnableBackgroundMerge: false,
	IndexType:             index.HashMap,
	ShardNum:              16,
	FileIOType:            fio.MemoryMap,
	DataFileMergeRatio:    0.5,
}

DefaultOptions 默认Options, 供示例程序使用

View Source
var DefaultWriteBatchOptions = WriteBatchOptions{
	MaxBatchNum: 10000,
	SyncWrites:  true,
}

DefaultWriteBatchOptions 默认事务 Options, 供测试使用

Functions

func FcpPxtU

func FcpPxtU() error

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB bitcask存储引擎客户端

func Open

func Open(options Options) (*DB, error)

Open 客户端初始化

func (*DB) Backup

func (db *DB) Backup(dir string) error

Backup 数据库备份

func (*DB) Close

func (db *DB) Close() error

Close 关闭数据库

func (*DB) Delete

func (db *DB) Delete(key []byte) error

Delete 根据 key 删除数据

func (*DB) Fold

func (db *DB) Fold(fn func(key []byte, value []byte) bool) error

Fold 对数据库所有项执行自定义操作, 项改变不会同步数据库

func (*DB) Get

func (db *DB) Get(key []byte) ([]byte, error)

Get 根据 key 读取数据

func (*DB) ListKeys

func (db *DB) ListKeys() [][]byte

ListKeys 获取数据库中的所有 key

func (*DB) Merge

func (db *DB) Merge() error

Merge 立即执行 Merge 过程 todo 扩展点:新增定时任务和清除策略配置项, 监控数据状态, 进行自动清理 todo 优化点:使用性能更高的 merge 方法

func (*DB) NewIterator

func (db *DB) NewIterator(opts IteratorOptions) *Iterator

func (*DB) NewWriteBatch

func (db *DB) NewWriteBatch(opts WriteBatchOptions) *WriteBatch

NewWriteBatch 创建新 WriteBatch 实例

func (*DB) Put

func (db *DB) Put(key []byte, value []byte) error

Put 新增元素

func (*DB) Stat

func (db *DB) Stat() *Stat

Stat 获取当前时刻数据库统计信息

func (*DB) Sync

func (db *DB) Sync() error

Sync 数据持久化

type Iterator

type Iterator struct {
	// contains filtered or unexported fields
}

Iterator 数据库层迭代器, 面向用户

func (*Iterator) Close

func (it *Iterator) Close()

Close 关闭迭代器 释放相关资源

func (*Iterator) Key

func (it *Iterator) Key() []byte

Key 返回当前位置的 key

func (*Iterator) Next

func (it *Iterator) Next()

Next 遍历下一个满足条件的元素

func (*Iterator) Rewind

func (it *Iterator) Rewind()

Rewind 迭代器重置回到起点

func (*Iterator) Seek

func (it *Iterator) Seek(key []byte)

Seek 返回首个大于(小于)等于指定 key 的目标 key

func (*Iterator) Valid

func (it *Iterator) Valid() bool

Valid 判断是否遍历完成

func (*Iterator) Value

func (it *Iterator) Value() ([]byte, error)

Value 返回当前位置 key 对应的实际 value

type IteratorOptions

type IteratorOptions struct {
	// key 过滤前缀, 默认为空
	Prefix []byte
	// 是否降序遍历, 默认为false
	Reverse bool
}

IteratorOptions 索引迭代器配置项

type Options

type Options struct {
	DirPath               string          // 数据目录
	DataFileSize          int64           // 数据文件最大容量, 单位字节
	SyncStrategy          SyncStrategy    // 持久化策略
	BytesPerSync          uint            // 新写入数据量阈值
	IndexType             index.IndexType // 索引类型
	FileIOType            fio.FileIOType  // 文件 IO 类型
	EnableBackgroundMerge bool            // 是否启用后台定时 merge
	DataFileMergeRatio    float32         // 执行 merge 的无效数据占比阈值
	ShardNum              int             // 索引分片数量
}

Options 用户配置项

type Stat

type Stat struct {
	KeyNum          int   // 当前 key 的数量
	DataFileNum     uint  // 当前数据文件数量
	ReclaimableSize int64 // 当前 merge 可回收的数据量, 单位字节
	DiskSize        int64 // 数据目录的磁盘占用空间大小
}

Stat 实时统计信息 todo 扩展点:后续进行维护和利用

type SyncStrategy

type SyncStrategy byte
const (
	No SyncStrategy = iota // 由操作系统决定

	Always // 立即持久化

	Threshold // 新写入数据量达到阈值持久化
)

type WriteBatch

type WriteBatch struct {
	// contains filtered or unexported fields
}

WriteBatch 事务客户端 todo 优化点:新增方法结束自动提交的事务形式 todo 优化点:新增 Get 方法

func (*WriteBatch) Commit

func (wb *WriteBatch) Commit() error

Commit 事务提交, 将暂存数据持久化并更新索引

func (*WriteBatch) Delete

func (wb *WriteBatch) Delete(key []byte) error

Delete 根据 key 删除元素

func (*WriteBatch) Put

func (wb *WriteBatch) Put(key, value []byte) error

type WriteBatchOptions

type WriteBatchOptions struct {
	// 单个批次最大日志记录数量
	MaxBatchNum uint
	// 提交事务时是否立即持久化
	SyncWrites bool
}

WriteBatchOptions 批量写入配置项

Directories

Path Synopsis
cmd command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址