mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* log_buffer: find a fetched offset in a disk chunk by its offset A stateless read caches disk reads in chunks aligned to 1000 offsets and picked the requested message by its distance from the aligned start. A chunk read from disk begins at the first offset stored at or above that start, so once the partition's oldest files are gone the chunk begins later and the read returned messages from further on, under the requested offsets. The message is now found by its offset, and the next offset follows the last message returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: start a loaded partition's log at its earliest stored offset A loaded partition reported its earliest offset as 0 and its log start as the start of its memory, so neither said where the stored data begins. The log buffer now keeps the earliest offset still stored: a leader seeds it from the offset ranges on its files when it loads, it only moves up, and the partition's offset info and log start report it. A stateless read below it fails with ErrOffsetOutOfRange instead of being answered from a later file under the requested offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: purge a partition's files past its topic's retention A topic's retention was stored but never applied, so a topic that is not re-partitioned kept every flushed file. Every five minutes the broker now purges each partition it leads whose topic has retention enabled. It deletes the oldest run of files whose newest message is older than the retention, stopping at the first file still retained so the stored offsets stay contiguous, and always keeps the file with the highest offset, which a later load continues offsets from. A log file is judged by when it was flushed and a parquet file by its newest row; a parquet file is deleted together with its source log files. The partition's log start is raised before the deletes, and each delete is a transaction conditioned on the partition's fence token, so a leader that lost its fence deletes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1) The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the same value for its unknown and publisher-not-found errors. Today the mapped code only reaches error text, but a fetch path that answers OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker failure reset a consumer. The code is now -1. The gateway only tests these codes against 0 and against specific codes, and the cached assignment is still dropped on the broker's own code 1, so nothing treated 1 as success or depended on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE A read below the earliest retained offset failed like any other read, so FetchMessage reported a storage error and the gateway answered KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever once retention has purged it. FetchMessage now answers ErrOffsetOutOfRange with its own broker code, the earliest retained offset as LogStartOffset, and the requested offset as NextOffset. The gateway carries it as ErrOffsetOutOfRange and answers the partition with OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset to earliest asks ListOffsets, which reports the retained start through the leader's range info. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep a disk chunk's entries in offset order A disk read filled its 1000-offset chunk with the first 1000 entries in the order the files listed, and the lookup searches the chunk by offset. Files whose names sort out of offset order deliver entries out of order, so the chunk held the wrong offsets and was cached that way. It now keeps only the chunk's offsets, wherever they come, and sorts them before caching. * mq broker: purge a partition's files in offset order The purge walked a partition's files in name order and stopped at the first one still retained. Names sort by the start of a window, which can be earlier than older files' after a reload, so a file holding higher offsets could be purged ahead of a retained one below it, leaving a hole. The walk now goes by each file's first offset, taking a parquet file that records none from its first source, and by name among equals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: round a log file's flush time up to bound its messages A log file without a recorded newest timestamp is judged by its Mtime, which the filer keeps in whole seconds, so a file flushed later in the cutoff's second looked older than messages it may hold. The purge now takes the end of that second as the bound. A recorded newest timestamp is still used as is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep one entry per offset in a disk chunk A disk read goes through a partition's log files and then its parquet files, and a parquet file holds the same offsets as the log files it was compacted from, so a chunk could take an offset twice and a fetch returned the duplicate as the next message. The chunk now keeps the first entry for each offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: reread a cached disk chunk that lacks the fetched offset A disk chunk can be cached while its later offsets are still in memory. Once those are flushed and memory moves on, a fetch past the cached part hit the cache, found nothing, and returned no messages until the chunk was evicted. A cached chunk that does not hold the fetched offset is now dropped and read from disk again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's offset range from its sources The compactor took a parquet file's offset range from its entries' offsets above 0 and recorded it only when the lowest was above 0, so a file compacted from a partition's first window recorded no range, and one whose entries started at 0 would have claimed to start at 1. The range now comes from the source log files' recorded ranges, including one that starts at offset 0, and is left out unless every source records one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: keep the earliest offset at or below files that record no range The earliest stored offset was the lowest offset any file records, so a file that records none, such as a parquet file compacted from a partition's first window or a log file flushed without a range, was left out. A reload or a purge could then start the log above offsets a read can still return, and ListOffsets for the earliest offset left them out. OffsetRange now takes the whole entry and keeps the earliest offset at 0 while a log or parquet file records no range, except a parquet file whose listed sources are all present, as their ranges cover it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a partition whose files cannot all be placed by offset The purge ordered a data file that records no offsets, and whose sources give none, as if it held the lowest, so an expired one could be deleted while a retained file below its offsets stayed, leaving a hole. A partition holding such a file is now left alone; only files written before offsets were recorded lack them. * mq broker: purge a parquet file only when each of its sources has expired The purge deleted every source of an expired parquet file along with it, judging the whole group by the parquet file's newest timestamp. Message timestamps are not ordered across reloads, so a parquet file can hold an expired source next to one still retained, and the retained one went early. A parquet group is now purged only when the parquet file and each source in it are past the cutoff on their own; otherwise the walk stops there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's lowest and highest timestamps The compactor recorded a parquet file's timestamp range from its first and last rows. Message timestamps are not ordered across reloads, so the last row need not be the newest, and the recorded ts_max could sit below messages the file holds, making it look older to the retention purge and to readers that skip files by time. It now records the lowest and highest timestamps over all rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: keep each compacted row's offset in the _offset column The compaction schema had no _offset column, so a schematized row's offset was dropped and a schemaless row never carried one, while the parquet reader expects the column and a fetch places rows by offset. The compactor now adds the column when the schema lacks it and fills it for every row, schemaless ones included, when the source files record their offsets; otherwise it is left null. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: read a parquet file by its own columns and mark unknown offsets The parquet reader always expected an _offset column and read rows by column position, so a file compacted before the column existed was read out of alignment and panicked with an index out of range. A row with no real offset also read back as offset 0, so a disk chunk, which keeps one entry per offset, collapsed such rows into one. The reader now uses the _offset column only when the file has it, trusts it only when the file records its offset range, and reports any other row with offset -1, which keeps it out of reads by offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a purge group that reaches past the first retained offset A parquet file is purged with its sources as one group, and the sources need not be contiguous: an expired parquet file could list expired files on both sides of a retained one, so purging the group left a hole above the retained file. A group now goes only when every offset it and its sources cover lies below the first offset left behind; the walk keeps the first group that does not, and the ones after it. A log file whose offsets a retained parquet file also starts at now stays until that parquet file goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: give compaction test fixtures file ids no other fixture uses The parquet reader caches chunks in a package-wide cache keyed by file id, and each compaction fixture numbered its file ids from 1, so one fixture could read another's cached bytes; with -count=3 a test read a parquet file from an earlier run and failed. File ids are now numbered across all fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: compact legacy log files apart from ones that record offsets A compaction group could hold a legacy log file without an offset range next to files that record one, and a parquet file keeps its rows' offsets only when every source records them, so the ranged rows lost their offsets and could no longer be fetched by offset. Groups now split where a file's having an offset range differs from the group's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: treat a parquet file's end as unknown when a source is gone A parquet file that records no offset range took its last offset from the sources still present, so one whose later source was already gone looked as if it ended below a retained file and was purged, though it may hold that source's offsets above the retained one. A gone or unranged source now leaves the end unknown, and the group stays. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
503 lines
18 KiB
Go
503 lines
18 KiB
Go
package log_buffer
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
// ReadMessagesAtOffset provides Kafka-style stateless reads from LogBuffer
|
|
// Each call is completely independent - no state maintained between calls
|
|
// Thread-safe for concurrent reads at different offsets
|
|
//
|
|
// This is the recommended API for stateless clients like Kafka gateway
|
|
// Unlike Subscribe loops, this:
|
|
// 1. Returns immediately with available data (or empty if none)
|
|
// 2. Does not maintain any session state
|
|
// 3. Safe for concurrent calls
|
|
// 4. No cancellation/restart complexity
|
|
//
|
|
// Returns:
|
|
// - messages: Array of messages starting at startOffset
|
|
// - nextOffset: Offset to use for next fetch
|
|
// - highWaterMark: Highest offset available in partition
|
|
// - endOfPartition: True if no more data available
|
|
// - err: Any error encountered
|
|
func (logBuffer *LogBuffer) ReadMessagesAtOffset(startOffset int64, maxMessages int, maxBytes int) (
|
|
messages []*filer_pb.LogEntry,
|
|
nextOffset int64,
|
|
highWaterMark int64,
|
|
endOfPartition bool,
|
|
err error,
|
|
) {
|
|
// Quick validation
|
|
if maxMessages <= 0 {
|
|
maxMessages = 100 // Default reasonable batch size
|
|
}
|
|
if maxBytes <= 0 {
|
|
maxBytes = 4 * 1024 * 1024 // 4MB default
|
|
}
|
|
|
|
messages = make([]*filer_pb.LogEntry, 0, maxMessages)
|
|
nextOffset = startOffset
|
|
|
|
// Try to read from in-memory buffers first (hot path)
|
|
logBuffer.RLock()
|
|
currentBufferEnd := logBuffer.offset
|
|
bufferStartOffset := logBuffer.bufferStartOffset
|
|
highWaterMark = currentBufferEnd
|
|
|
|
if logStartOffset := logBuffer.logStartOffset; startOffset < logStartOffset {
|
|
logBuffer.RUnlock()
|
|
return messages, startOffset, highWaterMark, false, fmt.Errorf("offset %d is before the log start offset %d: %w", startOffset, logStartOffset, ErrOffsetOutOfRange)
|
|
}
|
|
|
|
// Special case: empty buffer (no data written yet)
|
|
if currentBufferEnd == 0 && bufferStartOffset == 0 && logBuffer.pos == 0 {
|
|
logBuffer.RUnlock()
|
|
// Return empty result - partition exists but has no data yet
|
|
// Preserve the requested offset in nextOffset
|
|
return messages, startOffset, 0, true, nil
|
|
}
|
|
|
|
// Check if requested offset is in current buffer
|
|
if startOffset >= bufferStartOffset && startOffset < currentBufferEnd {
|
|
// Read from current buffer
|
|
glog.V(4).Infof("[StatelessRead] Reading from current buffer: start=%d, end=%d",
|
|
bufferStartOffset, currentBufferEnd)
|
|
|
|
if logBuffer.pos > 0 {
|
|
// Make a copy of the buffer to avoid concurrent modification
|
|
bufCopy := make([]byte, logBuffer.pos)
|
|
copy(bufCopy, logBuffer.buf[:logBuffer.pos])
|
|
logBuffer.RUnlock() // Release lock early
|
|
|
|
// Parse messages from buffer copy
|
|
messages, nextOffset, _, err = parseMessagesFromBuffer(
|
|
bufCopy, startOffset, maxMessages, maxBytes)
|
|
|
|
if err != nil {
|
|
return nil, startOffset, highWaterMark, false, err
|
|
}
|
|
|
|
glog.V(4).Infof("[StatelessRead] Read %d messages from current buffer, nextOffset=%d",
|
|
len(messages), nextOffset)
|
|
|
|
// Check if we reached the end
|
|
endOfPartition = (nextOffset >= currentBufferEnd) && (len(messages) == 0 || len(messages) < maxMessages)
|
|
return messages, nextOffset, highWaterMark, endOfPartition, nil
|
|
}
|
|
|
|
// Buffer is empty but offset is in range - check previous buffers
|
|
logBuffer.RUnlock()
|
|
|
|
// Try previous buffers
|
|
logBuffer.RLock()
|
|
for _, prevBuf := range logBuffer.prevBuffers.buffers {
|
|
if startOffset >= prevBuf.startOffset && startOffset <= prevBuf.offset {
|
|
if prevBuf.size > 0 {
|
|
// Found in previous buffer
|
|
bufCopy := make([]byte, prevBuf.size)
|
|
copy(bufCopy, prevBuf.buf[:prevBuf.size])
|
|
logBuffer.RUnlock()
|
|
|
|
messages, nextOffset, _, err = parseMessagesFromBuffer(
|
|
bufCopy, startOffset, maxMessages, maxBytes)
|
|
|
|
if err != nil {
|
|
return nil, startOffset, highWaterMark, false, err
|
|
}
|
|
|
|
glog.V(4).Infof("[StatelessRead] Read %d messages from previous buffer, nextOffset=%d",
|
|
len(messages), nextOffset)
|
|
|
|
endOfPartition = false // More data might be in current buffer
|
|
return messages, nextOffset, highWaterMark, endOfPartition, nil
|
|
}
|
|
// Empty previous buffer means data was flushed to disk - fall through to disk read
|
|
glog.V(2).Infof("[StatelessRead] Data at offset %d was flushed, attempting disk read", startOffset)
|
|
break
|
|
}
|
|
}
|
|
logBuffer.RUnlock()
|
|
|
|
// Data not in memory - attempt disk read if configured
|
|
// Don't return error here - data may be on disk!
|
|
// Fall through to disk read logic below
|
|
glog.V(2).Infof("[StatelessRead] Data at offset %d not in memory (buffer: %d-%d), attempting disk read",
|
|
startOffset, bufferStartOffset, currentBufferEnd)
|
|
// Don't return error - continue to disk read check below
|
|
} else {
|
|
// Offset is not in current buffer - check previous buffers FIRST before going to disk
|
|
// This handles the case where data was just flushed but is still in prevBuffers
|
|
|
|
for _, prevBuf := range logBuffer.prevBuffers.buffers {
|
|
if startOffset >= prevBuf.startOffset && startOffset <= prevBuf.offset {
|
|
if prevBuf.size > 0 {
|
|
// Found in previous buffer!
|
|
bufCopy := make([]byte, prevBuf.size)
|
|
copy(bufCopy, prevBuf.buf[:prevBuf.size])
|
|
logBuffer.RUnlock()
|
|
|
|
messages, nextOffset, _, err = parseMessagesFromBuffer(
|
|
bufCopy, startOffset, maxMessages, maxBytes)
|
|
|
|
if err != nil {
|
|
return nil, startOffset, highWaterMark, false, err
|
|
}
|
|
|
|
endOfPartition = false // More data might exist
|
|
return messages, nextOffset, highWaterMark, endOfPartition, nil
|
|
}
|
|
// Empty previous buffer - data was flushed to disk
|
|
glog.V(2).Infof("[StatelessRead] Found empty previous buffer for offset %d, will try disk", startOffset)
|
|
break
|
|
}
|
|
}
|
|
logBuffer.RUnlock()
|
|
}
|
|
|
|
// If we get here, unlock if not already unlocked
|
|
// (Note: logBuffer.RUnlock() was called above in all paths)
|
|
|
|
// Data not in memory - try disk read
|
|
// This handles two cases:
|
|
// 1. startOffset < bufferStartOffset: Historical data
|
|
// 2. startOffset in buffer range but not in memory: Data was flushed (from fall-through above)
|
|
if startOffset < currentBufferEnd {
|
|
// Historical data or flushed data - try to read from disk if ReadFromDiskFn is configured
|
|
if startOffset < bufferStartOffset {
|
|
glog.Errorf("[StatelessRead] CASE 1: Historical data - offset %d < bufferStart %d",
|
|
startOffset, bufferStartOffset)
|
|
} else {
|
|
glog.Errorf("[StatelessRead] CASE 2: Flushed data - offset %d in range [%d, %d) but not in memory",
|
|
startOffset, bufferStartOffset, currentBufferEnd)
|
|
}
|
|
|
|
// Check if disk read function is configured
|
|
if logBuffer.ReadFromDiskFn == nil {
|
|
glog.Errorf("[StatelessRead] CRITICAL: ReadFromDiskFn is NIL! Cannot read from disk.")
|
|
if startOffset < bufferStartOffset {
|
|
return messages, startOffset, highWaterMark, false, fmt.Errorf("offset %d too old (earliest in-memory: %d), and ReadFromDiskFn is nil",
|
|
startOffset, bufferStartOffset)
|
|
}
|
|
return messages, startOffset, highWaterMark, false, fmt.Errorf("offset %d not in memory (buffer: %d-%d), and ReadFromDiskFn is nil",
|
|
startOffset, bufferStartOffset, currentBufferEnd)
|
|
}
|
|
|
|
// Read from disk (this is async/non-blocking if the ReadFromDiskFn is properly implemented)
|
|
// The ReadFromDiskFn should handle its own timeouts and not block indefinitely
|
|
diskMessages, diskNextOffset, diskErr := readHistoricalDataFromDisk(
|
|
logBuffer, startOffset, maxMessages, maxBytes, highWaterMark)
|
|
|
|
if diskErr != nil {
|
|
glog.Errorf("[StatelessRead] CRITICAL: Disk read FAILED for offset %d: %v", startOffset, diskErr)
|
|
// IMPORTANT: Return retryable error instead of silently returning empty!
|
|
return messages, startOffset, highWaterMark, false, fmt.Errorf("disk read failed for offset %d: %v", startOffset, diskErr)
|
|
}
|
|
|
|
if len(diskMessages) == 0 {
|
|
glog.Errorf("[StatelessRead] WARNING: Disk read returned 0 messages for offset %d (HWM=%d, bufferStart=%d)",
|
|
startOffset, highWaterMark, bufferStartOffset)
|
|
}
|
|
|
|
// Return disk data
|
|
endOfPartition = diskNextOffset >= bufferStartOffset && len(diskMessages) < maxMessages
|
|
return diskMessages, diskNextOffset, highWaterMark, endOfPartition, nil
|
|
}
|
|
|
|
// startOffset >= currentBufferEnd - future offset, no data available yet
|
|
glog.V(4).Infof("[StatelessRead] Future offset %d >= buffer end %d, no data available",
|
|
startOffset, currentBufferEnd)
|
|
return messages, startOffset, highWaterMark, true, nil
|
|
}
|
|
|
|
// readHistoricalDataFromDisk reads messages from disk for historical offsets
|
|
// This is called when the requested offset is older than what's in memory
|
|
// Uses an in-memory cache to avoid repeated disk I/O for the same chunks
|
|
func readHistoricalDataFromDisk(
|
|
logBuffer *LogBuffer,
|
|
startOffset int64,
|
|
maxMessages int,
|
|
maxBytes int,
|
|
highWaterMark int64,
|
|
) (messages []*filer_pb.LogEntry, nextOffset int64, err error) {
|
|
const chunkSize = 1000 // Size of each cached chunk
|
|
|
|
// Calculate chunk start offset (aligned to chunkSize boundary)
|
|
chunkStartOffset := (startOffset / chunkSize) * chunkSize
|
|
|
|
// Try to get from cache first
|
|
cachedMessages, cacheHit := getCachedDiskChunk(logBuffer, chunkStartOffset)
|
|
|
|
if cacheHit {
|
|
result, nextOff := extractMessagesFromCache(cachedMessages, startOffset, maxMessages, maxBytes)
|
|
if len(result) > 0 && result[0].Offset == startOffset {
|
|
return result, nextOff, nil
|
|
}
|
|
// cached while later offsets were still in memory; they may be on disk by now
|
|
logBuffer.diskChunkCache.mu.Lock()
|
|
delete(logBuffer.diskChunkCache.chunks, chunkStartOffset)
|
|
logBuffer.diskChunkCache.mu.Unlock()
|
|
}
|
|
|
|
// Not in cache - read entire chunk from disk for caching
|
|
chunkMessages := make([]*filer_pb.LogEntry, 0, chunkSize)
|
|
chunkEndOffset := chunkStartOffset + chunkSize
|
|
|
|
// Create a position for the chunk start
|
|
chunkPosition := MessagePosition{
|
|
IsOffsetBased: true,
|
|
Offset: chunkStartOffset,
|
|
}
|
|
|
|
// Files whose names sort out of offset order deliver entries out of order, so
|
|
// keep the chunk's offsets wherever they come and stop a bounded way past it.
|
|
outside := 0
|
|
// log files and the parquet files compacted from them can both deliver an offset
|
|
seen := make(map[int64]bool, chunkSize)
|
|
eachMessageFn := func(logEntry *filer_pb.LogEntry) (isDone bool, err error) {
|
|
if logEntry.Offset < chunkStartOffset || logEntry.Offset >= chunkEndOffset {
|
|
outside++
|
|
return outside >= chunkSize, nil
|
|
}
|
|
if seen[logEntry.Offset] {
|
|
return false, nil
|
|
}
|
|
seen[logEntry.Offset] = true
|
|
chunkMessages = append(chunkMessages, logEntry)
|
|
return len(chunkMessages) >= chunkSize, nil
|
|
}
|
|
|
|
// Read chunk from disk
|
|
_, _, readErr := logBuffer.ReadFromDiskFn(chunkPosition, 0, eachMessageFn)
|
|
|
|
if readErr != nil {
|
|
glog.Errorf("[DiskRead] CRITICAL: ReadFromDiskFn returned ERROR: %v", readErr)
|
|
return nil, startOffset, fmt.Errorf("failed to read from disk: %w", readErr)
|
|
}
|
|
|
|
// Cache the chunk for future reads
|
|
sort.Slice(chunkMessages, func(i, j int) bool { return chunkMessages[i].Offset < chunkMessages[j].Offset })
|
|
if len(chunkMessages) > 0 {
|
|
cacheDiskChunk(logBuffer, chunkStartOffset, chunkMessages[len(chunkMessages)-1].Offset, chunkMessages)
|
|
} else {
|
|
glog.Errorf("[DiskRead] WARNING: ReadFromDiskFn returned 0 messages for chunkStart=%d", chunkStartOffset)
|
|
}
|
|
|
|
// Extract requested messages from the chunk
|
|
result, resNextOffset := extractMessagesFromCache(chunkMessages, startOffset, maxMessages, maxBytes)
|
|
return result, resNextOffset, nil
|
|
}
|
|
|
|
// getCachedDiskChunk retrieves a cached disk chunk if available
|
|
func getCachedDiskChunk(logBuffer *LogBuffer, chunkStartOffset int64) ([]*filer_pb.LogEntry, bool) {
|
|
logBuffer.diskChunkCache.mu.RLock()
|
|
defer logBuffer.diskChunkCache.mu.RUnlock()
|
|
|
|
if chunk, exists := logBuffer.diskChunkCache.chunks[chunkStartOffset]; exists {
|
|
// Update last access time
|
|
chunk.lastAccess = time.Now()
|
|
return chunk.messages, true
|
|
}
|
|
|
|
return nil, false
|
|
}
|
|
|
|
// cacheDiskChunk stores a disk chunk in the cache with LRU eviction
|
|
func cacheDiskChunk(logBuffer *LogBuffer, startOffset, endOffset int64, messages []*filer_pb.LogEntry) {
|
|
logBuffer.diskChunkCache.mu.Lock()
|
|
defer logBuffer.diskChunkCache.mu.Unlock()
|
|
|
|
// Check if we need to evict old chunks (LRU policy)
|
|
if len(logBuffer.diskChunkCache.chunks) >= logBuffer.diskChunkCache.maxChunks {
|
|
// Find least recently used chunk
|
|
var oldestOffset int64
|
|
var oldestTime time.Time
|
|
first := true
|
|
|
|
for offset, chunk := range logBuffer.diskChunkCache.chunks {
|
|
if first || chunk.lastAccess.Before(oldestTime) {
|
|
oldestOffset = offset
|
|
oldestTime = chunk.lastAccess
|
|
first = false
|
|
}
|
|
}
|
|
|
|
// Evict oldest chunk
|
|
delete(logBuffer.diskChunkCache.chunks, oldestOffset)
|
|
glog.V(4).Infof("[DiskCache] Evicted chunk at offset %d (LRU)", oldestOffset)
|
|
}
|
|
|
|
// Store new chunk
|
|
logBuffer.diskChunkCache.chunks[startOffset] = &CachedDiskChunk{
|
|
startOffset: startOffset,
|
|
endOffset: endOffset,
|
|
messages: messages,
|
|
lastAccess: time.Now(),
|
|
}
|
|
}
|
|
|
|
// extractMessagesFromCache returns the chunk's messages from startOffset on. They are
|
|
// found by offset, because a chunk starts at its first stored offset, not at its aligned start.
|
|
func extractMessagesFromCache(chunkMessages []*filer_pb.LogEntry, startOffset int64, maxMessages, maxBytes int) ([]*filer_pb.LogEntry, int64) {
|
|
first := sort.Search(len(chunkMessages), func(i int) bool { return chunkMessages[i].Offset >= startOffset })
|
|
if first == len(chunkMessages) {
|
|
// not on disk; the caller checks the memory buffers
|
|
return nil, startOffset
|
|
}
|
|
|
|
messages := make([]*filer_pb.LogEntry, 0, maxMessages)
|
|
nextOffset := startOffset
|
|
totalBytes := 0
|
|
|
|
for _, entry := range chunkMessages[first:] {
|
|
if len(messages) >= maxMessages {
|
|
break
|
|
}
|
|
entrySize := proto.Size(entry)
|
|
if totalBytes > 0 && totalBytes+entrySize > maxBytes {
|
|
break
|
|
}
|
|
|
|
messages = append(messages, entry)
|
|
totalBytes += entrySize
|
|
nextOffset = entry.Offset + 1
|
|
}
|
|
|
|
glog.V(4).Infof("[DiskCache] Extracted %d messages from cache (offset %d-%d, bytes=%d)",
|
|
len(messages), startOffset, nextOffset-1, totalBytes)
|
|
|
|
return messages, nextOffset
|
|
}
|
|
|
|
// parseMessagesFromBuffer parses messages from a buffer byte slice
|
|
// This is thread-safe as it operates on a copy of the buffer
|
|
func parseMessagesFromBuffer(buf []byte, startOffset int64, maxMessages int, maxBytes int) (
|
|
messages []*filer_pb.LogEntry,
|
|
nextOffset int64,
|
|
totalBytes int,
|
|
err error,
|
|
) {
|
|
messages = make([]*filer_pb.LogEntry, 0, maxMessages)
|
|
nextOffset = startOffset
|
|
totalBytes = 0
|
|
foundStart := false
|
|
|
|
messagesInBuffer := 0
|
|
for pos := 0; pos+4 < len(buf) && len(messages) < maxMessages && totalBytes < maxBytes; {
|
|
// Read message size
|
|
size := util.BytesToUint32(buf[pos : pos+4])
|
|
if pos+4+int(size) > len(buf) {
|
|
// Incomplete message at end of buffer
|
|
glog.V(4).Infof("[parseMessages] Incomplete message at pos %d, size %d, bufLen %d",
|
|
pos, size, len(buf))
|
|
break
|
|
}
|
|
|
|
// Parse message
|
|
entryData := buf[pos+4 : pos+4+int(size)]
|
|
logEntry := &filer_pb.LogEntry{}
|
|
if err = logEntry.UnmarshalVT(entryData); err != nil {
|
|
glog.Warningf("[parseMessages] Failed to unmarshal message: %v", err)
|
|
pos += 4 + int(size)
|
|
continue
|
|
}
|
|
|
|
messagesInBuffer++
|
|
|
|
// Initialize foundStart from first message
|
|
if !foundStart {
|
|
// Find the first message at or after startOffset
|
|
if logEntry.Offset >= startOffset {
|
|
foundStart = true
|
|
nextOffset = logEntry.Offset
|
|
} else {
|
|
// Skip messages before startOffset
|
|
glog.V(3).Infof("[parseMessages] Skipping message at offset %d (before startOffset %d)", logEntry.Offset, startOffset)
|
|
pos += 4 + int(size)
|
|
continue
|
|
}
|
|
}
|
|
|
|
// Check if this message matches expected offset
|
|
if foundStart && logEntry.Offset >= startOffset {
|
|
glog.V(3).Infof("[parseMessages] Adding message at offset %d (count=%d)", logEntry.Offset, len(messages)+1)
|
|
messages = append(messages, logEntry)
|
|
totalBytes += 4 + int(size)
|
|
nextOffset = logEntry.Offset + 1
|
|
}
|
|
|
|
pos += 4 + int(size)
|
|
}
|
|
|
|
glog.V(4).Infof("[parseMessages] Parsed %d messages, nextOffset=%d, totalBytes=%d",
|
|
len(messages), nextOffset, totalBytes)
|
|
|
|
return messages, nextOffset, totalBytes, nil
|
|
}
|
|
|
|
// GetHighWaterMark returns the highest offset available in this partition
|
|
// This is a lightweight operation for clients to check partition state
|
|
func (logBuffer *LogBuffer) GetHighWaterMark() int64 {
|
|
logBuffer.RLock()
|
|
defer logBuffer.RUnlock()
|
|
return logBuffer.offset
|
|
}
|
|
|
|
// GetLogStartOffset returns the earliest offset still stored, in memory or on disk.
|
|
func (logBuffer *LogBuffer) GetLogStartOffset() int64 {
|
|
logBuffer.RLock()
|
|
defer logBuffer.RUnlock()
|
|
return logBuffer.logStartOffset
|
|
}
|
|
|
|
// SetLogStartOffset raises the earliest offset still stored; reads below it are out of range.
|
|
func (logBuffer *LogBuffer) SetLogStartOffset(offset int64) {
|
|
logBuffer.Lock()
|
|
defer logBuffer.Unlock()
|
|
logBuffer.logStartOffset = max(logBuffer.logStartOffset, offset)
|
|
}
|
|
|
|
// WaitForDataWithTimeout waits up to maxWaitMs for data to be available at startOffset
|
|
// Returns true if data became available, false if timeout
|
|
// This allows "long poll" behavior for real-time consumers
|
|
func (logBuffer *LogBuffer) WaitForDataWithTimeout(startOffset int64, maxWaitMs int) bool {
|
|
if maxWaitMs <= 0 {
|
|
return false
|
|
}
|
|
|
|
timeout := time.NewTimer(time.Duration(maxWaitMs) * time.Millisecond)
|
|
defer timeout.Stop()
|
|
|
|
// Register for notifications
|
|
notifyChan := logBuffer.RegisterSubscriber(fmt.Sprintf("fetch-%d", startOffset))
|
|
defer logBuffer.UnregisterSubscriber(fmt.Sprintf("fetch-%d", startOffset))
|
|
|
|
// Check if data is already available
|
|
logBuffer.RLock()
|
|
currentEnd := logBuffer.offset
|
|
logBuffer.RUnlock()
|
|
|
|
if currentEnd >= startOffset {
|
|
return true
|
|
}
|
|
|
|
// Wait for notification or timeout
|
|
select {
|
|
case <-notifyChan:
|
|
// Data might be available now
|
|
logBuffer.RLock()
|
|
currentEnd := logBuffer.offset
|
|
logBuffer.RUnlock()
|
|
return currentEnd >= startOffset
|
|
case <-timeout.C:
|
|
return false
|
|
}
|
|
}
|