package kgo import ( "context" "errors" "fmt" "maps" "math" "slices" "sort" "strings" "sync" "sync/atomic" "time" "github.com/twmb/franz-go/pkg/kerr" "github.com/twmb/franz-go/pkg/kgo/internal/xsync" "github.com/twmb/franz-go/pkg/kmsg" ) // Offset is a message offset in a partition. type Offset struct { at int64 relative int64 epoch int32 currentEpoch int32 // set by us when mapping offsets to brokers noReset bool afterMilli bool lookback time.Duration // for atLookback and atRewind } // Random negatives, only significant within this package. const ( atCommitted = -999 atRewind = -998 // RewindOffset: d before the last consumed record atLookback = -997 // LookbackOffset: d before the newest record ) // MarshalJSON implements json.Marshaler. func (o Offset) MarshalJSON() ([]byte, error) { if o.at == atRewind || o.at == atLookback { return fmt.Appendf(nil, `{"At":%d,"Lookback":"%s","Epoch":%d,"CurrentEpoch":%d}`, o.at, o.lookback, o.epoch, o.currentEpoch), nil } if o.relative == 0 { return fmt.Appendf(nil, `{"At":%d,"Epoch":%d,"CurrentEpoch":%d}`, o.at, o.epoch, o.currentEpoch), nil } return fmt.Appendf(nil, `{"At":%d,"Relative":%d,"Epoch":%d,"CurrentEpoch":%d}`, o.at, o.relative, o.epoch, o.currentEpoch), nil } // String returns the offset as a string; the purpose of this is for logs. func (o Offset) String() string { if o.at == atRewind || o.at == atLookback { return fmt.Sprintf("{%d lookback %s e%d ce%d}", o.at, o.lookback, o.epoch, o.currentEpoch) } if o.relative == 0 { return fmt.Sprintf("{%d e%d ce%d}", o.at, o.epoch, o.currentEpoch) } else if o.relative > 0 { return fmt.Sprintf("{%d+%d e%d ce%d}", o.at, o.relative, o.epoch, o.currentEpoch) } return fmt.Sprintf("{%d-%d e%d ce%d}", o.at, -o.relative, o.epoch, o.currentEpoch) } // EpochOffset returns this offset as an EpochOffset, allowing visibility into // what this offset actually currently is. func (o Offset) EpochOffset() EpochOffset { return EpochOffset{ Epoch: o.epoch, Offset: o.at, } } // NewOffset creates and returns an offset to use in [ConsumePartitions] or // [ConsumeResetOffset]. // // The default offset begins at the end. func NewOffset() Offset { return Offset{ at: -1, epoch: -1, } } // NoResetOffset returns an offset that can be used as a "none" option for the // [ConsumeResetOffset] option. By default, NoResetOffset starts consuming from // the beginning of partitions (similar to NewOffset().AtStart()). This can be // changed with AtEnd, Relative, etc. // // Using this offset will make it such that if OffsetOutOfRange is ever // encountered while consuming, rather than trying to recover, the client will // return the error to the user and enter a fatal state (for the affected // partition). func NoResetOffset() Offset { return Offset{ at: -1, epoch: -1, noReset: true, } } // AfterMilli returns an offset that consumes from the first offset after a // given timestamp. This option is *not* compatible with any At options (nor // Relative nor WithEpoch); using any of those will clear the special // millisecond state. // // This option can be used to consume at the end of existing partitions, but at // the start of any new partitions that are created later: // // AfterMilli(time.Now().UnixMilli()) // // By default when using this offset, if consuming encounters an // OffsetOutOfRange error, consuming will reset to the first offset after this // timestamp. You can use NoResetOffset().AfterMilli(...) to instead switch the // client to a fatal state (for the affected partition). func (o Offset) AfterMilli(millisec int64) Offset { o.at = millisec o.relative = 0 o.epoch = -1 o.afterMilli = true return o } // LookbackOffset returns an offset that begins a duration before the newest // record in a partition: the first record stamped at or after that record's // timestamp minus d. This is Kafka's auto.offset.reset "by_duration". // // The newest record's timestamp comes from ListOffsets v7, Kafka 3.0 // (KIP-734). On brokers without it, the client uses the current time minus d // instead. // // As a reset offset, this keeps the last d of a partition after data loss. A // negative duration is treated as zero. Relative and WithEpoch have no effect // on this offset. func LookbackOffset(d time.Duration) Offset { return Offset{at: atLookback, epoch: -1, afterMilli: true, lookback: max(d, 0)} } // RewindOffset returns an offset that resumes a duration before the last // record the client consumed. It is only valid as a [ConsumeResetOffset]; see // that option. A negative duration is treated as zero. Relative and WithEpoch // have no effect on this offset. func RewindOffset(d time.Duration) Offset { return Offset{at: atRewind, epoch: -1, afterMilli: true, lookback: max(d, 0)} } // AtStart copies 'o' and returns an offset starting at the beginning of a // partition. func (o Offset) AtStart() Offset { o.afterMilli = false o.at = -2 return o } // AtEnd copies 'o' and returns an offset starting at the end of a partition. // If you want to consume at the end of the topic as it exists right now, but // at the beginning of new partitions as they are added to the topic later, // check out AfterMilli. func (o Offset) AtEnd() Offset { o.afterMilli = false o.at = -1 return o } // AtCommitted copies 'o' and returns an offset that is used *only if* // there is an existing commit. This is only useful for group consumers. // If a partition being consumed does not have a commit, the partition will // enter a fatal state and return an error from PollFetches. // // Using this function automatically opts into [NoResetOffset]. func (o Offset) AtCommitted() Offset { o.noReset = true o.afterMilli = false o.at = atCommitted return o } // Relative copies 'o' and returns an offset that starts 'n' relative to what // 'o' currently is. If 'o' is at the end (from [AtEnd]), Relative(-100) will // begin 100 before the end. func (o Offset) Relative(n int64) Offset { o.afterMilli = false o.relative = n return o } // WithEpoch copies 'o' and returns an offset with the given epoch. This epoch // is used for truncation detection; the default of -1 implies no truncation // detection. func (o Offset) WithEpoch(e int32) Offset { o.afterMilli = false if e < 0 { e = -1 } o.epoch = e return o } // At returns a copy of the calling offset, changing the returned offset to // begin at exactly the requested offset. // // There are two potential special offsets to use: -2 allows for consuming at // the start, and -1 allows for consuming at the end. These two offsets are // equivalent to calling AtStart or AtEnd. // // If the offset is less than -2, the client bounds it to -2 to consume at the // start. func (o Offset) At(at int64) Offset { o.afterMilli = false if at < -2 { at = -2 } o.at = at return o } // listMilli returns the timestamp a reset by this offset lists by, given the // millisecond of the last record consumed. Only a by-time offset lists at all. func (o Offset) listMilli(lastConsumedMilli int64) int64 { if o.at == atRewind { return lookbackMilli(lastConsumedMilli, o.lookback) } return max(o.at, 1) } func lookbackMilli(milli int64, d time.Duration) int64 { back := d.Milliseconds() if milli-back > milli { // avoid wraparound on massive durations return 1 } return max(milli-back, 1) // never a reserved timestamp (-1 end, -2 start) } type consumer struct { bufferedRecords atomic.Int64 bufferedBytes atomic.Int64 cl *Client pausedMu xsync.Mutex // grabbed when updating paused paused atomic.Value // loaded when issuing fetches // mu is grabbed when // - polling fetches, for quickly draining sources / updating group uncommitted // - calling assignPartitions (group / direct updates) mu xsync.Mutex d *directConsumer // if non-nil, we are consuming partitions directly g *groupConsumer // if non-nil, we are consuming as a group member s *shareConsumer // if non-nil, we are consuming as a share group member // On metadata update, if the consumer is set (direct or group), the // client begins a goroutine that updates the consumer kind's // assignments. // // This is done in a goroutine to not block the metadata loop, because // the update **could** wait on a group consumer leaving if a // concurrent LeaveGroup is called, or if restarting a session takes // just a little bit of time. // // The update realistically should be instantaneous, but if it is slow, // some metadata updates could pile up. We loop with our atomic work // loop, which collapses repeated updates into one extra update, so we // loop as little as necessary. outstandingMetadataUpdates workLoop // pollActive / pollWake implement strict-pull gating when // MaxConcurrentFetches == 0. See manageFetchConcurrency for the full // description of the protocol; this pair is the input side. pollActive atomic.Bool pollWake chan struct{} // buffered(1); nil when maxConcurrentFetches != 0 // sessionChangeMu is grabbed when a session is stopped and held through // when a session can be started again. The sole purpose is to block an // assignment change running concurrently with a metadata update. sessionChangeMu xsync.Mutex session atomic.Value // *consumerSession kill atomic.Bool // leaving is set by the first LeaveGroupContext, which starts the // leave with its context. Later calls, including Close's, only wait. leaving atomic.Bool usingCursors usedCursors sourcesReadyMu xsync.Mutex sourcesReadyCond *sync.Cond sourcesReadyForDraining []*source fakeReadyForDraining []Fetch // deferredFetchHooks collects unbuffered fetch-record hook // dispatches captured while c.mu/sourcesReadyMu are held (see // source.hookDeferUnbuffered for the deadlock walkthrough). Guarded // by sourcesReadyMu. Pollers drain it synchronously after their fill // critical section releases the locks; stopSession's discard path // drains it asynchronously because its callers still hold c.mu. deferredFetchHooks []func() pollWaitMu xsync.Mutex pollWaitC *sync.Cond pollWaitState uint64 // 0 == nothing, low 32 bits: # pollers, high 32: # waiting rebalances } func (c *consumer) loadPaused() pausedTopics { return c.paused.Load().(pausedTopics) } func (c *consumer) clonePaused() pausedTopics { return c.paused.Load().(pausedTopics).clone() } func (c *consumer) storePaused(p pausedTopics) { c.paused.Store(p) } func (c *consumer) waitAndAddPoller() { if !c.cl.cfg.blockRebalanceOnPoll { return } c.pollWaitMu.Lock() defer c.pollWaitMu.Unlock() if c.pollWaitState&math.MaxUint32 == 0 { for c.pollWaitState>>32 != 0 { c.pollWaitC.Wait() } } // Rebalance always takes priority, but if there are no active // rebalances, our poll blocks rebalances. c.pollWaitState++ } func (c *consumer) unaddPoller() { if !c.cl.cfg.blockRebalanceOnPoll { return } c.pollWaitMu.Lock() defer c.pollWaitMu.Unlock() // AllowRebalance zeroes the poller count outright. If the user calls it // while another goroutine's poll is still in flight (a contract // violation: AllowRebalance means "all pollers are done"), that poll's // release lands here after the mask and must not decrement: the low 32 // bits would underflow and borrow into the rebalance count, permanently // blocking both polls and rebalances. A poller whose accounting was // force-cleared simply no-ops its release. if c.pollWaitState&math.MaxUint32 > 0 { c.pollWaitState-- } c.pollWaitC.Broadcast() } func (c *consumer) allowRebalance() { if !c.cl.cfg.blockRebalanceOnPoll { return } c.pollWaitMu.Lock() defer c.pollWaitMu.Unlock() // When allowing rebalances, the user is explicitly saying all pollers // are done. We mask them out. c.pollWaitState &= math.MaxUint32 << 32 c.pollWaitC.Broadcast() } func (c *consumer) waitAndAddRebalance() { c.waitAndAddRebalanceMaybeSignal(true) } // waitAndAddRebalanceSilent is waitAndAddRebalance without the // OnPartitionsCallbackBlocked signal. Used by LeaveGroup: the gate guards // assignPartitions invalidation rather than a user callback, so signaling // "your callback is blocked" would be misleading. func (c *consumer) waitAndAddRebalanceSilent() { c.waitAndAddRebalanceMaybeSignal(false) } func (c *consumer) waitAndAddRebalanceMaybeSignal(signal bool) { if !c.cl.cfg.blockRebalanceOnPoll { return } var blockedCalled bool c.pollWaitMu.Lock() defer c.pollWaitMu.Unlock() c.pollWaitState += 1 << 32 for c.pollWaitState&math.MaxUint32 != 0 { if signal && !blockedCalled { if c.cl.cfg.onBlocked != nil { go c.cl.cfg.onBlocked(c.cl.ctx, c.cl) } blockedCalled = true } c.pollWaitC.Wait() } } func (c *consumer) unaddRebalance() { if !c.cl.cfg.blockRebalanceOnPoll { return } c.pollWaitMu.Lock() defer c.pollWaitMu.Unlock() c.pollWaitState -= 1 << 32 c.pollWaitC.Broadcast() } // BufferedFetchRecords returns the number of records currently buffered from // fetching within the client. // // This can be used as a gauge to determine how behind your application is for // processing records the client has fetched. Note that it is perfectly normal // to see a spike of buffered records, which would correspond to a fetch // response being processed just before a call to this function. It is only // problematic if for you if this function is consistently returning large // values. func (cl *Client) BufferedFetchRecords() int64 { return cl.consumer.bufferedRecords.Load() } // BufferedFetchBytes returns the number of bytes currently buffered from // fetching within the client. This is the sum of all keys, values, and header // keys/values. See the related [BufferedFetchRecords] for more information. func (cl *Client) BufferedFetchBytes() int64 { return cl.consumer.bufferedBytes.Load() } type usedCursors map[*cursor]struct{} func (u *usedCursors) use(c *cursor) { if *u == nil { *u = make(map[*cursor]struct{}) } (*u)[c] = struct{}{} } func (c *consumer) init(cl *Client) { c.cl = cl c.paused.Store(make(pausedTopics)) c.sourcesReadyCond = sync.NewCond(&c.sourcesReadyMu) c.pollWaitC = sync.NewCond(&c.pollWaitMu) if cl.cfg.maxConcurrentFetches == 0 { c.pollWake = make(chan struct{}, 1) } if len(cl.cfg.topics) > 0 || len(cl.cfg.partitions) > 0 { defer cl.triggerUpdateMetadataNow("querying metadata for consumer initialization") // we definitely want to trigger a metadata update } if len(cl.cfg.shareGroup) > 0 { c.initShare() } else if len(cl.cfg.group) == 0 { c.initDirect() } else { c.initGroup() } } func (c *consumer) consuming() bool { return c.g != nil || c.d != nil || c.s != nil } // runDeferredFetchHooks dispatches unbuffered fetch-record hooks that were // captured under the consumer locks. Called by pollers with no locks held, // after their fill critical section; each queued dispatch runs exactly once // (the swap under sourcesReadyMu is the ownership handoff). A concurrent // poller or invalidation may have queued more dispatches since ours were // captured; running them here too is fine -- ordering across concurrent // pollers is inherently unordered. func (c *consumer) runDeferredFetchHooks() { c.sourcesReadyMu.Lock() fns := c.deferredFetchHooks c.deferredFetchHooks = nil c.sourcesReadyMu.Unlock() for _, fn := range fns { fn() } } // addSourceReadyForDraining tracks that a source needs its buffered fetch // consumed. func (c *consumer) addSourceReadyForDraining(source *source) { c.sourcesReadyMu.Lock() c.sourcesReadyForDraining = append(c.sourcesReadyForDraining, source) c.sourcesReadyMu.Unlock() c.sourcesReadyCond.Broadcast() } // addFakeReadyForDraining saves a fake fetch that has important partition // errors--data loss or auth failures. func (c *consumer) addFakeReadyForDraining(topic string, partition int32, err error, why string) { c.cl.cfg.logger.Log(LogLevelInfo, "injecting fake fetch with an error", "err", err, "why", why) c.sourcesReadyMu.Lock() c.fakeReadyForDraining = append(c.fakeReadyForDraining, Fetch{Topics: []FetchTopic{{ Topic: topic, Partitions: []FetchPartition{{ Partition: partition, Err: err, }}, }}}) c.sourcesReadyMu.Unlock() c.sourcesReadyCond.Broadcast() } // NewErrFetch returns a fake fetch containing a single empty topic with a // single partition of -1 with the given error. func NewErrFetch(err error) Fetches { return []Fetch{{ Topics: []FetchTopic{{ Topic: "", Partitions: []FetchPartition{{ Partition: -1, Err: err, }}, }}, }} } // PollFetches waits for fetches to be available, returning as soon as any // broker returns a fetch. If the context is nil, this function will return // immediately with any currently buffered records. It is functionally // equivalent to calling PollRecords(ctx, 0). // // If the client is closed, a fake fetch will be injected that has no topic, a // partition of -1, and a partition error of ErrClientClosed. If the context is // canceled, a fake fetch will be injected with ctx.Err. These injected errors // can be used to break out of a poll loop. // // It is important to check all partition errors in the returned fetches. If // any partition has a fatal error and actually had no records, fake fetch will // be injected with the error. // // If you are group consuming, a rebalance can happen under the hood while you // process the returned fetches. This can result in duplicate work, and you may // accidentally commit to partitions that you no longer own. You can prevent // this by using BlockRebalanceOnPoll, but this comes with different tradeoffs. // See the documentation on BlockRebalanceOnPoll for more information. func (cl *Client) PollFetches(ctx context.Context) Fetches { return cl.PollRecords(ctx, 0) } // PollRecords waits for fetches to be available, returning as soon as any // broker returns a fetch. If the context is nil, this function will return // immediately with any currently buffered fetches. // // If the client is closed, a fake fetch will be injected that has no topic, a // partition of -1, and a partition error of ErrClientClosed. If the context is // canceled, a fake fetch will be injected with ctx.Err. These injected errors // can be used to break out of a poll loop. // // This returns a maximum of maxPollRecords total across all fetches, or // returns all buffered records if maxPollRecords is <= 0. // // It is important to check all partition errors in the returned fetches. If // any partition has a fatal error and actually had no records, fake fetch will // be injected with the error. // // If you are group consuming, a rebalance can happen under the hood while you // process the returned fetches. This can result in duplicate work, and you may // accidentally commit to partitions that you no longer own. You can prevent // this by using BlockRebalanceOnPoll, but this comes with different tradeoffs. // See the documentation on BlockRebalanceOnPoll for more information. func (cl *Client) PollRecords(ctx context.Context, maxPollRecords int) Fetches { cl.cfg.hooks.each(func(h Hook) { if hh, ok := h.(HookPollStart); ok { hh.OnPollStart(ctx) } }) if maxPollRecords == 0 { maxPollRecords = -1 } c := &cl.consumer if c.pollWake != nil { // Store before sending on pollWake: a successful send // synchronizes-before the receive, so the reader's subsequent // pollActive.Load observes this Store. If the send hits the // default (buffer already full), ordering is irrelevant -- // manageFetchConcurrency reloads pollActive on its next event. c.pollActive.Store(true) select { case c.pollWake <- struct{}{}: default: } defer func() { c.pollActive.Store(false) select { case c.pollWake <- struct{}{}: default: } }() } if c.s != nil { return c.s.poll(ctx, maxPollRecords) } c.g.undirtyUncommitted() // If the user gave us a canceled context, we bail immediately after // un-dirty-ing marked records. We still need to add a poller to block // rebalances if configured, since we are returning a fetch. if ctx != nil { select { case <-ctx.Done(): c.waitAndAddPoller() return NewErrFetch(ctx.Err()) default: } } var fetches Fetches fill := func() { if c.cl.cfg.blockRebalanceOnPoll { c.waitAndAddPoller() defer func() { if len(fetches) == 0 { c.unaddPoller() } }() } paused := c.loadPaused() // A group can grab the consumer lock then the group mu and // assign partitions. The group mu is grabbed to update its // uncommitted map. Assigning partitions clears sources ready // for draining. // // We need to grab the consumer mu to ensure proper lock // ordering and prevent lock inversion. Polling fetches also // updates the group's uncommitted map; if we do not grab the // consumer mu at the top, we have a problem: without the lock, // we could have grabbed some sources, then a group assigned, // and after the assign, we update uncommitted with fetches // from the old assignment c.mu.Lock() defer c.mu.Unlock() // A panic below must not leave sourcesReadyMu locked: Close // would block on it, and the panic would never print. var realFetches Fetches func() { c.sourcesReadyMu.Lock() defer c.sourcesReadyMu.Unlock() if maxPollRecords < 0 { for _, ready := range c.sourcesReadyForDraining { if f := ready.takeBuffered(paused); len(f.Topics) > 0 { fetches = append(fetches, f) } } c.sourcesReadyForDraining = nil } else { var one *pollOne if len(fetches) == 0 && len(c.sourcesReadyForDraining) > 0 && maxPollRecords > 0 { one = new(pollOne) } for len(c.sourcesReadyForDraining) > 0 && maxPollRecords > 0 { source := c.sourcesReadyForDraining[0] fetch, taken, drained := source.takeNBuffered(paused, maxPollRecords, one) if drained { c.sourcesReadyForDraining = c.sourcesReadyForDraining[1:] } maxPollRecords -= taken if len(fetch.Topics) == 0 { continue // every partition was paused } if one != nil { one.f[0] = fetch fetches = one.f[:] one = nil continue } fetches = append(fetches, fetch) } } realFetches = fetches fetches = append(fetches, c.fakeReadyForDraining...) c.fakeReadyForDraining = nil }() if len(realFetches) == 0 { return } // Before returning, we want to update our uncommitted. If we // updated after, then we could end up with weird interactions // with group invalidations where we return a stale fetch after // committing in onRevoke. // // A blocking onRevoke commit, on finish, allows a new group // session to start. If we returned stale fetches that did not // have their uncommitted offset tracked, then we would allow // duplicates. if c.g != nil { c.g.updateUncommitted(realFetches) } } // We try filling fetches once before waiting. If we have no context, // we guarantee that we just drain anything available and return. for { fill() c.runDeferredFetchHooks() if len(fetches) > 0 || ctx == nil { return fetches } done := make(chan struct{}) quit := false go func() { c.sourcesReadyMu.Lock() defer c.sourcesReadyMu.Unlock() defer close(done) for !quit && len(c.sourcesReadyForDraining) == 0 && len(c.fakeReadyForDraining) == 0 { c.sourcesReadyCond.Wait() } }() exit := func() { c.sourcesReadyMu.Lock() quit = true c.sourcesReadyMu.Unlock() c.sourcesReadyCond.Broadcast() } select { case <-cl.ctx.Done(): exit() c.waitAndAddPoller() return NewErrFetch(ErrClientClosed) case <-ctx.Done(): exit() c.waitAndAddPoller() return NewErrFetch(ctx.Err()) case <-done: } } } // AllowRebalance allows a consumer group to rebalance if it was blocked by you // polling records in tandem with the BlockRebalanceOnPoll option. // // You can poll many times before calling this function; this function // internally resets the poll count and allows any blocked rebalances to // continue. Rebalances take priority: if a rebalance is blocked, and you allow // rebalances and then immediately poll, your poll will be blocked until the // rebalance completes. Internally, this function simply waits for lost // partitions to stop being fetched before allowing you to poll again. func (cl *Client) AllowRebalance() { cl.consumer.allowRebalance() } // UpdateFetchMaxBytes updates the max bytes that a fetch request will ask for // and the max partition bytes that a fetch request will ask for each // partition. func (cl *Client) UpdateFetchMaxBytes(maxBytes, maxPartBytes int32) { cl.cfg.maxBytes.store(maxBytes) cl.cfg.maxPartBytes.store(maxPartBytes) } // PauseFetchTopics sets the client to no longer fetch the given topics and // returns all currently paused topics. Paused topics persist until resumed. // You can call this function with no topics to simply receive the list of // currently paused topics. // // Pausing topics is independent from pausing individual partitions with the // PauseFetchPartitions method. If you pause partitions for a topic with // PauseFetchPartitions, and then pause that same topic with PauseFetchTopics, // the individually paused partitions will not be unpaused if you only call // ResumeFetchTopics. func (cl *Client) PauseFetchTopics(topics ...string) []string { c := &cl.consumer if len(topics) == 0 { return c.loadPaused().pausedTopics() } c.pausedMu.Lock() defer c.pausedMu.Unlock() paused := c.clonePaused() paused.addTopics(topics...) c.storePaused(paused) return paused.pausedTopics() } // PauseFetchPartitions sets the client to no longer fetch the given partitions // and returns all currently paused partitions. Paused partitions persist until // resumed. You can call this function with no partitions to simply receive the // list of currently paused partitions. // // Pausing individual partitions is independent from pausing topics with the // PauseFetchTopics method. If you pause partitions for a topic with // PauseFetchPartitions, and then pause that same topic with PauseFetchTopics, // the individually paused partitions will not be unpaused if you only call // ResumeFetchTopics. func (cl *Client) PauseFetchPartitions(topicPartitions map[string][]int32) map[string][]int32 { c := &cl.consumer if len(topicPartitions) == 0 { return c.loadPaused().pausedPartitions() } c.pausedMu.Lock() defer c.pausedMu.Unlock() paused := c.clonePaused() paused.addPartitions(topicPartitions) c.storePaused(paused) return paused.pausedPartitions() } // ResumeFetchTopics resumes fetching the input topics if they were previously // paused. Resuming topics that are not currently paused is a per-topic no-op. // See the documentation on PauseFetchTopics for more details. // // Note that resuming does not interrupt a fetch already in flight: resumed // topics are included in the next fetch to each broker, after that broker's // in-flight fetch completes. A fetch with no new data waits up to // FetchMaxWait (default 5s). If you pause and resume often, consider // lowering FetchMaxWait. func (cl *Client) ResumeFetchTopics(topics ...string) { defer cl.allSources(func(s *source) { s.maybeConsume() }) c := &cl.consumer c.pausedMu.Lock() defer c.pausedMu.Unlock() paused := c.clonePaused() paused.delTopics(topics...) c.storePaused(paused) } // ResumeFetchPartitions resumes fetching the input partitions if they were // previously paused. Resuming partitions that are not currently paused is a // per-topic no-op. See the documentation on PauseFetchPartitions for more // details, and ResumeFetchTopics for how resuming interacts with an in-flight // fetch. func (cl *Client) ResumeFetchPartitions(topicPartitions map[string][]int32) { defer cl.allSources(func(s *source) { s.maybeConsume() }) c := &cl.consumer c.pausedMu.Lock() defer c.pausedMu.Unlock() paused := c.clonePaused() paused.delPartitions(topicPartitions) c.storePaused(paused) } // SetOffsets sets the partitions in setOffsets to the given offsets. // Fetching continues from the new offset. SetOffsets skips a partition that // is not being consumed and skips a negative offset. // // If using transactions, it is advised to just use a GroupTransactSession and // avoid this function entirely. // // If using group consuming, it is strongly recommended to call SetOffsets // from the goroutine that polls, while no revoke can run: use // BlockRebalanceOnPoll and call SetOffsets before AllowRebalance. func (cl *Client) SetOffsets(setOffsets map[string]map[int32]EpochOffset) { cl.setOffsets(setOffsets, true) } func (cl *Client) setOffsets(setOffsets map[string]map[int32]EpochOffset, user bool) { if len(setOffsets) == 0 { return } // We assignPartitions before returning, so we grab the consumer lock // first to preserve consumer mu => group mu ordering, or to ensure // no concurrent metadata assign for direct consuming. c := &cl.consumer c.mu.Lock() defer c.mu.Unlock() var assigns map[string]map[int32]Offset var tps *topicsPartitions switch { case c.d != nil: assigns = c.d.applySetOffsets(setOffsets) tps = c.d.tps case c.g != nil: assigns = c.g.applySetOffsets(setOffsets, user) tps = c.g.tps } if len(assigns) == 0 { return } if user { c.assignPartitions(assigns, assignSetMatching, tps, "from manual SetOffsets") } else { c.assignPartitions(assigns, assignSetMatching, tps, "") } } // This is guaranteed to be called in a blocking metadata fn, which ensures // that metadata does not load the tps we are changing. Basically, we ensure // everything w.r.t. consuming is at a stand still. func (c *consumer) purgeTopics(topics []string) { if c.g == nil && c.d == nil && c.s == nil { return } c.mu.Lock() defer c.mu.Unlock() if c.s != nil { c.s.purgeTopics(topics) // save a useless map alloc by doing this early, not in the block below return } purgeAssignments := make(map[string]map[int32]Offset, len(topics)) for _, topic := range topics { purgeAssignments[topic] = nil } // assignPartitions removes the topics from 'tps', which removes them // from FUTURE metadata requests meaning they will not be repopulated // in the future. Any loaded tps is fine; metadata updates the topic // pointers underneath -- metadata does not re-store the tps itself // with any new topics that we just purged (except in the case of regex, // which is impossible to permanently purge anyway). // // We are guarded from adding back to 'using' via the consumer mu; // this cannot run concurrent with findNewAssignments. Thus, we first // purge tps, then clear using, and once the lock releases, findNewAssignments // will use the now-purged tps and will not add back to using. if c.g != nil { c.g.mu.Lock() // required when updating using defer c.g.mu.Unlock() // The rebalance this purge causes commits our uncommitted // offsets. By then the topic is gone from tps and uncommittedFrom // cannot tell it was recreated, so we drop its offsets now. tps := c.g.tps.load() for _, topic := range topics { if _, recreated := c.g.uncommittedFrom(tps, topic); recreated { delete(c.g.uncommitted, topic) } } c.assignPartitions(purgeAssignments, assignPurgeMatching, c.g.tps, fmt.Sprintf("purge of %v requested", topics)) for _, topic := range topics { delete(c.g.using, topic) delete(c.g.reSeen, topic) } // Our subscription shrank; reconcile per protocol. This must NOT // feed rejoinCh in 848 mode (signalSubscriptionChange forces a // heartbeat instead): a rejoinCh bounce there runs the session-end // revoke's nowAssigned read-modify-write concurrently with live // heartbeats, losing a heartbeat's nowAssigned store. c.g.signalSubscriptionChange("topics purged from consuming") } else { c.assignPartitions(purgeAssignments, assignPurgeMatching, c.d.tps, fmt.Sprintf("purge of %v requested", topics)) for _, topic := range topics { delete(c.d.using, topic) delete(c.d.reSeen, topic) delete(c.d.m, topic) delete(c.d.ps, topic) } } } // AddConsumeTopics adds new topics to be consumed. This function is a no-op if // the client is configured to consume via regex. // // Note that if you are directly consuming and specified ConsumePartitions, // this function will not add the rest of the partitions for a topic unless the // topic has been previously purged. That is, if you directly consumed only one // of five partitions originally, this will not add the other four until the // entire topic is purged. // // A topic name that is empty or longer than 249 bytes is skipped and logged: // no topic can have such a name. func (cl *Client) AddConsumeTopics(topics ...string) { c := &cl.consumer if len(topics) == 0 || !c.consuming() || cl.cfg.regex { return } if topics = slices.DeleteFunc(slices.Clone(topics), cl.invalidConsumeTopic); len(topics) == 0 { return } // We can do this outside of the metadata loop because we are strictly // adding new topics and forbid regex consuming. c.mu.Lock() defer c.mu.Unlock() if c.g != nil { c.g.tps.storeTopics(topics) } else if c.s != nil { c.s.tps.storeTopics(topics) } else { c.d.tps.storeTopics(topics) for _, topic := range topics { c.d.m.addt(topic) } } cl.triggerUpdateMetadataNow("from AddConsumeTopics") } // Reports, and logs, a name that validate refuses in ConsumeTopics: an empty // name spins on UNKNOWN_TOPIC metadata forever, and a name long enough makes // our metadata request too long to encode. func (cl *Client) invalidConsumeTopic(topic string) bool { if topic != "" && len(topic) <= maxTopicLen { return false } cl.cfg.logger.Log(LogLevelWarn, "skipping a topic name that is empty or too long to consume", "len", len(topic)) return true } // GetConsumeTopics retrieves a list of current topics being consumed. func (cl *Client) GetConsumeTopics() []string { c := &cl.consumer if !c.consuming() { return nil } var m map[string]*topicPartitions var ok bool if c.g != nil { m, ok = c.g.tps.v.Load().(topicsPartitionsData) } else if c.s != nil { m, ok = c.s.tps.v.Load().(topicsPartitionsData) } else { m, ok = c.d.tps.v.Load().(topicsPartitionsData) } if !ok { return nil } topics := make([]string, 0, len(m)) for k := range m { topics = append(topics, k) } return topics } // AddConsumePartitions adds new partitions to be consumed at the given // offsets. This function works only for direct, non-regex consumers. // // A topic name that is empty or longer than 249 bytes is deleted from the // partitions map and logged: no topic can have such a name. func (cl *Client) AddConsumePartitions(partitions map[string]map[int32]Offset) { c := &cl.consumer if c.d == nil || cl.cfg.regex { return } var topics []string for t, ps := range partitions { if len(ps) == 0 || cl.invalidConsumeTopic(t) { delete(partitions, t) continue } topics = append(topics, t) } if len(partitions) == 0 { return } c.mu.Lock() defer c.mu.Unlock() c.d.tps.storeTopics(topics) for t, ps := range partitions { if c.d.ps[t] == nil { c.d.ps[t] = make(map[int32]Offset) } for p, o := range ps { c.d.m.add(t, p) c.d.ps[t][p] = o } } cl.triggerUpdateMetadataNow("from AddConsumePartitions") } // RemoveConsumePartitions removes partitions from being consumed. This // function works only for direct, non-regex consumers. // // This method does not purge the concept of any topics from the client -- if // you remove all partitions from a topic that was being consumed, metadata // fetches will still occur for the topic. If you want to remove the topic // entirely, use PurgeTopicsFromClient. // // If you specified ConsumeTopics and this function removes all partitions for // a topic, the topic will no longer be consumed. func (cl *Client) RemoveConsumePartitions(partitions map[string][]int32) { c := &cl.consumer if c.d == nil || cl.cfg.regex { return } for t, ps := range partitions { if len(ps) == 0 { delete(partitions, t) continue } } if len(partitions) == 0 { return } c.mu.Lock() defer c.mu.Unlock() removeOffsets := make(map[string]map[int32]Offset, len(partitions)) for t, ps := range partitions { removePartitionOffsets := make(map[int32]Offset, len(ps)) for _, p := range ps { removePartitionOffsets[p] = Offset{} } removeOffsets[t] = removePartitionOffsets } c.assignPartitions(removeOffsets, assignInvalidateMatching, c.d.tps, fmt.Sprintf("remove of %v requested", partitions)) for t, ps := range partitions { for _, p := range ps { c.d.using.remove(t, p) c.d.m.remove(t, p) delete(c.d.ps[t], p) } if len(c.d.ps[t]) == 0 { delete(c.d.ps, t) } } } // assignHow controls how assignPartitions operates. type assignHow int8 const ( // This option simply assigns new offsets, doing nothing with existing // offsets / active fetches / buffered fetches. assignWithoutInvalidating assignHow = iota // This option invalidates active fetches so they will not buffer and // drops all buffered fetches, and then continues to assign the new // assignments. assignInvalidateAll // This option does not assign, but instead invalidates any active // fetches for "assigned" (actually lost) partitions. This additionally // drops all buffered fetches, because they could contain partitions we // lost. Thus, with this option, the actual offset in the map is // meaningless / a dummy offset. assignInvalidateMatching assignPurgeMatching // The counterpart to assignInvalidateMatching, assignSetMatching // resets all matching partitions to the specified offset / epoch. assignSetMatching ) func (h assignHow) String() string { switch h { case assignWithoutInvalidating: return "assigning everything new, keeping current assignment" case assignInvalidateAll: return "unassigning everything" case assignInvalidateMatching: return "unassigning any currently assigned matching partition that is in the input" case assignPurgeMatching: return "unassigning and purging any partition matching the input topics" case assignSetMatching: return "reassigning any currently assigned matching partition to the input" } return "" } type fmtAssignment map[string]map[int32]Offset func (f fmtAssignment) String() string { var sb strings.Builder var topicsWritten int for topic, partitions := range f { topicsWritten++ sb.WriteString(topic) sb.WriteString("[") var partitionsWritten int for partition, offset := range partitions { fmt.Fprintf(&sb, "%d%s", partition, offset) partitionsWritten++ if partitionsWritten < len(partitions) { sb.WriteString(" ") } } sb.WriteString("]") if topicsWritten < len(f) { sb.WriteString(", ") } } return sb.String() } // assignPartitions, called under the consumer's mu, is used to set new cursors // or add to the existing cursors. // // We do not need to pass tps when we are invalidating all. All other cases, // we want the tps: guarding the session may create a new session needing it, // and stopping the session needs it for the restart. func (c *consumer) assignPartitions(assignments map[string]map[int32]Offset, how assignHow, tps *topicsPartitions, why string) { if c.mu.TryLock() { c.mu.Unlock() panic("assignPartitions called without holding the consumer lock, this is a bug in franz-go, please open an issue at github.com/twmb/franz-go") } // The internal code can avoid giving an assign reason in cases where // the caller logs itself immediately before assigning. We only log if // there is a reason. if len(why) > 0 && c.cl.cfg.logger.Level() >= LogLevelInfo { c.cl.cfg.logger.Log(LogLevelInfo, "assigning partitions", "why", why, "how", how, "input", fmtAssignment(assignments), ) } var session *consumerSession var loadOffsets listOrEpochLoads defer func() { if session == nil { // if nil, we stopped the session session = c.startNewSession(tps) } else { // else we guarded it c.unguardSessionChange(session) } loadOffsets.loadWithSession(session, "loading offsets in new session from assign") // odds are this assign came from a metadata update, so no reason to force a refresh with loadWithSessionNow // If we started a new session or if we unguarded, we have one // worker. This one worker allowed us to safely add our load // offsets before the session could be concurrently stopped // again. Now that we have added the load offsets, we allow the // session to be stopped. session.decWorker() }() if how == assignWithoutInvalidating { // Guarding a session change can actually create a new session // if we had no session before, which is why we need to pass in // our topicPartitions. session = c.guardSessionChange(tps) } else { loadOffsets, _ = c.stopSession() // First, over all cursors currently in use, we unset them or set them // directly as appropriate. Anything we do not unset, we keep. var keep usedCursors for usedCursor := range c.usingCursors { shouldKeep := true if how == assignInvalidateAll { usedCursor.unset() shouldKeep = false } else { // invalidateMatching or setMatching if assignTopic, ok := assignments[usedCursor.topic]; ok { if how == assignPurgeMatching { // topic level usedCursor.source.removeCursor(usedCursor) shouldKeep = false } else if assignPart, ok := assignTopic[usedCursor.partition]; ok { if how == assignInvalidateMatching { usedCursor.unset() shouldKeep = false } else { // how == assignSetMatching usedCursor.setOffset(cursorOffset{ offset: assignPart.at, lastConsumedEpoch: assignPart.epoch, }) // This partition can have a pending list or epoch // load: an OffsetOutOfRange reload, or an epoch // validation from a leader move. The cursor is then // unusable and the load's completion is its only // re-enabler -- and that completion would also // overwrite the offset we just set with the load's // now-stale result. A transact session resetting to // committed offsets after an abort would be undone: // consumption would resume at the pre-abort position, // never re-consuming the aborted records. The set // offset is the new truth: drop the load and // re-enable the cursor ourselves. Safe here because // the session is stopped (no source can use the // cursor until the new session starts). // // A cursor stopped by a batch over // MaxDecompressBatchBytes is re-enabled // the same way: the set offset is how the // user skips the batch. The stopped cursor // can have a pending load too, so we clear // `fatal` whether or not we dropped a load: // allowUsable does nothing while `fatal` is // set. wasFatal := usedCursor.fatal.Swap(false) if loadOffsets.removeLoad(usedCursor.topic, usedCursor.partition) || wasFatal { usedCursor.allowUsable() } } } } } if shouldKeep { keep.use(usedCursor) } } c.usingCursors = keep // For any partition that was listing offsets or loading // epochs, we want to ensure that if we are keeping those // partitions, we re-start the list/load. // // Note that we do not need to unset cursors here; anything // that actually resulted in a cursor is forever tracked in // usedCursors. We only do not have used cursors if an // assignment went straight to listing / epoch loading, and // that list/epoch never finished. switch how { case assignWithoutInvalidating: // Nothing to do -- this is handled above. case assignInvalidateAll: loadOffsets = listOrEpochLoads{} case assignSetMatching: // The cursor walk above set every partition with a cursor // in use. A partition still on its first offset load has // no cursor in use, and the load would start the partition // at the load's offset rather than the set offset: we drop // the load and assign the set offset below like a new // assignment. Any other partition has no cursor in use and // no load: the partition is not being consumed, and we // drop the partition. loading := make(map[string]map[int32]Offset) for t, ps := range assignments { var loadingTopic map[int32]Offset for p, o := range ps { if loadOffsets.removeLoad(t, p) { if loadingTopic == nil { loadingTopic = make(map[int32]Offset) loading[t] = loadingTopic } loadingTopic[p] = o } } } assignments = loading case assignInvalidateMatching: loadOffsets.keepFilter(func(t string, p int32) bool { if assignTopic, ok := assignments[t]; ok { if _, ok := assignTopic[p]; ok { return false } } return true }) case assignPurgeMatching: // This is slightly different than invalidate in that // we invalidate whole topics. loadOffsets.keepFilter(func(t string, _ int32) bool { _, ok := assignments[t] return !ok // assignments are topics to purge -- do NOT keep the topic if it is being purged }) // We have to purge from tps _after_ the session is // stopped. If we purge early while the session is // ongoing, then another goroutine could be loading and // using tps and expecting topics not yet removed from // assignPartitions to still be there. Specifically, // mapLoadsToBrokers could be expecting topic foo to be // there (from the session!), so if we purge foo before // stopping the session, we will panic. topics := make([]string, 0, len(assignments)) for t := range assignments { topics = append(topics, t) } tps.purgeTopics(topics) } } // This assignment could contain nothing (for the purposes of // invalidating active fetches), so we only do this if needed. With // assignSetMatching, assignments now holds only the partitions on their // first offset load: we dropped the loads above, and the loop below // assigns the set offsets like a new assignment. if len(assignments) == 0 || (how != assignWithoutInvalidating && how != assignSetMatching) { return } c.cl.cfg.logger.Log(LogLevelDebug, "assign requires loading offsets") // We could have a prior handleListOrEpochResults finishing concurrent // with a new assignment. We need to guard below, because list/epoch // results can set offsets for loaded cursors. // // Example: I was just cooperatively assigned p1o10e3, and I issued an // epoch request to validate data loss. I was then assigned p2o4e-1: // there is no epoch to validate, so we immediately begin consuming // at the offset. The epoch request returns and tries also using the // cursor concurrently. We need to guard it. // // If we stopped the session (assignSetMatching), no results can // arrive until the new session starts. if session != nil { session.listOrEpochMu.Lock() defer session.listOrEpochMu.Unlock() } topics := tps.load() for topic, partitions := range assignments { topicPartitions := topics.loadTopic(topic) // should be non-nil if topicPartitions == nil { c.cl.cfg.logger.Log(LogLevelError, "BUG! consumer was assigned topic that we did not ask for in ConsumeTopics nor ConsumePartitions, skipping!", "topic", topic) continue } for partition, offset := range partitions { // If we are loading the first record after a millisec, // we go directly to listing offsets. Epoch validation // does not ever set afterMilli. if offset.afterMilli { loadOffsets.addLoad(topic, partition, loadTypeList, offsetLoad{ Offset: offset, }) continue } // First, if the request is exact, get rid of the relative // portion. We are modifying a copy of the offset, i.e. we // are appropriately not modifying 'assignments' itself. if offset.at >= 0 { offset.at += offset.relative if offset.at < 0 { offset.at = 0 } offset.relative = 0 } // If we are requesting an exact offset with an epoch, // we do truncation detection and then use the offset. // // Otherwise, an epoch is specified without an exact // request which is useless for us, or a request is // specified without a known epoch. // // The client ensures the epoch is non-negative from // fetch offsets only if the broker supports KIP-320, // but we do not override the user manually specifying // an epoch. if offset.at >= 0 && offset.epoch >= 0 { loadOffsets.addLoad(topic, partition, loadTypeEpoch, offsetLoad{ Offset: offset, }) continue } // If an exact offset is specified and we have loaded // the partition, we use it. We have to use epoch -1 // rather than the latest loaded epoch on the partition // because the offset being requested to use could be // from an epoch after OUR loaded epoch. Otherwise, we // could update the metadata, see the later epoch, // request the end offset for our prior epoch, and then // think data loss occurred. // // If an offset is unspecified or we have not loaded // the partition, we list offsets to find out what to // use. if offset.at >= 0 && partition >= 0 && partition < int32(len(topicPartitions.partitions)) { part := topicPartitions.partitions[partition] cursor := part.cursor cursor.setOffset(cursorOffset{ offset: offset.at, lastConsumedEpoch: -1, }) cursor.allowUsable() c.usingCursors.use(cursor) continue } // If the offset is atCommitted, then no offset was // loaded from FetchOffsets. We inject an error and // avoid using this partition. if offset.at == atCommitted { c.addFakeReadyForDraining(topic, partition, errNoCommittedOffset, "notification of uncommitted partition") continue } loadOffsets.addLoad(topic, partition, loadTypeList, offsetLoad{ Offset: offset, }) } } } // filterMetadataAllTopics, called BEFORE doOnMetadataUpdate, evaluates // all topics received against the user provided regex and returns the // topics we will consume. // // We never match internal topics. The broker can still assign one to us // when it resolves the regex itself (KIP-848 with no excludes); see // adoptAssignedTopic. func (c *consumer) filterMetadataAllTopics(latest map[string]*metadataTopic) []string { var rns reNews defer rns.log(&c.cl.cfg) c.mu.Lock() defer c.mu.Unlock() var reSeen map[string]bool if c.g != nil { reSeen = c.g.reSeen } else if c.s != nil { reSeen = c.s.reSeen } else { reSeen = c.d.reSeen } // We evaluate regexes in sorted order so that the log is deterministic // when a topic matches multiple regexes. var includes []string keep := make([]string, 0, len(latest)) for topic, mt := range latest { // loadErr should only be non-nil when requesting all topics // if this is with auto-topic-creation && the creation failed. // That is, we should not consume the topic since we just // tried creating it and creating it failed. if mt.loadErr != nil { continue } want, seen := reSeen[topic] if !seen { if includes == nil { includes = slices.Sorted(maps.Keys(c.cl.cfg.topics)) } var matchedRe string for _, rawRe := range includes { if want = c.cl.cfg.topics[rawRe].MatchString(topic); want { matchedRe = rawRe break } } switch { case !want: rns.skip(topic) case mt.isInternal: want = false rns.skipInternal(topic) default: for rawEx, re := range c.cl.cfg.excludeTopics { if re.MatchString(topic) { want = false rns.exclude(rawEx, topic) break } } if want { rns.add(matchedRe, topic) } } reSeen[topic] = want } if want { keep = append(keep, topic) } } return keep } func (c *consumer) doOnMetadataUpdate() { if !c.consuming() { return } // See the comment on the outstandingMetadataUpdates field for why this // block below. if c.outstandingMetadataUpdates.maybeBegin() { doUpdate := func() { // We forbid reassignments while we do a quick check for // new assignments--for the direct consumer particularly, // this prevents TOCTOU, and guards against a concurrent // assignment from SetOffsets. c.mu.Lock() defer c.mu.Unlock() switch { case c.d != nil: if new := c.d.findNewAssignments(); len(new) > 0 { c.assignPartitions(new, assignWithoutInvalidating, c.d.tps, "new assignments from direct consumer") } case c.g != nil: c.g.findNewAssignments() case c.s != nil: c.s.maybeStartManage() } go c.loadSession().doOnMetadataUpdate() } go func() { again := true for again { doUpdate() again = c.outstandingMetadataUpdates.maybeFinish(false) } }() } } func (s *consumerSession) doOnMetadataUpdate() { if s == nil || s == noConsumerSession { // no session started yet return } s.listOrEpochMu.Lock() defer s.listOrEpochMu.Unlock() if s.listOrEpochMetaCh == nil { return // nothing waiting to load epochs / offsets } select { case s.listOrEpochMetaCh <- struct{}{}: default: } } type offsetLoadMap map[string]map[int32]offsetLoad // offsetLoad is effectively an Offset, but also includes when we last // consumed. type offsetLoad struct { lastConsumedMilli int64 // for handling OffsetOutOfRange Offset } func (o offsetLoadMap) errToLoaded(err error) []loadedOffset { var loaded []loadedOffset for t, ps := range o { for p, o := range ps { loaded = append(loaded, loadedOffset{ topic: t, partition: p, err: err, request: o, }) } } return loaded } // Combines list and epoch loads into one type for simplicity. type listOrEpochLoads struct { // List and Epoch are public so that anything marshaling through // reflect (i.e. json) can see the fields. List offsetLoadMap Epoch offsetLoadMap } type listOrEpochLoadType uint8 const ( loadTypeList listOrEpochLoadType = iota loadTypeEpoch ) func (l listOrEpochLoadType) String() string { switch l { case loadTypeList: return "list" default: return "epoch" } } // adds an offset to be loaded, ensuring it exists only in the final loadType. func (l *listOrEpochLoads) addLoad(t string, p int32, loadType listOrEpochLoadType, load offsetLoad) { l.removeLoad(t, p) dst := &l.List if loadType == loadTypeEpoch { dst = &l.Epoch } if *dst == nil { *dst = make(offsetLoadMap) } ps := (*dst)[t] if ps == nil { ps = make(map[int32]offsetLoad) (*dst)[t] = ps } ps[p] = load } func (l *listOrEpochLoads) removeLoad(t string, p int32) (removed bool) { for _, m := range []offsetLoadMap{ l.List, l.Epoch, } { if m == nil { continue } ps := m[t] if ps == nil { continue } if _, exists := ps[p]; !exists { continue } delete(ps, p) removed = true if len(ps) == 0 { delete(m, t) } } return removed } func (l listOrEpochLoads) each(fn func(string, int32)) { for _, m := range []offsetLoadMap{ l.List, l.Epoch, } { for topic, partitions := range m { for partition := range partitions { fn(topic, partition) } } } } func (l *listOrEpochLoads) keepFilter(keep func(string, int32) bool) { for _, m := range []offsetLoadMap{ l.List, l.Epoch, } { for t, ps := range m { for p := range ps { if !keep(t, p) { delete(ps, p) if len(ps) == 0 { delete(m, t) } } } } } } // Merges loads into the caller; used to coalesce loads while a metadata update // is happening (see the only use below). func (l *listOrEpochLoads) mergeFrom(src listOrEpochLoads) { for _, srcs := range []struct { m offsetLoadMap loadType listOrEpochLoadType }{ {src.List, loadTypeList}, {src.Epoch, loadTypeEpoch}, } { for t, ps := range srcs.m { for p, load := range ps { l.addLoad(t, p, srcs.loadType, load) } } } } func (l listOrEpochLoads) isEmpty() bool { return len(l.List) == 0 && len(l.Epoch) == 0 } func (l listOrEpochLoads) loadWithSession(s *consumerSession, why string) { if !l.isEmpty() { s.incWorker() go s.listOrEpoch(l, false, why) } } func (l listOrEpochLoads) loadWithSessionNow(s *consumerSession, why string) bool { if !l.isEmpty() { s.incWorker() go s.listOrEpoch(l, true, why) return true } return false } // fetchManager controls fetch concurrency. Sources register their desire to // fetch, and the manager grants permission up to the configured limit. This // type is shared by consumerSession (regular consumers) and shareConsumer // (share groups). type fetchManager struct { ctx context.Context cancel func() // pollActive + pollWake are the consumer's strict-pull-mode state // (MaxConcurrentFetches == 0). Both are nil otherwise. The atomic // is the ground truth ("a poll is in progress"); the channel kicks // the select loop to re-read it. See consumer.pollActive comment. pollActive *atomic.Bool pollWake chan struct{} // We receive desires from sources, we reply when they can fetch, and // they send back when they are done. Thus, three level chan. desireFetchCh chan chan chan bool cancelFetchCh chan chan chan bool allowedFetches int fetchManagerStarted atomic.Bool // atomic, once true, we start the fetch manager } func newFetchManager(ctx context.Context, cancel func(), pollActive *atomic.Bool, pollWake chan struct{}, maxConcurrentFetches int) fetchManager { return fetchManager{ ctx: ctx, cancel: cancel, pollActive: pollActive, pollWake: pollWake, // NOTE: This channel must be unbuffered. If it is buffered, // then we can exit manageFetchConcurrency when we should not // and have a deadlock: // // * source sends to desireFetchCh, is buffered // * source seeds context canceled, tries sending to cancelFetchCh // * session concurrently sees context canceled // * session has not drained desireFetchCh, sees activeFetches is 0 // * session exits // * source permanently hangs sending to desireFetchCh // // By having desireFetchCh unbuffered, we *ensure* that if the // source indicates it wants a fetch, the session knows it and // tracks it in wantFetch. // // See #198. desireFetchCh: make(chan chan chan bool), cancelFetchCh: make(chan chan chan bool, 4), allowedFetches: maxConcurrentFetches, } } func (fm *fetchManager) desireFetch() chan chan chan bool { if !fm.fetchManagerStarted.Swap(true) { go fm.manageFetchConcurrency() } return fm.desireFetchCh } func (fm *fetchManager) manageFetchConcurrency() { var ( activeFetches int doneFetch = make(chan bool, 20) wantFetch []chan chan bool pollAllowed bool ctxCh = fm.ctx.Done() wantQuit bool ) for { select { case register := <-fm.desireFetchCh: wantFetch = append(wantFetch, register) case cancel := <-fm.cancelFetchCh: var found bool for i, want := range wantFetch { if want == cancel { wantFetch = slices.Delete(wantFetch, i, i+1) found = true break } } // If we did not find the channel, then we have already // sent to it, removed it from our wantFetch list, and // bumped activeFetches. if !found { activeFetches-- } case <-doneFetch: activeFetches-- case <-ctxCh: wantQuit = true ctxCh = nil case <-fm.pollWake: // Wake only; the post-select Load below picks up // the current pollActive value. } // pollActive is the ground truth; re-read after every event, // not only on the pollWake case. Two reasons the Load cannot // move into the kick case: // 1. newFetchManager may be constructed after PollRecords has // already run (pollActive==true, wake already consumed or // silently dropped into a full buffer). The first // iteration needs to observe pollActive=true without a // wake to unblock first. // 2. pollActive can flip true => false between the wake's // buffer send and our Load. Re-reading on every event // (desireFetch, cancel, doneFetch, ctx) ensures we never // treat a stale "true" as authoritative for gating the // next fetch. // Missed wakes (buffer-full default) are harmless because the // next event triggers another Load. if fm.pollActive != nil { pollAllowed = fm.pollActive.Load() } if len(wantFetch) > 0 && (activeFetches < fm.allowedFetches || pollAllowed && activeFetches == 0 || fm.allowedFetches < 0) { // negative means unbounded wantFetch[0] <- doneFetch wantFetch = wantFetch[1:] activeFetches++ continue } // We cannot return while sources are still registered in // wantFetch: each of them is (or is about to be) blocked // sending on cancelFetchCh, which only we drain. Returning // early orphans those sends once the channel's small buffer // fills; the sources then hold session workers forever and // stopSession never finishes (consumer deadlock). Keep // looping until every registered source has canceled. if wantQuit && activeFetches == 0 && len(wantFetch) == 0 { return } } } // A consumer session is responsible for an era of fetching records for a set // of cursors. The set can be added to without killing an active session, but // it cannot be removed from. Removing any cursor from being consumed kills the // current consumer session and begins a new one. type consumerSession struct { c *consumer // tps tracks the topics that were assigned in this session. We use // this field to build and handle list offset / load epoch requests. tps *topicsPartitions fetchManager // Workers signify the number of fetch and list / epoch goroutines that // are currently running within the context of this consumer session. // Stopping a session only returns once workers hits zero. workersMu xsync.Mutex workersCond *sync.Cond workers int // listOrEpochMu largely guards the below. It is a sub-mutex of the // consumer mutex to guard one concurrent data access (see below in // assignPartitions). listOrEpochMu xsync.Mutex listOrEpochLoadsWaiting listOrEpochLoads listOrEpochMetaCh chan struct{} // non-nil if Loads is non-nil, signalled on meta update listOrEpochLoadsLoading listOrEpochLoads } func (c *consumer) newConsumerSession(tps *topicsPartitions) *consumerSession { if tps == nil || len(tps.load()) == 0 { return noConsumerSession } ctx, cancel := context.WithCancel(c.cl.ctx) session := &consumerSession{ c: c, tps: tps, fetchManager: newFetchManager(ctx, cancel, &c.pollActive, c.pollWake, c.cl.cfg.maxConcurrentFetches), } session.workersCond = sync.NewCond(&session.workersMu) return session } func (s *consumerSession) incWorker() { if s == noConsumerSession { // from startNewSession return } s.workersMu.Lock() defer s.workersMu.Unlock() s.workers++ } func (s *consumerSession) decWorker() { if s == noConsumerSession { // from followup to startNewSession return } s.workersMu.Lock() defer s.workersMu.Unlock() s.workers-- if s.workers == 0 { s.workersCond.Broadcast() } } // noConsumerSession exists because we cannot store nil into an atomic.Value. var noConsumerSession = new(consumerSession) func (c *consumer) loadSession() *consumerSession { if session := c.session.Load(); session != nil { return session.(*consumerSession) } return noConsumerSession } // Guards against a session being stopped, and must be paired with an unguard. // This returns a new session if there was no session. // // The purpose of this function is when performing additive-only changes to an // existing session, because additive-only changes can avoid killing a running // session. func (c *consumer) guardSessionChange(tps *topicsPartitions) *consumerSession { c.sessionChangeMu.Lock() session := c.loadSession() if session == noConsumerSession { // If there is no session, we simply store one. This is fine; // sources will be able to begin a fetch loop, but they will // have no cursors to consume yet. session = c.newConsumerSession(tps) c.session.Store(session) } return session } // For the same reason below as in startNewSession, we inc a worker before // unguarding. This allows the unguarding to execute a bit of logic if // necessary before the session can be stopped. func (c *consumer) unguardSessionChange(session *consumerSession) { session.incWorker() c.sessionChangeMu.Unlock() } // Stops an active consumer session if there is one, and does not return until // all fetching, listing, offset for leader epoching is complete. This // invalidates any buffered fetches for the previous session and returns any // partitions that were listing offsets or loading epochs. func (c *consumer) stopSession() (listOrEpochLoads, *topicsPartitions) { c.sessionChangeMu.Lock() session := c.loadSession() if session == noConsumerSession { return listOrEpochLoads{}, nil // we had no session } // Before storing noConsumerSession, cancel our old. This pairs // with the reverse ordering in source, which checks noConsumerSession // then checks the session context. session.cancel() // At this point, any in progress fetches, offset lists, or epoch loads // will quickly die. c.session.Store(noConsumerSession) // At this point, no source can be started, because the session is // noConsumerSession. session.workersMu.Lock() for session.workers > 0 { session.workersCond.Wait() } session.workersMu.Unlock() // At this point, all fetches, lists, and loads are dead. We can close // our num-fetches manager without worrying about a source trying to // register itself. c.cl.allSources(func(s *source) { s.session.reset() }) // At this point, if we begin fetching anew, then the sources will not // be using stale fetch sessions. c.sourcesReadyMu.Lock() defer c.sourcesReadyMu.Unlock() for _, ready := range c.sourcesReadyForDraining { ready.discardBuffered() } c.sourcesReadyForDraining = nil // The discards above deferred their unbuffered-hook dispatches, and // they cannot run synchronously here: our callers hold c.mu (and // sessionChangeMu), the very locks a re-entrant hook needs. The // discarded records were never polled, so there is no user-visible // ordering to preserve; dispatch async. if fns := c.deferredFetchHooks; len(fns) > 0 { c.deferredFetchHooks = nil go func() { for _, fn := range fns { fn() } }() } // At this point, we have invalidated any buffered data from the prior // session. We deliberately leave c.fakeReadyForDraining so the user can // still observe errors that happened in the dying session (data loss, // list/epoch failures, no-committed-offset notices, etc.). A consequence // is that the user's next poll may surface an error for a partition the // new assignment does not include; callers that key off fake-fetch errors // for committing must check current ownership before acting. The session // is dead. session.listOrEpochLoadsWaiting.mergeFrom(session.listOrEpochLoadsLoading) return session.listOrEpochLoadsWaiting, session.tps } // Starts a new consumer session, allowing fetches to happen. // // If there are no topic partitions to start with, this returns noConsumerSession. // // This is returned with 1 worker; decWorker must be called after return. The // 1 worker allows for initialization work to prevent the session from being // immediately stopped. func (c *consumer) startNewSession(tps *topicsPartitions) *consumerSession { if c.kill.Load() { tps = nil } session := c.newConsumerSession(tps) c.session.Store(session) // Ensure that this session is usable before being stopped immediately. // The caller must dec workers. session.incWorker() // At this point, sources can start consuming. c.sessionChangeMu.Unlock() c.cl.allSources(func(s *source) { s.maybeConsume() }) // At this point, any source that was not consuming because it saw the // session was stopped has been notified to potentially start consuming // again. The session is alive. return session } // This function is responsible for issuing ListOffsets or // OffsetForLeaderEpoch. These requests's responses are only handled within // the context of a consumer session. func (s *consumerSession) listOrEpoch(waiting listOrEpochLoads, immediate bool, why string) { defer s.decWorker() // It is possible for a metadata update to try to migrate partition // loads if the update moves partitions between brokers. If we are // closing the client, the consumer session could already be stopped, // but this stops before the metadata goroutine is killed. So, if we // are in this function but actually have no session, we return. if s == noConsumerSession { return } // We must set up listOrEpochMetaCh BEFORE triggering metadata. If we // trigger first and set the channel second, there is a race where the // metadata update completes and doOnMetadataUpdate checks for the // channel before we create it, causing the signal to be lost. With the // channel created first, doOnMetadataUpdate will always find the // channel and signal it. // // Race without this ordering: // 1. listOrEpoch: triggerUpdateMetadata -> sends trigger // 2. listOrEpoch: goroutine descheduled under load // 3. metadata loop: processes trigger, runs doOnMetadataUpdate // 4. doOnMetadataUpdate: listOrEpochMetaCh is nil -> returns (signal lost) // 5. listOrEpoch: resumes, creates listOrEpochMetaCh, waits forever s.listOrEpochMu.Lock() // collapse any listOrEpochs that occur during meta update into one if !s.listOrEpochLoadsWaiting.isEmpty() { s.listOrEpochLoadsWaiting.mergeFrom(waiting) s.listOrEpochMu.Unlock() return } s.listOrEpochLoadsWaiting = waiting s.listOrEpochMetaCh = make(chan struct{}, 1) s.listOrEpochMu.Unlock() wait := true if immediate { s.c.cl.triggerUpdateMetadataNow(why) } else { wait = s.c.cl.triggerUpdateMetadata(false, why) // avoid trigger if within refresh interval } if wait { select { case <-s.ctx.Done(): return case <-s.listOrEpochMetaCh: } } // If the session is dying, park: the loads were stored in waiting above, // and stopSession returns waiting loads to the caller for the next // session. Without this check, a dying session whose metadata is fresh // busy-loops until metadataMinAge elapses: wait is false above, so we // would issue requests on the dead context, every one fails instantly, // the reload timer below is canceled by the same dead context, and its // loadWithSession re-enters this function - burning CPU and holding the // session-stop (every revoke, leave, close, or seek) for the full // metadataMinAge. if s.ctx.Err() != nil { return } s.listOrEpochMu.Lock() loading := s.listOrEpochLoadsWaiting s.listOrEpochLoadsLoading.mergeFrom(loading) s.listOrEpochLoadsWaiting = listOrEpochLoads{} s.listOrEpochMetaCh = nil s.listOrEpochMu.Unlock() brokerLoads := s.mapLoadsToBrokers(loading) results := make(chan loadedOffsets, 2*len(brokerLoads)) // each broker can receive up to two requests var issued, received int for broker, brokerLoad := range brokerLoads { s.c.cl.cfg.logger.Log(LogLevelDebug, "offsets to load broker", "broker", broker.meta.NodeID, "load", brokerLoad) if len(brokerLoad.List) > 0 { issued++ go s.c.cl.listOffsetsForBrokerLoad(s.ctx, broker, brokerLoad.List, s.tps, results) } if len(brokerLoad.Epoch) > 0 { issued++ go s.c.cl.loadEpochsForBrokerLoad(s.ctx, broker, brokerLoad.Epoch, s.tps, results) } } var reloads, followUps listOrEpochLoads defer func() { if !reloads.isEmpty() { s.incWorker() go func() { // Before we dec our worker, we must add the // reloads back into the session's waiting loads. // Doing so allows a concurrent stopSession to // track the waiting loads, whereas if we did not // add things back to the session, we could abandon // loading these offsets and have a stuck cursor. defer s.decWorker() defer reloads.loadWithSession(s, "reload offsets from load failure") after := time.NewTimer(time.Second) defer after.Stop() select { case <-after.C: case <-s.ctx.Done(): return } }() } }() // We must drain all results before returning so that the // sub-goroutines complete within this worker's lifetime. If the // session is stopped, the context cancellation propagates to each // sub-goroutine's broker.waitResp, so they will finish quickly. // Without draining, stopSession can return (having seen workers=0) // and purgeTopics can modify tps while a sub-goroutine still // references it. for received != issued { loaded := <-results received++ reload, followUp := s.handleListOrEpochResults(loaded) reloads.mergeFrom(reload) followUps.mergeFrom(followUp) } followUps.loadWithSession(s, "reset by time after an undefined epoch offset") } // Called within a consumer session, this function handles results from list // offsets or epoch loads and returns any loads that should be retried. // // To us, all errors are reloadable. We either have request level retryable // errors (unknown partition, etc) or non-retryable errors (auth), or we have // request issuing errors (no dial, connection cut repeatedly). // // For retryable request errors, we may as well back off a little bit to allow // Kafka to harmonize if the topic exists / etc. // // For non-retryable request errors, we may as well retry to both (a) allow the // user more signals about a problem that they can maybe fix within Kafka (i.e. // the auth), and (b) force the user to notice errors. // // For request issuing errors, we may as well continue to retry because there // is not much else we can do. RequestWith already retries, but returns when // the retry limit is hit. We will backoff 1s and then allow RequestWith to // continue requesting and backing off. func (s *consumerSession) handleListOrEpochResults(loaded loadedOffsets) (reloads, followUps listOrEpochLoads) { // This function can be running twice concurrently, so we need to guard // listOrEpochLoadsLoading and usingCursors. For simplicity, we just // guard this entire function. debug := s.c.cl.cfg.logger.Level() >= LogLevelDebug var using map[string]map[int32]EpochOffset type epochOffsetWhy struct { EpochOffset error } var reloading map[string]map[int32]epochOffsetWhy if debug { using = make(map[string]map[int32]EpochOffset) reloading = make(map[string]map[int32]epochOffsetWhy) defer func() { t := "list" if loaded.loadType == loadTypeEpoch { t = "epoch" } s.c.cl.cfg.logger.Log(LogLevelDebug, fmt.Sprintf("handled %s results", t), "broker", logID(loaded.broker), "using", using, "reloading", reloading) }() } s.listOrEpochMu.Lock() defer s.listOrEpochMu.Unlock() for _, load := range loaded.loaded { s.listOrEpochLoadsLoading.removeLoad(load.topic, load.partition) // remove the tracking of this load from our session use := func() { if debug { tusing := using[load.topic] if tusing == nil { tusing = make(map[int32]EpochOffset) using[load.topic] = tusing } tusing[load.partition] = EpochOffset{load.leaderEpoch, load.offset} } // Preserve lastConsumedTime (for AfterMilli fallback on // subsequent OffsetOutOfRange) and hwm (for lag metrics) // across validation loads. The cursor is currently // unusable (we're about to allowUsable it), so reading // the prior cursorOffset here is safe: no concurrent // fetch observes useState=true yet. prior := load.cursor.cursorOffset load.cursor.setOffset(cursorOffset{ offset: load.offset, lastConsumedEpoch: load.leaderEpoch, lastConsumedTime: prior.lastConsumedTime, hwm: prior.hwm, }) load.cursor.allowUsable() s.c.usingCursors.use(load.cursor) } _, isDataLoss := errors.AsType[*ErrDataLoss](load.err) switch { case isDataLoss: s.c.addFakeReadyForDraining(load.topic, load.partition, load.err, "notification of data loss") // signal we lost data, but set the cursor to what we can use() case load.err == nil: use() case errors.Is(load.err, errResetAfterUndefinedEpoch): followUps.addLoad(load.topic, load.partition, loadTypeList, load.request) default: // from ErrorCode in a response, or broker request err, or request is canceled as our session is ending reloads.addLoad(load.topic, load.partition, loaded.loadType, load.request) if !kerr.IsRetriable(load.err) && !isRetryableBrokerErr(load.err) && !isDialNonTimeoutErr(load.err) && !isContextErr(load.err) && s.c.cl.ctx.Err() == nil { // non-retryable response error; signal such in a response s.c.addFakeReadyForDraining(load.topic, load.partition, load.err, fmt.Sprintf("notification of non-retryable error from %s request", loaded.loadType)) } if debug { treloading := reloading[load.topic] if treloading == nil { treloading = make(map[int32]epochOffsetWhy) reloading[load.topic] = treloading } treloading[load.partition] = epochOffsetWhy{EpochOffset{load.leaderEpoch, load.offset}, load.err} } } } return reloads, followUps } // Splits the loads into per-broker loads, mapping each partition to the broker // that leads that partition. func (s *consumerSession) mapLoadsToBrokers(loads listOrEpochLoads) map[*broker]listOrEpochLoads { brokerLoads := make(map[*broker]listOrEpochLoads) s.c.cl.brokersMu.RLock() // hold mu so we can check if partition leaders exist defer s.c.cl.brokersMu.RUnlock() brokers := s.c.cl.brokers seed := s.c.cl.loadSeeds()[0] topics := s.tps.load() for _, loads := range []struct { m offsetLoadMap loadType listOrEpochLoadType }{ {loads.List, loadTypeList}, {loads.Epoch, loadTypeEpoch}, } { for topic, partitions := range loads.m { topicPartitions := topics.loadTopic(topic) // this must exist, it not existing would be a bug for partition, offset := range partitions { // We default to the first seed broker if we have no loaded // the broker leader for this partition (we should have). // Worst case, we get an error for the partition and retry. broker := seed if partition >= 0 && partition < int32(len(topicPartitions.partitions)) { topicPartition := topicPartitions.partitions[partition] if tryBroker := findBroker(brokers, topicPartition.leader); tryBroker != nil { broker = tryBroker } offset.currentEpoch = topicPartition.leaderEpoch // ensure we set our latest epoch for the partition } brokerLoad := brokerLoads[broker] brokerLoad.addLoad(topic, partition, loads.loadType, offset) brokerLoads[broker] = brokerLoad } } } return brokerLoads } // The result of ListOffsets or OffsetForLeaderEpoch for an individual // partition. type loadedOffset struct { topic string partition int32 // The following three are potentially unset if the error is non-nil // and not ErrDataLoss; these are what we loaded. cursor *cursor offset int64 leaderEpoch int32 // Any error encountered for loading this partition, or for epoch // loading, potentially ErrDataLoss. If this error is not retryable, we // avoid reloading the offset and instead inject a fake partition for // PollFetches containing this error. err error // The original request. request offsetLoad } // The results of ListOffsets or OffsetForLeaderEpoch for an individual broker. type loadedOffsets struct { broker int32 loaded []loadedOffset loadType listOrEpochLoadType } func (l *loadedOffsets) add(a loadedOffset) { l.loaded = append(l.loaded, a) } func (l *loadedOffsets) addAll(as []loadedOffset) loadedOffsets { l.loaded = append(l.loaded, as...) return *l } // alignListResps prunes two ListOffsets responses to the topics and partitions // they have in common, sorted, so that the same index in either response is the // same partition. A partition erroring in one keeps that error in both. func alignListResps(a, b *kmsg.ListOffsetsResponse) { for _, r := range []*kmsg.ListOffsetsResponse{ a, b, } { ts := r.Topics sort.Slice(ts, func(i, j int) bool { return ts[i].Topic < ts[j].Topic }) for i := range ts { ps := ts[i].Partitions sort.Slice(ps, func(i, j int) bool { return ps[i].Partition < ps[j].Partition }) } } lt := a.Topics rt := b.Topics lkeept := lt[:0] rkeept := rt[:0] // Over each response, we only keep the topic if the topics match. for len(lt) > 0 && len(rt) > 0 { if lt[0].Topic < rt[0].Topic { lt = lt[1:] continue } if rt[0].Topic < lt[0].Topic { rt = rt[1:] continue } // As well, for topics that match, we only keep partitions that // match. In this case, we also want both partitions to be // error free, otherwise we keep an error on both. If one has // old style offsets, both must. lp := lt[0].Partitions rp := rt[0].Partitions lkeepp := lp[:0] rkeepp := rp[:0] for len(lp) > 0 && len(rp) > 0 { if lp[0].Partition < rp[0].Partition { lp = lp[1:] continue } if rp[0].Partition < lp[0].Partition { rp = rp[1:] continue } if len(lp[0].OldStyleOffsets) > 0 && len(rp[0].OldStyleOffsets) == 0 || len(lp[0].OldStyleOffsets) == 0 && len(rp[0].OldStyleOffsets) > 0 { lp = lp[1:] rp = rp[1:] continue } if lp[0].ErrorCode != 0 { rp[0].ErrorCode = lp[0].ErrorCode } else if rp[0].ErrorCode != 0 { lp[0].ErrorCode = rp[0].ErrorCode } lkeepp = append(lkeepp, lp[0]) rkeepp = append(rkeepp, rp[0]) lp = lp[1:] rp = rp[1:] } // Now we update the partitions in the topic we are keeping, // and keep our topic. lt[0].Partitions = lkeepp rt[0].Partitions = rkeepp lkeept = append(lkeept, lt[0]) rkeept = append(rkeept, rt[0]) lt = lt[1:] rt = rt[1:] } // Finally, update each response with the topics we kept. The shapes // and indices are the same. a.Topics = lkeept b.Topics = rkeept } func (cl *Client) listOffsetsForBrokerLoad(ctx context.Context, broker *broker, load offsetLoadMap, tps *topicsPartitions, results chan<- loadedOffsets) { loaded := loadedOffsets{broker: broker.meta.NodeID, loadType: loadTypeList} lookbacks, err := cl.lookbackMillis(ctx, broker, load) if err != nil { results <- loaded.addAll(load.errToLoaded(err)) return } req1, req2, req3 := load.buildListReq(cl.cfg.isolationLevel, cl.cfg.resetOffset, lookbacks) w1 := broker.issue(ctx, req1) var w2, w3 *respWaiter if req2 != nil { w2 = broker.issue(ctx, req2) } if req3 != nil { w3 = broker.issue(ctx, req3) } var ( kresp2 kmsg.Response err2 error kresp3 kmsg.Response err3 error ) kresp, err := w1.wait() if w2 != nil { kresp2, err2 = w2.wait() } if w3 != nil { kresp3, err3 = w3.wait() } if err == nil { err = err2 } if err == nil { err = err3 } if err != nil { results <- loaded.addAll(load.errToLoaded(err)) return } topics := tps.load() resp := kresp.(*kmsg.ListOffsetsResponse) // If we issued a second req to check that an exact offset is in // bounds, then regrettably for safety, we have to ensure that the // shapes of both responses match, and the topic & partition at each // index matches. Anything that does not match is skipped (and would be // a bug from Kafka), and we at the end return UnknownTopicOrPartition. // With a by-time req as well, three pairwise passes leave all three // responses the same shape: the last pass prunes the first response // down to whatever the by-time pass removed from the second. var resp2, resp3 *kmsg.ListOffsetsResponse if req2 != nil { resp2 = kresp2.(*kmsg.ListOffsetsResponse) alignListResps(resp, resp2) } if req3 != nil { resp3 = kresp3.(*kmsg.ListOffsetsResponse) alignListResps(resp2, resp3) alignListResps(resp, resp2) } poffset := func(p *kmsg.ListOffsetsResponseTopicPartition) int64 { offset := p.Offset if len(p.OldStyleOffsets) > 0 { offset = p.OldStyleOffsets[0] // list offsets v0 } return offset } for i, rTopic := range resp.Topics { topic := rTopic.Topic loadParts, ok := load[topic] if !ok { continue // should not happen: kafka replied with something we did not ask for } topicPartitions := topics.loadTopic(topic) // must be non-nil at this point for j, rPartition := range rTopic.Partitions { partition := rPartition.Partition loadPart, ok := loadParts[partition] if !ok { continue // should not happen: kafka replied with something we did not ask for } if err := kerr.ErrorForCode(rPartition.ErrorCode); err != nil { delete(loadParts, partition) if len(loadParts) == 0 { delete(load, topic) } loaded.add(loadedOffset{ topic: topic, partition: partition, err: err, request: loadPart, }) continue // partition err: handled in results } if partition < 0 || partition >= int32(len(topicPartitions.partitions)) { continue // should not happen: we have not seen this partition from a metadata response } topicPartition := topicPartitions.partitions[partition] delete(loadParts, partition) if len(loadParts) == 0 { delete(load, topic) } offset := poffset(&rPartition) epoch := rPartition.LeaderEpoch var err error end := func() (int64, int32) { p := &resp2.Topics[i].Partitions[j] return poffset(p), p.LeaderEpoch } third := func() (int64, int32) { p := &resp3.Topics[i].Partitions[j] return poffset(p), p.LeaderEpoch } // We ensured the resp2 shape is as we want and has no // error, so resp2 lookups are safe. if loadPart.lastConsumedMilli != 0 { n := loadPart.at start, startEpoch := offset, epoch end, endEpoch := end() if n < start { // The broker deleted what we were consuming. Every record left is one we never // consumed, so the start is exact: no policy, and no data loss to report beyond // the warning we already logged. offset, epoch = start, startEpoch } else { // The log shrank below us, at a point we cannot determine: the epoch path either // did not run or could not answer. ConsumeResetOffset decides where we resume, // and we never resume ahead of where we were. An offset we did not list, our own // or one moved by a relative amount, has no epoch to validate against, so it // gets -1. r := cl.cfg.resetOffset switch { case r.at == atLookback: // Keep the last d of the log, even if that is ahead of us. if offset, epoch = third(); offset == -1 { offset, epoch = end, endEpoch } case r.afterMilli || r.at == atRewind: // If the by-time answer is ahead of us, the records between are // stamped older than our last record and we never read them, so // we keep our offset; no answer at all means the same thing. offset, epoch = n, -1 if byTime, byTimeEpoch := third(); byTime >= 0 && byTime <= n { offset, epoch = byTime, byTimeEpoch } case r.at == -2: offset, epoch = start, startEpoch if r.relative != 0 { offset, epoch = offset+r.relative, -1 } case r.at == -1: offset, epoch = end, endEpoch if r.relative != 0 { offset, epoch = offset+r.relative, -1 } default: offset, epoch = r.at+r.relative, -1 } if offset < start { offset, epoch = start, startEpoch } if offset > end { offset, epoch = end, endEpoch } err = &ErrDataLoss{topic, partition, n, loadPart.epoch, offset, epoch} } } else if loadPart.afterMilli || loadPart.at == atLookback { // If after a milli, if the milli is after the // end of a partition, the offset is -1. We use // our end offset request: anything after the // end offset *now* is after our milli. if offset == -1 { offset, epoch = end() } } else if loadPart.at >= 0 { // If an exact offset, we listed start and end. // We validate the offset is within bounds. end, endEpoch := end() want := loadPart.at + loadPart.relative if want >= offset { offset, epoch = want, -1 } if want >= end { offset, epoch = end, endEpoch } } else if loadPart.at == -2 && loadPart.relative > 0 { // Relative to the start: both start & end were // issued, and we bound to the end. offset, epoch = offset+loadPart.relative, -1 if end, endEpoch := end(); offset >= end { offset, epoch = end, endEpoch } } else if loadPart.at == -1 && loadPart.relative < 0 { // Relative to the end: both start & end were // issued, offset is currently the start, so we // set to the end and then bound to the start. start, startEpoch := offset, epoch end, _ := end() offset, epoch = end+loadPart.relative, -1 if offset <= start { offset, epoch = start, startEpoch } } // Every arm above yields a non-negative offset from a // well-behaved broker: by-time listings exist only for // afterMilli and for a reset after consuming, whose -1 // is replaced by the end listing and by the offset we // were at, and the start/end/exact arms bound within // the responses. A negative offset here means the broker // violated the protocol; clamping to 0 (the old // behavior) would silently re-consume the partition // from the start. Surface the misbehavior and retry // the load instead. if offset < 0 { loaded.add(loadedOffset{ topic: topic, partition: partition, err: errNegativeListedOffset, request: loadPart, }) continue } loaded.add(loadedOffset{ topic: topic, partition: partition, cursor: topicPartition.cursor, offset: offset, leaderEpoch: epoch, err: err, request: loadPart, }) } } results <- loaded.addAll(load.errToLoaded(kerr.UnknownTopicOrPartition)) } func (cl *Client) loadEpochsForBrokerLoad(ctx context.Context, broker *broker, load offsetLoadMap, tps *topicsPartitions, results chan<- loadedOffsets) { loaded := loadedOffsets{broker: broker.meta.NodeID, loadType: loadTypeEpoch} kresp, err := broker.waitResp(ctx, load.buildEpochReq()) if err != nil { results <- loaded.addAll(load.errToLoaded(err)) return } // If the negotiated version is < 2, we are speaking to an old broker: // possible mid-roll when metadata (with leader epochs) came from an // upgraded broker while the partition leader is not yet upgraded. The // request then goes out without CurrentLeaderEpoch fencing, and a v0 // response carries no LeaderEpoch (kmsg defaults it to -1). Validation // still compares EndOffset and completes, just unfenced and without // epoch information - a degraded but correct fallback for a window // that only exists rolling from pre-KIP-320 brokers. topics := tps.load() resp := kresp.(*kmsg.OffsetForLeaderEpochResponse) for _, rTopic := range resp.Topics { topic := rTopic.Topic loadParts, ok := load[topic] if !ok { continue // should not happen: kafka replied with something we did not ask for } topicPartitions := topics.loadTopic(topic) // must be non-nil at this point for _, rPartition := range rTopic.Partitions { partition := rPartition.Partition loadPart, ok := loadParts[partition] if !ok { continue // should not happen: kafka replied with something we did not ask for } if err := kerr.ErrorForCode(rPartition.ErrorCode); err != nil { delete(loadParts, partition) if len(loadParts) == 0 { delete(load, topic) } loaded.add(loadedOffset{ topic: topic, partition: partition, err: err, request: loadPart, }) continue // partition err: handled in results } if partition < 0 || partition >= int32(len(topicPartitions.partitions)) { continue // should not happen: we have not seen this partition from a metadata response } topicPartition := topicPartitions.partitions[partition] delete(loadParts, partition) if len(loadParts) == 0 { delete(load, topic) } // Epoch loading never uses noReset nor afterMilli; // this at is the offset we wanted to consume and are // validating. offset := loadPart.at var err error switch { case rPartition.EndOffset < 0: // KIP-320 UNDEFINED_EPOCH_OFFSET: the broker has no record of the epoch we asked about. Its epoch // cache is empty, or ends before the epoch we consumed at: an unclean election to a replica // without history, or a leader that diverged from the one we consumed from. Asking again gets // the same answer, since a leader's cache only gains the epochs it writes itself. We cannot // locate where the log diverged, so we reset exactly as an out of range fetch after consuming // does; see handleReqResp. // // lastConsumedMilli is non-zero only if we consumed something. With nothing consumed there is // no loss to reset from, and with NoResetOffset we never move, so in both cases we keep the // offset we were validating rather than strand the cursor. If that offset is no longer in // the log, the next fetch returns OFFSET_OUT_OF_RANGE and the fetch path handles it. if loadPart.lastConsumedMilli != 0 && !cl.cfg.resetOffset.noReset { loaded.add(loadedOffset{ topic: topic, partition: partition, err: errResetAfterUndefinedEpoch, request: offsetLoad{ lastConsumedMilli: loadPart.lastConsumedMilli, Offset: NewOffset().At(offset).WithEpoch(loadPart.epoch), }, }) continue } case rPartition.EndOffset < offset: err = &ErrDataLoss{topic, partition, offset, loadPart.epoch, rPartition.EndOffset, rPartition.LeaderEpoch} offset = rPartition.EndOffset } loaded.add(loadedOffset{ topic: topic, partition: partition, cursor: topicPartition.cursor, offset: offset, leaderEpoch: rPartition.LeaderEpoch, err: err, request: loadPart, }) } } results <- loaded.addAll(load.errToLoaded(kerr.UnknownTopicOrPartition)) } // lookbackMillis returns the timestamp each LookbackOffset in the load lists // by: the newest record's timestamp minus the duration, from ListOffsets -3 // (v7, KIP-734). A broker without v7 answers -3 as an ordinary timestamp, so // we only ask when the cluster advertises v7, and a broker that still answers // with an error keeps the current time instead. A load with no LookbackOffset // costs one pass over the map. func (cl *Client) lookbackMillis(ctx context.Context, broker *broker, load offsetLoadMap) (map[string]map[int32]int64, error) { lookback := func(l offsetLoad) (Offset, bool) { offset := l.Offset if l.lastConsumedMilli != 0 { offset = cl.cfg.resetOffset } return offset, offset.at == atLookback } var ( lookbacks map[string]map[int32]int64 req *kmsg.ListOffsetsRequest now int64 ) for topic, partitions := range load { for partition, l := range partitions { offset, ok := lookback(l) if !ok { continue } if lookbacks == nil { lookbacks = make(map[string]map[int32]int64) now = time.Now().UnixMilli() if cl.supportsKeyVersion(int16(kmsg.ListOffsets), 7) { req = kmsg.NewPtrListOffsetsRequest() req.ReplicaID = -1 req.IsolationLevel = cl.cfg.isolationLevel } } if lookbacks[topic] == nil { lookbacks[topic] = make(map[int32]int64) if req != nil { t := kmsg.NewListOffsetsRequestTopic() t.Topic = topic req.Topics = append(req.Topics, t) } } lookbacks[topic][partition] = lookbackMilli(now, offset.lookback) if req == nil { continue } p := kmsg.NewListOffsetsRequestTopicPartition() p.Partition = partition p.CurrentLeaderEpoch = l.currentEpoch p.Timestamp = -3 t := &req.Topics[len(req.Topics)-1] t.Partitions = append(t.Partitions, p) } } if req == nil { return lookbacks, nil } kresp, err := broker.waitResp(ctx, req) if err != nil { return nil, err } // A version-capped client, or an older broker mid-roll, negotiates // below v7 and the broker answered -3 as an ordinary timestamp. resp := kresp.(*kmsg.ListOffsetsResponse) if resp.Version < 7 { return lookbacks, nil } for _, t := range resp.Topics { for _, p := range t.Partitions { if offset, ok := lookback(load[t.Topic][p.Partition]); ok && p.ErrorCode == 0 && p.Timestamp >= 0 { lookbacks[t.Topic][p.Partition] = lookbackMilli(p.Timestamp, offset.lookback) } } } return lookbacks, nil } // In general this returns one request, but if the user is using exact offsets // rather than start/end, then we issue both the start and end requests to // ensure the user's requested offset is within bounds. A load resetting after // an out of range fetch also issues a third request, listing by the // millisecond of the last record the cursor consumed. func (o offsetLoadMap) buildListReq(isolationLevel int8, reset Offset, lookbacks map[string]map[int32]int64) (r1, r2, r3 *kmsg.ListOffsetsRequest) { r1 = kmsg.NewPtrListOffsetsRequest() r1.ReplicaID = -1 r1.IsolationLevel = isolationLevel r1.Topics = make([]kmsg.ListOffsetsRequestTopic, 0, len(o)) var createEnd, createByTime bool for topic, partitions := range o { parts := make([]kmsg.ListOffsetsRequestTopicPartition, 0, len(partitions)) for partition, offset := range partitions { // If this is a milli request, we issue two lists: if // our milli is after the end of a partition, we get no // offset back and we want to know the start offset // (since it will be after our milli). // // If we are using an exact offset request, we issue // the start and end so that we can bound the exact // offset to being within that range. // // If we are using a relative offset, we potentially // issue the end request because relative may shift us // too far in the other direction. // // If we are resetting after falling out of range while // consuming, we issue the by-time list as well: we // resume by time, bounded by the start and the end. timestamp := offset.at switch { case offset.at == atLookback: timestamp = lookbacks[topic][partition] createEnd = true case offset.at == atRewind: // nothing consumed, so nothing to rewind from timestamp = -2 case offset.afterMilli: createEnd = true case timestamp >= 0 || timestamp == -2 && offset.relative > 0 || timestamp == -1 && offset.relative < 0: timestamp = -2 createEnd = true } // A reset lists by time only if the policy resuming it needs a // timestamp; AtStart and AtEnd resolve from the other two lists. if offset.lastConsumedMilli != 0 && (reset.afterMilli || reset.at == atRewind || reset.at == atLookback) { createByTime = true } p := kmsg.NewListOffsetsRequestTopicPartition() p.Partition = partition p.CurrentLeaderEpoch = offset.currentEpoch // KIP-320 p.Timestamp = timestamp p.MaxNumOffsets = 1 parts = append(parts, p) } t := kmsg.NewListOffsetsRequestTopic() t.Topic = topic t.Partitions = parts r1.Topics = append(r1.Topics, t) } if createEnd { r2 = kmsg.NewPtrListOffsetsRequest() *r2 = *r1 r2.Topics = slices.Clone(r1.Topics) for i := range r1.Topics { l := &r2.Topics[i] r := &r1.Topics[i] *l = *r l.Partitions = slices.Clone(r.Partitions) for i := range l.Partitions { l.Partitions[i].Timestamp = -1 } } } // A reset after consuming also lists by the last consumed timestamp. // The request keeps every partition in the batch, because // alignListResps prunes a partition that is missing from any one // response. Partitions that are not resetting list the end again, // which we ignore. if createByTime { r3 = kmsg.NewPtrListOffsetsRequest() *r3 = *r1 r3.Topics = slices.Clone(r1.Topics) for i := range r1.Topics { l := &r3.Topics[i] r := &r1.Topics[i] *l = *r l.Partitions = slices.Clone(r.Partitions) for i := range l.Partitions { p := &l.Partitions[i] p.Timestamp = -1 if milli := o[r.Topic][p.Partition].lastConsumedMilli; milli != 0 { p.Timestamp = reset.listMilli(milli) if reset.at == atLookback { p.Timestamp = lookbacks[r.Topic][p.Partition] } } } } } return r1, r2, r3 } func (o offsetLoadMap) buildEpochReq() *kmsg.OffsetForLeaderEpochRequest { req := kmsg.NewPtrOffsetForLeaderEpochRequest() req.ReplicaID = -1 req.Topics = make([]kmsg.OffsetForLeaderEpochRequestTopic, 0, len(o)) for topic, partitions := range o { parts := make([]kmsg.OffsetForLeaderEpochRequestTopicPartition, 0, len(partitions)) for partition, offset := range partitions { p := kmsg.NewOffsetForLeaderEpochRequestTopicPartition() p.Partition = partition p.CurrentLeaderEpoch = offset.currentEpoch p.LeaderEpoch = offset.epoch parts = append(parts, p) } t := kmsg.NewOffsetForLeaderEpochRequestTopic() t.Topic = topic t.Partitions = parts req.Topics = append(req.Topics, t) } return req }