Files
seaweedfs/weed/mq/logstore/read_log_from_disk.go
T
Chris LuandClaude Opus 5.5 bc1b805c82 mq: copy a table-backed topic's sealed log data into its Iceberg table (#13256)
* mq: export logstore's log file offset range and control entry checks

The topic table writer decides what is sealed from a partition's file
offset ranges and drops the same control entries compaction drops, so it
calls these instead of keeping copies.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: tell which of a partition's files its leader will not write again

A topic table may only take what is sealed. The fence names a writer
and an epoch, not a file, and each flushed window lands whole as a new
file under it, so every log file but the one holding the highest offsets
is sealed; the newest may still be followed by a window in flight. A
sealed fence takes no more windows, so all of its files are. Parquet
left by mq.topic.compact rewrites earlier logs and is always sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a topic table's copied offsets in its snapshot summary

Each append records seaweedfs.mq.offsets, the first offset of every
partition not yet in the table. A snapshot that rewrote files without
carrying the map defers to its newest ancestor that has one; a table with
snapshots and no map anywhere holds rows of unknown offsets and is not
written to.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: build a topic table's rows from log entries

A message becomes a row of its table: the system columns from the log
entry, then the record's fields by name, or the whole message in _value
for a schemaless topic. Rows are laid out in the table's current schema
through iceberg-go's Arrow mapping, so the Parquet file they are written
as carries the table's field ids and the types Iceberg readers expect.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: compare topic tables by name in topictable

The table writer in the worker has to tell whether topic.conf still names
the table a job was proposed for, by bucket ARN, namespace and name, the
same way the broker compares a configure request with what is stored. The
comparison moves next to the rest of the topic table layout so both call
it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's offset map through maintenance snapshots

Compaction, delete rewrites and manifest rewrites keep a table's rows,
so the offsets a topic table holds are unchanged by them. Their
snapshots now carry the parent's seaweedfs.mq.offsets, so the topic
writer and readers find the map on the current snapshot rather than
only on an ancestor that snapshot expiry may remove.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: start a table's running totals at its first snapshot

Totals were only carried from a parent that recorded them, so a table
whose first snapshot the worker wrote never got total-records or
total-data-files, and no later snapshot could carry them. A snapshot
without a parent adds to an empty table, whose totals are zero.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's sealed log data into its Iceberg table

copyTopicTable reads each partition from the offset the table's current
snapshot records up to what its leader has sealed, through the merged
reader that already serves log files and compacted parquet, and writes
the rows as data files under data/<_partition>/ named by their offset
range. A file holds one partition value, so it never spans partitions or
days, and its rows are one contiguous offset run in offset order.

The append goes through commitWithRetry and records the advanced offset
map in seaweedfs.mq.offsets. Each attempt re-checks that topic.conf
still names the table and that the table still names the topic, and
re-reads the map: a partition another writer moved since this run
planned keeps that writer's offset, and this run's files for it are
removed, so no offset is appended twice. A run that dies before its
commit leaves only unreferenced files for orphan removal. Log files are
left in place; the broker cannot read the table yet.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: run mq_topic_table for topics that name an Iceberg table

The worker registers an mq_topic_table job beside iceberg_maintenance and
runs it in the Iceberg lane. Detection reads every topic.conf under
/topics; a topic naming a table is due once one of its partitions has
128 MiB sealed past the table's offsets or a sealed file 5 minutes old.
Execution takes the filer lock mq.table.<namespace>.<topic>, so one
writer copies a topic at a time, and copies only while topic.conf still
names the table the job was proposed for; a topic that left it ends the
job without failing it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy only into the table whose UUID topic.conf recorded

A table dropped and replaced at the topic's table name still carries
the name, and may carry the topic's property if its creator copied it.
The broker records the UUID of the table it created or adopted in
topic.conf, so the writer checks it before planning and again before
each commit attempt, and stops rather than append the topic's offsets
to a table that is not the one the topic holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep keyless and valueless messages in a topic table

The table becomes a topic's only copy once copied logs are deleted, and
the writer dropped what compaction drops: every message without a key
or without a value. Those are data; a Kafka record with a null key is
one. The only control entry the log holds is a publisher's close
marker, which the broker stores without its Ctrl, as an entry with
neither key nor value. IsControlMarker names exactly that, IsControlEntry
keeps its wider rule for compaction, and the writer skips markers only.

A keyless message gets a null _key. A skipped marker's offset stays
below the partition's offset in the map, so the table records it as an
offset that held no message rather than a gap left to fill.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: change a topic's table under its table writer's lock

A configure that left a table checked it for snapshots, then saved
topic.conf. The table writer checks topic.conf before each commit, so a
detach saved between that check and the commit's CAS left a table
holding the topic's data with no topic. The broker now takes the
writer's filer lock, mq.table.<namespace>.<topic>, before the release
check and keeps it through the topic.conf save, so it sees what the
writer committed, and the writer sees the change before committing.

The wait is bounded at 15 seconds: a configure behind a long copy is
Unavailable and retried rather than holding the configure RPC. The lock
key moves to topictable so the broker and the worker share it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: make a topic table's record columns optional

A field's is_required became a required column, so a message missing
that field could not be written and the table writer stopped at its
offset. Once copied logs are deleted the table is the topic's only copy,
so every message needs a row. Record fields now map to optional columns
at every level; the system columns stay required. Adopting a table still
refuses one whose record columns are required, since it could not take
such a message.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a message its topic's record type cannot hold in _value

A schematized topic's tombstone, or a value that is not a RecordValue
of its type, stopped the table writer at its offset, and once copied
logs are deleted the table is the only copy. Every topic table now has
an optional _value column. A message whose value is empty, does not
parse, carries bytes a RecordValue does not have, names a field the
table lacks, or holds a value its column cannot take gets null record
columns and its raw bytes in _value. A decoded message leaves _value
null. A row is checked whole before any column takes it, so a fallback
leaves no partial row behind.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's history into its table in bounded runs

A run read every sealed offset past the table's map and committed only at
the end, so a topic attached with a long history could not finish within
the job's one-hour timeout: each attempt rewrote the same files, removed
them on cancel, and the map never moved. A run now stops at a file boundary
once it has written 4 GiB and commits the offsets its files cover; the next
detection picks up the rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: decode a record read back from compacted parquet into its columns

logstore's parquet reader hands back a schematized row as its RecordValue,
which still holds the file's _ts_ns, _key and _offset columns. The row
writer took those for fields outside the table, so every message the copy
read from mq.topic.compact's parquet landed as raw _value with null record
columns. Those three fields are the entry's own and are now passed over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: map a repeated field already typed as a list to one list

The Kafka protobuf and JSON Schema decoders describe a repeated field with
both a ListType and IsRepeated, and their values are one ListValue deep.
mapField wrapped the list type again, so the column became list<list<T>>
and every message with a non-empty repeated field fell back to raw _value.
Avro gives the item type with IsRepeated, which still gets wrapped once.
MQ's own parquet schema already ignores IsRepeated on a list type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: keep a decimal past its column's precision in _value

rescaleDecimal checked only that the rescaled value fit 128 bits, so an
unscaled value from 10^38 up to 2^127 was written into the decimal(38,18)
column, which engines then read as an overflow or null. The value is now
checked against the column's precision, so such a message keeps its raw
bytes in _value like any other value the record type cannot hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: bound a published decimal before rescaling it

A DecimalValue's scale, precision and bytes come from the publisher,
and rescaling to the column built 10^|18-scale| before checking
anything, so one message with an extreme scale could hold a worker's
CPU and memory on every retry of the copy. A scale or precision beyond
the column's 38 digits, or a magnitude longer than 32 bytes, cannot fit
decimal(38, 18) and is refused before any arithmetic; the message keeps
its row with its bytes in _value like any other value its column cannot
take.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's files when its commit's outcome is unknown

A commit whose update of the table entry failed without an answer, a
reset connection or a deadline, may still have been applied by the
filer. The run then deleted its data files and manifests, and
commitWithRetry its new metadata file, leaving a committed snapshot
pointing at files that were gone.

Such a failure is now errCommitOutcomeUnknown, and commitWithRetry keeps
the metadata file for it. The topic table writer reads the table again:
a snapshot it built that is in the current lineage is a commit, kept and
reported as one. Otherwise, or when the table cannot be read, the files
stay for orphan removal, since an update still in flight could land
after the read. Only a refused commit, a conflict or a stopped run,
deletes them.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: count a partition's rows after its last flush

copyPartition returned total and flush() in one statement, and Go does
not order reading total against calling flush, so the rows of the last
file could be left out of the count. The last flush now runs first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: report the rows a topic table commit kept

A run's rows_written was every row it staged, though a commit attempt
drops the files of a partition another writer already moved, and a run
that commits nothing reported its staged rows all the same. It is now
the record count of the files the committed snapshot added.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: wait for a topic's table writer outside topicConfLock

A configure that moved a topic off its table waited up to 15 seconds
for the table writer's lock while holding topicConfLock, which every
configure, lookup cache miss and rebalance of every topic takes, and a
caller that gave up kept waiting.

The configure now reads topic.conf first and, when the request moves
the topic off the table it names, takes the writer's lock before
topicConfLock, the order the writer keeps since it never takes
topicConfLock. The wait ends when the caller's context does, and a grant
that arrives after that is released. A configure that finds the table
changed under topicConfLock without holding the writer's lock is
Unavailable and retried.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound the topic.conf read a table change starts with

The read that decides whether a configure must wait for the table
writer runs before topicConfLock, and so before the 30 second bound
lockTopicConf puts on calls made under it. A caller without a deadline
then hung on a filer that took the read and never answered. The read
now gets the same bound of its own, still outside topicConfLock.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep what an unanswered maintenance commit may reference

Compaction, delete rewrite and manifest rewrite delete everything they
wrote when their commit fails. When the failure is an update of the
table entry that went unanswered, the filer may have applied it, and
the table then points at data files, manifests and a manifest list that
were just deleted. Those are now left for orphan removal on
errCommitOutcomeUnknown, as the topic table writer already does;
conflicts and other definite failures still clean up. Snapshot expiry
deletes nothing before its commit succeeds and needed no change.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: test a topic table retry that keeps only one partition's files

A run whose commit loses to a writer that copied only one of its
partitions keeps the other partition's file. The test checks that the
retry reports only that file's rows and that each offset lands once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: wait for the detach's refused lock request in the table lock test

A fixed sleep did not show the detach had reached the table lock, so a
late goroutine let the lookup pass with nothing waiting. The fake filer
now counts refused lock requests and the test waits for the first one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: check the table writer's lock before saving a table change

A configure that moves a topic off its table holds the writer's lock
from its release check through the topic.conf save, but never looked at
it again. A lease that lapsed meanwhile, its renewals failing, may
already be the writer's, which can then commit to the table the
configure is about to detach. The configure now checks that it still
holds the lock right before the save and is Unavailable otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic table copy's lock and topic last before committing

Each commit attempt checked the lock, topic.conf and the table's owner
before writing its manifests and manifest list, and nothing after, so a
lease that lapsed or a detach that landed while they were written went
unnoticed. The attempt now checks again once they are written, the last
step before commitWithRetry saves the metadata file and updates the
table pointer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: read a topic's conf with the topic table job's context

The table writer and detection read topic.conf with ReadConfFile, which
takes no context, so a filer that took the read and never answered held
the job, its worker slot and its renewed table lock, and held up
detection, past any cancel. They now read through
ReadConfFileWithMetadata with the job's or the detection's context, so
a cancelled job ends and lets its lock go.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:29:34 -08:00

509 lines
18 KiB
Go

package logstore
import (
"cmp"
"context"
"encoding/binary"
"fmt"
"math"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/protobuf/proto"
)
// logFileIndexStride is how many log files one logFileIndex mark stands for.
const logFileIndexStride = 64
// logFileIndex marks every logFileIndexStride-th log file name of a partition, so a
// read can list from near its position instead of from the first file.
type logFileIndex struct {
sync.Mutex
marks []logFileMark
lastName string
unmarked int
// maxOffset is the highest offset recorded so far; a later name starting below it
// makes the partition unordered, as files written under clock skew can be
maxOffset int64
unordered bool
// lastTsNs bounds the messages of every file added; while open, the last file added
// records no last message time and is bounded only once the next file is seen
lastTsNs int64
open bool
}
type logFileMark struct {
name string
minOffset int64
hasOffsets bool
// earlierTsNs bounds the messages of every file sorting before this one
earlierTsNs int64
}
// add records log files in listing order, as listed from a mark or from the start.
func (x *logFileIndex) add(entries []*filer_pb.Entry) {
x.Lock()
defer x.Unlock()
for _, entry := range entries {
if entry.Name <= x.lastName {
continue
}
minOffset, maxOffset, hasOffsets := LogFileOffsets(entry)
if hasOffsets {
x.unordered = x.unordered || minOffset < x.maxOffset
x.maxOffset = max(x.maxOffset, maxOffset)
}
if x.open {
// a file without its last message time was named by its first and ended before the
// next file began, which only a next name not moved later than its messages tells
nameEndTsNs := int64(math.MaxInt64)
if nameTime, err := topic.ParseLogFileTime(entry.Name); err == nil {
if firstTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMin); !ok || firstTsNs >= nameTime.UnixNano() {
nameEndTsNs = nameTime.Add(time.Second).UnixNano() - 1
}
}
x.lastTsNs, x.open = max(x.lastTsNs, nameEndTsNs), false
}
if len(x.marks) == 0 || x.unmarked >= logFileIndexStride-1 {
x.marks = append(x.marks, logFileMark{name: entry.Name, minOffset: minOffset, hasOffsets: hasOffsets, earlierTsNs: x.lastTsNs})
x.unmarked = 0
} else {
x.unmarked++
}
if lastTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMax); ok {
x.lastTsNs = max(x.lastTsNs, lastTsNs)
} else {
x.open = true
}
x.lastName = entry.Name
}
}
// markBefore is the last mark before which every file ends before tsNs, or "" for the
// start, so a listing from it skips nothing at or after tsNs whatever the names say.
func (x *logFileIndex) markBefore(tsNs int64) string {
x.Lock()
defer x.Unlock()
if i := sort.Search(len(x.marks), func(i int) bool { return x.marks[i].earlierTsNs >= tsNs }); i > 0 {
return x.marks[i-1].name
}
return ""
}
// markAtOffset is the last marked file starting at or before offset, or "" for the start.
// Where offsets grow with names, no earlier file can hold offset, including one with no
// offset range; an unordered partition is always read from the start.
func (x *logFileIndex) markAtOffset(offset int64) string {
x.Lock()
defer x.Unlock()
if x.unordered {
return ""
}
for i := len(x.marks) - 1; i >= 0; i-- {
if m := x.marks[i]; m.hasOffsets && m.minOffset <= offset {
return m.name
}
}
return ""
}
// LogFileOffsets is the offset range a log file records, if it records one.
func LogFileOffsets(entry *filer_pb.Entry) (minOffset, maxOffset int64, ok bool) {
minBytes, maxBytes := entry.Extended[mq.ExtendedAttrOffsetMin], entry.Extended[mq.ExtendedAttrOffsetMax]
if len(minBytes) != 8 || len(maxBytes) != 8 {
return 0, 0, false
}
return int64(binary.BigEndian.Uint64(minBytes)), int64(binary.BigEndian.Uint64(maxBytes)), true
}
// logFileStartsAfter reports whether a log file's first message is after stopTime. A name
// can be later than that message; files recording no first message time were named by it.
func logFileStartsAfter(entry *filer_pb.Entry, stopTime time.Time) bool {
if firstTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMin); ok {
return firstTsNs > stopTime.UnixNano()
}
return topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT)
}
// sortByOffset orders the files recording an offset range by their first offset within
// the places they hold, so files without a range stay where they are. Names follow
// offsets except where files were written under clock skew.
func sortByOffset(files []*filer_pb.Entry) {
var places []int
var ranged []*filer_pb.Entry
for i, file := range files {
if _, _, ok := LogFileOffsets(file); ok {
places = append(places, i)
ranged = append(ranged, file)
}
}
slices.SortStableFunc(ranged, func(a, b *filer_pb.Entry) int {
aMin, _, _ := LogFileOffsets(a)
bMin, _, _ := LogFileOffsets(b)
return cmp.Compare(aMin, bMin)
})
for i, place := range places {
files[place] = ranged[i]
}
}
// logFileTsNs is the message time a log file records under key, if it records one.
func logFileTsNs(entry *filer_pb.Entry, key string) (int64, bool) {
if b := entry.Extended[key]; len(b) == 8 {
return int64(binary.BigEndian.Uint64(b)), true
}
return 0, false
}
// logReader lists the log files a read needs before reading them, so a merged read
// knows which offsets the log files hold before anything is delivered.
type logReader struct {
list func(startPosition log_buffer.MessagePosition, stopTsNs int64) ([]*filer_pb.Entry, error)
read func(candidateFiles []*filer_pb.Entry, startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error)
}
func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) log_buffer.LogReadFromDiskFuncType {
logs := newLogReader(filerClient, t, p)
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
candidateFiles, err := logs.list(startPosition, stopTsNs)
if err != nil {
return log_buffer.MessagePosition{}, false, err
}
return logs.read(candidateFiles, startPosition, stopTsNs, eachLogEntryFn)
}
}
func newLogReader(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) logReader {
partitionDir := topic.PartitionDir(t, p)
index := &logFileIndex{}
// Create a small cache for recently-read file chunks (3 files, 60s TTL)
// This significantly reduces Filer load when multiple consumers are catching up
fileCache := log_buffer.NewDiskBufferCache(3, 60*time.Second)
lookupFileIdFn := filer.LookupFn(filerClient)
eachChunkFn := func(buf []byte, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, isDone bool, err error) {
entriesSkipped := 0
entriesProcessed := 0
for pos := 0; pos+4 < len(buf); {
size := util.BytesToUint32(buf[pos : pos+4])
if pos+4+int(size) > len(buf) {
err = fmt.Errorf("GenLogOnDiskReadFunc: read [%d,%d) from [0,%d)", pos, pos+int(size)+4, len(buf))
return
}
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
pos += 4 + int(size)
err = fmt.Errorf("unexpected unmarshal mq_pb.Message: %w", err)
return
}
// Filter by offset if this is an offset-based subscription
if isOffsetBased {
if logEntry.Offset < startOffset {
entriesSkipped++
pos += 4 + int(size)
continue
}
} else {
// Filter by timestamp for timestamp-based subscriptions
if logEntry.TsNs <= starTsNs {
pos += 4 + int(size)
continue
}
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
return
}
}
// fmt.Printf(" read logEntry: %v, ts %v\n", string(logEntry.Key), time.Unix(0, logEntry.TsNs).UTC())
if isDone, err = eachLogEntryFn(logEntry); err != nil {
err = fmt.Errorf("process log entry %v: %w", logEntry, err)
return
}
processedTsNs = logEntry.TsNs
entriesProcessed++
if isDone {
return
}
pos += 4 + int(size)
}
return
}
eachFileFn := func(entry *filer_pb.Entry, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, isDone bool, err error) {
if len(entry.Content) > 0 {
// skip .offset files
return
}
var urlStrings []string
for _, chunk := range entry.Chunks {
if chunk.Size == 0 {
continue
}
if chunk.IsChunkManifest {
glog.Warningf("this should not happen. unexpected chunk manifest in %s/%s", partitionDir, entry.Name)
return
}
urlStrings, err = lookupFileIdFn(context.Background(), chunk.FileId)
if err != nil {
glog.V(1).Infof("lookup %s failed: %v", chunk.FileId, err)
err = fmt.Errorf("lookup %s: %v", chunk.FileId, err)
return
}
if len(urlStrings) == 0 {
glog.V(1).Infof("no url found for %s", chunk.FileId)
err = fmt.Errorf("no url found for %s", chunk.FileId)
return
}
glog.V(2).Infof("lookup %s returned %d URLs", chunk.FileId, len(urlStrings))
// Try to get data from cache first
cacheKey := fmt.Sprintf("%s/%s/%d/%s", t.Name, p.String(), p.RangeStart, chunk.FileId)
if cachedData, _, found := fileCache.Get(cacheKey); found {
if cachedData == nil {
// Negative cache hit - data doesn't exist
continue
}
// Positive cache hit - data exists
var chunkTsNs int64
chunkTsNs, isDone, err = eachChunkFn(cachedData, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
processedTsNs = max(processedTsNs, chunkTsNs)
if err != nil {
glog.V(1).Infof("eachChunkFn failed on cached data: %v", err)
return
}
if isDone {
return
}
continue
}
// Cache miss - try one of the urlString until util.Get(urlString) succeeds
var processed bool
for _, urlString := range urlStrings {
// TODO optimization opportunity: reuse the buffer
var data []byte
glog.V(2).Infof("trying to fetch data from %s", urlString)
if data, _, err = util_http.Get(urlString); err == nil {
glog.V(2).Infof("successfully fetched %d bytes from %s", len(data), urlString)
processed = true
// Store in cache for future reads
fileCache.Put(cacheKey, data, startOffset)
var chunkTsNs int64
chunkTsNs, isDone, err = eachChunkFn(data, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
processedTsNs = max(processedTsNs, chunkTsNs)
if err != nil {
glog.V(1).Infof("eachChunkFn failed: %v", err)
return
}
if isDone {
return
}
break
} else {
glog.V(2).Infof("failed to fetch from %s: %v", urlString, err)
}
}
if !processed {
// Store negative cache entry - data doesn't exist or all URLs failed
fileCache.Put(cacheKey, nil, startOffset)
glog.V(1).Infof("no data processed for %s %s - all URLs failed", entry.Name, chunk.FileId)
err = fmt.Errorf("no data processed for %s %s", entry.Name, chunk.FileId)
return
}
}
return
}
list := func(startPosition log_buffer.MessagePosition, stopTsNs int64) (candidateFiles []*filer_pb.Entry, err error) {
resumeFileName := startPosition.Time.UTC().Format(topic.TIME_FORMAT)
startTsNs := startPosition.Time.UnixNano()
startFileName := index.markBefore(startTsNs)
stopTime := time.Unix(0, stopTsNs)
// Check if this is an offset-based subscription
isOffsetBased := startPosition.IsOffsetBased
var startOffset int64
if isOffsetBased {
startOffset = startPosition.Offset
startFileName = index.markAtOffset(startOffset)
glog.V(1).Infof("disk read start: topic=%s partition=%s startOffset=%d",
t.Name, p, startOffset)
}
// For offset-based reads, skip files whose offset range ends before the offset
var foundStartFile bool
var listed []*filer_pb.Entry
var beforeResume *filer_pb.Entry
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// First pass: collect all relevant files with their metadata
glog.V(2).Infof("listing directory %s for offset %d startFileName=%q", partitionDir, startOffset, startFileName)
return filer_pb.SeaweedList(context.Background(), client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if entry.IsDirectory || entry.Name == topic.PartitionFenceName {
return nil
}
if strings.HasSuffix(entry.Name, ".parquet") {
return nil
}
if strings.HasSuffix(entry.Name, ".offset") {
return nil
}
listed = append(listed, entry)
if stopTsNs != 0 && logFileStartsAfter(entry, stopTime) {
return nil
}
// OPTIMIZATION: For offset-based reads, check if this file contains the requested offset
if isOffsetBased {
glog.V(3).Infof("found file %s", entry.Name)
// Check if file has offset range metadata
if fileMinOffset, fileMaxOffset, ok := LogFileOffsets(entry); ok {
// Skip files that don't contain our offset range
if startOffset > fileMaxOffset {
return nil
}
// If we haven't found the start file yet, check if this file contains it
if !foundStartFile && startOffset >= fileMinOffset && startOffset <= fileMaxOffset {
foundStartFile = true
}
}
// If file doesn't have offset metadata, include it (might be old format)
} else if entry.Name < resumeFileName {
lastTsNs, recorded := logFileTsNs(entry, mq.ExtendedAttrTimestampMax)
if !recorded {
// such a file is named by its first message, so of these only the last can still hold the resume point
beforeResume = entry
return nil
}
// a name moved later bounds nothing, so its file's own last message decides
if lastTsNs < startTsNs {
return nil
}
}
if beforeResume != nil {
candidateFiles = append(candidateFiles, beforeResume)
beforeResume = nil
}
// Add file to candidates for processing
candidateFiles = append(candidateFiles, entry)
glog.V(3).Infof("added candidate file %s (total=%d)", entry.Name, len(candidateFiles))
return nil
}, startFileName, true, math.MaxInt32)
})
if err != nil {
glog.Errorf("failed to list directory %s: %v", partitionDir, err)
return
}
if beforeResume != nil {
candidateFiles = append(candidateFiles, beforeResume)
}
index.add(listed)
if isOffsetBased {
sortByOffset(candidateFiles)
}
glog.V(2).Infof("found %d candidate files for topic=%s partition=%s offset=%d",
len(candidateFiles), t.Name, p, startOffset)
return candidateFiles, nil
}
read := func(candidateFiles []*filer_pb.Entry, startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
startTsNs := startPosition.Time.UnixNano()
isOffsetBased := startPosition.IsOffsetBased
var startOffset int64
if isOffsetBased {
startOffset = startPosition.Offset
}
var processedTsNs int64
if len(candidateFiles) == 0 {
glog.V(2).Infof("no files found in %s", partitionDir)
return startPosition, isDone, nil
}
// Second pass: process the filtered files
// CRITICAL: For offset-based reads, process ALL candidate files in one call
// This prevents multiple ReadFromDiskFn calls with 1.127s overhead each
var filesProcessed int
var lastProcessedOffset int64
var lastDeliveredOffset, lastDeliveredTsNs int64
deliver := func(logEntry *filer_pb.LogEntry) (bool, error) {
lastDeliveredOffset, lastDeliveredTsNs = logEntry.Offset, logEntry.TsNs
return eachLogEntryFn(logEntry)
}
for _, entry := range candidateFiles {
var fileTsNs int64
if fileTsNs, isDone, err = eachFileFn(entry, deliver, startTsNs, stopTsNs, startOffset, isOffsetBased); err != nil {
return lastReadPosition, isDone, err
}
if fileTsNs > 0 {
// files sort by name, which a slow leader's window can hold out of time order
processedTsNs = max(processedTsNs, fileTsNs)
filesProcessed++
}
if isDone {
if isOffsetBased {
return log_buffer.NewMessagePositionFromOffset(lastDeliveredOffset + 1), true, nil
}
return log_buffer.NewMessagePosition(lastDeliveredTsNs, -2), true, nil
}
// For offset-based reads, track the last processed offset
// We need to continue reading ALL files to avoid multiple disk read calls
if isOffsetBased {
// Extract the last offset from the file's extended attributes
if _, fileMaxOffset, ok := LogFileOffsets(entry); ok && fileMaxOffset > lastProcessedOffset {
lastProcessedOffset = fileMaxOffset
}
}
}
if isOffsetBased && filesProcessed > 0 {
// Return a position that indicates we've read all disk data up to lastProcessedOffset
// This prevents the subscription from calling ReadFromDiskFn again for these offsets
lastReadPosition = log_buffer.NewMessagePositionFromOffset(lastProcessedOffset + 1)
} else {
// CRITICAL FIX: If no files were processed (e.g., all data already consumed),
// return the requested offset to prevent busy loop
if isOffsetBased {
// For offset-based reads with no data, return the requested offset
// This signals "I've checked, there's no data at this offset, move forward"
lastReadPosition = log_buffer.NewMessagePositionFromOffset(startOffset)
} else {
// For timestamp-based reads, return error (-2)
lastReadPosition = log_buffer.NewMessagePosition(processedTsNs, -2)
}
}
return
}
return logReader{list: list, read: read}
}