mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
* mq: seal a partition's fence when a repartition drains it Draining a partition shut it down and answered at once: its last window was still being flushed, and its fence was left unsealed. A publisher still holding the old assignment could then load the range again on its leader at the same epoch and append to a range the topic no longer lists, so nothing could treat a removed range as complete. The drain now waits for the last flush, waiting out a retirement already pending too, and seals the fence before it answers; a drained range its leader does not have loaded has its stored fence sealed as found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: serve a sealed range a repartition removed from its files A repartition drops the old ranges from the topic, and a fetch for one was answered partition not found, so whatever a consumer had not read from it was out of reach. A fetch naming a generation and range the topic no longer assigns, whose fence is sealed, is now served read-only by any broker: a stopped log buffer over the range's files, with its log start and high-water mark read from them, answers through the same stateless read as a live partition, out-of-range included. A reader is reused for 30 seconds, so a purge elsewhere shows soon. An unassigned range whose fence is not sealed may still take writes and keeps the old answer. The test filer can now keep what is uploaded to it, so flushed windows read back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: list a topic's retired ranges in the partition lookup LookupTopicBrokers takes include_retired and then also answers retired_partitions: each sealed range of an earlier generation the topic no longer assigns that still holds data, with its log start and high-water mark, read from the range's files. A consumer can find what a repartition left behind and fetch it. Unsealed ranges are left out, since they may still take writes. The test filer lists the directories an entry's path implies, as the filer does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: purge retired ranges past retention The retention pass hands each partition with expired files to its leader, but it walked only the topic's current assignments, so a range a repartition retired kept its files forever. The balancer now purges each sealed retired range itself, deleting its expired files under the sealed fence as read. As for a live partition the newest file stays, so the range keeps its high-water mark and a read below the raised log start is out of range. The purging broker drops its cached reader of the range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: the offset scan of a partition's files stops with its caller Retired fetches and listings, the retention pass and a follower take-over now pass their context to the filer scan, so a cancelled lookup or a broker shutting down does not wait on a filer that stops sending entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's old ranges only after saving the new topic.conf A repartition drained the old ranges before saving the topic.conf that replaces them, and a drain now seals them. When that save failed, the ranges topic.conf still assigned were sealed: their leader could not take their fence again, and with every broker healthy nothing moved the epoch on, so the topic took no more writes. The old ranges are now drained after the save, so a failed save leaves them assigned, unsealed and writable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: leave a drained range's fence to a holder still renewing it A drained range its leader had not loaded had its stored fence sealed as found. If a follower had taken that fence over and was still storing the records it acked, the seal replaced its token, so its remaining writes failed the fence check and those records never reached the range. The drain now seals a found fence only once nobody has renewed it for fenceSealWait, the same test a new leader applies; a holder still renewing it seals it itself when done, and the drain waits for that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: seal a range drained while its broker shuts down Once a broker shutdown has started it retires every partition itself, so removing one for a drain reports false, and the drain answered success without sealing the range. It now waits for the shutdown's last flush of the partition and seals the fence like any other drain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: read retired ranges without a log buffer, dropping old readers on access Each retired range's reader was a stopped log buffer, which still allocated the buffers and windows a writer needs, and cached readers past their time were dropped only when another was created. A retired range is now read through ReadFlushedMessagesAtOffset, the stateless disk read with its chunk cache and nothing else, answering out-of-range and end of partition as a live buffer does; the disk read helpers take the read function and cache instead of a buffer. Readers past retiredReaderTTL are dropped on every lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound the retention pass over retired ranges The pass over a topic's retired ranges ran under the broker's own context, so a filer that stopped answering its listing or offset scan held the balancer's retention loop for good. Each topic's pass over its retired ranges now has generationPassTimeout, as handing expired partitions to their leaders does. The test also covers a fetch of a retired range returning with its caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: a drain seals a stale fence only as it read it A drained range its leader had not loaded is sealed once its fence has gone fenceSealWait without a renewal. The seal required only the fence's token, which a renewal keeps, so a holder that renewed between the drain's read and its seal still had the fence sealed under it, and its remaining writes failed the fence check. The seal now requires the entry as read, as a new leader's take does, and a drain that loses that race looks again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish the drains a stopped balancer left behind A repartition saves the new topic.conf and then drains the old ranges. A balancer that stopped in between left them unsealed, and nothing came back to them: repair looks only at topic.conf, and retired reads, listing and retention skip unsealed ranges, so their records were out of reach. The balancer's periodic pass now also looks for range directories that topic.conf no longer names and whose fence is unsealed, and asks the broker holding the fence to drain the range, which flushes what it holds and seals it. A holder that does not answer is drained by the balancer itself, which seals the fence only once nobody has renewed it for fenceSealWait. Each topic's pass is bounded by generationPassTimeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish a predecessor's drains on taking the balancer lock The pass that finishes drains a stopped balancer left behind ran only with the retention loop, so after a balancer restart its old ranges could stay unsealed, and unreadable, for up to five minutes. A broker that finds itself the balancer now runs the pass once right away in the background, bounded per topic as the periodic one is, so the wait is down to the fenceSealWait rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: report a drain's error on the test goroutine Two drain tests ran the drain, which fails the test on error, in a goroutine of their own, where failing only ends that goroutine and leaves the test waiting or passing on what it saw. The drain's error now comes back over the channel the test already waits on, and the test fails there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's replaced ranges outside the topic.conf lock A repartition drained the replaced ranges while it still held topicConfLock, under the lock's 30-second deadline, and the drain now waits for each range's last flush and seal. A slow flush held every cache-miss read of topic.conf behind the lock, could run the shared deadline out and leave a range unsealed, and left the new ranges' assignment to a context that had already expired. The new ranges are now assigned under the lock, and the replaced ones drained after it is released, with a deadline of their own sized for a flush and a seal that may wait out fenceSealWait. A range the drain does not get to is finished by the balancer's pass over orphaned ranges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: move a retired read past offsets no stored entry holds A read of a retired range at an offset no stored entry holds, below the high-water mark, answered no records with the same next offset and no end of partition, so a consumer asked for that offset again forever. Such a stretch is a gap in the offsets or entries the log could not place. The read now looks for the lowest stored offset after it and reads from there, and when none is held up to the high-water mark it answers the end of the partition at the high-water mark. Below the log start the read is still out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: serve a client only the partition generation it names A partition is found by its range alone, so a fetch naming an older generation of a range the topic still assigns, not sealed and so not read as retired, was answered from the live partition of the newer generation: the client read records of a generation it never asked for, at offsets that mean something else there. A client that names a generation now gets only that one: one that is not the assigned generation, or not the one loaded, is refused with the partition not found a removed unsealed range gets. A client that names none still matches by range. A publisher refused this way looks the topic up again, as it does when the balancer is ahead of the cached topic.conf, and the unflushed-message query and the flush notification check the generation too. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: decide orphaned ranges under the topic.conf lock from the stored conf The pass that finishes unfinished drains took topic.conf from the cache and listed the stored ranges without the topic.conf lock. A balancer just elected with a stale cache, or a repartition saving its new generation between the read and the listing, made current ranges look orphaned, and they were drained and sealed. The pass now takes topicConfLock, reads topic.conf from the filer, lists the stored ranges and decides under it, then drains what it found once the lock is released; a repartition cannot assign a generation that is already gone, so the decision holds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: drain only the partition generation a drain names A drain found the loaded partition by its boundaries alone. A topic repartitioned 1 -> 2 -> 1 has its first range and its current one on the same boundaries, so finishing the first one's unfinished drain removed and sealed the current range instead. A drain naming a generation now takes a loaded partition only of that generation; otherwise it seals the named generation's stored fence, as for a range its leader has not loaded. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: leave an orphaned range's own drain time when its holder stalls Finishing an orphaned range's drain asks the broker holding its fence first and drains the range itself when that fails. The holder's call had the whole per-topic deadline, so a holder that took the call and never answered used it up, and the drain here then ran on an expired context and did nothing. The holder now gets half the time that is left, keeping the rest for the drain here. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: end an unflushed query a broker would redirect to itself A broker still holding an older generation of a range it now leads under a newer one refuses a query for the newer generation, looks the range up, finds itself as the leader, and redirected the query to itself, which did the same again until the caller gave up. When the lookup names this broker the query now ends with an error saying the generation is assigned here but not loaded; a lookup naming another broker is still followed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: refuse a loaded generation the topic no longer assigns After a split the old range stays loaded on its broker until the drain unloads and seals it. A fetch naming that generation passed the generation check, since no assignment shares its range any more, and was served from a buffer that is neither assigned nor sealed. A loaded partition is now served by generation only while topic.conf assigns it; the cache is reread once before refusing, so a broker whose cache predates the assignment that loaded the partition still serves it. Once the drain unloads and seals it, the retired reader serves it from its files. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq logstore: retry a parquet reader whose topic.conf read failed The parquet reader reads topic.conf once, when it is built, and a failed read left it a reader that finds nothing, for good. A merged offset read then skipped the compacted offsets to the first log file, and a sealed partition's reader, finding nothing stored, ended the partition at its high water mark. The reader is now set up on its first read and again on each read while topic.conf cannot be read, failing those reads; a topic.conf that does not exist still means no compacted rows. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a drained range from reloading until its seal lands A drain unlisted the range once its last flush landed, before sealing its fence. A publisher whose topic.conf cache still assigned the range to this broker could load it again in between, take the fence at the same epoch, and make the seal fail, leaving the range unsealed after the repartition. The drain now holds the range as retiring until its seal returns, so a loader waits and then finds the fence sealed. A failed seal releases it, unsealed and unassigned, for the orphan pass. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: seal a drained range only once all it accepted is stored A drain sealed the fence after the partition's last flush returned, without asking whether that flush stored anything. A flush abandoned when a broker stop ran out its flush budget drops the window and breaks the follow stream so the follower stores its copy, but the seal could land first, and the follower, finding the fence sealed, gave up records the leader had acknowledged. The drain now seals only when the flushed watermark reaches the last accepted offset; otherwise it leaves the fence to the follower and fails, and a later drain or the orphan pass finds it sealed by the follower or seals it once it is stale. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
559 lines
20 KiB
Go
559 lines
20 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.ReadFromDiskFn, logBuffer.diskChunkCache, 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
|
|
}
|
|
|
|
// diskChunkSize is the offsets one disk read caches together.
|
|
const diskChunkSize = 1000
|
|
|
|
// NewDiskChunkCache caches the chunks a reader of stored files reads.
|
|
func NewDiskChunkCache() *DiskChunkCache {
|
|
return &DiskChunkCache{chunks: make(map[int64]*CachedDiskChunk), maxChunks: 16}
|
|
}
|
|
|
|
// ReadFlushedMessagesAtOffset reads a partition that takes no more writes from
|
|
// its stored files alone, answering as ReadMessagesAtOffset does for a live one:
|
|
// out of range below logStartOffset, and the end of the partition at highWaterMark.
|
|
func ReadFlushedMessagesAtOffset(readFromDisk LogReadFromDiskFuncType, cache *DiskChunkCache, logStartOffset, highWaterMark, startOffset int64, maxMessages, maxBytes int) (messages []*filer_pb.LogEntry, nextOffset int64, endOfPartition bool, err error) {
|
|
if startOffset < logStartOffset {
|
|
return nil, startOffset, false, fmt.Errorf("offset %d is before the log start offset %d: %w", startOffset, logStartOffset, ErrOffsetOutOfRange)
|
|
}
|
|
if startOffset >= highWaterMark {
|
|
return nil, startOffset, true, nil
|
|
}
|
|
messages, nextOffset, err = readHistoricalDataFromDisk(readFromDisk, cache, startOffset, maxMessages, maxBytes, highWaterMark)
|
|
if err == nil && len(messages) == 0 {
|
|
// no stored entry holds startOffset or the rest of its chunk: a gap in the
|
|
// offsets, or entries the log could not place; read on from the next one held
|
|
var next int64
|
|
if next, err = nextStoredOffset(readFromDisk, startOffset); err == nil {
|
|
if next < 0 || next >= highWaterMark {
|
|
return nil, highWaterMark, true, nil
|
|
}
|
|
messages, nextOffset, err = readHistoricalDataFromDisk(readFromDisk, cache, next, maxMessages, maxBytes, highWaterMark)
|
|
nextOffset = max(nextOffset, next)
|
|
}
|
|
}
|
|
if err != nil {
|
|
return nil, startOffset, false, fmt.Errorf("disk read failed for offset %d: %w", startOffset, err)
|
|
}
|
|
return messages, nextOffset, nextOffset >= highWaterMark, nil
|
|
}
|
|
|
|
// nextStoredOffset is the lowest offset at or after from that a stored entry
|
|
// holds, among the first chunk's worth read, or -1 when none does.
|
|
func nextStoredOffset(readFromDisk LogReadFromDiskFuncType, from int64) (int64, error) {
|
|
next, seen := int64(-1), 0
|
|
_, _, err := readFromDisk(NewMessagePositionFromOffset(from), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
|
|
if logEntry.Offset < from {
|
|
return false, nil
|
|
}
|
|
if next < 0 || logEntry.Offset < next {
|
|
next = logEntry.Offset
|
|
}
|
|
seen++
|
|
// files whose names sort out of offset order deliver entries out of order
|
|
return seen >= diskChunkSize, nil
|
|
})
|
|
return next, err
|
|
}
|
|
|
|
// 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(
|
|
readFromDisk LogReadFromDiskFuncType,
|
|
cache *DiskChunkCache,
|
|
startOffset int64,
|
|
maxMessages int,
|
|
maxBytes int,
|
|
highWaterMark int64,
|
|
) (messages []*filer_pb.LogEntry, nextOffset int64, err error) {
|
|
const chunkSize = diskChunkSize
|
|
|
|
// Calculate chunk start offset (aligned to chunkSize boundary)
|
|
chunkStartOffset := (startOffset / chunkSize) * chunkSize
|
|
|
|
// Try to get from cache first
|
|
cachedMessages, cacheHit := getCachedDiskChunk(cache, 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
|
|
cache.mu.Lock()
|
|
delete(cache.chunks, chunkStartOffset)
|
|
cache.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 := readFromDisk(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(cache, 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(cache *DiskChunkCache, chunkStartOffset int64) ([]*filer_pb.LogEntry, bool) {
|
|
cache.mu.RLock()
|
|
defer cache.mu.RUnlock()
|
|
|
|
if chunk, exists := cache.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(cache *DiskChunkCache, startOffset, endOffset int64, messages []*filer_pb.LogEntry) {
|
|
cache.mu.Lock()
|
|
defer cache.mu.Unlock()
|
|
|
|
// Check if we need to evict old chunks (LRU policy)
|
|
if len(cache.chunks) >= cache.maxChunks {
|
|
// Find least recently used chunk
|
|
var oldestOffset int64
|
|
var oldestTime time.Time
|
|
first := true
|
|
|
|
for offset, chunk := range cache.chunks {
|
|
if first || chunk.lastAccess.Before(oldestTime) {
|
|
oldestOffset = offset
|
|
oldestTime = chunk.lastAccess
|
|
first = false
|
|
}
|
|
}
|
|
|
|
// Evict oldest chunk
|
|
delete(cache.chunks, oldestOffset)
|
|
glog.V(4).Infof("[DiskCache] Evicted chunk at offset %d (LRU)", oldestOffset)
|
|
}
|
|
|
|
// Store new chunk
|
|
cache.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
|
|
}
|
|
}
|