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. |
| 22 | _ event.ValueWatch = &Value{} |
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. |
| 28 | type Value struct { |
| 29 | etcd client.Namespaced |
| 30 | key string |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 31 | keyEnd string |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 32 | decoder BytesDecoder |
| 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. |
| 70 | func NewValue(etcd client.Namespaced, key string, decoder BytesDecoder, options ...*Option) *Value { |
| 71 | res := &Value{ |
| 72 | etcd: etcd, |
| 73 | key: key, |
| 74 | keyEnd: key, |
| 75 | decoder: decoder, |
| 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 | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 87 | // BytesDecoder is a function that converts bytes retrieved from etcd into an |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 88 | // end-user facing value. Additionally, a key is available so that returned |
| 89 | // values can be augmented with the location they were retrieved from. This is |
| 90 | // especially useful when returning values resulting from an etcd range. |
| 91 | // |
| 92 | // If an error is returned, the Get call performed on a watcher configured with |
| 93 | // this decoder will fail, swallowing that particular update, but the watcher |
| 94 | // will continue to work. Any provided BytesDecoder implementations must be safe |
| 95 | // to copy. |
| 96 | type BytesDecoder = func(key []byte, data []byte) (interface{}, error) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 97 | |
| 98 | // NoDecoder is a no-op decoder which passes through the retrieved bytes as a |
| 99 | // []byte type to the user. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 100 | func NoDecoder(key []byte, data []byte) (interface{}, error) { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 101 | return data, nil |
| 102 | } |
| 103 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 104 | func (e *Value) Watch() event.Watcher { |
| 105 | ctx, ctxC := context.WithCancel(context.Background()) |
| 106 | return &watcher{ |
| 107 | Value: *e, |
| 108 | |
| 109 | ctx: ctx, |
| 110 | ctxC: ctxC, |
| 111 | |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 112 | current: make(map[string][]byte), |
| 113 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 114 | getSem: make(chan struct{}, 1), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | type watcher struct { |
| 119 | // Value copy, used to configure the behaviour of this watcher. |
| 120 | Value |
| 121 | |
| 122 | // ctx is the context that expresses the liveness of this watcher. It is |
| 123 | // canceled when the watcher is closed, and the etcd Watch hangs off of it. |
| 124 | ctx context.Context |
| 125 | ctxC context.CancelFunc |
| 126 | |
| 127 | // getSem is a semaphore used to limit concurrent Get calls and throw an |
| 128 | // error if concurrent access is attempted. |
| 129 | getSem chan struct{} |
| 130 | |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 131 | // backlogged is a list of keys retrieved from etcd but not yet returned via |
| 132 | // Get. These items are not a replay of all the updates from etcd, but are |
| 133 | // already compacted to deduplicate updates to the same object (ie., if the |
| 134 | // 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] | 135 | // only contain one update for A and B each, with the first update for A being |
| 136 | // discarded upon arrival of the second update). |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 137 | // |
| 138 | // The keys are an index into the current map, which contains the values |
| 139 | // retrieved, including ones that have already been returned via Get. This |
| 140 | // persistence allows us to deduplicate spurious updates to the user, in which |
| 141 | // etcd returned a new revision of a key, but the data stayed the same. |
| 142 | backlogged [][]byte |
| 143 | // current map, keyed from etcd key into etcd value at said key. This map |
| 144 | // persists alongside an etcd connection, permitting deduplication of spurious |
| 145 | // etcd updates even across multiple Get calls. |
| 146 | current map[string][]byte |
| 147 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 148 | // prev is the etcd store revision of a previously completed etcd Get/Watch |
| 149 | // call, used to resume a Watch call in case of failures. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 150 | prev *int64 |
| 151 | // wc is the etcd watch channel, or nil if no channel is yet open. |
| 152 | wc clientv3.WatchChan |
| 153 | |
| 154 | // testRaceWG is an optional WaitGroup that, if set, will be waited upon |
| 155 | // after the initial KV value retrieval, but before the watch is created. |
| 156 | // This is only used for testing. |
| 157 | testRaceWG *sync.WaitGroup |
| 158 | // testSetupWG is an optional WaitGroup that, if set, will be waited upon |
| 159 | // after the etcd watch is created. |
| 160 | // This is only used for testing. |
| 161 | testSetupWG *sync.WaitGroup |
| 162 | } |
| 163 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 164 | // setup initiates wc (the watch channel from etcd) after retrieving the initial |
| 165 | // value(s) with a get operation. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 166 | func (w *watcher) setup(ctx context.Context) error { |
| 167 | if w.wc != nil { |
| 168 | return nil |
| 169 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 170 | ranged := w.key != w.keyEnd |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 171 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 172 | // First, check if some data under this key/range already exists. |
| 173 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 174 | // We use an exponential backoff and retry here as the initial Get can fail |
| 175 | // if the cluster is unstable (eg. failing over). We only fail the retry if |
| 176 | // the context expires. |
| 177 | bo := backoff.NewExponentialBackOff() |
| 178 | bo.MaxElapsedTime = 0 |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 179 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 180 | err := backoff.Retry(func() error { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 181 | |
| 182 | var getOpts []clientv3.OpOption |
| 183 | if ranged { |
| 184 | getOpts = append(getOpts, clientv3.WithRange(w.keyEnd)) |
| 185 | } |
| 186 | get, err := w.etcd.Get(ctx, w.key, getOpts...) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 187 | if err != nil { |
| 188 | return fmt.Errorf("when retrieving initial value: %w", err) |
| 189 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 190 | |
| 191 | // Assert that the etcd API is behaving as expected. |
| 192 | if !ranged && len(get.Kvs) > 1 { |
| 193 | panic("More than one key returned in unary GET response") |
| 194 | } |
| 195 | |
| 196 | // After a successful Get, save the revision to watch from and re-build the |
| 197 | // backlog from scratch based on what was available in the etcd store at that |
| 198 | // time. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 199 | w.prev = &get.Header.Revision |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 200 | |
| 201 | w.backlogged = nil |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 202 | w.current = make(map[string][]byte) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 203 | for _, kv := range get.Kvs { |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 204 | w.backlogged = append(w.backlogged, kv.Key) |
| 205 | w.current[string(kv.Key)] = kv.Value |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 206 | } |
| 207 | return nil |
| 208 | |
| 209 | }, backoff.WithContext(bo, ctx)) |
| 210 | |
| 211 | if w.testRaceWG != nil { |
| 212 | w.testRaceWG.Wait() |
| 213 | } |
| 214 | if err != nil { |
| 215 | return err |
| 216 | } |
| 217 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 218 | watchOpts := []clientv3.OpOption{ |
| 219 | clientv3.WithRev(*w.prev + 1), |
| 220 | } |
| 221 | if ranged { |
| 222 | watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd)) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 223 | } |
| 224 | w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...) |
| 225 | |
| 226 | if w.testSetupWG != nil { |
| 227 | w.testSetupWG.Wait() |
| 228 | } |
| 229 | return nil |
| 230 | } |
| 231 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 232 | // backfill blocks until a backlog of items is available. An error is returned |
| 233 | // if the context is canceled. |
| 234 | func (w *watcher) backfill(ctx context.Context) error { |
| 235 | // Keep watching for watch events. |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 236 | for { |
| 237 | var resp *clientv3.WatchResponse |
| 238 | select { |
| 239 | case r := <-w.wc: |
| 240 | resp = &r |
| 241 | case <-ctx.Done(): |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 242 | return ctx.Err() |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 243 | } |
| 244 | |
| 245 | if resp.Canceled { |
| 246 | // Only allow for watches to be canceled due to context |
| 247 | // cancellations. Any other error is something we need to handle, |
| 248 | // eg. a client close or compaction error. |
| 249 | if errors.Is(resp.Err(), ctx.Err()) { |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 250 | return fmt.Errorf("watch canceled: %w", resp.Err()) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | // Attempt to reconnect. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 254 | if w.wc != nil { |
| 255 | // If a wc already exists, close it. This forces a reconnection |
| 256 | // by the next setup call. |
| 257 | w.ctxC() |
| 258 | w.ctx, w.ctxC = context.WithCancel(context.Background()) |
| 259 | w.wc = nil |
| 260 | } |
| 261 | if err := w.setup(ctx); err != nil { |
| 262 | return fmt.Errorf("failed to setup watcher: %w", err) |
| 263 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 264 | continue |
| 265 | } |
| 266 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 267 | w.prev = &resp.Header.Revision |
| 268 | // Spurious watch event with no update? Keep trying. |
| 269 | if len(resp.Events) == 0 { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 270 | continue |
| 271 | } |
| 272 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 273 | // Process updates into compacted list, transforming deletions into value: nil |
| 274 | // keyValues. This maps an etcd key into a pointer in the already existing |
| 275 | // backlog list. It will then be used to compact all updates into the smallest |
| 276 | // backlog possible (by overriding previously backlogged items for a key if this |
| 277 | // key is encountered again). |
| 278 | // |
| 279 | // TODO(q3k): this could be stored in the watcher state to not waste time on |
| 280 | // each update, but it's good enough for now. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 281 | for _, ev := range resp.Events { |
| 282 | var value []byte |
| 283 | switch ev.Type { |
| 284 | case clientv3.EventTypeDelete: |
| 285 | case clientv3.EventTypePut: |
| 286 | value = ev.Kv.Value |
| 287 | default: |
| 288 | return fmt.Errorf("invalid event type %v", ev.Type) |
| 289 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 290 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 291 | keyS := string(ev.Kv.Key) |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 292 | prev := w.current[keyS] |
| 293 | if !bytes.Equal(prev, value) { |
| 294 | w.backlogged = append(w.backlogged, ev.Kv.Key) |
| 295 | w.current[keyS] = value |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 296 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 297 | } |
| 298 | |
| 299 | // Still nothing in backlog? Keep trying. |
| 300 | if len(w.backlogged) == 0 { |
| 301 | continue |
| 302 | } |
| 303 | |
| 304 | return nil |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 305 | } |
| 306 | } |
| 307 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 308 | type GetOption struct { |
| 309 | backlogOnly bool |
| 310 | } |
| 311 | |
| 312 | var ( |
| 313 | // BacklogOnly will prevent Get from blocking on waiting for more updates from |
| 314 | // etcd, by instead returning BacklogDone whenever no more data is currently |
| 315 | // locally available. This is different however, from establishing that there |
| 316 | // are no more pending updates from the etcd cluster - the only way to ensure |
| 317 | // the local client is up to date is by performing Get calls without this option |
| 318 | // set. |
| 319 | // |
| 320 | // This mode of retrieval should only be used for the retrieval of the existing |
| 321 | // data in the etcd cluster on the initial creation of the Watcher (by |
| 322 | // repeatedly calling Get until BacklogDone isreturned), and shouldn't be set |
| 323 | // for any subsequent call. Any use of this option after that initial fetch is |
| 324 | // undefined behaviour that exposes the internals of the Get implementation, and |
| 325 | // must not be relied on. However, in the future, this behaviour might be |
| 326 | // formalized. |
| 327 | // |
| 328 | // This mode is particularly useful for ranged watchers. Non-ranged watchers can |
| 329 | // still use this option to distinguish between blocking because of the |
| 330 | // nonexistence of an object vs. blocking because of networking issues. However, |
| 331 | // non-ranged retrieval semantics generally will rarely need to make this |
| 332 | // distinction. |
| 333 | BacklogOnly = GetOption{backlogOnly: true} |
| 334 | |
| 335 | // BacklogDone is returned by Get when BacklogOnly is set and there is no more |
| 336 | // event data stored in the Watcher client, ie. when the initial cluster state |
| 337 | // of the requested key has been retrieved. |
| 338 | BacklogDone = errors.New("no more backlogged data") |
| 339 | ) |
| 340 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 341 | // Get implements the Get method of the Watcher interface. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 342 | // It can return an error in three cases: |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 343 | // - the given context is canceled (in which case, the given error will wrap |
| 344 | // the context error) |
| 345 | // - the watcher's BytesDecoder returned an error (in which case the error |
| 346 | // returned by the BytesDecoder will be returned verbatim) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 347 | // - it has been called with BacklogOnly and the Watcher has no more local |
| 348 | // event data to return (see BacklogOnly for more information on the |
| 349 | // semantics of this mode of operation) |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 350 | // Note that transient and permanent etcd errors are never returned, and the |
| 351 | // Get call will attempt to recover from these errors as much as possible. This |
| 352 | // also means that the user of the Watcher will not be notified if the |
| 353 | // underlying etcd client disconnects from the cluster, or if the cluster loses |
| 354 | // quorum. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 355 | // |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 356 | // TODO(q3k): implement leases to allow clients to be notified when there are |
| 357 | // transient cluster/quorum/partition errors, if needed. |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 358 | // |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 359 | // TODO(q3k): implement internal, limited buffering for backlogged data not yet |
| 360 | // consumed by client, as etcd client library seems to use an unbound buffer in |
| 361 | // case this happens ( see: watcherStream.buf in clientv3). |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 362 | func (w *watcher) Get(ctx context.Context, opts ...event.GetOption) (interface{}, error) { |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 363 | select { |
| 364 | case w.getSem <- struct{}{}: |
| 365 | default: |
| 366 | return nil, fmt.Errorf("cannot Get() concurrently on a single waiter") |
| 367 | } |
| 368 | defer func() { |
| 369 | <-w.getSem |
| 370 | }() |
| 371 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 372 | backlogOnly := false |
| 373 | for _, optI := range opts { |
| 374 | opt, ok := optI.(GetOption) |
| 375 | if !ok { |
| 376 | return nil, fmt.Errorf("get options must be of type etcd.GetOption") |
| 377 | } |
| 378 | if opt.backlogOnly { |
| 379 | backlogOnly = true |
| 380 | } |
| 381 | } |
| 382 | |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 383 | // Early check for context cancelations, preventing spurious contact with etcd |
| 384 | // if there's no need to. |
| 385 | if w.ctx.Err() != nil { |
| 386 | return nil, w.ctx.Err() |
| 387 | } |
| 388 | |
| 389 | if err := w.setup(ctx); err != nil { |
| 390 | return nil, fmt.Errorf("when setting up watcher: %w", err) |
| 391 | } |
| 392 | |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 393 | if backlogOnly && len(w.backlogged) == 0 { |
| 394 | return nil, BacklogDone |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 395 | } |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 396 | |
| 397 | // Update backlog from etcd if needed. |
| 398 | if len(w.backlogged) < 1 { |
| 399 | err := w.backfill(ctx) |
| 400 | if err != nil { |
| 401 | return nil, fmt.Errorf("when watching for new value: %w", err) |
| 402 | } |
| 403 | } |
| 404 | // Backlog is now guaranteed to contain at least one element. |
| 405 | |
| 406 | ranged := w.key != w.keyEnd |
| 407 | if !ranged { |
| 408 | // For non-ranged queries, drain backlog fully. |
| 409 | if len(w.backlogged) != 1 { |
Serge Bazanski | 9d97118 | 2022-06-23 17:44:13 +0200 | [diff] [blame] | 410 | panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged)) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 411 | } |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 412 | k := w.backlogged[0] |
| 413 | v := w.current[string(k)] |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 414 | w.backlogged = nil |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 415 | return w.decoder(k, v) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 416 | } else { |
| 417 | // For ranged queries, pop one ranged query off the backlog. |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 418 | k := w.backlogged[0] |
| 419 | v := w.current[string(k)] |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 420 | w.backlogged = w.backlogged[1:] |
Serge Bazanski | 832bc77 | 2022-04-07 12:33:01 +0200 | [diff] [blame] | 421 | return w.decoder(k, v) |
Serge Bazanski | 8d45a05 | 2021-10-18 17:24:24 +0200 | [diff] [blame] | 422 | } |
Serge Bazanski | c89df2f | 2021-04-27 15:51:37 +0200 | [diff] [blame] | 423 | } |
| 424 | |
| 425 | func (w *watcher) Close() error { |
| 426 | w.ctxC() |
| 427 | return nil |
| 428 | } |