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