| | | 1 | | #nullable enable |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Concurrent; |
| | | 4 | | using System.Threading; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using dotnet_etcd.interfaces; |
| | | 7 | | using Etcdserverpb; |
| | | 8 | | using Grpc.Core; |
| | | 9 | | |
| | | 10 | | namespace dotnet_etcd; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Manages a bidirectional streaming connection to the etcd watch API |
| | | 14 | | /// </summary> |
| | | 15 | | public class Watcher : IWatcher |
| | | 16 | | { |
| | 72 | 17 | | private readonly ConcurrentDictionary<long, Action<WatchResponse>> _callbacks = new(); |
| | 72 | 18 | | private readonly CancellationTokenSource _cts = new(); |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// gRPC allows only one pending write per stream ("Only one write can be pending at a time"). |
| | | 22 | | /// Creates and cancels are issued from user threads and from the reconnect loop, so the writes |
| | | 23 | | /// must be serialized. The lock covers the write only — never a wait for a server response, or |
| | | 24 | | /// a create awaiting its acknowledgement would block every cancel and reconnect behind it. |
| | | 25 | | /// </summary> |
| | 72 | 26 | | private readonly SemaphoreSlim _writeLock = new(1, 1); |
| | | 27 | | |
| | | 28 | | private readonly IAsyncDuplexStreamingCall<WatchRequest, WatchResponse> _streamingCall; |
| | | 29 | | private readonly Action? _onConnectionFailure; |
| | | 30 | | |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Creates a new Watcher |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="streamingCall">The streaming call to use</param> |
| | | 36 | | /// <param name="onConnectionFailure">Action to invoke when connection fails</param> |
| | 72 | 37 | | public Watcher(IAsyncDuplexStreamingCall<WatchRequest, WatchResponse> streamingCall, Action? onConnectionFailure = n |
| | 72 | 38 | | { |
| | 72 | 39 | | _streamingCall = streamingCall ?? throw new ArgumentNullException(nameof(streamingCall)); |
| | 71 | 40 | | _onConnectionFailure = onConnectionFailure; |
| | 71 | 41 | | _ = ProcessWatchResponses(); |
| | 71 | 42 | | } |
| | | 43 | | |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Creates a watch for the specified request |
| | | 47 | | /// </summary> |
| | | 48 | | /// <param name="request">The watch request</param> |
| | | 49 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 50 | | /// <returns>A task that completes when the watch is created</returns> |
| | | 51 | | public async Task CreateWatchAsync(WatchRequest request, Action<WatchResponse> callback) |
| | 83 | 52 | | { |
| | 83 | 53 | | ArgumentNullException.ThrowIfNull(request); |
| | | 54 | | |
| | 82 | 55 | | ArgumentNullException.ThrowIfNull(callback); |
| | | 56 | | |
| | 81 | 57 | | long watchId = request.CreateRequest.WatchId; |
| | | 58 | | |
| | | 59 | | // Register before writing: the server can answer before WriteAsync returns. |
| | 81 | 60 | | _callbacks[watchId] = callback; |
| | | 61 | | |
| | | 62 | | try |
| | 81 | 63 | | { |
| | 81 | 64 | | await WriteAsync(request).ConfigureAwait(false); |
| | 81 | 65 | | } |
| | 0 | 66 | | catch |
| | 0 | 67 | | { |
| | | 68 | | // The create never reached the server; don't leave a callback behind for a watch that |
| | | 69 | | // does not exist. |
| | 0 | 70 | | _callbacks.TryRemove(watchId, out _); |
| | 0 | 71 | | throw; |
| | | 72 | | } |
| | 81 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Cancels a watch with the specified ID |
| | | 77 | | /// </summary> |
| | | 78 | | /// <param name="watchId">The ID of the watch to cancel</param> |
| | | 79 | | /// <returns>A task that completes when the watch is canceled</returns> |
| | | 80 | | public async Task CancelWatchAsync(long watchId) |
| | 2 | 81 | | { |
| | | 82 | | // Send a cancel request |
| | 2 | 83 | | WatchRequest request = new() { CancelRequest = new WatchCancelRequest { WatchId = watchId } }; |
| | | 84 | | |
| | 2 | 85 | | await WriteAsync(request).ConfigureAwait(false); |
| | | 86 | | |
| | | 87 | | // Remove the callback |
| | 2 | 88 | | _callbacks.TryRemove(watchId, out _); |
| | 2 | 89 | | } |
| | | 90 | | |
| | | 91 | | private async Task WriteAsync(WatchRequest request) |
| | 83 | 92 | | { |
| | 83 | 93 | | await _writeLock.WaitAsync(_cts.Token).ConfigureAwait(false); |
| | | 94 | | try |
| | 83 | 95 | | { |
| | 83 | 96 | | await _streamingCall.RequestStream.WriteAsync(request).ConfigureAwait(false); |
| | 83 | 97 | | } |
| | | 98 | | finally |
| | 83 | 99 | | { |
| | 83 | 100 | | _writeLock.Release(); |
| | 83 | 101 | | } |
| | 83 | 102 | | } |
| | | 103 | | |
| | | 104 | | private async Task ProcessWatchResponses() |
| | 71 | 105 | | { |
| | | 106 | | try |
| | 71 | 107 | | { |
| | 226 | 108 | | while (await _streamingCall.ResponseStream.MoveNext(_cts.Token)) |
| | 155 | 109 | | { |
| | 155 | 110 | | WatchResponse response = _streamingCall.ResponseStream.Current; |
| | 155 | 111 | | if (!_callbacks.TryGetValue(response.WatchId, out Action<WatchResponse>? cb)) |
| | 9 | 112 | | { |
| | 9 | 113 | | continue; |
| | | 114 | | } |
| | | 115 | | |
| | 146 | 116 | | cb(response); |
| | | 117 | | |
| | | 118 | | // If the watch was canceled, remove the callback after invoking it |
| | 146 | 119 | | if (response.Canceled) |
| | 2 | 120 | | { |
| | 2 | 121 | | _callbacks.TryRemove(response.WatchId, out _); |
| | 2 | 122 | | } |
| | 146 | 123 | | } |
| | 0 | 124 | | } |
| | 11 | 125 | | catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled) |
| | 1 | 126 | | { |
| | | 127 | | // This is expected when the stream is canceled |
| | 1 | 128 | | } |
| | 34 | 129 | | catch (OperationCanceledException) |
| | 34 | 130 | | { |
| | | 131 | | // This is expected when the token is canceled |
| | 34 | 132 | | } |
| | 10 | 133 | | catch (RpcException ex) |
| | 10 | 134 | | { |
| | | 135 | | // Log a simplified message for expected connection failures |
| | 10 | 136 | | Console.WriteLine($"Watch stream connection lost: {ex.StatusCode} - {ex.Message}"); |
| | 10 | 137 | | _onConnectionFailure?.Invoke(); |
| | 10 | 138 | | } |
| | 0 | 139 | | catch (Exception ex) |
| | 0 | 140 | | { |
| | | 141 | | // Log the exception |
| | 0 | 142 | | await Console.Error.WriteAsync($"Error processing watch responses: {ex}"); |
| | 0 | 143 | | _onConnectionFailure?.Invoke(); |
| | | 144 | | #if DEBUG |
| | | 145 | | // Only re-throw in debug mode to help with debugging |
| | 0 | 146 | | throw; |
| | | 147 | | #endif |
| | | 148 | | } |
| | 45 | 149 | | } |
| | | 150 | | |
| | | 151 | | /// <summary> |
| | | 152 | | /// Disposes the watch stream |
| | | 153 | | /// </summary> |
| | | 154 | | public void Dispose() |
| | 45 | 155 | | { |
| | 45 | 156 | | _cts.Cancel(); |
| | 45 | 157 | | _streamingCall.Dispose(); |
| | | 158 | | |
| | | 159 | | // Deliberately not disposing _writeLock/_cts: a write may be in flight, and disposing them |
| | | 160 | | // underneath it would surface as an ObjectDisposedException from inside the semaphore instead |
| | | 161 | | // of the stream's own cancellation. Neither holds an unmanaged resource here, so letting the |
| | | 162 | | // GC reclaim them is safe. |
| | | 163 | | |
| | 45 | 164 | | GC.SuppressFinalize(this); |
| | 45 | 165 | | } |
| | | 166 | | } |