| | | 1 | | #nullable enable |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Concurrent; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using dotnet_etcd.interfaces; |
| | | 9 | | using Etcdserverpb; |
| | | 10 | | using Google.Protobuf; |
| | | 11 | | using Grpc.Core; |
| | | 12 | | using Mvccpb; |
| | | 13 | | |
| | | 14 | | namespace dotnet_etcd; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Manages watch streams and provides a way to cancel watches |
| | | 18 | | /// </summary> |
| | | 19 | | public class WatchManager : IWatchManager |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// How long to wait for etcd to acknowledge a watch before giving up. Generous, because the |
| | | 23 | | /// stream may have to reconnect (e.g. the server is restarting) before the create is accepted. |
| | | 24 | | /// </summary> |
| | 2 | 25 | | private static readonly TimeSpan CreateWatchTimeout = TimeSpan.FromSeconds(30); |
| | | 26 | | |
| | 360 | 27 | | private readonly object _lockObject = new(); |
| | 360 | 28 | | private readonly ConcurrentDictionary<long, WatchCancellation> _watches = new(); |
| | 360 | 29 | | private readonly ConcurrentDictionary<long, long> _watchIdMapping = new(); |
| | | 30 | | |
| | | 31 | | /// <summary>Watches whose create request is still awaiting the server's Created acknowledgement.</summary> |
| | 360 | 32 | | private readonly ConcurrentDictionary<long, TaskCompletionSource<WatchResponse>> _pendingCreates = new(); |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Tail of the callback chain. Every response is appended to this single chain so user |
| | | 36 | | /// callbacks run off the receive loop but remain serialized and ordered, as they were when the |
| | | 37 | | /// loop invoked them inline. Note a slow callback queues responses without bound — callbacks |
| | | 38 | | /// must not block indefinitely. |
| | | 39 | | /// </summary> |
| | 360 | 40 | | private readonly object _dispatchLock = new(); |
| | | 41 | | |
| | 360 | 42 | | private Task _dispatchChain = Task.CompletedTask; |
| | | 43 | | |
| | | 44 | | private readonly |
| | | 45 | | Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>> |
| | | 46 | | _watchStreamFactory; |
| | | 47 | | |
| | | 48 | | private bool _disposed; |
| | 360 | 49 | | private long _nextWatchId = 1; |
| | | 50 | | private Watcher? _watchStream; |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Creates a new WatchManager |
| | | 54 | | /// </summary> |
| | | 55 | | /// <param name="watchStreamFactory">A factory function that creates a new watch stream</param> |
| | 360 | 56 | | public WatchManager( |
| | 360 | 57 | | Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>> |
| | 720 | 58 | | watchStreamFactory) => _watchStreamFactory = |
| | 360 | 59 | | watchStreamFactory ?? throw new ArgumentNullException(nameof(watchStreamFactory)); |
| | | 60 | | |
| | | 61 | | /// <summary> |
| | | 62 | | /// Creates a new watch request |
| | | 63 | | /// </summary> |
| | | 64 | | /// <param name="request">The watch requests to create</param> |
| | | 65 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 66 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 67 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 68 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 69 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 70 | | public async Task<long> WatchAsync(WatchRequest request, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 71 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 72 | 72 | | { |
| | 72 | 73 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 74 | | |
| | | 75 | | // Create a new watch stream if needed |
| | 71 | 76 | | EnsureWatchStream(headers, deadline, cancellationToken); |
| | | 77 | | |
| | | 78 | | // Generate a new watch ID |
| | 71 | 79 | | long watchId = Interlocked.Increment(ref _nextWatchId); |
| | | 80 | | |
| | | 81 | | // Create a cancellation token source that can be used to cancel the watch |
| | 71 | 82 | | CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 83 | | |
| | | 84 | | // Work on our own copy: the watch id is stamped onto the request and the reconnect path |
| | | 85 | | // rewrites StartRevision on it, and neither should mutate the caller's object (which callers |
| | | 86 | | // may reuse across watches). |
| | 71 | 87 | | request = request.Clone(); |
| | 71 | 88 | | request.CreateRequest.WatchId = watchId; |
| | | 89 | | |
| | | 90 | | // Create a watch cancellation object |
| | 71 | 91 | | WatchCancellation watchCancellation = new() |
| | 71 | 92 | | { |
| | 71 | 93 | | WatchId = watchId, |
| | 71 | 94 | | CancellationTokenSource = cts, |
| | 71 | 95 | | Request = request, |
| | 71 | 96 | | Callback = WrappedCallback, |
| | 71 | 97 | | |
| | 71 | 98 | | // Seed the resume point with the revision the caller asked to start from (etcd clientv3 |
| | 71 | 99 | | // does the same: `nextRev := w.initReq.rev`). Without this, a watch created with an |
| | 71 | 100 | | // explicit StartRevision would look identical to a "from now" watch, and the Created ack — |
| | 71 | 101 | | // which carries the *current* cluster revision — would advance the resume point past the |
| | 71 | 102 | | // backlog the caller asked to replay. |
| | 71 | 103 | | NextRevision = request.CreateRequest.StartRevision |
| | 71 | 104 | | }; |
| | | 105 | | |
| | | 106 | | // Completed when etcd acknowledges the watch. Continuations MUST run asynchronously: the |
| | | 107 | | // callback below is invoked from the stream's receive loop, so resuming the awaiting caller |
| | | 108 | | // inline would run its code on that loop and stall event delivery for every watch on the |
| | | 109 | | // stream (and deadlock outright if the caller then blocks). |
| | 71 | 110 | | TaskCompletionSource<WatchResponse> acknowledged = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | | 111 | | |
| | | 112 | | // Register the watch BEFORE writing the create request: the server can answer while WriteAsync |
| | | 113 | | // is still in flight, and both TrackResumeRevision and the reconnect loop ignore watches that |
| | | 114 | | // are not in _watches yet. |
| | 71 | 115 | | _watches[watchId] = watchCancellation; |
| | 71 | 116 | | _pendingCreates[watchId] = acknowledged; |
| | | 117 | | |
| | | 118 | | try |
| | 71 | 119 | | { |
| | 71 | 120 | | await _watchStream!.CreateWatchAsync(request, WrappedCallback).ConfigureAwait(false); |
| | | 121 | | |
| | | 122 | | // Wait until etcd has actually registered the watch. Creating a watch is asynchronous on |
| | | 123 | | // the server, so until the Created ack arrives the watch does not exist: a caller that |
| | | 124 | | // wrote a key as soon as Watch() returned could have the write applied first and never |
| | | 125 | | // see the event. If the stream dies while we wait, HandleConnectionFailure re-sends the |
| | | 126 | | // create on the new stream and its ack completes this same task. |
| | 71 | 127 | | TimeSpan ackTimeout = AckTimeoutFor(deadline); |
| | | 128 | | |
| | 71 | 129 | | WatchResponse ack = await acknowledged.Task |
| | 71 | 130 | | .WaitAsync(ackTimeout, cts.Token) |
| | 71 | 131 | | .ConfigureAwait(false); |
| | | 132 | | |
| | 71 | 133 | | if (ack.Canceled) |
| | 0 | 134 | | { |
| | 0 | 135 | | throw new RpcException(new Status(StatusCode.FailedPrecondition, |
| | 0 | 136 | | $"etcd rejected the watch: {ack.CancelReason}")); |
| | | 137 | | } |
| | 71 | 138 | | } |
| | 0 | 139 | | catch (Exception ex) |
| | 0 | 140 | | { |
| | | 141 | | // The watch was never established. Cancel first so any response that shows up late is |
| | | 142 | | // ignored, then drop the entry so the reconnect loop won't try to re-register a watch the |
| | | 143 | | // caller believes failed. |
| | 0 | 144 | | _watches.TryRemove(watchId, out _); |
| | 0 | 145 | | SafeCancel(cts); |
| | 0 | 146 | | cts.Dispose(); |
| | | 147 | | |
| | | 148 | | // The server may nonetheless have registered the watch (e.g. we timed out waiting for an |
| | | 149 | | // ack that was merely slow). Best-effort tear it down rather than leak a server-side |
| | | 150 | | // watcher that streams into a callback nobody listens to. |
| | 0 | 151 | | if (_watchStream != null) |
| | 0 | 152 | | { |
| | 0 | 153 | | _ = _watchStream.CancelWatchAsync(watchId).ContinueWith( |
| | 0 | 154 | | t => _ = t.Exception, TaskScheduler.Default); |
| | 0 | 155 | | } |
| | | 156 | | |
| | 0 | 157 | | throw ex is TimeoutException |
| | 0 | 158 | | ? new RpcException(new Status(StatusCode.DeadlineExceeded, |
| | 0 | 159 | | $"etcd did not acknowledge the watch within {AckTimeoutFor(deadline).TotalSeconds:0}s")) |
| | 0 | 160 | | : ex; |
| | | 161 | | } |
| | | 162 | | finally |
| | 71 | 163 | | { |
| | 71 | 164 | | _pendingCreates.TryRemove(watchId, out _); |
| | 71 | 165 | | } |
| | | 166 | | |
| | 71 | 167 | | return watchId; |
| | | 168 | | |
| | | 169 | | // Create a wrapper callback that checks if the watch has been canceled |
| | | 170 | | void WrappedCallback(WatchResponse response) |
| | 146 | 171 | | { |
| | | 172 | | // Complete the create before the cancellation guard below: a watch that is cancelled or |
| | | 173 | | // disposed while its create is still in flight must still release the awaiting caller |
| | | 174 | | // rather than leave it blocked until the timeout. |
| | 146 | 175 | | if ((response.Created || response.Canceled) && |
| | 146 | 176 | | _pendingCreates.TryGetValue(watchId, out TaskCompletionSource<WatchResponse>? pending)) |
| | 71 | 177 | | { |
| | 71 | 178 | | pending.TrySetResult(response); |
| | 71 | 179 | | } |
| | | 180 | | |
| | 146 | 181 | | if (cts.IsCancellationRequested) |
| | 2 | 182 | | { |
| | 2 | 183 | | return; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | // If this is a creation response, update our watch ID mapping |
| | 144 | 187 | | if (response.Created) |
| | 78 | 188 | | { |
| | | 189 | | // Map the server-assigned watch ID to our client-generated watch ID |
| | 78 | 190 | | _watchIdMapping[response.WatchId] = watchId; |
| | 78 | 191 | | } |
| | | 192 | | |
| | | 193 | | // Track the revision to resume from on reconnect so no events are missed in the gap. |
| | 144 | 194 | | TrackResumeRevision(watchId, response); |
| | | 195 | | |
| | 144 | 196 | | Dispatch(watchId, response, callback, cts); |
| | 146 | 197 | | } |
| | 71 | 198 | | } |
| | | 199 | | |
| | | 200 | | /// <summary> |
| | | 201 | | /// Hands a response to the user's callback off the stream's receive loop. |
| | | 202 | | /// <para> |
| | | 203 | | /// The receive loop invokes callbacks inline, so running user code on it would let one slow |
| | | 204 | | /// or blocking callback stall event delivery for every watch on the stream — and a callback |
| | | 205 | | /// that starts another watch would deadlock outright, because the loop it is blocking is the |
| | | 206 | | /// only thing that could deliver the new watch's acknowledgement. |
| | | 207 | | /// </para> |
| | | 208 | | /// <para> |
| | | 209 | | /// Responses are appended to a single chain, so callbacks stay serialized and in order |
| | | 210 | | /// exactly as they were when they ran on the receive loop. That matters: overloads such as |
| | | 211 | | /// WatchRange(string[] paths, method) hand the SAME delegate to several watches, and those |
| | | 212 | | /// callers are entitled to assume it is never entered concurrently. |
| | | 213 | | /// </para> |
| | | 214 | | /// </summary> |
| | | 215 | | private void Dispatch(long watchId, WatchResponse response, Action<WatchResponse> callback, |
| | | 216 | | CancellationTokenSource cts) |
| | 144 | 217 | | { |
| | 144 | 218 | | lock (_dispatchLock) |
| | 144 | 219 | | { |
| | 144 | 220 | | _dispatchChain = _dispatchChain.ContinueWith(_ => |
| | 144 | 221 | | { |
| | 144 | 222 | | if (cts.IsCancellationRequested) |
| | 0 | 223 | | { |
| | 0 | 224 | | return; |
| | 144 | 225 | | } |
| | 144 | 226 | | |
| | 144 | 227 | | try |
| | 144 | 228 | | { |
| | 144 | 229 | | callback(response); |
| | 144 | 230 | | } |
| | 0 | 231 | | catch (Exception ex) |
| | 0 | 232 | | { |
| | 144 | 233 | | // A throwing user callback must not fault the chain and silently stop delivery of |
| | 144 | 234 | | // every subsequent event for this watch. |
| | 0 | 235 | | Console.Error.WriteLine($"Watch callback for watch {watchId} threw: {ex}"); |
| | 0 | 236 | | } |
| | 288 | 237 | | }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); |
| | 144 | 238 | | } |
| | 144 | 239 | | } |
| | | 240 | | |
| | | 241 | | /// <summary> |
| | | 242 | | /// How long to wait for the create acknowledgement. Honours the caller's deadline when one is |
| | | 243 | | /// given, so a caller that asked for a short deadline is not held for the full default. |
| | | 244 | | /// </summary> |
| | | 245 | | private static TimeSpan AckTimeoutFor(DateTime? deadline) |
| | 71 | 246 | | { |
| | 71 | 247 | | if (deadline == null) |
| | 70 | 248 | | { |
| | 70 | 249 | | return CreateWatchTimeout; |
| | | 250 | | } |
| | | 251 | | |
| | 1 | 252 | | TimeSpan remaining = deadline.Value.ToUniversalTime() - DateTime.UtcNow; |
| | 1 | 253 | | return remaining < TimeSpan.Zero ? TimeSpan.Zero |
| | 1 | 254 | | : remaining < CreateWatchTimeout ? remaining |
| | 1 | 255 | | : CreateWatchTimeout; |
| | 71 | 256 | | } |
| | | 257 | | |
| | | 258 | | /// <summary> |
| | | 259 | | /// Cancels a token source that another owner may already have disposed. Cancel() throws on a |
| | | 260 | | /// disposed source (Dispose() itself is idempotent), and both the create-failure path and |
| | | 261 | | /// CancelWatch/Dispose can reach the same source. |
| | | 262 | | /// </summary> |
| | | 263 | | private static void SafeCancel(CancellationTokenSource cts) |
| | 33 | 264 | | { |
| | | 265 | | try |
| | 33 | 266 | | { |
| | 33 | 267 | | cts.Cancel(); |
| | 33 | 268 | | } |
| | 0 | 269 | | catch (ObjectDisposedException) |
| | 0 | 270 | | { |
| | | 271 | | // Already torn down by the other owner; nothing to do. |
| | 0 | 272 | | } |
| | 33 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// Advances the stored resume revision for a watch based on a received response, mirroring the |
| | | 277 | | /// etcd clientv3 "nextRev" logic: after an event batch resume from lastEvent.ModRevision + 1; |
| | | 278 | | /// for a created/progress notification with no events, advance to the header revision. A |
| | | 279 | | /// compaction cancel resets the resume point to the compact revision. Only ever moves forward. |
| | | 280 | | /// </summary> |
| | | 281 | | private void TrackResumeRevision(long clientWatchId, WatchResponse response) |
| | 144 | 282 | | { |
| | 144 | 283 | | if (!_watches.TryGetValue(clientWatchId, out WatchCancellation? watch)) |
| | 0 | 284 | | { |
| | 0 | 285 | | return; |
| | | 286 | | } |
| | | 287 | | |
| | 144 | 288 | | long candidate = watch.NextRevision; |
| | | 289 | | |
| | 144 | 290 | | if (response.Canceled && response.CompactRevision > 0) |
| | 1 | 291 | | { |
| | | 292 | | // Our resume point was compacted away; the earliest we can resume from is CompactRevision. |
| | 1 | 293 | | candidate = response.CompactRevision; |
| | 1 | 294 | | } |
| | 143 | 295 | | else if (response.Created) |
| | 78 | 296 | | { |
| | | 297 | | // A Created ack carries the CURRENT cluster revision, which says nothing about what this |
| | | 298 | | // watch has observed. Only use it to seed a brand new "watch from now" watch: for a watch |
| | | 299 | | // being re-registered after a reconnect (StartRevision > 0) the server is about to replay |
| | | 300 | | // the backlog from that revision, and advancing to the ack's header would skip straight |
| | | 301 | | // past it — losing exactly the events the resume exists to recover. |
| | 78 | 302 | | if (candidate == 0 && response.Header != null && response.Header.Revision > 0) |
| | 66 | 303 | | { |
| | 66 | 304 | | candidate = response.Header.Revision + 1; |
| | 66 | 305 | | } |
| | 78 | 306 | | } |
| | 65 | 307 | | else if (response.Events != null && response.Events.Count > 0) |
| | 64 | 308 | | { |
| | 64 | 309 | | long lastModRevision = response.Events[^1].Kv.ModRevision; |
| | 64 | 310 | | if (lastModRevision + 1 > candidate) |
| | 20 | 311 | | { |
| | 20 | 312 | | candidate = lastModRevision + 1; |
| | 20 | 313 | | } |
| | 64 | 314 | | } |
| | 1 | 315 | | else if (response.Header != null && response.Header.Revision > 0) |
| | 1 | 316 | | { |
| | | 317 | | // Progress notification (no events): everything up to the header revision has been |
| | | 318 | | // observed, so the next start revision is header.Revision + 1. |
| | 1 | 319 | | long boundary = response.Header.Revision + 1; |
| | 1 | 320 | | if (boundary > candidate) |
| | 1 | 321 | | { |
| | 1 | 322 | | candidate = boundary; |
| | 1 | 323 | | } |
| | 1 | 324 | | } |
| | | 325 | | |
| | 144 | 326 | | watch.NextRevision = candidate; |
| | 144 | 327 | | } |
| | | 328 | | |
| | | 329 | | /// <summary> |
| | | 330 | | /// Creates a new watch request |
| | | 331 | | /// </summary> |
| | | 332 | | /// <param name="request">The watch request to create</param> |
| | | 333 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 334 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 335 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 336 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 337 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 338 | | public long Watch(WatchRequest request, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 339 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 38 | 340 | | { |
| | | 341 | | // Run the async method synchronously. GetAwaiter().GetResult() rather than Wait()+Result so a |
| | | 342 | | // failure surfaces as the RpcException the async overloads throw, not wrapped in an |
| | | 343 | | // AggregateException that a `catch (RpcException)` would miss. |
| | 76 | 344 | | Task<long> task = Task.Run(() => WatchAsync(request, callback, headers, deadline, cancellationToken), cancellati |
| | 38 | 345 | | return task.GetAwaiter().GetResult(); |
| | 38 | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Watches a specific key |
| | | 350 | | /// </summary> |
| | | 351 | | /// <param name="key">Key to watch</param> |
| | | 352 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 353 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 354 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 355 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 356 | | /// <returns>Watch ID</returns> |
| | | 357 | | public long Watch(string key, Action<WatchEvent> action, Metadata? headers = null, DateTime? deadline = null, |
| | | 358 | | CancellationToken cancellationToken = default) |
| | 2 | 359 | | { |
| | 2 | 360 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 361 | | |
| | | 362 | | // Create a watch request for the key |
| | 1 | 363 | | WatchRequest request = new() |
| | 1 | 364 | | { |
| | 1 | 365 | | CreateRequest = new WatchCreateRequest |
| | 1 | 366 | | { |
| | 1 | 367 | | Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true |
| | 1 | 368 | | } |
| | 1 | 369 | | }; |
| | | 370 | | |
| | | 371 | | // Call the Watch method with the request |
| | 1 | 372 | | return Watch(request, Callback, headers, deadline, cancellationToken); |
| | | 373 | | |
| | | 374 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | | 375 | | void Callback(WatchResponse response) |
| | 2 | 376 | | { |
| | 2 | 377 | | if (response.Events == null) |
| | 0 | 378 | | { |
| | 0 | 379 | | return; |
| | | 380 | | } |
| | | 381 | | |
| | 8 | 382 | | foreach (Event evt in response.Events) |
| | 1 | 383 | | { |
| | 1 | 384 | | WatchEvent watchEvent = new() { Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Ty |
| | 1 | 385 | | action(watchEvent); |
| | 1 | 386 | | } |
| | 2 | 387 | | } |
| | 1 | 388 | | } |
| | | 389 | | |
| | | 390 | | /// <summary> |
| | | 391 | | /// Watches a range of keys with a prefix |
| | | 392 | | /// </summary> |
| | | 393 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 394 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 395 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 396 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 397 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 398 | | /// <returns>Watch ID</returns> |
| | | 399 | | public long WatchRange(string prefixKey, Action<WatchEvent> action, Metadata? headers = null, |
| | | 400 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 401 | | { |
| | 1 | 402 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 403 | | |
| | | 404 | | // Create a watch request for the range |
| | 1 | 405 | | WatchRequest request = new() |
| | 1 | 406 | | { |
| | 1 | 407 | | CreateRequest = new WatchCreateRequest |
| | 1 | 408 | | { |
| | 1 | 409 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 410 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 411 | | ProgressNotify = true, |
| | 1 | 412 | | PrevKv = true |
| | 1 | 413 | | } |
| | 1 | 414 | | }; |
| | | 415 | | |
| | | 416 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 417 | | Action<WatchResponse> callback = response => |
| | 2 | 418 | | { |
| | 2 | 419 | | if (response.Events == null) |
| | 0 | 420 | | { |
| | 0 | 421 | | return; |
| | 1 | 422 | | } |
| | 1 | 423 | | |
| | 8 | 424 | | foreach (Event evt in response.Events) |
| | 1 | 425 | | { |
| | 1 | 426 | | WatchEvent watchEvent = new() |
| | 1 | 427 | | { |
| | 1 | 428 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 429 | | }; |
| | 1 | 430 | | action(watchEvent); |
| | 1 | 431 | | } |
| | 3 | 432 | | }; |
| | | 433 | | |
| | | 434 | | // Call the Watch method with the request |
| | 1 | 435 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 436 | | } |
| | | 437 | | |
| | | 438 | | /// <summary> |
| | | 439 | | /// Watches a specific key with start revision |
| | | 440 | | /// </summary> |
| | | 441 | | /// <param name="key">Key to watch</param> |
| | | 442 | | /// <param name="startRevision">Start revision</param> |
| | | 443 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 444 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 445 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 446 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 447 | | /// <returns>Watch ID</returns> |
| | | 448 | | public long Watch(string key, long startRevision, Action<WatchEvent> action, Metadata? headers = null, |
| | | 449 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 450 | | { |
| | 1 | 451 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 452 | | |
| | | 453 | | // Create a watch request for the key with start revision |
| | 1 | 454 | | WatchRequest request = new() |
| | 1 | 455 | | { |
| | 1 | 456 | | CreateRequest = new WatchCreateRequest |
| | 1 | 457 | | { |
| | 1 | 458 | | Key = ByteString.CopyFromUtf8(key), |
| | 1 | 459 | | StartRevision = startRevision, |
| | 1 | 460 | | ProgressNotify = true, |
| | 1 | 461 | | PrevKv = true |
| | 1 | 462 | | } |
| | 1 | 463 | | }; |
| | | 464 | | |
| | | 465 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 466 | | Action<WatchResponse> callback = response => |
| | 2 | 467 | | { |
| | 2 | 468 | | if (response.Events == null) |
| | 0 | 469 | | { |
| | 0 | 470 | | return; |
| | 1 | 471 | | } |
| | 1 | 472 | | |
| | 8 | 473 | | foreach (Event evt in response.Events) |
| | 1 | 474 | | { |
| | 1 | 475 | | WatchEvent watchEvent = new() |
| | 1 | 476 | | { |
| | 1 | 477 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 478 | | }; |
| | 1 | 479 | | action(watchEvent); |
| | 1 | 480 | | } |
| | 3 | 481 | | }; |
| | | 482 | | |
| | | 483 | | // Call the Watch method with the request |
| | 1 | 484 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 485 | | } |
| | | 486 | | |
| | | 487 | | /// <summary> |
| | | 488 | | /// Watches a range of keys with a prefix and start revision |
| | | 489 | | /// </summary> |
| | | 490 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 491 | | /// <param name="startRevision">Start revision</param> |
| | | 492 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 493 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 494 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 495 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 496 | | /// <returns>Watch ID</returns> |
| | | 497 | | public long WatchRange(string prefixKey, long startRevision, Action<WatchEvent> action, Metadata? headers = null, |
| | | 498 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 499 | | { |
| | 1 | 500 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 501 | | |
| | | 502 | | // Create a watch request for the range with start revision |
| | 1 | 503 | | WatchRequest request = new() |
| | 1 | 504 | | { |
| | 1 | 505 | | CreateRequest = new WatchCreateRequest |
| | 1 | 506 | | { |
| | 1 | 507 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 508 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 509 | | StartRevision = startRevision, |
| | 1 | 510 | | ProgressNotify = true, |
| | 1 | 511 | | PrevKv = true |
| | 1 | 512 | | } |
| | 1 | 513 | | }; |
| | | 514 | | |
| | | 515 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 516 | | Action<WatchResponse> callback = response => |
| | 2 | 517 | | { |
| | 2 | 518 | | if (response.Events == null) |
| | 0 | 519 | | { |
| | 0 | 520 | | return; |
| | 1 | 521 | | } |
| | 1 | 522 | | |
| | 8 | 523 | | foreach (Event evt in response.Events) |
| | 1 | 524 | | { |
| | 1 | 525 | | WatchEvent watchEvent = new() |
| | 1 | 526 | | { |
| | 1 | 527 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 528 | | }; |
| | 1 | 529 | | action(watchEvent); |
| | 1 | 530 | | } |
| | 3 | 531 | | }; |
| | | 532 | | |
| | | 533 | | // Call the Watch method with the request |
| | 1 | 534 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 535 | | } |
| | | 536 | | |
| | | 537 | | /// <summary> |
| | | 538 | | /// Watches a specific key asynchronously |
| | | 539 | | /// </summary> |
| | | 540 | | /// <param name="key">Key to watch</param> |
| | | 541 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 542 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 543 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 544 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 545 | | /// <returns>Watch ID</returns> |
| | | 546 | | public async Task<long> WatchAsync(string key, Action<WatchEvent> action, Metadata? headers = null, |
| | | 547 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 548 | | { |
| | 1 | 549 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 550 | | |
| | | 551 | | // Create a watch request for the key |
| | 1 | 552 | | WatchRequest request = new() |
| | 1 | 553 | | { |
| | 1 | 554 | | CreateRequest = new WatchCreateRequest |
| | 1 | 555 | | { |
| | 1 | 556 | | Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true |
| | 1 | 557 | | } |
| | 1 | 558 | | }; |
| | | 559 | | |
| | | 560 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 561 | | Action<WatchResponse> callback = response => |
| | 2 | 562 | | { |
| | 2 | 563 | | if (response.Events == null) |
| | 0 | 564 | | { |
| | 0 | 565 | | return; |
| | 1 | 566 | | } |
| | 1 | 567 | | |
| | 8 | 568 | | foreach (Event evt in response.Events) |
| | 1 | 569 | | { |
| | 1 | 570 | | WatchEvent watchEvent = new() |
| | 1 | 571 | | { |
| | 1 | 572 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 573 | | }; |
| | 1 | 574 | | action(watchEvent); |
| | 1 | 575 | | } |
| | 3 | 576 | | }; |
| | | 577 | | |
| | | 578 | | // Call the WatchAsync method with the request |
| | 1 | 579 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 580 | | } |
| | | 581 | | |
| | | 582 | | /// <summary> |
| | | 583 | | /// Watches a range of keys with a prefix asynchronously |
| | | 584 | | /// </summary> |
| | | 585 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 586 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 587 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 588 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 589 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 590 | | /// <returns>Watch ID</returns> |
| | | 591 | | public async Task<long> WatchRangeAsync(string prefixKey, Action<WatchEvent> action, Metadata? headers = null, |
| | | 592 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 593 | | { |
| | 1 | 594 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 595 | | |
| | | 596 | | // Create a watch request for the range |
| | 1 | 597 | | WatchRequest request = new() |
| | 1 | 598 | | { |
| | 1 | 599 | | CreateRequest = new WatchCreateRequest |
| | 1 | 600 | | { |
| | 1 | 601 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 602 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 603 | | ProgressNotify = true, |
| | 1 | 604 | | PrevKv = true |
| | 1 | 605 | | } |
| | 1 | 606 | | }; |
| | | 607 | | |
| | | 608 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 609 | | Action<WatchResponse> callback = response => |
| | 2 | 610 | | { |
| | 2 | 611 | | if (response.Events == null) |
| | 0 | 612 | | { |
| | 0 | 613 | | return; |
| | 1 | 614 | | } |
| | 1 | 615 | | |
| | 8 | 616 | | foreach (Event evt in response.Events) |
| | 1 | 617 | | { |
| | 1 | 618 | | WatchEvent watchEvent = new() |
| | 1 | 619 | | { |
| | 1 | 620 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 621 | | }; |
| | 1 | 622 | | action(watchEvent); |
| | 1 | 623 | | } |
| | 3 | 624 | | }; |
| | | 625 | | |
| | | 626 | | // Call the WatchAsync method with the request |
| | 1 | 627 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 628 | | } |
| | | 629 | | |
| | | 630 | | /// <summary> |
| | | 631 | | /// Watches a specific key with start revision asynchronously |
| | | 632 | | /// </summary> |
| | | 633 | | /// <param name="key">Key to watch</param> |
| | | 634 | | /// <param name="startRevision">Start revision</param> |
| | | 635 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 636 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 637 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 638 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 639 | | /// <returns>Watch ID</returns> |
| | | 640 | | public async Task<long> WatchAsync(string key, long startRevision, Action<WatchEvent> action, |
| | | 641 | | Metadata? headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 642 | | { |
| | 1 | 643 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 644 | | |
| | | 645 | | // Create a watch request for the key with start revision |
| | 1 | 646 | | WatchRequest request = new() |
| | 1 | 647 | | { |
| | 1 | 648 | | CreateRequest = new WatchCreateRequest |
| | 1 | 649 | | { |
| | 1 | 650 | | Key = ByteString.CopyFromUtf8(key), |
| | 1 | 651 | | StartRevision = startRevision, |
| | 1 | 652 | | ProgressNotify = true, |
| | 1 | 653 | | PrevKv = true |
| | 1 | 654 | | } |
| | 1 | 655 | | }; |
| | | 656 | | |
| | | 657 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 658 | | Action<WatchResponse> callback = response => |
| | 2 | 659 | | { |
| | 2 | 660 | | if (response.Events == null) |
| | 0 | 661 | | { |
| | 0 | 662 | | return; |
| | 1 | 663 | | } |
| | 1 | 664 | | |
| | 8 | 665 | | foreach (Event evt in response.Events) |
| | 1 | 666 | | { |
| | 1 | 667 | | WatchEvent watchEvent = new() |
| | 1 | 668 | | { |
| | 1 | 669 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 670 | | }; |
| | 1 | 671 | | action(watchEvent); |
| | 1 | 672 | | } |
| | 3 | 673 | | }; |
| | | 674 | | |
| | | 675 | | // Call the WatchAsync method with the request |
| | 1 | 676 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 677 | | } |
| | | 678 | | |
| | | 679 | | /// <summary> |
| | | 680 | | /// Watches a range of keys with a prefix and start revision asynchronously |
| | | 681 | | /// </summary> |
| | | 682 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 683 | | /// <param name="startRevision">Start revision</param> |
| | | 684 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 685 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 686 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 687 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 688 | | /// <returns>Watch ID</returns> |
| | | 689 | | public async Task<long> WatchRangeAsync(string prefixKey, long startRevision, Action<WatchEvent> action, |
| | | 690 | | Metadata? headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 691 | | { |
| | 1 | 692 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 693 | | |
| | | 694 | | // Create a watch request for the range with start revision |
| | 1 | 695 | | WatchRequest request = new() |
| | 1 | 696 | | { |
| | 1 | 697 | | CreateRequest = new WatchCreateRequest |
| | 1 | 698 | | { |
| | 1 | 699 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 700 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 701 | | StartRevision = startRevision, |
| | 1 | 702 | | ProgressNotify = true, |
| | 1 | 703 | | PrevKv = true |
| | 1 | 704 | | } |
| | 1 | 705 | | }; |
| | | 706 | | |
| | | 707 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 708 | | Action<WatchResponse> callback = response => |
| | 2 | 709 | | { |
| | 2 | 710 | | if (response.Events == null) |
| | 0 | 711 | | { |
| | 0 | 712 | | return; |
| | 1 | 713 | | } |
| | 1 | 714 | | |
| | 8 | 715 | | foreach (Event evt in response.Events) |
| | 1 | 716 | | { |
| | 1 | 717 | | WatchEvent watchEvent = new() |
| | 1 | 718 | | { |
| | 1 | 719 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 720 | | }; |
| | 1 | 721 | | action(watchEvent); |
| | 1 | 722 | | } |
| | 3 | 723 | | }; |
| | | 724 | | |
| | | 725 | | // Call the WatchAsync method with the request |
| | 1 | 726 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 727 | | } |
| | | 728 | | |
| | | 729 | | /// <summary> |
| | | 730 | | /// Watches a key range |
| | | 731 | | /// </summary> |
| | | 732 | | /// <param name="path">The path to watch</param> |
| | | 733 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 734 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 735 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 736 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 737 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 738 | | public long WatchRange(string path, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 739 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 740 | | { |
| | 1 | 741 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 742 | | |
| | | 743 | | // Create a watch request for the range |
| | 1 | 744 | | WatchRequest request = new() |
| | 1 | 745 | | { |
| | 1 | 746 | | CreateRequest = new WatchCreateRequest |
| | 1 | 747 | | { |
| | 1 | 748 | | Key = ByteString.CopyFromUtf8(path), |
| | 1 | 749 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(path)), |
| | 1 | 750 | | ProgressNotify = true, |
| | 1 | 751 | | PrevKv = true |
| | 1 | 752 | | } |
| | 1 | 753 | | }; |
| | | 754 | | |
| | | 755 | | // Call the Watch method with the request |
| | 1 | 756 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 757 | | } |
| | | 758 | | |
| | | 759 | | /// <summary> |
| | | 760 | | /// Cancels a watch request |
| | | 761 | | /// </summary> |
| | | 762 | | /// <param name="watchId">The ID of the watch to cancel</param> |
| | | 763 | | public void CancelWatch(long watchId) |
| | 2 | 764 | | { |
| | 2 | 765 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 766 | | |
| | 2 | 767 | | if (!_watches.TryRemove(watchId, out WatchCancellation? watchCancellation)) |
| | 1 | 768 | | { |
| | 1 | 769 | | return; |
| | | 770 | | } |
| | | 771 | | |
| | | 772 | | // Cancel the watch |
| | 1 | 773 | | SafeCancel(watchCancellation.CancellationTokenSource); |
| | | 774 | | |
| | | 775 | | // Find the server watch ID that corresponds to our client watch ID |
| | 1 | 776 | | long serverWatchId = GetServerWatchId(watchId); |
| | | 777 | | |
| | | 778 | | // Cancel the watch on the server if we found a mapping |
| | 1 | 779 | | if (serverWatchId != -1 && _watchStream != null) |
| | 1 | 780 | | { |
| | 1 | 781 | | _watchIdMapping.TryRemove(serverWatchId, out _); |
| | 1 | 782 | | _watchStream.CancelWatchAsync(serverWatchId).ContinueWith(_ => |
| | 1 | 783 | | { |
| | 1 | 784 | | // Ignore exceptions |
| | 2 | 785 | | }); |
| | 1 | 786 | | } |
| | | 787 | | |
| | | 788 | | // Dispose the cancellation token source |
| | 1 | 789 | | watchCancellation.CancellationTokenSource.Dispose(); |
| | 2 | 790 | | } |
| | | 791 | | |
| | | 792 | | /// <summary> |
| | | 793 | | /// Disposes the watch manager |
| | | 794 | | /// </summary> |
| | | 795 | | public void Dispose() |
| | 109 | 796 | | { |
| | 109 | 797 | | if (_disposed) |
| | 1 | 798 | | { |
| | 1 | 799 | | return; |
| | | 800 | | } |
| | | 801 | | |
| | 108 | 802 | | _disposed = true; |
| | | 803 | | |
| | | 804 | | // Release anyone still waiting for a watch to be acknowledged, so disposing the manager can |
| | | 805 | | // never leave a caller blocked until the create timeout. |
| | 324 | 806 | | foreach (TaskCompletionSource<WatchResponse> pending in _pendingCreates.Values) |
| | 0 | 807 | | { |
| | 0 | 808 | | pending.TrySetException(new ObjectDisposedException(nameof(WatchManager))); |
| | 0 | 809 | | } |
| | | 810 | | |
| | 108 | 811 | | _pendingCreates.Clear(); |
| | | 812 | | |
| | | 813 | | // Cancel all watches |
| | 388 | 814 | | foreach (WatchCancellation watchCancellation in _watches.Values) |
| | 32 | 815 | | { |
| | 32 | 816 | | SafeCancel(watchCancellation.CancellationTokenSource); |
| | 32 | 817 | | watchCancellation.CancellationTokenSource.Dispose(); |
| | 32 | 818 | | } |
| | | 819 | | |
| | 108 | 820 | | _watches.Clear(); |
| | | 821 | | |
| | | 822 | | // Dispose the watch stream |
| | 108 | 823 | | if (_watchStream != null) |
| | 31 | 824 | | { |
| | 31 | 825 | | _watchStream.Dispose(); |
| | 31 | 826 | | _watchStream = null; |
| | 31 | 827 | | } |
| | | 828 | | |
| | 108 | 829 | | GC.SuppressFinalize(this); |
| | 109 | 830 | | } |
| | | 831 | | |
| | | 832 | | private static string GetRangeEnd(string path) |
| | 5 | 833 | | { |
| | | 834 | | // Calculate the range end for the given path |
| | | 835 | | // This is the same logic used in EtcdClient.GetRangeEnd |
| | 5 | 836 | | byte[] bytes = Encoding.UTF8.GetBytes(path); |
| | 10 | 837 | | for (int i = bytes.Length - 1; i >= 0; i--) |
| | 5 | 838 | | { |
| | 5 | 839 | | if (bytes[i] >= 0xff) |
| | 0 | 840 | | { |
| | 0 | 841 | | continue; |
| | | 842 | | } |
| | | 843 | | |
| | 5 | 844 | | bytes[i]++; |
| | 5 | 845 | | return Encoding.UTF8.GetString(bytes, 0, i + 1); |
| | | 846 | | } |
| | | 847 | | |
| | 0 | 848 | | return string.Empty; |
| | 5 | 849 | | } |
| | | 850 | | |
| | | 851 | | /// <summary> |
| | | 852 | | /// Gets the server watch ID for a client watch ID |
| | | 853 | | /// </summary> |
| | | 854 | | /// <param name="clientWatchId">The client watch ID</param> |
| | | 855 | | /// <returns>The server watch ID, or -1 if not found</returns> |
| | | 856 | | private long GetServerWatchId(long clientWatchId) |
| | 1 | 857 | | { |
| | 4 | 858 | | foreach (KeyValuePair<long, long> kvp in _watchIdMapping) |
| | 1 | 859 | | { |
| | 1 | 860 | | if (kvp.Value == clientWatchId) |
| | 1 | 861 | | { |
| | 1 | 862 | | return kvp.Key; |
| | | 863 | | } |
| | 0 | 864 | | } |
| | | 865 | | |
| | 0 | 866 | | return -1; |
| | 1 | 867 | | } |
| | | 868 | | |
| | | 869 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 870 | | private void EnsureWatchStream(Metadata? headers, DateTime? deadline, CancellationToken cancellationToken) |
| | 80 | 871 | | { |
| | 80 | 872 | | lock (_lockObject) |
| | 80 | 873 | | { |
| | 80 | 874 | | if (_watchStream != null) |
| | 14 | 875 | | { |
| | 14 | 876 | | return; |
| | | 877 | | } |
| | | 878 | | |
| | | 879 | | // Create a new watch stream |
| | 66 | 880 | | IAsyncDuplexStreamingCall<WatchRequest, WatchResponse> watchStreamCall = |
| | 66 | 881 | | _watchStreamFactory(headers, deadline, cancellationToken); |
| | 66 | 882 | | _watchStream = new Watcher(watchStreamCall, HandleConnectionFailure); |
| | 66 | 883 | | } |
| | 80 | 884 | | } |
| | | 885 | | |
| | | 886 | | private void HandleConnectionFailure() |
| | 9 | 887 | | { |
| | | 888 | | Watcher? abandoned; |
| | | 889 | | |
| | 9 | 890 | | lock (_lockObject) |
| | 9 | 891 | | { |
| | 9 | 892 | | abandoned = _watchStream; |
| | 9 | 893 | | _watchStream = null; |
| | 9 | 894 | | _watchIdMapping.Clear(); |
| | 9 | 895 | | } |
| | | 896 | | |
| | | 897 | | // Tear the old stream down. Leaving it undisposed keeps its receive loop, gRPC call and |
| | | 898 | | // callbacks alive: if that stream is in fact still healthy, etcd goes on delivering the same |
| | | 899 | | // events on it as well as on the replacement, and every event is handed to the callback twice. |
| | 9 | 900 | | abandoned?.Dispose(); |
| | | 901 | | |
| | | 902 | | // Must run async to avoid blocking the caller (which might be the dead stream loop) |
| | 9 | 903 | | Task.Run(async () => |
| | 9 | 904 | | { |
| | 9 | 905 | | try |
| | 9 | 906 | | { |
| | 9 | 907 | | // Wait small delay to allow network to stabilize |
| | 9 | 908 | | await Task.Delay(500); |
| | 9 | 909 | | |
| | 9 | 910 | | lock (_lockObject) |
| | 9 | 911 | | { |
| | 9 | 912 | | if (_disposed) return; |
| | 9 | 913 | | EnsureWatchStream(null, null, default); |
| | 9 | 914 | | } |
| | 9 | 915 | | |
| | 9 | 916 | | bool anyFailed = false; |
| | 9 | 917 | | |
| | 45 | 918 | | foreach (var watch in _watches.Values) |
| | 9 | 919 | | { |
| | 9 | 920 | | // Resume from the revision after the last observed event so events written while |
| | 9 | 921 | | // the stream was down are replayed instead of lost. A watch whose create was never |
| | 9 | 922 | | // acknowledged has nothing to resume from, but nothing can have been missed either: |
| | 9 | 923 | | // its Watch() call has not returned yet, so the caller cannot have written anything. |
| | 9 | 924 | | if (watch.NextRevision > 0 && watch.Request.CreateRequest != null) |
| | 8 | 925 | | { |
| | 8 | 926 | | watch.Request.CreateRequest.StartRevision = watch.NextRevision; |
| | 8 | 927 | | } |
| | 9 | 928 | | |
| | 9 | 929 | | try |
| | 9 | 930 | | { |
| | 9 | 931 | | await _watchStream!.CreateWatchAsync(watch.Request, watch.Callback).ConfigureAwait(false); |
| | 9 | 932 | | } |
| | 0 | 933 | | catch (Exception ex) |
| | 0 | 934 | | { |
| | 9 | 935 | | // Keep going: one watch failing to re-register must not strand the others. But |
| | 9 | 936 | | // remember it failed — swallowing it here would otherwise disable the retry |
| | 9 | 937 | | // below and leave that watch silently dead for the life of the client. |
| | 0 | 938 | | anyFailed = true; |
| | 0 | 939 | | Console.Error.WriteLine($"Failed to re-register watch {watch.WatchId}: {ex.Message}"); |
| | 0 | 940 | | } |
| | 9 | 941 | | } |
| | 9 | 942 | | |
| | 9 | 943 | | if (anyFailed) |
| | 0 | 944 | | { |
| | 0 | 945 | | throw new InvalidOperationException("one or more watches could not be re-registered"); |
| | 9 | 946 | | } |
| | 9 | 947 | | } |
| | 0 | 948 | | catch (Exception ex) |
| | 0 | 949 | | { |
| | 0 | 950 | | Console.Error.WriteLine($"Watch reconnection failed: {ex.Message}"); |
| | 9 | 951 | | // Retry in 5s |
| | 0 | 952 | | _ = Task.Delay(5000).ContinueWith(_ => HandleConnectionFailure()); |
| | 0 | 953 | | } |
| | 18 | 954 | | }); |
| | 9 | 955 | | } |
| | | 956 | | |
| | | 957 | | private class WatchCancellation |
| | | 958 | | { |
| | 71 | 959 | | public long WatchId { get; set; } |
| | 137 | 960 | | public required CancellationTokenSource CancellationTokenSource { get; set; } |
| | 96 | 961 | | public required WatchRequest Request { get; set; } |
| | 80 | 962 | | public required Action<WatchResponse> Callback { get; set; } |
| | | 963 | | |
| | | 964 | | |
| | | 965 | | /// <summary> |
| | | 966 | | /// The revision to resume this watch from if the stream is re-established. Tracks the |
| | | 967 | | /// revision after the last event/notification observed, so a reconnect does not miss |
| | | 968 | | /// events written during the gap (mirrors the etcd clientv3 nextRev behavior). |
| | | 969 | | /// </summary> |
| | 376 | 970 | | public long NextRevision { get; set; } |
| | | 971 | | } |
| | | 972 | | } |