Documentation
¶
Index ¶
- Variables
- func CountRecordBatchMessages(recordSet []byte) int
- func PatchRecordBatchBaseOffset(batch *RecordBatch, baseOffset int64)
- type AppendResult
- type BucketChecker
- type ByteRange
- type ConditionalIndexReplacer
- type ConditionalIndexWriter
- type IdempotentAppendResult
- type IndexBuilder
- type IndexEntry
- type IndexObject
- type MemoryS3Client
- func (m *MemoryS3Client) DeleteIndex(ctx context.Context, key string) error
- func (m *MemoryS3Client) DeleteSegment(ctx context.Context, key string) error
- func (m *MemoryS3Client) DownloadIndex(ctx context.Context, key string) ([]byte, error)
- func (m *MemoryS3Client) DownloadIndexObject(ctx context.Context, key string) (IndexObject, error)
- func (m *MemoryS3Client) DownloadSegment(ctx context.Context, key string, rng *ByteRange) ([]byte, error)
- func (m *MemoryS3Client) EnsureBucket(ctx context.Context) error
- func (m *MemoryS3Client) ListSegments(ctx context.Context, prefix string) ([]S3Object, error)
- func (m *MemoryS3Client) UploadIndex(ctx context.Context, key string, body []byte) error
- func (m *MemoryS3Client) UploadIndexIfAbsent(ctx context.Context, key string, body []byte) error
- func (m *MemoryS3Client) UploadIndexIfMatch(ctx context.Context, key string, body []byte, etag string) error
- func (m *MemoryS3Client) UploadSegment(ctx context.Context, key string, body []byte) error
- type PartitionLog
- func (l *PartitionLog) AppendBatch(ctx context.Context, batch RecordBatch) (*AppendResult, error)
- func (l *PartitionLog) AppendBatches(ctx context.Context, batches []RecordBatch, forceFlush bool) (*AppendResult, error)
- func (l *PartitionLog) AppendIdempotentBatches(ctx context.Context, batches []RecordBatch) (*IdempotentAppendResult, error)
- func (l *PartitionLog) BufferedHighWatermark() int64
- func (l *PartitionLog) CheckOwnership() error
- func (l *PartitionLog) DrainAndRelease(release func())
- func (l *PartitionLog) EarliestOffset() int64
- func (l *PartitionLog) Flush(ctx context.Context) error
- func (l *PartitionLog) Read(ctx context.Context, offset int64, maxBytes int32) ([]byte, error)
- func (l *PartitionLog) RestoreFromS3(ctx context.Context) (lastOffset int64, restoreErr error)
- type PartitionLogConfig
- type PartitionLogOptions
- type RecordBatch
- type RecoveredPartition
- type RecoveredSegment
- type S3Client
- type S3Config
- type S3Object
- type SegmentArtifact
- type SegmentWriterConfig
- type TopicRecoveryConfig
- type TopicRecoveryResult
- type WriteBuffer
- type WriteBufferConfig
Constants ¶
This section is empty.
Variables ¶
var ( ErrOutOfOrderSequence = errors.New("out of order producer sequence") ErrInvalidProducerEpoch = errors.New("invalid producer epoch") ErrInvalidProducerBatch = errors.New("invalid idempotent record batch") )
var ErrAppendOutcomeUnknown = errors.New("append outcome is unknown")
ErrAppendOutcomeUnknown means records reached S3 but their offset publication could not be confirmed. It must not be treated as a pre-write rejection.
var ErrConditionRejected = conditionRejectedError{}
var ErrConditionUnsupported = errors.New("conditional request not supported")
var ErrConditionalConflict = errors.New("conditional request conflict")
var ErrLogFenced = errors.New("partition log requires reload")
ErrLogFenced marks a terminal handle; create and restore a new log to continue.
var ErrNotFound = errors.New("not found")
var ErrObjectStorage = errors.New("object storage request failed")
var ErrOffsetOutOfRange = errors.New("offset out of range")
ErrOffsetOutOfRange is returned when the requested offset is outside persisted data.
var ErrPreconditionFailed = errors.New("precondition failed")
Functions ¶
func CountRecordBatchMessages ¶
CountRecordBatchMessages sums the message counts encoded in a record set. The record set is expected to be a concatenation of Kafka record batches as produced by the broker.
func PatchRecordBatchBaseOffset ¶
func PatchRecordBatchBaseOffset(batch *RecordBatch, baseOffset int64)
PatchRecordBatchBaseOffset overwrites the base offset field in the Kafka record batch header.
Types ¶
type AppendResult ¶
AppendResult contains offsets for a flushed batch.
type BucketChecker ¶
type ConditionalIndexWriter ¶
type IdempotentAppendResult ¶ added in v2.1.0
type IdempotentAppendResult struct {
AppendResult
Duplicate bool
}
IdempotentAppendResult distinguishes newly persisted records from a retry acknowledged at its original offsets. The published AppendResult stays intact.
type IndexBuilder ¶
type IndexBuilder struct {
// contains filtered or unexported fields
}
IndexBuilder tracks offsets and file positions for sparse indexing.
func NewIndexBuilder ¶
func NewIndexBuilder(interval int32) *IndexBuilder
NewIndexBuilder creates a builder that emits an entry every interval messages.
func (*IndexBuilder) BuildBytes ¶
func (b *IndexBuilder) BuildBytes() ([]byte, error)
BuildBytes encodes the index header and entries.
func (*IndexBuilder) Entries ¶
func (b *IndexBuilder) Entries() []*IndexEntry
Entries returns the recorded index entries.
type IndexEntry ¶
IndexEntry mirrors a sparse index row.
func ParseIndex ¶
func ParseIndex(data []byte) ([]*IndexEntry, error)
ParseIndex validates and returns entries from serialized bytes.
type MemoryS3Client ¶
type MemoryS3Client struct {
// contains filtered or unexported fields
}
MemoryS3Client is an in-memory implementation of S3Client for development/testing.
func NewMemoryS3Client ¶
func NewMemoryS3Client() *MemoryS3Client
NewMemoryS3Client initializes the in-memory S3 client.
func (*MemoryS3Client) DeleteIndex ¶
func (m *MemoryS3Client) DeleteIndex(ctx context.Context, key string) error
func (*MemoryS3Client) DeleteSegment ¶
func (m *MemoryS3Client) DeleteSegment(ctx context.Context, key string) error
func (*MemoryS3Client) DownloadIndex ¶
func (*MemoryS3Client) DownloadIndexObject ¶
func (m *MemoryS3Client) DownloadIndexObject(ctx context.Context, key string) (IndexObject, error)
func (*MemoryS3Client) DownloadSegment ¶
func (*MemoryS3Client) EnsureBucket ¶
func (m *MemoryS3Client) EnsureBucket(ctx context.Context) error
func (*MemoryS3Client) ListSegments ¶
func (*MemoryS3Client) UploadIndex ¶
func (*MemoryS3Client) UploadIndexIfAbsent ¶
func (*MemoryS3Client) UploadIndexIfMatch ¶
func (*MemoryS3Client) UploadSegment ¶
type PartitionLog ¶
type PartitionLog struct {
// contains filtered or unexported fields
}
PartitionLog coordinates buffering, segment serialization, S3 uploads, and caching.
func NewPartitionLog ¶
func NewPartitionLog(namespace string, topic string, partition int32, startOffset int64, s3Client S3Client, cache *cache.SegmentCache, cfg PartitionLogConfig, onFlush func(context.Context, *SegmentArtifact), onS3Op func(string, time.Duration, error), sem *semaphore.Weighted) *PartitionLog
NewPartitionLog constructs a log for a topic partition.
func NewPartitionLogWithOptions ¶
func NewPartitionLogWithOptions(namespace string, topic string, partition int32, startOffset int64, s3Client S3Client, cache *cache.SegmentCache, cfg PartitionLogOptions, onFlush func(context.Context, *SegmentArtifact), onS3Op func(string, time.Duration, error), sem *semaphore.Weighted) *PartitionLog
NewPartitionLogWithOptions constructs a log with lease fencing and offset commits.
func (*PartitionLog) AppendBatch ¶
func (l *PartitionLog) AppendBatch(ctx context.Context, batch RecordBatch) (*AppendResult, error)
AppendBatch appends one batch through the atomic record-set path.
func (*PartitionLog) AppendBatches ¶
func (l *PartitionLog) AppendBatches(ctx context.Context, batches []RecordBatch, forceFlush bool) (*AppendResult, error)
AppendBatches stages a partition's complete Produce record set as one write. A failed build or upload leaves the live buffer and offsets unchanged. An immutable segment may still exist after failure; a fenced handle must be replaced and restored before further reads or writes. forceFlush makes the whole set durable before returning; otherwise the normal buffer thresholds apply. Concurrent readers see only previously accepted data.
func (*PartitionLog) AppendIdempotentBatches ¶ added in v2.1.0
func (l *PartitionLog) AppendIdempotentBatches(ctx context.Context, batches []RecordBatch) (*IdempotentAppendResult, error)
AppendIdempotentBatches validates sequences and deduplicates under the same append lock that assigns offsets. Every accepted new set is flushed, even if ordinary writes are configured to buffer, so no acknowledged sequence exists only in process memory. Recovery derives this state from the same S3 bytes.
func (*PartitionLog) BufferedHighWatermark ¶
func (l *PartitionLog) BufferedHighWatermark() int64
BufferedHighWatermark returns the in-memory high-watermark: one past the last offset this log has assigned (whether that offset is in a flushed segment or still in the write buffer). It is NOT durable. The flushed/durable high-watermark is the metadata store's NextOffset, advanced only on flush.
In flush-disabled / acks=0 mode no flush fires for the buffered tail, so the durable watermark lags. The fetch handler uses this value, gated on flushOnAck=false, to make acknowledged-but-buffered records consumable while the process lives. These records are LOST on restart: the buffer is in-memory and RestoreFromS3 rebuilds from segments only. This is a read-after-ack visibility helper for the non-default config, not a durability guarantee.
func (*PartitionLog) CheckOwnership ¶
func (l *PartitionLog) CheckOwnership() error
CheckOwnership rejects handles fenced by lease loss or a terminal upload failure.
func (*PartitionLog) DrainAndRelease ¶
func (l *PartitionLog) DrainAndRelease(release func())
DrainAndRelease waits for the active append, then releases ownership before another append can start. The caller must block new lease acquisitions first.
func (*PartitionLog) EarliestOffset ¶
func (l *PartitionLog) EarliestOffset() int64
EarliestOffset returns the lowest offset available in the log.
func (*PartitionLog) Flush ¶
func (l *PartitionLog) Flush(ctx context.Context) error
Flush persists the current buffer through the atomic record-set path. A terminal upload failure fences the handle without deleting durable objects.
func (*PartitionLog) Read ¶
Read loads the segment containing the requested offset. When the requested offset falls in a gap (e.g. after an orphaned segment was skipped during restore), Read snaps forward to the next available segment.
func (*PartitionLog) RestoreFromS3 ¶
func (l *PartitionLog) RestoreFromS3(ctx context.Context) (lastOffset int64, restoreErr error)
RestoreFromS3 rebuilds segment ranges from objects already stored in S3.
type PartitionLogConfig ¶
type PartitionLogConfig struct {
Buffer WriteBufferConfig
Segment SegmentWriterConfig
ReadAheadSegments int
CacheEnabled bool
Logger *slog.Logger
}
PartitionLogConfig configures per-partition log behavior.
type PartitionLogOptions ¶
type PartitionLogOptions struct {
PartitionLogConfig
// CheckOwnership fences handles retained across a lease handoff.
CheckOwnership func() error
// CommitOffsets publishes durable offsets while readers wait. It must not call this log.
CommitOffsets func(context.Context, *SegmentArtifact) error
}
PartitionLogOptions adds lease fencing without changing the published config.
type RecordBatch ¶
RecordBatch carries a Kafka record batch blob plus metadata required for indexing.
func NewRecordBatchFromBytes ¶
func NewRecordBatchFromBytes(data []byte) (RecordBatch, error)
NewRecordBatchFromBytes parses Kafka record batch metadata and returns a RecordBatch struct.
type RecoveredPartition ¶
type RecoveredPartition struct {
Partition int32
SegmentsCopied int
LastOffset int64
Segments []RecoveredSegment
}
RecoveredPartition summarizes copied data for one partition.
type RecoveredSegment ¶
type RecoveredSegment struct {
Partition int32
BaseOffset int64
LastOffset int64
SizeBytes int64
CreatedAt time.Time
SourceKey string
TargetKey string
SourceIndex string
TargetIndex string
}
RecoveredSegment describes one copied segment/index pair.
type S3Client ¶
type S3Client interface {
// UploadSegment creates an immutable object; an existing key must return ErrPreconditionFailed.
UploadSegment(ctx context.Context, key string, body []byte) error
UploadIndex(ctx context.Context, key string, body []byte) error
DeleteSegment(ctx context.Context, key string) error
DeleteIndex(ctx context.Context, key string) error
DownloadSegment(ctx context.Context, key string, rng *ByteRange) ([]byte, error)
DownloadIndex(ctx context.Context, key string) ([]byte, error)
ListSegments(ctx context.Context, prefix string) ([]S3Object, error)
EnsureBucket(ctx context.Context) error
}
S3Client is the abstraction used by storage to read/write segments.
type S3Config ¶
type S3Config struct {
Bucket string
Region string
Endpoint string
ForcePathStyle bool
AccessKeyID string
SecretAccessKey string
SessionToken string
KMSKeyARN string
MaxConnections int
}
S3Config describes connection details for AWS S3 or compatible endpoints.
type SegmentArtifact ¶
type SegmentArtifact struct {
BaseOffset int64
LastOffset int64
MessageCount int32
CreatedAt time.Time
SegmentBytes []byte
IndexBytes []byte
RelativeIndex []*IndexEntry
}
SegmentArtifact contains serialized segment + index bytes ready for upload.
func BuildSegment ¶
func BuildSegment(cfg SegmentWriterConfig, batches []RecordBatch, created time.Time) (*SegmentArtifact, error)
BuildSegment assembles segment + index bytes from buffered batches.
type SegmentWriterConfig ¶
type SegmentWriterConfig struct {
IndexIntervalMessages int32
}
SegmentWriterConfig controls serialization.
type TopicRecoveryConfig ¶
type TopicRecoveryConfig struct {
SourceNamespace string
SourceTopic string
TargetNamespace string
TargetTopic string
RestoreTo time.Time
Partitions []int32
}
TopicRecoveryConfig defines a segment-granular topic restore into a new topic.
type TopicRecoveryResult ¶
type TopicRecoveryResult struct {
SourceNamespace string
SourceTopic string
TargetNamespace string
TargetTopic string
RestoreTo time.Time
SegmentsCopied int
Partitions []RecoveredPartition
}
TopicRecoveryResult is the outcome of a restore run.
func RecoverTopicToTimestamp ¶
func RecoverTopicToTimestamp(ctx context.Context, s3 S3Client, cfg TopicRecoveryConfig) (*TopicRecoveryResult, error)
RecoverTopicToTimestamp copies immutable segment/index pairs into a new topic and truncates the final candidate segment at the first record whose timestamp exceeds the requested cutoff.
type WriteBuffer ¶
type WriteBuffer struct {
// contains filtered or unexported fields
}
WriteBuffer accumulates record batches prior to segment serialization.
func NewWriteBuffer ¶
func NewWriteBuffer(cfg WriteBufferConfig) *WriteBuffer
NewWriteBuffer creates an empty buffer.
func (*WriteBuffer) Append ¶
func (b *WriteBuffer) Append(batch RecordBatch)
Append adds a batch to the buffer.
func (*WriteBuffer) Drain ¶
func (b *WriteBuffer) Drain() []RecordBatch
Drain returns all buffered batches and resets counters.
func (*WriteBuffer) RecordsFrom ¶
func (b *WriteBuffer) RecordsFrom(offset int64, maxBytes int32) []byte
RecordsFrom returns the raw bytes of buffered batches needed to serve a read starting at offset, concatenated, non-destructively. A batch is included when its last offset (BaseOffset+LastOffsetDelta) is >= offset, i.e. the batch that contains the requested offset plus every batch after it.
maxBytes caps the result. The first matching batch is always returned in full even if it alone exceeds maxBytes, so a read can always make progress (this mirrors how Kafka returns at least one batch regardless of fetch.max.bytes). maxBytes <= 0 is treated as "first matching batch only": a non-positive cap returns a single bounded unit rather than draining the whole buffered tail, so a malformed or zero PartitionMaxBytes can never produce an unbounded response.
Returns nil when no buffered batch reaches offset.
This makes acked-but-not-yet-flushed records readable (Kafka read-after-ack): flush is append-triggered, so a partition that goes quiet leaves its tail in the buffer; without this the fetch path (segments only) returns ErrOffsetOutOfRange for those acked offsets.
func (*WriteBuffer) ShouldFlush ¶
func (b *WriteBuffer) ShouldFlush(now time.Time) bool
ShouldFlush checks if size thresholds or time elapsed require a flush.
func (*WriteBuffer) Size ¶
func (b *WriteBuffer) Size() int
Size returns the accumulated byte count (for tests/metrics).