storage

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	B  = 1
	KB = 1024 * B
	MB = 1024 * KB
	GB = 1024 * MB
)

Variables

View Source
var (
	ErrValueTooLarge       = errors.New("the data size can't larger than segment size")
	ErrPendingSizeTooLarge = errors.New("the upper bound of pendingWrites can't larger than segment size")
	ErrMustStartWith       = errors.New("segment file extension must start with '.'")
	ErrLargeBlockCache     = errors.New("blockcache must be smaller than segment")
)
View Source
var (
	ErrClosed     = errors.New("the segment file is closed")
	ErrInvalidCRC = errors.New("invalid crc, the data may be corrupted")
)
View Source
var DefaultOptions = Options{
	DirPath:        os.TempDir(),
	SegmentSize:    GB,
	SegmentFileExt: ".SEG",
	BlockCache:     32 * KB * 10,
	Sync:           false,
	BytesPerSync:   0,
}

Functions

func GetSegmentSource

func GetSegmentSource(dir, ext string, id uint32) string

Types

type ChunkPosition

type ChunkPosition struct {
	SegmentId uint32
	// BlockNumber The block number of the chunk in the segment file.
	BlockNumber uint32
	// ChunkOffset The start offset of the chunk in the segment file.
	ChunkOffset int64
	// ChunkSize How many bytes the chunk data takes up in the segment file.
	ChunkSize uint32
}

한국어 설명: ChunkPosition 구조체는 세그먼트 파일 내에서 청크의 위치를 나타냅니다. 이 구조체는 세그먼트 파일로부터 데이터를 읽어올 때 사용됩니다. 구조체의 각 필드는 다음과 같은 정보를 담고 있습니다:

SegmentId: 청크가 속한 세그먼트 파일의 고유 식별자입니다. BlockNumber: 세그먼트 파일 내에서 청크가 위치한 블록 번호입니다. ChunkOffset: 세그먼트 파일 내에서 청크의 시작 오프셋(위치)을 나타냅니다. ChunkSize: 세그먼트 파일 내에서 청크 데이터가 차지하는 바이트 수입니다. 이 구조체는 특정 청크의 정확한 위치와 크기 정보를 제공함으로써, 파일 내에서 데이터를 효과적으로 찾아서 읽을 수 있도록 도와줍니다.

English Explanation: The ChunkPosition struct represents the position of a chunk within a segment file. It is used to read data from the segment file. Each field in the struct provides specific information:

SegmentId: The unique identifier for the segment file to which the chunk belongs. BlockNumber: The number of the block within the segment file where the chunk is located. ChunkOffset: The starting offset of the chunk within the segment file. ChunkSize: The number of bytes that the chunk data occupies within the segment file. This struct facilitates efficient data retrieval by providing precise location and size information for a given chunk within a file.

func DecodeChunkPosition

func DecodeChunkPosition(buf []byte) *ChunkPosition

func (*ChunkPosition) Encode

func (cp *ChunkPosition) Encode() []byte

func (*ChunkPosition) EncodeFixedSize

func (cp *ChunkPosition) EncodeFixedSize() []byte

type ChunkType

type ChunkType = byte
const (
	CtFull ChunkType = iota
	CtFirst
	CtMid
	CtEnd
)

type Options

type Options struct {
	DirPath        string
	SegmentSize    int64
	SegmentFileExt string
	BlockCache     uint32
	Sync           bool
	BytesPerSync   uint32
}

type Reader

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

한국어 설명: Reader 구조체는 Write-Ahead Log(WAL)에 대한 리더를 나타냅니다. 이 구조체는 세그먼트 ID에 따라 정렬된 segmentReader 구조체의 슬라이스인 segmentReaders와 현재 슬라이스 내에서 활성화된 segmentReader의 인덱스인 currentReader로 구성됩니다.

segmentReaders: 각각의 segmentReader는 WAL의 특정 세그먼트 파일에서 데이터를 읽는 역할을 합니다. 이 슬라이스는 모든 세그먼트 리더를 포함하고 있으며, 세그먼트 ID 순으로 정렬되어 있습니다. currentReader: 현재 읽고 있는 세그먼트 리더의 위치를 가리키는 인덱스입니다. 이 필드를 사용하여 segmentReaders 슬라이스를 순회할 수 있습니다. Reader 구조체는 WAL의 다양한 세그먼트 파일들을 순차적으로 읽기 위해 사용되며, 로그의 데이터를 순차적으로 처리할 수 있도록 도와줍니다.

English Explanation: The Reader struct represents a reader for the Write-Ahead Log (WAL). It is composed of segmentReaders, which is a slice of segmentReader structures sorted by their segment id, and currentReader, which indicates the index of the active segmentReader within the slice.

segmentReaders: Each segmentReader is responsible for reading data from a specific segment file within the WAL. This slice contains all the segment readers, organized in order of their segment IDs. currentReader: This is the index that points to the currently active segmentReader in the slice. It is used to iterate over the segmentReaders slice. The Reader struct is used to sequentially read through the different segment files in the WAL, facilitating the orderly processing of the logged data.

func (*Reader) CurrentChunkPosition

func (r *Reader) CurrentChunkPosition() *ChunkPosition

func (*Reader) CurrentSegmentId

func (r *Reader) CurrentSegmentId() uint32

func (*Reader) Next

func (r *Reader) Next() ([]byte, *ChunkPosition, error)

func (*Reader) SkipCurrentSegment

func (r *Reader) SkipCurrentSegment()

type WAL

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

한국어 설명: WAL 구조체는 들어오는 쓰기 작업에 대한 내구성과 장애 허용(fault-tolerance)을 제공하는 Write-Ahead Log 구조를 나타냅니다. 이 구조체는 새로운 들어오는 쓰기 작업에 사용되는 현재 세그먼트 파일인 activeSegment와 읽기 작업에 사용되는 이전 세그먼트 파일의 맵인 olderSegments로 구성됩니다.

options: WAL의 다양한 구성 옵션을 저장합니다. mu: 동시에 WAL 데이터 구조에 접근할 때 사용되는 동기화 매커니즘으로, sync.RWMutex를 사용하여 안전한 접근과 수정을 보장합니다. blockCache: 디스크 I/O를 줄여 읽기 성능을 향상시키기 위해 최근에 접근한 데이터 블록을 저장하는 LRU(Least Recently Used) 캐시입니다. uint64 타입의 키와 []byte 타입의 값을 가지는 lru.Cache 구조체를 사용하여 구현됩니다.

English Explanation: The WAL struct represents a Write-Ahead Log structure that provides durability and fault tolerance for incoming write operations. It is composed of an activeSegment, which is the current segment file for new incoming writes, and olderSegments, a map of segment files used for reading operations.

options: Stores various configuration options for the WAL. mu: A sync.RWMutex used for synchronizing concurrent access to the WAL data structure, ensuring safe access and modification. blockCache: An LRU (Least Recently Used) cache that stores recently accessed data blocks to improve read performance by reducing disk I/O. It is implemented using an lru.Cache structure with keys of type uint64 and values of type []byte.

func Open

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

func (*WAL) BootingActiveSegment

func (wal *WAL) BootingActiveSegment() error

한국어 설명: BootingActiveSegment 함수는 WAL(Write-Ahead Log)의 현재 활성 세그먼트를 동기화하고 새로운 활성 세그먼트를 준비하는 역할을 합니다. 이 함수는 다음과 같은 작업을 순차적으로 수행합니다:

wal 구조체의 mu 락을 획득하여 동시성 문제를 방지합니다. 현재 활성 세그먼트의 데이터를 디스크에 동기화합니다. 새로운 세그먼트를 로드하기 위해 loadSegment 함수를 호출합니다. 이 때, 새 세그먼트의 ID는 현재 활성 세그먼트의 ID에 1을 더한 값입니다. 새로 로드된 세그먼트를 wal 구조체의 activeSegment로 설정합니다. 기존의 활성 세그먼트를 olderSegments 맵에 추가하여, 이후 읽기 연산에 사용할 수 있도록 합니다. 모든 작업이 성공적으로 완료되면 nil을 반환하여 오류가 없음을 나타냅니다. 만약 동기화하거나 새 세그먼트를 로드하는 과정에서 오류가 발생하면, 해당 오류를 반환합니다. English Explanation: The BootingActiveSegment function is responsible for synchronizing the current active segment of the WAL (Write-Ahead Log) and preparing a new active segment. The function performs the following steps in sequence:

It acquires the mu lock of the wal struct to prevent concurrency issues. It synchronizes the data of the current active segment to disk. It calls the loadSegment function to load a new segment, with the new segment's ID being one greater than the current active segment's ID. It sets the newly loaded segment as the activeSegment of the wal struct. It adds the former active segment to the olderSegments map for later read operations. If all operations complete successfully, it returns nil to indicate no errors. If an error occurs during synchronization or segment loading, the function returns the error.

func (*WAL) ClearPendingWrites

func (wal *WAL) ClearPendingWrites()

func (*WAL) Close

func (wal *WAL) Close() error

func (*WAL) Delete

func (wal *WAL) Delete() error

func (*WAL) GetActiveID

func (wal *WAL) GetActiveID() uint32

func (*WAL) IsNull

func (wal *WAL) IsNull() bool

func (*WAL) NewReader

func (wal *WAL) NewReader() *Reader

func (*WAL) NewReaderWithMax

func (wal *WAL) NewReaderWithMax(segId uint32) *Reader

func (*WAL) NewReaderWithStart

func (wal *WAL) NewReaderWithStart(startPos *ChunkPosition) (*Reader, error)

func (*WAL) PendingWrites

func (wal *WAL) PendingWrites(data []byte)

func (*WAL) Read

func (wal *WAL) Read(pos *ChunkPosition) ([]byte, error)

func (*WAL) RenameFileExt

func (wal *WAL) RenameFileExt(ext string) error

func (*WAL) Sync

func (wal *WAL) Sync() error

func (*WAL) Write

func (wal *WAL) Write(data []byte) (*ChunkPosition, error)

func (*WAL) WriteAll

func (wal *WAL) WriteAll() ([]*ChunkPosition, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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