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