< Summary

Information
Class: dotnet_etcd.WatchManager
Assembly: dotnet-etcd
File(s): /home/runner/work/dotnet-etcd/dotnet-etcd/dotnet-etcd/watchclient/WatchManager.cs
Line coverage
91%
Covered lines: 509
Uncovered lines: 45
Coverable lines: 554
Total lines: 1009
Line coverage: 91.8%
Branch coverage
82%
Covered branches: 94
Total branches: 114
Branch coverage: 82.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%22100%
WatchAsync()90%1010100%
WrappedCallback()100%1010100%
Dispatch(...)50%2291.3%
AckTimeoutFor(...)83.33%66100%
SafeCancel(...)100%1162.5%
TrackResumeRevision(...)88.46%262694.11%
Watch(...)100%11100%
Watch(...)100%11100%
Callback()75%4480%
WatchRange(...)75%4493.33%
Watch(...)75%4493.33%
WatchRange(...)75%4493.54%
WatchAsync()100%11100%
WatchRangeAsync()100%11100%
WatchAsync()100%11100%
WatchRangeAsync()100%11100%
WatchRange(...)100%11100%
CancelWatch(...)66.66%66100%
CancelWatchQuietly(...)100%2272.72%
Dispose()87.5%8886.95%
GetServerWatchId(...)50%4477.77%
EnsureWatchStream(...)100%22100%
HandleConnectionFailure()100%2279.41%
get_WatchId()100%11100%
get_CancellationTokenSource()100%11100%
get_Request()100%11100%
get_Callback()100%11100%
get_NextRevision()100%11100%

File(s)

/home/runner/work/dotnet-etcd/dotnet-etcd/dotnet-etcd/watchclient/WatchManager.cs

#LineLine coverage
 1#nullable enable
 2using System;
 3using System.Collections.Concurrent;
 4using System.Collections.Generic;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using dotnet_etcd.interfaces;
 8using Etcdserverpb;
 9using Google.Protobuf;
 10using Grpc.Core;
 11using Mvccpb;
 12
 13namespace dotnet_etcd;
 14
 15/// <summary>
 16///     Manages watch streams and provides a way to cancel watches
 17/// </summary>
 18public 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>
 224    private static readonly TimeSpan CreateWatchTimeout = TimeSpan.FromSeconds(30);
 25
 43426    private readonly object _lockObject = new();
 43427    private readonly ConcurrentDictionary<long, WatchCancellation> _watches = new();
 43428    private readonly ConcurrentDictionary<long, long> _watchIdMapping = new();
 29
 30    /// <summary>Watches whose create request is still awaiting the server's Created acknowledgement.</summary>
 43431    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>
 43439    private readonly object _dispatchLock = new();
 40
 43441    private Task _dispatchChain = Task.CompletedTask;
 42
 43    private readonly
 44        Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>>
 45        _watchStreamFactory;
 46
 47    private bool _disposed;
 43448    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>
 43455    public WatchManager(
 43456        Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>>
 86857            watchStreamFactory) => _watchStreamFactory =
 43458        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)
 9478    {
 9479        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.
 9386        EnsureWatchStream(headers, null, default);
 87
 88        // Generate a new watch ID
 9389        long watchId = Interlocked.Increment(ref _nextWatchId);
 90
 91        // Create a cancellation token source that can be used to cancel the watch
 9392        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).
 9397        request = request.Clone();
 9398        request.CreateRequest.WatchId = watchId;
 99
 100        // Create a watch cancellation object
 93101        WatchCancellation watchCancellation = new()
 93102        {
 93103            WatchId = watchId,
 93104            CancellationTokenSource = cts,
 93105            Request = request,
 93106            Callback = WrappedCallback,
 93107
 93108            // Seed the resume point with the revision the caller asked to start from (etcd clientv3
 93109            // does the same: `nextRev := w.initReq.rev`). Without this, a watch created with an
 93110            // explicit StartRevision would look identical to a "from now" watch, and the Created ack —
 93111            // which carries the *current* cluster revision — would advance the resume point past the
 93112            // backlog the caller asked to replay.
 93113            NextRevision = request.CreateRequest.StartRevision
 93114        };
 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).
 93120        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.
 93125        _watches[watchId] = watchCancellation;
 93126        _pendingCreates[watchId] = acknowledged;
 127
 128        try
 93129        {
 93130            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.
 93137            TimeSpan ackTimeout = AckTimeoutFor(deadline);
 138
 93139            WatchResponse ack = await acknowledged.Task
 93140                .WaitAsync(ackTimeout, cts.Token)
 93141                .ConfigureAwait(false);
 142
 92143            if (ack.Canceled)
 1144            {
 1145                throw new RpcException(new Status(StatusCode.FailedPrecondition,
 1146                    $"etcd rejected the watch: {ack.CancelReason}"));
 147            }
 91148        }
 2149        catch (Exception ex)
 2150        {
 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.
 2154            _watches.TryRemove(watchId, out _);
 2155            SafeCancel(cts);
 2156            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.
 2161            if (_watchStream != null)
 2162            {
 2163                _ = _watchStream.CancelWatchAsync(watchId).ContinueWith(
 4164                    t => _ = t.Exception, TaskScheduler.Default);
 2165            }
 166
 2167            throw ex is TimeoutException
 2168                ? new RpcException(new Status(StatusCode.DeadlineExceeded,
 2169                    $"etcd did not acknowledge the watch within {AckTimeoutFor(deadline).TotalSeconds:0}s"))
 2170                : ex;
 171        }
 172        finally
 93173        {
 93174            _pendingCreates.TryRemove(watchId, out _);
 93175        }
 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.
 91179        if (deadline.HasValue)
 4180        {
 4181            TimeSpan remaining = deadline.Value.ToUniversalTime() - DateTime.UtcNow;
 4182            cts.CancelAfter(remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero);
 4183        }
 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.
 173187        cts.Token.Register(() => _ = Task.Run(() => CancelWatchQuietly(watchId)));
 188
 91189        return watchId;
 190
 191        // Create a wrapper callback that checks if the watch has been canceled
 192        void WrappedCallback(WatchResponse response)
 190193        {
 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.
 190197            if ((response.Created || response.Canceled) &&
 190198                _pendingCreates.TryGetValue(watchId, out TaskCompletionSource<WatchResponse>? pending))
 92199            {
 92200                pending.TrySetResult(response);
 92201            }
 202
 190203            if (cts.IsCancellationRequested)
 2204            {
 2205                return;
 206            }
 207
 208            // If this is a creation response, update our watch ID mapping
 188209            if (response.Created)
 99210            {
 211                // Map the server-assigned watch ID to our client-generated watch ID
 99212                _watchIdMapping[response.WatchId] = watchId;
 99213            }
 214
 215            // Track the revision to resume from on reconnect so no events are missed in the gap.
 188216            TrackResumeRevision(watchId, response);
 217
 188218            Dispatch(watchId, response, callback, cts);
 190219        }
 91220    }
 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)
 188239    {
 188240        lock (_dispatchLock)
 188241        {
 188242            _dispatchChain = _dispatchChain.ContinueWith(_ =>
 188243            {
 188244                if (cts.IsCancellationRequested)
 0245                {
 0246                    return;
 188247                }
 188248
 188249                try
 188250                {
 188251                    callback(response);
 187252                }
 1253                catch (Exception ex)
 1254                {
 188255                    // A throwing user callback must not fault the chain and silently stop delivery of
 188256                    // every subsequent event for this watch.
 1257                    Console.Error.WriteLine($"Watch callback for watch {watchId} threw: {ex}");
 1258                }
 376259            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
 188260        }
 188261    }
 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)
 94268    {
 94269        if (deadline == null)
 88270        {
 88271            return CreateWatchTimeout;
 272        }
 273
 6274        TimeSpan remaining = deadline.Value.ToUniversalTime() - DateTime.UtcNow;
 6275        return remaining < TimeSpan.Zero ? TimeSpan.Zero
 6276            : remaining < CreateWatchTimeout ? remaining
 6277            : CreateWatchTimeout;
 94278    }
 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)
 43286    {
 287        try
 43288        {
 43289            cts.Cancel();
 43290        }
 0291        catch (ObjectDisposedException)
 0292        {
 293            // Already torn down by the other owner; nothing to do.
 0294        }
 43295    }
 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)
 188304    {
 188305        if (!_watches.TryGetValue(clientWatchId, out WatchCancellation? watch))
 0306        {
 0307            return;
 308        }
 309
 188310        long candidate = watch.NextRevision;
 311
 188312        if (response.Canceled && response.CompactRevision > 0)
 1313        {
 314            // Our resume point was compacted away; the earliest we can resume from is CompactRevision.
 1315            candidate = response.CompactRevision;
 1316        }
 187317        else if (response.Created)
 99318        {
 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.
 99324            if (candidate == 0 && response.Header != null && response.Header.Revision > 0)
 86325            {
 86326                candidate = response.Header.Revision + 1;
 86327            }
 99328        }
 88329        else if (response.Events != null && response.Events.Count > 0)
 85330        {
 85331            long lastModRevision = response.Events[^1].Kv.ModRevision;
 85332            if (lastModRevision + 1 > candidate)
 26333            {
 26334                candidate = lastModRevision + 1;
 26335            }
 85336        }
 3337        else if (response.Header != null && response.Header.Revision > 0)
 1338        {
 339            // Progress notification (no events): everything up to the header revision has been
 340            // observed, so the next start revision is header.Revision + 1.
 1341            long boundary = response.Header.Revision + 1;
 1342            if (boundary > candidate)
 1343            {
 1344                candidate = boundary;
 1345            }
 1346        }
 347
 188348        watch.NextRevision = candidate;
 188349    }
 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)
 52362    {
 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.
 104366        Task<long> task = Task.Run(() => WatchAsync(request, callback, headers, deadline, cancellationToken), cancellati
 52367        return task.GetAwaiter().GetResult();
 52368    }
 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)
 2381    {
 2382        ObjectDisposedException.ThrowIf(_disposed, this);
 383
 384        // Create a watch request for the key
 1385        WatchRequest request = new()
 1386        {
 1387            CreateRequest = new WatchCreateRequest
 1388            {
 1389                Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true
 1390            }
 1391        };
 392
 393        // Call the Watch method with the request
 1394        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)
 2398        {
 2399            if (response.Events == null)
 0400            {
 0401                return;
 402            }
 403
 8404            foreach (Event evt in response.Events)
 1405            {
 1406                WatchEvent watchEvent = new() { Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Ty
 1407                action(watchEvent);
 1408            }
 2409        }
 1410    }
 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)
 1423    {
 1424        ObjectDisposedException.ThrowIf(_disposed, this);
 425
 426        // Create a watch request for the range
 1427        WatchRequest request = new()
 1428        {
 1429            CreateRequest = new WatchCreateRequest
 1430            {
 1431                Key = ByteString.CopyFromUtf8(prefixKey),
 1432                RangeEnd = EtcdClient.GetRangeEnd(ByteString.CopyFromUtf8(prefixKey)),
 1433                ProgressNotify = true,
 1434                PrevKv = true
 1435            }
 1436        };
 437
 438        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1439        Action<WatchResponse> callback = response =>
 2440        {
 2441            if (response.Events == null)
 0442            {
 0443                return;
 1444            }
 1445
 8446            foreach (Event evt in response.Events)
 1447            {
 1448                WatchEvent watchEvent = new()
 1449                {
 1450                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1451                };
 1452                action(watchEvent);
 1453            }
 3454        };
 455
 456        // Call the Watch method with the request
 1457        return Watch(request, callback, headers, deadline, cancellationToken);
 1458    }
 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)
 1472    {
 1473        ObjectDisposedException.ThrowIf(_disposed, this);
 474
 475        // Create a watch request for the key with start revision
 1476        WatchRequest request = new()
 1477        {
 1478            CreateRequest = new WatchCreateRequest
 1479            {
 1480                Key = ByteString.CopyFromUtf8(key),
 1481                StartRevision = startRevision,
 1482                ProgressNotify = true,
 1483                PrevKv = true
 1484            }
 1485        };
 486
 487        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1488        Action<WatchResponse> callback = response =>
 2489        {
 2490            if (response.Events == null)
 0491            {
 0492                return;
 1493            }
 1494
 8495            foreach (Event evt in response.Events)
 1496            {
 1497                WatchEvent watchEvent = new()
 1498                {
 1499                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1500                };
 1501                action(watchEvent);
 1502            }
 3503        };
 504
 505        // Call the Watch method with the request
 1506        return Watch(request, callback, headers, deadline, cancellationToken);
 1507    }
 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)
 1521    {
 1522        ObjectDisposedException.ThrowIf(_disposed, this);
 523
 524        // Create a watch request for the range with start revision
 1525        WatchRequest request = new()
 1526        {
 1527            CreateRequest = new WatchCreateRequest
 1528            {
 1529                Key = ByteString.CopyFromUtf8(prefixKey),
 1530                RangeEnd = EtcdClient.GetRangeEnd(ByteString.CopyFromUtf8(prefixKey)),
 1531                StartRevision = startRevision,
 1532                ProgressNotify = true,
 1533                PrevKv = true
 1534            }
 1535        };
 536
 537        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1538        Action<WatchResponse> callback = response =>
 2539        {
 2540            if (response.Events == null)
 0541            {
 0542                return;
 1543            }
 1544
 8545            foreach (Event evt in response.Events)
 1546            {
 1547                WatchEvent watchEvent = new()
 1548                {
 1549                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1550                };
 1551                action(watchEvent);
 1552            }
 3553        };
 554
 555        // Call the Watch method with the request
 1556        return Watch(request, callback, headers, deadline, cancellationToken);
 1557    }
 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)
 1570    {
 1571        ObjectDisposedException.ThrowIf(_disposed, this);
 572
 573        // Create a watch request for the key
 1574        WatchRequest request = new()
 1575        {
 1576            CreateRequest = new WatchCreateRequest
 1577            {
 1578                Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true
 1579            }
 1580        };
 581
 582        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1583        Action<WatchResponse> callback = response =>
 2584        {
 2585            if (response.Events == null)
 0586            {
 0587                return;
 1588            }
 1589
 8590            foreach (Event evt in response.Events)
 1591            {
 1592                WatchEvent watchEvent = new()
 1593                {
 1594                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1595                };
 1596                action(watchEvent);
 1597            }
 3598        };
 599
 600        // Call the WatchAsync method with the request
 1601        return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false);
 1602    }
 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)
 1615    {
 1616        ObjectDisposedException.ThrowIf(_disposed, this);
 617
 618        // Create a watch request for the range
 1619        WatchRequest request = new()
 1620        {
 1621            CreateRequest = new WatchCreateRequest
 1622            {
 1623                Key = ByteString.CopyFromUtf8(prefixKey),
 1624                RangeEnd = EtcdClient.GetRangeEnd(ByteString.CopyFromUtf8(prefixKey)),
 1625                ProgressNotify = true,
 1626                PrevKv = true
 1627            }
 1628        };
 629
 630        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1631        Action<WatchResponse> callback = response =>
 2632        {
 2633            if (response.Events == null)
 0634            {
 0635                return;
 1636            }
 1637
 8638            foreach (Event evt in response.Events)
 1639            {
 1640                WatchEvent watchEvent = new()
 1641                {
 1642                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1643                };
 1644                action(watchEvent);
 1645            }
 3646        };
 647
 648        // Call the WatchAsync method with the request
 1649        return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false);
 1650    }
 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)
 1664    {
 1665        ObjectDisposedException.ThrowIf(_disposed, this);
 666
 667        // Create a watch request for the key with start revision
 1668        WatchRequest request = new()
 1669        {
 1670            CreateRequest = new WatchCreateRequest
 1671            {
 1672                Key = ByteString.CopyFromUtf8(key),
 1673                StartRevision = startRevision,
 1674                ProgressNotify = true,
 1675                PrevKv = true
 1676            }
 1677        };
 678
 679        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1680        Action<WatchResponse> callback = response =>
 2681        {
 2682            if (response.Events == null)
 0683            {
 0684                return;
 1685            }
 1686
 8687            foreach (Event evt in response.Events)
 1688            {
 1689                WatchEvent watchEvent = new()
 1690                {
 1691                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1692                };
 1693                action(watchEvent);
 1694            }
 3695        };
 696
 697        // Call the WatchAsync method with the request
 1698        return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false);
 1699    }
 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)
 1713    {
 1714        ObjectDisposedException.ThrowIf(_disposed, this);
 715
 716        // Create a watch request for the range with start revision
 1717        WatchRequest request = new()
 1718        {
 1719            CreateRequest = new WatchCreateRequest
 1720            {
 1721                Key = ByteString.CopyFromUtf8(prefixKey),
 1722                RangeEnd = EtcdClient.GetRangeEnd(ByteString.CopyFromUtf8(prefixKey)),
 1723                StartRevision = startRevision,
 1724                ProgressNotify = true,
 1725                PrevKv = true
 1726            }
 1727        };
 728
 729        // Create a wrapper callback that converts the WatchResponse to a WatchEvent
 1730        Action<WatchResponse> callback = response =>
 2731        {
 2732            if (response.Events == null)
 0733            {
 0734                return;
 1735            }
 1736
 8737            foreach (Event evt in response.Events)
 1738            {
 1739                WatchEvent watchEvent = new()
 1740                {
 1741                    Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type
 1742                };
 1743                action(watchEvent);
 1744            }
 3745        };
 746
 747        // Call the WatchAsync method with the request
 1748        return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false);
 1749    }
 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)
 1762    {
 1763        ObjectDisposedException.ThrowIf(_disposed, this);
 764
 765        // Create a watch request for the range
 1766        WatchRequest request = new()
 1767        {
 1768            CreateRequest = new WatchCreateRequest
 1769            {
 1770                Key = ByteString.CopyFromUtf8(path),
 1771                RangeEnd = EtcdClient.GetRangeEnd(ByteString.CopyFromUtf8(path)),
 1772                ProgressNotify = true,
 1773                PrevKv = true
 1774            }
 1775        };
 776
 777        // Call the Watch method with the request
 1778        return Watch(request, callback, headers, deadline, cancellationToken);
 1779    }
 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)
 8786    {
 8787        ObjectDisposedException.ThrowIf(_disposed, this);
 788
 8789        if (!_watches.TryRemove(watchId, out WatchCancellation? watchCancellation))
 2790        {
 2791            return;
 792        }
 793
 794        // Cancel the watch
 6795        SafeCancel(watchCancellation.CancellationTokenSource);
 796
 797        // Find the server watch ID that corresponds to our client watch ID
 6798        long serverWatchId = GetServerWatchId(watchId);
 799
 800        // Cancel the watch on the server if we found a mapping
 6801        if (serverWatchId != -1 && _watchStream != null)
 6802        {
 6803            _watchIdMapping.TryRemove(serverWatchId, out _);
 6804            _watchStream.CancelWatchAsync(serverWatchId).ContinueWith(_ =>
 6805            {
 6806                // Ignore exceptions
 12807            });
 6808        }
 809
 810        // Dispose the cancellation token source
 6811        watchCancellation.CancellationTokenSource.Dispose();
 8812    }
 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)
 41819    {
 41820        if (_disposed)
 35821        {
 35822            return;
 823        }
 824
 825        try
 6826        {
 6827            CancelWatch(watchId);
 6828        }
 0829        catch (ObjectDisposedException)
 0830        {
 831            // Disposed between the check and the call; nothing left to cancel.
 0832        }
 41833    }
 834
 835    /// <summary>
 836    ///     Disposes the watch manager
 837    /// </summary>
 838    public void Dispose()
 136839    {
 136840        if (_disposed)
 4841        {
 4842            return;
 843        }
 844
 132845        _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.
 396849        foreach (TaskCompletionSource<WatchResponse> pending in _pendingCreates.Values)
 0850        {
 0851            pending.TrySetException(new ObjectDisposedException(nameof(WatchManager)));
 0852        }
 853
 132854        _pendingCreates.Clear();
 855
 856        // Cancel all watches
 466857        foreach (WatchCancellation watchCancellation in _watches.Values)
 35858        {
 35859            SafeCancel(watchCancellation.CancellationTokenSource);
 35860            watchCancellation.CancellationTokenSource.Dispose();
 35861        }
 862
 132863        _watches.Clear();
 864
 865        // Dispose the watch stream
 132866        if (_watchStream != null)
 38867        {
 38868            _watchStream.Dispose();
 38869            _watchStream = null;
 38870        }
 871
 132872        GC.SuppressFinalize(this);
 136873    }
 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)
 6881    {
 24882        foreach (KeyValuePair<long, long> kvp in _watchIdMapping)
 6883        {
 6884            if (kvp.Value == clientWatchId)
 6885            {
 6886                return kvp.Key;
 887            }
 0888        }
 889
 0890        return -1;
 6891    }
 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)
 104901    {
 104902        lock (_lockObject)
 104903        {
 104904            if (_watchStream != null)
 21905            {
 21906                return;
 907            }
 908
 909            // Create a new watch stream
 83910            IAsyncDuplexStreamingCall<WatchRequest, WatchResponse> watchStreamCall =
 83911                _watchStreamFactory(headers, deadline, cancellationToken);
 83912            _watchStream = new Watcher(watchStreamCall, HandleConnectionFailure);
 83913        }
 104914    }
 915
 916    private void HandleConnectionFailure()
 12917    {
 918        Watcher? abandoned;
 919
 12920        lock (_lockObject)
 12921        {
 12922            abandoned = _watchStream;
 12923            _watchStream = null;
 12924            _watchIdMapping.Clear();
 12925        }
 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.
 12930        abandoned?.Dispose();
 931
 932        // Must run async to avoid blocking the caller (which might be the dead stream loop)
 12933        Task.Run(async () =>
 12934        {
 12935            try
 12936            {
 12937                // Wait small delay to allow network to stabilize
 12938                await Task.Delay(500);
 12939
 12940                lock (_lockObject)
 12941                {
 13942                   if (_disposed) return;
 11943                   EnsureWatchStream(null, null, default);
 11944                }
 12945
 11946                bool anyFailed = false;
 12947
 53948                foreach (var watch in _watches.Values)
 10949                {
 12950                    // A watch whose deadline or token fired while the stream was down is on its way out
 12951                    // of _watches; re-registering it would resurrect it on the new stream.
 10952                    if (watch.CancellationTokenSource.IsCancellationRequested)
 0953                    {
 0954                        continue;
 12955                    }
 12956
 12957                    // Resume from the revision after the last observed event so events written while
 12958                    // the stream was down are replayed instead of lost. A watch whose create was never
 12959                    // acknowledged has nothing to resume from, but nothing can have been missed either:
 12960                    // its Watch() call has not returned yet, so the caller cannot have written anything.
 10961                    if (watch.NextRevision > 0 && watch.Request.CreateRequest != null)
 9962                    {
 9963                        watch.Request.CreateRequest.StartRevision = watch.NextRevision;
 9964                    }
 12965
 12966                    try
 10967                    {
 10968                        await _watchStream!.CreateWatchAsync(watch.Request, watch.Callback).ConfigureAwait(false);
 10969                    }
 0970                    catch (Exception ex)
 0971                    {
 12972                        // Keep going: one watch failing to re-register must not strand the others. But
 12973                        // remember it failed — swallowing it here would otherwise disable the retry
 12974                        // below and leave that watch silently dead for the life of the client.
 0975                        anyFailed = true;
 0976                        Console.Error.WriteLine($"Failed to re-register watch {watch.WatchId}: {ex.Message}");
 0977                    }
 10978                }
 12979
 11980                if (anyFailed)
 0981                {
 0982                    throw new InvalidOperationException("one or more watches could not be re-registered");
 12983                }
 11984            }
 0985            catch (Exception ex)
 0986            {
 0987                Console.Error.WriteLine($"Watch reconnection failed: {ex.Message}");
 12988                // Retry in 5s
 0989                _ = Task.Delay(5000).ContinueWith(_ => HandleConnectionFailure());
 0990            }
 24991        });
 12992    }
 993
 994    private class WatchCancellation
 995    {
 93996        public long WatchId { get; set; }
 185997        public required CancellationTokenSource CancellationTokenSource { get; set; }
 121998        public required WatchRequest Request { get; set; }
 103999        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>
 4881007        public long NextRevision { get; set; }
 1008    }
 1009}

Methods/Properties

.cctor()
.ctor(System.Func`4<Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken,dotnet_etcd.interfaces.IAsyncDuplexStreamingCall`2<Etcdserverpb.WatchRequest,Etcdserverpb.WatchResponse>>)
WatchAsync()
WrappedCallback()
Dispatch(System.Int64,Etcdserverpb.WatchResponse,System.Action`1<Etcdserverpb.WatchResponse>,System.Threading.CancellationTokenSource)
AckTimeoutFor(System.Nullable`1<System.DateTime>)
SafeCancel(System.Threading.CancellationTokenSource)
TrackResumeRevision(System.Int64,Etcdserverpb.WatchResponse)
Watch(Etcdserverpb.WatchRequest,System.Action`1<Etcdserverpb.WatchResponse>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
Watch(System.String,System.Action`1<dotnet_etcd.WatchEvent>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
Callback()
WatchRange(System.String,System.Action`1<dotnet_etcd.WatchEvent>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
Watch(System.String,System.Int64,System.Action`1<dotnet_etcd.WatchEvent>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
WatchRange(System.String,System.Int64,System.Action`1<dotnet_etcd.WatchEvent>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
WatchAsync()
WatchRangeAsync()
WatchAsync()
WatchRangeAsync()
WatchRange(System.String,System.Action`1<Etcdserverpb.WatchResponse>,Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
CancelWatch(System.Int64)
CancelWatchQuietly(System.Int64)
Dispose()
GetServerWatchId(System.Int64)
EnsureWatchStream(Grpc.Core.Metadata,System.Nullable`1<System.DateTime>,System.Threading.CancellationToken)
HandleConnectionFailure()
get_WatchId()
get_CancellationTokenSource()
get_Request()
get_Callback()
get_NextRevision()