Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 1 | package etcd |
| 2 | |
| 3 | import ( |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 4 | "bytes" |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "sync" |
| 9 | |
| 10 | "github.com/cenkalti/backoff/v4" |
Lorenz Brun | d13c1c6 | 2022-03-30 19:58:58 +0200 | [diff] [blame] | 11 | clientv3 "go.etcd.io/etcd/client/v3" |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 12 | |
| 13 | "source.monogon.dev/metropolis/node/core/consensus/client" |
| 14 | "source.monogon.dev/metropolis/pkg/event" |
| 15 | ) |
| 16 | |
| 17 | var ( |
Serge Bazanski | fac8b2e | 2021-05-04 12:23:26 +0200 | [diff] [blame] | 18 | // Type assert that *Value implements event.ValueWatcher. We do this |
| 19 | // artificially, as there currently is no code path that needs this to be |
| 20 | // strictly true. However, users of this library might want to rely on the |
| 21 | // Value type instead of particular Value implementations. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 22 | _ event.ValueWatch[StringAt] = &Value[StringAt]{} |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 23 | ) |
| 24 | |
| 25 | // Value is an 'Event Value' backed in an etcd cluster, accessed over an |
| 26 | // etcd client. This is a stateless handle and can be copied and shared across |
| 27 | // goroutines. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 28 | type Value[T any] struct { |
| 29 | decoder func(key, value []byte) (T, error) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 30 | etcd client.Namespaced |
| 31 | key string |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 32 | keyEnd string |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 33 | } |
| 34 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 35 | type Option struct { |
| 36 | rangeEnd string |
| 37 | } |
| 38 | |
| 39 | // Range creates a Value that is backed a range of etcd key/value pairs from |
| 40 | // 'key' passed to NewValue to 'end' passed to Range. |
| 41 | // |
| 42 | // The key range semantics (ie. lexicographic ordering) are the same as in etcd |
| 43 | // ranges, so for example to retrieve all keys prefixed by `foo/` key should be |
| 44 | // `foo/` and end should be `foo0`. |
| 45 | // |
| 46 | // For any update in the given range, the decoder will be called and its result |
| 47 | // will trigger the return of a Get() call. The decoder should return a type |
| 48 | // that lets the user distinguish which of the multiple objects in the range got |
| 49 | // updated, as the Get() call returns no additional information about the |
| 50 | // location of the retrieved object by itself. |
| 51 | // |
| 52 | // The order of values retrieved by Get() is currently fully arbitrary and must |
| 53 | // not be relied on. It's possible that in the future the order of updates and |
| 54 | // the blocking behaviour of Get will be formalized, but this is not yet the |
| 55 | // case. Instead, the data returned should be treated as eventually consistent |
| 56 | // with the etcd state. |
| 57 | // |
| 58 | // For some uses, it might be necessary to first retrieve all the objects |
| 59 | // contained within the range before starting to block on updates - in this |
| 60 | // case, the BacklogOnly option should be used when calling Get. |
| 61 | func Range(end string) *Option { |
| 62 | return &Option{ |
| 63 | rangeEnd: end, |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 64 | } |
| 65 | } |
| 66 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 67 | // NewValue creates a new Value for a given key(s) in an etcd client. The |
| 68 | // given decoder will be used to convert bytes retrieved from etcd into the |
| 69 | // interface{} value retrieved by Get by this value's watcher. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 70 | func NewValue[T any](etcd client.Namespaced, key string, decoder func(key, value []byte) (T, error), options ...*Option) *Value[T] { |
| 71 | res := &Value[T]{ |
| 72 | decoder: decoder, |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 73 | etcd: etcd, |
| 74 | key: key, |
| 75 | keyEnd: key, |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 76 | } |
| 77 | |
| 78 | for _, opt := range options { |
| 79 | if end := opt.rangeEnd; end != "" { |
| 80 | res.keyEnd = end |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return res |
| 85 | } |
| 86 | |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 87 | func DecoderNoop(_, value []byte) ([]byte, error) { |
| 88 | return value, nil |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 89 | } |
| 90 | |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 91 | func DecoderStringAt(key, value []byte) (StringAt, error) { |
| 92 | return StringAt{ |
| 93 | Key: string(key), |
| 94 | Value: string(value), |
| 95 | }, nil |
| 96 | } |
| 97 | |
| 98 | type StringAt struct { |
| 99 | Key string |
| 100 | Value string |
| 101 | } |
| 102 | |
| 103 | func (e *Value[T]) Watch() event.Watcher[T] { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 104 | ctx, ctxC := context.WithCancel(context.Background()) |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 105 | return &watcher[T]{ |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 106 | Value: *e, |
| 107 | |
| 108 | ctx: ctx, |
| 109 | ctxC: ctxC, |
| 110 | |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 111 | current: make(map[string][]byte), |
| 112 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 113 | getSem: make(chan struct{}, 1), |
| 114 | } |
| 115 | } |
| 116 | |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 117 | type watcher[T any] struct { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 118 | // Value copy, used to configure the behaviour of this watcher. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 119 | Value[T] |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 120 | |
| 121 | // ctx is the context that expresses the liveness of this watcher. It is |
| 122 | // canceled when the watcher is closed, and the etcd Watch hangs off of it. |
| 123 | ctx context.Context |
| 124 | ctxC context.CancelFunc |
| 125 | |
| 126 | // getSem is a semaphore used to limit concurrent Get calls and throw an |
| 127 | // error if concurrent access is attempted. |
| 128 | getSem chan struct{} |
| 129 | |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 130 | // backlogged is a list of keys retrieved from etcd but not yet returned via |
| 131 | // Get. These items are not a replay of all the updates from etcd, but are |
| 132 | // already compacted to deduplicate updates to the same object (ie., if the |
| 133 | // update stream from etcd is for keys A, B, and A, the backlogged list will |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 134 | // only contain one update for A and B each, with the first update for A being |
| 135 | // discarded upon arrival of the second update). |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 136 | // |
| 137 | // The keys are an index into the current map, which contains the values |
| 138 | // retrieved, including ones that have already been returned via Get. This |
| 139 | // persistence allows us to deduplicate spurious updates to the user, in which |
| 140 | // etcd returned a new revision of a key, but the data stayed the same. |
| 141 | backlogged [][]byte |
| 142 | // current map, keyed from etcd key into etcd value at said key. This map |
| 143 | // persists alongside an etcd connection, permitting deduplication of spurious |
| 144 | // etcd updates even across multiple Get calls. |
| 145 | current map[string][]byte |
| 146 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 147 | // prev is the etcd store revision of a previously completed etcd Get/Watch |
| 148 | // call, used to resume a Watch call in case of failures. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 149 | prev *int64 |
| 150 | // wc is the etcd watch channel, or nil if no channel is yet open. |
| 151 | wc clientv3.WatchChan |
| 152 | |
| 153 | // testRaceWG is an optional WaitGroup that, if set, will be waited upon |
| 154 | // after the initial KV value retrieval, but before the watch is created. |
| 155 | // This is only used for testing. |
| 156 | testRaceWG *sync.WaitGroup |
| 157 | // testSetupWG is an optional WaitGroup that, if set, will be waited upon |
| 158 | // after the etcd watch is created. |
| 159 | // This is only used for testing. |
| 160 | testSetupWG *sync.WaitGroup |
| 161 | } |
| 162 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 163 | // setup initiates wc (the watch channel from etcd) after retrieving the initial |
| 164 | // value(s) with a get operation. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 165 | func (w *watcher[T]) setup(ctx context.Context) error { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 166 | if w.wc != nil { |
| 167 | return nil |
| 168 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 169 | ranged := w.key != w.keyEnd |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 170 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 171 | // First, check if some data under this key/range already exists. |
| 172 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 173 | // We use an exponential backoff and retry here as the initial Get can fail |
| 174 | // if the cluster is unstable (eg. failing over). We only fail the retry if |
| 175 | // the context expires. |
| 176 | bo := backoff.NewExponentialBackOff() |
| 177 | bo.MaxElapsedTime = 0 |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 178 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 179 | err := backoff.Retry(func() error { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 180 | |
| 181 | var getOpts []clientv3.OpOption |
| 182 | if ranged { |
| 183 | getOpts = append(getOpts, clientv3.WithRange(w.keyEnd)) |
| 184 | } |
| 185 | get, err := w.etcd.Get(ctx, w.key, getOpts...) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 186 | if err != nil { |
| 187 | return fmt.Errorf("when retrieving initial value: %w", err) |
| 188 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 189 | |
| 190 | // Assert that the etcd API is behaving as expected. |
| 191 | if !ranged && len(get.Kvs) > 1 { |
| 192 | panic("More than one key returned in unary GET response") |
| 193 | } |
| 194 | |
| 195 | // After a successful Get, save the revision to watch from and re-build the |
| 196 | // backlog from scratch based on what was available in the etcd store at that |
| 197 | // time. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 198 | w.prev = &get.Header.Revision |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 199 | |
| 200 | w.backlogged = nil |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 201 | w.current = make(map[string][]byte) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 202 | for _, kv := range get.Kvs { |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 203 | w.backlogged = append(w.backlogged, kv.Key) |
| 204 | w.current[string(kv.Key)] = kv.Value |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 205 | } |
| 206 | return nil |
| 207 | |
| 208 | }, backoff.WithContext(bo, ctx)) |
| 209 | |
| 210 | if w.testRaceWG != nil { |
| 211 | w.testRaceWG.Wait() |
| 212 | } |
| 213 | if err != nil { |
| 214 | return err |
| 215 | } |
| 216 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 217 | watchOpts := []clientv3.OpOption{ |
| 218 | clientv3.WithRev(*w.prev + 1), |
| 219 | } |
| 220 | if ranged { |
| 221 | watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd)) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 222 | } |
| 223 | w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...) |
| 224 | |
| 225 | if w.testSetupWG != nil { |
| 226 | w.testSetupWG.Wait() |
| 227 | } |
| 228 | return nil |
| 229 | } |
| 230 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 231 | // backfill blocks until a backlog of items is available. An error is returned |
| 232 | // if the context is canceled. |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 233 | func (w *watcher[T]) backfill(ctx context.Context) error { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 234 | // Keep watching for watch events. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 235 | for { |
| 236 | var resp *clientv3.WatchResponse |
| 237 | select { |
| 238 | case r := <-w.wc: |
| 239 | resp = &r |
| 240 | case <-ctx.Done(): |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 241 | return ctx.Err() |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 242 | } |
| 243 | |
| 244 | if resp.Canceled { |
| 245 | // Only allow for watches to be canceled due to context |
| 246 | // cancellations. Any other error is something we need to handle, |
| 247 | // eg. a client close or compaction error. |
| 248 | if errors.Is(resp.Err(), ctx.Err()) { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 249 | return fmt.Errorf("watch canceled: %w", resp.Err()) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 250 | } |
| 251 | |
| 252 | // Attempt to reconnect. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 253 | if w.wc != nil { |
| 254 | // If a wc already exists, close it. This forces a reconnection |
| 255 | // by the next setup call. |
| 256 | w.ctxC() |
| 257 | w.ctx, w.ctxC = context.WithCancel(context.Background()) |
| 258 | w.wc = nil |
| 259 | } |
| 260 | if err := w.setup(ctx); err != nil { |
| 261 | return fmt.Errorf("failed to setup watcher: %w", err) |
| 262 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 263 | continue |
| 264 | } |
| 265 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 266 | w.prev = &resp.Header.Revision |
| 267 | // Spurious watch event with no update? Keep trying. |
| 268 | if len(resp.Events) == 0 { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 269 | continue |
| 270 | } |
| 271 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 272 | // Process updates into compacted list, transforming deletions into value: nil |
| 273 | // keyValues. This maps an etcd key into a pointer in the already existing |
| 274 | // backlog list. It will then be used to compact all updates into the smallest |
| 275 | // backlog possible (by overriding previously backlogged items for a key if this |
| 276 | // key is encountered again). |
| 277 | // |
| 278 | // TODO(q3k): this could be stored in the watcher state to not waste time on |
| 279 | // each update, but it's good enough for now. |
Serge Bazanski | bbb873d | 2022-06-24 14:22:39 +0200 | [diff] [blame] | 280 | |
| 281 | // Prepare a set of keys that already exist in the backlog. This will be used |
| 282 | // to make sure we don't duplicate backlog entries while maintaining a stable |
| 283 | // backlog order. |
| 284 | seen := make(map[string]bool) |
| 285 | for _, k := range w.backlogged { |
| 286 | seen[string(k)] = true |
| 287 | } |
| 288 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 289 | for _, ev := range resp.Events { |
| 290 | var value []byte |
| 291 | switch ev.Type { |
| 292 | case clientv3.EventTypeDelete: |
| 293 | case clientv3.EventTypePut: |
| 294 | value = ev.Kv.Value |
| 295 | default: |
| 296 | return fmt.Errorf("invalid event type %v", ev.Type) |
| 297 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 298 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 299 | keyS := string(ev.Kv.Key) |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 300 | prev := w.current[keyS] |
Serge Bazanski | bbb873d | 2022-06-24 14:22:39 +0200 | [diff] [blame] | 301 | // Short-circuit and skip updates with the same content as already present. |
| 302 | // These are sometimes emitted by etcd. |
| 303 | if bytes.Equal(prev, value) { |
| 304 | continue |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 305 | } |
Serge Bazanski | bbb873d | 2022-06-24 14:22:39 +0200 | [diff] [blame] | 306 | |
| 307 | // Only insert to backlog if not yet present, but maintain order. |
| 308 | if !seen[string(ev.Kv.Key)] { |
| 309 | w.backlogged = append(w.backlogged, ev.Kv.Key) |
| 310 | seen[string(ev.Kv.Key)] = true |
| 311 | } |
| 312 | // Regardless of backlog list, always update the key to its newest value. |
| 313 | w.current[keyS] = value |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 314 | } |
| 315 | |
| 316 | // Still nothing in backlog? Keep trying. |
| 317 | if len(w.backlogged) == 0 { |
| 318 | continue |
| 319 | } |
| 320 | |
| 321 | return nil |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 322 | } |
| 323 | } |
| 324 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 325 | type GetOption struct { |
| 326 | backlogOnly bool |
| 327 | } |
| 328 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 329 | // Get implements the Get method of the Watcher interface. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 330 | // It can return an error in three cases: |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 331 | // - the given context is canceled (in which case, the given error will wrap |
| 332 | // the context error) |
| 333 | // - the watcher's BytesDecoder returned an error (in which case the error |
| 334 | // returned by the BytesDecoder will be returned verbatim) |
| 335 | // - it has been called with BacklogOnly and the Watcher has no more local |
| 336 | // event data to return (see BacklogOnly for more information on the |
| 337 | // semantics of this mode of operation) |
| 338 | // |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 339 | // Note that transient and permanent etcd errors are never returned, and the |
| 340 | // Get call will attempt to recover from these errors as much as possible. This |
| 341 | // also means that the user of the Watcher will not be notified if the |
| 342 | // underlying etcd client disconnects from the cluster, or if the cluster loses |
| 343 | // quorum. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 344 | // |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 345 | // TODO(q3k): implement leases to allow clients to be notified when there are |
| 346 | // transient cluster/quorum/partition errors, if needed. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 347 | // |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 348 | // TODO(q3k): implement internal, limited buffering for backlogged data not yet |
| 349 | // consumed by client, as etcd client library seems to use an unbound buffer in |
| 350 | // case this happens ( see: watcherStream.buf in clientv3). |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 351 | func (w *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) { |
| 352 | var empty T |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 353 | select { |
| 354 | case w.getSem <- struct{}{}: |
| 355 | default: |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 356 | return empty, fmt.Errorf("cannot Get() concurrently on a single waiter") |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 357 | } |
| 358 | defer func() { |
| 359 | <-w.getSem |
| 360 | }() |
| 361 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 362 | backlogOnly := false |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 363 | var predicate func(t T) bool |
| 364 | for _, opt := range opts { |
| 365 | if opt.Predicate != nil { |
| 366 | predicate = opt.Predicate |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 367 | } |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 368 | if opt.BacklogOnly { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 369 | backlogOnly = true |
| 370 | } |
| 371 | } |
| 372 | |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 373 | ranged := w.key != w.keyEnd |
| 374 | if ranged && predicate != nil { |
| 375 | return empty, errors.New("filtering unimplemented for ranged etcd values") |
| 376 | } |
| 377 | if backlogOnly && predicate != nil { |
| 378 | return empty, errors.New("filtering unimplemented for backlog-only requests") |
| 379 | } |
| 380 | |
| 381 | for { |
| 382 | v, err := w.getUnlocked(ctx, ranged, backlogOnly) |
| 383 | if err != nil { |
| 384 | return empty, err |
| 385 | } |
| 386 | if predicate == nil || predicate(v) { |
| 387 | return v, nil |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | func (w *watcher[T]) getUnlocked(ctx context.Context, ranged, backlogOnly bool) (T, error) { |
| 393 | var empty T |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 394 | // Early check for context cancelations, preventing spurious contact with etcd |
| 395 | // if there's no need to. |
| 396 | if w.ctx.Err() != nil { |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 397 | return empty, w.ctx.Err() |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 398 | } |
| 399 | |
| 400 | if err := w.setup(ctx); err != nil { |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 401 | return empty, fmt.Errorf("when setting up watcher: %w", err) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 402 | } |
| 403 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 404 | if backlogOnly && len(w.backlogged) == 0 { |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 405 | return empty, event.BacklogDone |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 406 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 407 | |
| 408 | // Update backlog from etcd if needed. |
| 409 | if len(w.backlogged) < 1 { |
| 410 | err := w.backfill(ctx) |
| 411 | if err != nil { |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 412 | return empty, fmt.Errorf("when watching for new value: %w", err) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 413 | } |
| 414 | } |
| 415 | // Backlog is now guaranteed to contain at least one element. |
| 416 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 417 | if !ranged { |
| 418 | // For non-ranged queries, drain backlog fully. |
| 419 | if len(w.backlogged) != 1 { |
Serge Bazanski | 9d97118 | 2022-06-23 17:44:13 +0200 | [diff] [blame] | 420 | panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged)) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 421 | } |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 422 | k := w.backlogged[0] |
| 423 | v := w.current[string(k)] |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 424 | w.backlogged = nil |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 425 | return w.decoder(k, v) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 426 | } else { |
| 427 | // For ranged queries, pop one ranged query off the backlog. |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 428 | k := w.backlogged[0] |
| 429 | v := w.current[string(k)] |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 430 | w.backlogged = w.backlogged[1:] |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 431 | return w.decoder(k, v) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 432 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 433 | } |
| 434 | |
Serge Bazanski | 37110c3 | 2023-03-01 13:57:27 +0000 | [diff] [blame^] | 435 | func (w *watcher[T]) Close() error { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 436 | w.ctxC() |
| 437 | return nil |
| 438 | } |