|
| 1 | +// Copyright (c) 2026 Uber Technologies, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package consumer |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "sync" |
| 20 | + "time" |
| 21 | + |
| 22 | + "github.com/uber-go/tally" |
| 23 | + "github.com/uber/submitqueue/platform/extension/consumergate" |
| 24 | + extqueue "github.com/uber/submitqueue/platform/extension/messagequeue" |
| 25 | + "github.com/uber/submitqueue/platform/metrics" |
| 26 | + "go.uber.org/zap" |
| 27 | +) |
| 28 | + |
| 29 | +// Option configures optional consumer behavior at construction time. |
| 30 | +type Option func(*consumer) |
| 31 | + |
| 32 | +// WithGate installs the consumer-gate middleware: before each delivery reaches |
| 33 | +// its controller, the middleware consults gate state for the controller's |
| 34 | +// consumer group (and the delivery's partition) and parks the delivery while |
| 35 | +// the gate is closed. When no gate is configured, the middleware is absent and |
| 36 | +// the consumer behaves exactly as without it. See |
| 37 | +// platform/extension/consumergate and doc/rfc/consumer-gate.md. |
| 38 | +func WithGate(gate consumergate.Gate, cfg consumergate.Config) Option { |
| 39 | + return func(c *consumer) { |
| 40 | + def := consumergate.DefaultConfig() |
| 41 | + if cfg.RefreshIntervalMs <= 0 { |
| 42 | + cfg.RefreshIntervalMs = def.RefreshIntervalMs |
| 43 | + } |
| 44 | + if cfg.ParkExtensionMs <= 0 { |
| 45 | + cfg.ParkExtensionMs = def.ParkExtensionMs |
| 46 | + } |
| 47 | + c.gate = &gateMiddleware{ |
| 48 | + gate: gate, |
| 49 | + refreshInterval: time.Duration(cfg.RefreshIntervalMs) * time.Millisecond, |
| 50 | + parkExtensionMs: cfg.ParkExtensionMs, |
| 51 | + logger: c.logger.Named("consumer_gate"), |
| 52 | + scope: c.metricsScope.SubScope("gate"), |
| 53 | + cache: make(map[gateCacheKey]gateCacheEntry), |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// gateMiddleware parks deliveries whose controller's gate is closed. It sits |
| 59 | +// between the partition dispatch and the controller: dispatch is serial per |
| 60 | +// partition, so holding one delivery blocks exactly that partition; ack/nack |
| 61 | +// belong to the framework, so a delivery is held simply by not yet invoking |
| 62 | +// the controller. Stopping is a barrier, not preemption — a message already |
| 63 | +// inside Process when a gate closes runs to completion. |
| 64 | +type gateMiddleware struct { |
| 65 | + gate consumergate.Gate |
| 66 | + refreshInterval time.Duration |
| 67 | + parkExtensionMs int64 |
| 68 | + logger *zap.SugaredLogger |
| 69 | + scope tally.Scope |
| 70 | + |
| 71 | + // cache holds the last gate verdict per (consumer group, partition), |
| 72 | + // refreshed at most once per refreshInterval. The middleware therefore does |
| 73 | + // not hit the gate medium per message, and a parked delivery re-checks on |
| 74 | + // the same tick cadence. |
| 75 | + mu sync.Mutex |
| 76 | + cache map[gateCacheKey]gateCacheEntry |
| 77 | +} |
| 78 | + |
| 79 | +// gateCacheKey identifies one cached gate verdict. |
| 80 | +type gateCacheKey struct { |
| 81 | + consumerGroup string |
| 82 | + partitionKey string |
| 83 | +} |
| 84 | + |
| 85 | +// gateCacheEntry is a cached gate verdict and when it was read. |
| 86 | +type gateCacheEntry struct { |
| 87 | + gated bool |
| 88 | + at time.Time |
| 89 | +} |
| 90 | + |
| 91 | +// hold blocks while the controller's gate is closed for the delivery's |
| 92 | +// partition. It returns true when the delivery may proceed into the |
| 93 | +// controller, and false when the consumer is shutting down while parked — in |
| 94 | +// that case the caller must not process, ack, or nack: extension stops, |
| 95 | +// visibility lapses, and the queue redelivers normally. |
| 96 | +func (g *gateMiddleware) hold(ctx context.Context, controller Controller, delivery extqueue.Delivery) bool { |
| 97 | + const opName = "hold" |
| 98 | + |
| 99 | + consumerGroup := controller.ConsumerGroup() |
| 100 | + msg := delivery.Message() |
| 101 | + |
| 102 | + if !g.isGated(ctx, consumerGroup, msg.PartitionKey) { |
| 103 | + return true |
| 104 | + } |
| 105 | + |
| 106 | + // Record the parked delivery before blocking: the record is the observable |
| 107 | + // proof that the gate caught exactly this message. |
| 108 | + topicName := controller.TopicKey().String() |
| 109 | + parked := consumergate.Parked{ |
| 110 | + ConsumerGroup: consumerGroup, |
| 111 | + Topic: topicName, |
| 112 | + MessageID: msg.ID, |
| 113 | + PartitionKey: msg.PartitionKey, |
| 114 | + Payload: msg.Payload, |
| 115 | + Attempt: delivery.Attempt(), |
| 116 | + ParkedAtMs: time.Now().UnixMilli(), |
| 117 | + } |
| 118 | + if err := g.gate.RecordParked(ctx, parked); err != nil { |
| 119 | + metrics.NamedCounter(g.scope, opName, "park_record_errors", 1) |
| 120 | + g.logger.Errorw("failed to record parked delivery", |
| 121 | + "consumer_group", consumerGroup, |
| 122 | + "topic", topicName, |
| 123 | + "message_id", msg.ID, |
| 124 | + "error", err, |
| 125 | + ) |
| 126 | + } |
| 127 | + |
| 128 | + metrics.NamedCounter(g.scope, opName, "parked", 1) |
| 129 | + g.logger.Infow("delivery parked by consumer gate", |
| 130 | + "consumer_group", consumerGroup, |
| 131 | + "topic", topicName, |
| 132 | + "message_id", msg.ID, |
| 133 | + "partition_key", msg.PartitionKey, |
| 134 | + "attempt", delivery.Attempt(), |
| 135 | + ) |
| 136 | + |
| 137 | + ticker := time.NewTicker(g.refreshInterval) |
| 138 | + defer ticker.Stop() |
| 139 | + for { |
| 140 | + select { |
| 141 | + case <-ctx.Done(): |
| 142 | + // Shutdown while parked: leave the delivery in-flight and let the |
| 143 | + // visibility timeout lapse into a normal redelivery. |
| 144 | + metrics.NamedCounter(g.scope, opName, "shutdown_while_parked", 1) |
| 145 | + return false |
| 146 | + case <-ticker.C: |
| 147 | + } |
| 148 | + |
| 149 | + // Keep the parked delivery in-flight. ExtendVisibilityTimeout does not |
| 150 | + // increment the retry count, so parking never burns retry budget. |
| 151 | + if err := delivery.ExtendVisibilityTimeout(ctx, g.parkExtensionMs); err != nil { |
| 152 | + metrics.NamedCounter(g.scope, opName, "extend_errors", 1) |
| 153 | + g.logger.Errorw("failed to extend visibility of parked delivery", |
| 154 | + "consumer_group", consumerGroup, |
| 155 | + "topic", topicName, |
| 156 | + "message_id", msg.ID, |
| 157 | + "error", err, |
| 158 | + ) |
| 159 | + } |
| 160 | + |
| 161 | + if g.isGated(ctx, consumerGroup, msg.PartitionKey) { |
| 162 | + continue |
| 163 | + } |
| 164 | + |
| 165 | + if err := g.gate.RecordReleased(ctx, consumerGroup, topicName, msg.ID, time.Now().UnixMilli()); err != nil { |
| 166 | + metrics.NamedCounter(g.scope, opName, "release_record_errors", 1) |
| 167 | + g.logger.Errorw("failed to record released delivery", |
| 168 | + "consumer_group", consumerGroup, |
| 169 | + "topic", topicName, |
| 170 | + "message_id", msg.ID, |
| 171 | + "error", err, |
| 172 | + ) |
| 173 | + } |
| 174 | + metrics.NamedCounter(g.scope, opName, "released", 1) |
| 175 | + g.logger.Infow("parked delivery released by consumer gate", |
| 176 | + "consumer_group", consumerGroup, |
| 177 | + "topic", topicName, |
| 178 | + "message_id", msg.ID, |
| 179 | + "partition_key", msg.PartitionKey, |
| 180 | + ) |
| 181 | + return true |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +// isGated returns the cached gate verdict for the group/partition, refreshing |
| 186 | +// it from the gate medium when older than the refresh interval. Read failures |
| 187 | +// fail open: gating is auxiliary, and a broken gate medium must not become a |
| 188 | +// pipeline stall — the failure is surfaced via log and counter instead. |
| 189 | +func (g *gateMiddleware) isGated(ctx context.Context, consumerGroup, partitionKey string) bool { |
| 190 | + key := gateCacheKey{consumerGroup: consumerGroup, partitionKey: partitionKey} |
| 191 | + now := time.Now() |
| 192 | + |
| 193 | + g.mu.Lock() |
| 194 | + entry, ok := g.cache[key] |
| 195 | + g.mu.Unlock() |
| 196 | + if ok && now.Sub(entry.at) < g.refreshInterval { |
| 197 | + return entry.gated |
| 198 | + } |
| 199 | + |
| 200 | + gated, err := g.gate.IsGated(ctx, consumerGroup, partitionKey) |
| 201 | + if err != nil { |
| 202 | + metrics.NamedCounter(g.scope, "check", "read_errors", 1) |
| 203 | + g.logger.Errorw("failed to read gate state, failing open", |
| 204 | + "consumer_group", consumerGroup, |
| 205 | + "partition_key", partitionKey, |
| 206 | + "error", err, |
| 207 | + ) |
| 208 | + gated = false |
| 209 | + } |
| 210 | + |
| 211 | + // Cache the verdict — including the fail-open one, so a broken medium is |
| 212 | + // re-probed once per interval rather than once per message. |
| 213 | + g.mu.Lock() |
| 214 | + g.cache[key] = gateCacheEntry{gated: gated, at: now} |
| 215 | + g.mu.Unlock() |
| 216 | + |
| 217 | + return gated |
| 218 | +} |
0 commit comments