| | | 1 | | #nullable enable |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Concurrent; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using dotnet_etcd.interfaces; |
| | | 9 | | using Etcdserverpb; |
| | | 10 | | using Google.Protobuf; |
| | | 11 | | using Grpc.Core; |
| | | 12 | | using Mvccpb; |
| | | 13 | | |
| | | 14 | | namespace dotnet_etcd; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Manages watch streams and provides a way to cancel watches |
| | | 18 | | /// </summary> |
| | | 19 | | public class WatchManager : IWatchManager |
| | | 20 | | { |
| | 354 | 21 | | private readonly object _lockObject = new(); |
| | 354 | 22 | | private readonly ConcurrentDictionary<long, WatchCancellation> _watches = new(); |
| | 354 | 23 | | private readonly ConcurrentDictionary<long, long> _watchIdMapping = new(); |
| | | 24 | | |
| | | 25 | | private readonly |
| | | 26 | | Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>> |
| | | 27 | | _watchStreamFactory; |
| | | 28 | | |
| | | 29 | | private bool _disposed; |
| | 354 | 30 | | private long _nextWatchId = 1; |
| | | 31 | | private Watcher? _watchStream; |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Creates a new WatchManager |
| | | 35 | | /// </summary> |
| | | 36 | | /// <param name="watchStreamFactory">A factory function that creates a new watch stream</param> |
| | 354 | 37 | | public WatchManager( |
| | 354 | 38 | | Func<Metadata?, DateTime?, CancellationToken, IAsyncDuplexStreamingCall<WatchRequest, WatchResponse>> |
| | 708 | 39 | | watchStreamFactory) => _watchStreamFactory = |
| | 354 | 40 | | watchStreamFactory ?? throw new ArgumentNullException(nameof(watchStreamFactory)); |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Creates a new watch request |
| | | 44 | | /// </summary> |
| | | 45 | | /// <param name="request">The watch requests to create</param> |
| | | 46 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 47 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 48 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 49 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 50 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 51 | | public async Task<long> WatchAsync(WatchRequest request, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 52 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 65 | 53 | | { |
| | 65 | 54 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 55 | | |
| | | 56 | | // Create a new watch stream if needed |
| | 64 | 57 | | EnsureWatchStream(headers, deadline, cancellationToken); |
| | | 58 | | |
| | | 59 | | // Generate a new watch ID |
| | 64 | 60 | | long watchId = Interlocked.Increment(ref _nextWatchId); |
| | | 61 | | |
| | | 62 | | // Create a cancellation token source that can be used to cancel the watch |
| | 64 | 63 | | CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 64 | | |
| | | 65 | | // Create a watch cancellation object |
| | 64 | 66 | | WatchCancellation watchCancellation = new() |
| | 64 | 67 | | { |
| | 64 | 68 | | WatchId = watchId, |
| | 64 | 69 | | CancellationTokenSource = cts, |
| | 64 | 70 | | Request = request, |
| | 64 | 71 | | Callback = WrappedCallback |
| | 64 | 72 | | }; |
| | | 73 | | |
| | 64 | 74 | | request.CreateRequest.WatchId = watchId; |
| | | 75 | | // Create the watch |
| | 64 | 76 | | await _watchStream!.CreateWatchAsync(request, WrappedCallback).ConfigureAwait(false); |
| | | 77 | | |
| | | 78 | | // Add the watch cancellation to the dictionary |
| | 64 | 79 | | _watches[watchId] = watchCancellation; |
| | | 80 | | |
| | | 81 | | // Since we don't get a server watch ID from CreateWatchAsync, we can't map it |
| | | 82 | | // The server will assign a watch ID and include it in the watch response |
| | | 83 | | // Our wrappedCallback will handle this mapping when it receives the response |
| | | 84 | | |
| | 64 | 85 | | return watchId; |
| | | 86 | | |
| | | 87 | | // Create a wrapper callback that checks if the watch has been canceled |
| | | 88 | | void WrappedCallback(WatchResponse response) |
| | 77 | 89 | | { |
| | 77 | 90 | | if (cts.IsCancellationRequested) |
| | 0 | 91 | | { |
| | 0 | 92 | | return; |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | // If this is a creation response, update our watch ID mapping |
| | 77 | 96 | | if (response.Created) |
| | 12 | 97 | | { |
| | | 98 | | // Map the server-assigned watch ID to our client-generated watch ID |
| | 12 | 99 | | _watchIdMapping[response.WatchId] = watchId; |
| | 12 | 100 | | } |
| | | 101 | | |
| | | 102 | | // Track the revision to resume from on reconnect so no events are missed in the gap. |
| | 77 | 103 | | TrackResumeRevision(watchId, response); |
| | | 104 | | |
| | 77 | 105 | | callback(response); |
| | 77 | 106 | | } |
| | 64 | 107 | | } |
| | | 108 | | |
| | | 109 | | /// <summary> |
| | | 110 | | /// Advances the stored resume revision for a watch based on a received response, mirroring the |
| | | 111 | | /// etcd clientv3 "nextRev" logic: after an event batch resume from lastEvent.ModRevision + 1; |
| | | 112 | | /// for a created/progress notification with no events, advance to the header revision. A |
| | | 113 | | /// compaction cancel resets the resume point to the compact revision. Only ever moves forward. |
| | | 114 | | /// </summary> |
| | | 115 | | private void TrackResumeRevision(long clientWatchId, WatchResponse response) |
| | 77 | 116 | | { |
| | 77 | 117 | | if (!_watches.TryGetValue(clientWatchId, out WatchCancellation? watch)) |
| | 0 | 118 | | { |
| | 0 | 119 | | return; |
| | | 120 | | } |
| | | 121 | | |
| | 77 | 122 | | long candidate = watch.NextRevision; |
| | | 123 | | |
| | 77 | 124 | | if (response.Canceled && response.CompactRevision > 0) |
| | 1 | 125 | | { |
| | | 126 | | // Our resume point was compacted away; the earliest we can resume from is CompactRevision. |
| | 1 | 127 | | candidate = response.CompactRevision; |
| | 1 | 128 | | } |
| | 76 | 129 | | else if (response.Events != null && response.Events.Count > 0) |
| | 62 | 130 | | { |
| | 62 | 131 | | long lastModRevision = response.Events[^1].Kv.ModRevision; |
| | 62 | 132 | | if (lastModRevision + 1 > candidate) |
| | 61 | 133 | | { |
| | 61 | 134 | | candidate = lastModRevision + 1; |
| | 61 | 135 | | } |
| | 62 | 136 | | } |
| | 14 | 137 | | else if (response.Header != null && response.Header.Revision > 0) |
| | 11 | 138 | | { |
| | | 139 | | // Created response or progress notification (no events): everything up to the header |
| | | 140 | | // revision has been observed, so the next start revision is header.Revision + 1. |
| | 11 | 141 | | long boundary = response.Header.Revision + 1; |
| | 11 | 142 | | if (boundary > candidate) |
| | 11 | 143 | | { |
| | 11 | 144 | | candidate = boundary; |
| | 11 | 145 | | } |
| | 11 | 146 | | } |
| | | 147 | | |
| | 77 | 148 | | watch.NextRevision = candidate; |
| | 77 | 149 | | } |
| | | 150 | | |
| | | 151 | | /// <summary> |
| | | 152 | | /// Creates a new watch request |
| | | 153 | | /// </summary> |
| | | 154 | | /// <param name="request">The watch request to create</param> |
| | | 155 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 156 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 157 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 158 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 159 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 160 | | public long Watch(WatchRequest request, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 161 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 34 | 162 | | { |
| | | 163 | | // Run the async method synchronously |
| | 68 | 164 | | Task<long> task = Task.Run(() => WatchAsync(request, callback, headers, deadline, cancellationToken), cancellati |
| | 34 | 165 | | task.Wait(cancellationToken); |
| | 34 | 166 | | return task.Result; |
| | 34 | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Watches a specific key |
| | | 171 | | /// </summary> |
| | | 172 | | /// <param name="key">Key to watch</param> |
| | | 173 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 174 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 175 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 176 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 177 | | /// <returns>Watch ID</returns> |
| | | 178 | | public long Watch(string key, Action<WatchEvent> action, Metadata? headers = null, DateTime? deadline = null, |
| | | 179 | | CancellationToken cancellationToken = default) |
| | 2 | 180 | | { |
| | 2 | 181 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 182 | | |
| | | 183 | | // Create a watch request for the key |
| | 1 | 184 | | WatchRequest request = new() |
| | 1 | 185 | | { |
| | 1 | 186 | | CreateRequest = new WatchCreateRequest |
| | 1 | 187 | | { |
| | 1 | 188 | | Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true |
| | 1 | 189 | | } |
| | 1 | 190 | | }; |
| | | 191 | | |
| | | 192 | | // Call the Watch method with the request |
| | 1 | 193 | | return Watch(request, Callback, headers, deadline, cancellationToken); |
| | | 194 | | |
| | | 195 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | | 196 | | void Callback(WatchResponse response) |
| | 1 | 197 | | { |
| | 1 | 198 | | if (response.Events == null) |
| | 0 | 199 | | { |
| | 0 | 200 | | return; |
| | | 201 | | } |
| | | 202 | | |
| | 5 | 203 | | foreach (Event evt in response.Events) |
| | 1 | 204 | | { |
| | 1 | 205 | | WatchEvent watchEvent = new() { Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Ty |
| | 1 | 206 | | action(watchEvent); |
| | 1 | 207 | | } |
| | 1 | 208 | | } |
| | 1 | 209 | | } |
| | | 210 | | |
| | | 211 | | /// <summary> |
| | | 212 | | /// Watches a range of keys with a prefix |
| | | 213 | | /// </summary> |
| | | 214 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 215 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 216 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 217 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 218 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 219 | | /// <returns>Watch ID</returns> |
| | | 220 | | public long WatchRange(string prefixKey, Action<WatchEvent> action, Metadata? headers = null, |
| | | 221 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 222 | | { |
| | 1 | 223 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 224 | | |
| | | 225 | | // Create a watch request for the range |
| | 1 | 226 | | WatchRequest request = new() |
| | 1 | 227 | | { |
| | 1 | 228 | | CreateRequest = new WatchCreateRequest |
| | 1 | 229 | | { |
| | 1 | 230 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 231 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 232 | | ProgressNotify = true, |
| | 1 | 233 | | PrevKv = true |
| | 1 | 234 | | } |
| | 1 | 235 | | }; |
| | | 236 | | |
| | | 237 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 238 | | Action<WatchResponse> callback = response => |
| | 1 | 239 | | { |
| | 1 | 240 | | if (response.Events == null) |
| | 0 | 241 | | { |
| | 0 | 242 | | return; |
| | 1 | 243 | | } |
| | 1 | 244 | | |
| | 5 | 245 | | foreach (Event evt in response.Events) |
| | 1 | 246 | | { |
| | 1 | 247 | | WatchEvent watchEvent = new() |
| | 1 | 248 | | { |
| | 1 | 249 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 250 | | }; |
| | 1 | 251 | | action(watchEvent); |
| | 1 | 252 | | } |
| | 2 | 253 | | }; |
| | | 254 | | |
| | | 255 | | // Call the Watch method with the request |
| | 1 | 256 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 257 | | } |
| | | 258 | | |
| | | 259 | | /// <summary> |
| | | 260 | | /// Watches a specific key with start revision |
| | | 261 | | /// </summary> |
| | | 262 | | /// <param name="key">Key to watch</param> |
| | | 263 | | /// <param name="startRevision">Start revision</param> |
| | | 264 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 265 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 266 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 267 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 268 | | /// <returns>Watch ID</returns> |
| | | 269 | | public long Watch(string key, long startRevision, Action<WatchEvent> action, Metadata? headers = null, |
| | | 270 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 271 | | { |
| | 1 | 272 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 273 | | |
| | | 274 | | // Create a watch request for the key with start revision |
| | 1 | 275 | | WatchRequest request = new() |
| | 1 | 276 | | { |
| | 1 | 277 | | CreateRequest = new WatchCreateRequest |
| | 1 | 278 | | { |
| | 1 | 279 | | Key = ByteString.CopyFromUtf8(key), |
| | 1 | 280 | | StartRevision = startRevision, |
| | 1 | 281 | | ProgressNotify = true, |
| | 1 | 282 | | PrevKv = true |
| | 1 | 283 | | } |
| | 1 | 284 | | }; |
| | | 285 | | |
| | | 286 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 287 | | Action<WatchResponse> callback = response => |
| | 1 | 288 | | { |
| | 1 | 289 | | if (response.Events == null) |
| | 0 | 290 | | { |
| | 0 | 291 | | return; |
| | 1 | 292 | | } |
| | 1 | 293 | | |
| | 5 | 294 | | foreach (Event evt in response.Events) |
| | 1 | 295 | | { |
| | 1 | 296 | | WatchEvent watchEvent = new() |
| | 1 | 297 | | { |
| | 1 | 298 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 299 | | }; |
| | 1 | 300 | | action(watchEvent); |
| | 1 | 301 | | } |
| | 2 | 302 | | }; |
| | | 303 | | |
| | | 304 | | // Call the Watch method with the request |
| | 1 | 305 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <summary> |
| | | 309 | | /// Watches a range of keys with a prefix and start revision |
| | | 310 | | /// </summary> |
| | | 311 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 312 | | /// <param name="startRevision">Start revision</param> |
| | | 313 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 314 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 315 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 316 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 317 | | /// <returns>Watch ID</returns> |
| | | 318 | | public long WatchRange(string prefixKey, long startRevision, Action<WatchEvent> action, Metadata? headers = null, |
| | | 319 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 320 | | { |
| | 1 | 321 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 322 | | |
| | | 323 | | // Create a watch request for the range with start revision |
| | 1 | 324 | | WatchRequest request = new() |
| | 1 | 325 | | { |
| | 1 | 326 | | CreateRequest = new WatchCreateRequest |
| | 1 | 327 | | { |
| | 1 | 328 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 329 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 330 | | StartRevision = startRevision, |
| | 1 | 331 | | ProgressNotify = true, |
| | 1 | 332 | | PrevKv = true |
| | 1 | 333 | | } |
| | 1 | 334 | | }; |
| | | 335 | | |
| | | 336 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 337 | | Action<WatchResponse> callback = response => |
| | 1 | 338 | | { |
| | 1 | 339 | | if (response.Events == null) |
| | 0 | 340 | | { |
| | 0 | 341 | | return; |
| | 1 | 342 | | } |
| | 1 | 343 | | |
| | 5 | 344 | | foreach (Event evt in response.Events) |
| | 1 | 345 | | { |
| | 1 | 346 | | WatchEvent watchEvent = new() |
| | 1 | 347 | | { |
| | 1 | 348 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 349 | | }; |
| | 1 | 350 | | action(watchEvent); |
| | 1 | 351 | | } |
| | 2 | 352 | | }; |
| | | 353 | | |
| | | 354 | | // Call the Watch method with the request |
| | 1 | 355 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 356 | | } |
| | | 357 | | |
| | | 358 | | /// <summary> |
| | | 359 | | /// Watches a specific key asynchronously |
| | | 360 | | /// </summary> |
| | | 361 | | /// <param name="key">Key to watch</param> |
| | | 362 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 363 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 364 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 365 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 366 | | /// <returns>Watch ID</returns> |
| | | 367 | | public async Task<long> WatchAsync(string key, Action<WatchEvent> action, Metadata? headers = null, |
| | | 368 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 369 | | { |
| | 1 | 370 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 371 | | |
| | | 372 | | // Create a watch request for the key |
| | 1 | 373 | | WatchRequest request = new() |
| | 1 | 374 | | { |
| | 1 | 375 | | CreateRequest = new WatchCreateRequest |
| | 1 | 376 | | { |
| | 1 | 377 | | Key = ByteString.CopyFromUtf8(key), ProgressNotify = true, PrevKv = true |
| | 1 | 378 | | } |
| | 1 | 379 | | }; |
| | | 380 | | |
| | | 381 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 382 | | Action<WatchResponse> callback = response => |
| | 1 | 383 | | { |
| | 1 | 384 | | if (response.Events == null) |
| | 0 | 385 | | { |
| | 0 | 386 | | return; |
| | 1 | 387 | | } |
| | 1 | 388 | | |
| | 5 | 389 | | foreach (Event evt in response.Events) |
| | 1 | 390 | | { |
| | 1 | 391 | | WatchEvent watchEvent = new() |
| | 1 | 392 | | { |
| | 1 | 393 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 394 | | }; |
| | 1 | 395 | | action(watchEvent); |
| | 1 | 396 | | } |
| | 2 | 397 | | }; |
| | | 398 | | |
| | | 399 | | // Call the WatchAsync method with the request |
| | 1 | 400 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 401 | | } |
| | | 402 | | |
| | | 403 | | /// <summary> |
| | | 404 | | /// Watches a range of keys with a prefix asynchronously |
| | | 405 | | /// </summary> |
| | | 406 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 407 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 408 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 409 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 410 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 411 | | /// <returns>Watch ID</returns> |
| | | 412 | | public async Task<long> WatchRangeAsync(string prefixKey, Action<WatchEvent> action, Metadata? headers = null, |
| | | 413 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 414 | | { |
| | 1 | 415 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 416 | | |
| | | 417 | | // Create a watch request for the range |
| | 1 | 418 | | WatchRequest request = new() |
| | 1 | 419 | | { |
| | 1 | 420 | | CreateRequest = new WatchCreateRequest |
| | 1 | 421 | | { |
| | 1 | 422 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 423 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 424 | | ProgressNotify = true, |
| | 1 | 425 | | PrevKv = true |
| | 1 | 426 | | } |
| | 1 | 427 | | }; |
| | | 428 | | |
| | | 429 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 430 | | Action<WatchResponse> callback = response => |
| | 1 | 431 | | { |
| | 1 | 432 | | if (response.Events == null) |
| | 0 | 433 | | { |
| | 0 | 434 | | return; |
| | 1 | 435 | | } |
| | 1 | 436 | | |
| | 5 | 437 | | foreach (Event evt in response.Events) |
| | 1 | 438 | | { |
| | 1 | 439 | | WatchEvent watchEvent = new() |
| | 1 | 440 | | { |
| | 1 | 441 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 442 | | }; |
| | 1 | 443 | | action(watchEvent); |
| | 1 | 444 | | } |
| | 2 | 445 | | }; |
| | | 446 | | |
| | | 447 | | // Call the WatchAsync method with the request |
| | 1 | 448 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 449 | | } |
| | | 450 | | |
| | | 451 | | /// <summary> |
| | | 452 | | /// Watches a specific key with start revision asynchronously |
| | | 453 | | /// </summary> |
| | | 454 | | /// <param name="key">Key to watch</param> |
| | | 455 | | /// <param name="startRevision">Start revision</param> |
| | | 456 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 457 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 458 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 459 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 460 | | /// <returns>Watch ID</returns> |
| | | 461 | | public async Task<long> WatchAsync(string key, long startRevision, Action<WatchEvent> action, |
| | | 462 | | Metadata? headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 463 | | { |
| | 1 | 464 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 465 | | |
| | | 466 | | // Create a watch request for the key with start revision |
| | 1 | 467 | | WatchRequest request = new() |
| | 1 | 468 | | { |
| | 1 | 469 | | CreateRequest = new WatchCreateRequest |
| | 1 | 470 | | { |
| | 1 | 471 | | Key = ByteString.CopyFromUtf8(key), |
| | 1 | 472 | | StartRevision = startRevision, |
| | 1 | 473 | | ProgressNotify = true, |
| | 1 | 474 | | PrevKv = true |
| | 1 | 475 | | } |
| | 1 | 476 | | }; |
| | | 477 | | |
| | | 478 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 479 | | Action<WatchResponse> callback = response => |
| | 1 | 480 | | { |
| | 1 | 481 | | if (response.Events == null) |
| | 0 | 482 | | { |
| | 0 | 483 | | return; |
| | 1 | 484 | | } |
| | 1 | 485 | | |
| | 5 | 486 | | foreach (Event evt in response.Events) |
| | 1 | 487 | | { |
| | 1 | 488 | | WatchEvent watchEvent = new() |
| | 1 | 489 | | { |
| | 1 | 490 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 491 | | }; |
| | 1 | 492 | | action(watchEvent); |
| | 1 | 493 | | } |
| | 2 | 494 | | }; |
| | | 495 | | |
| | | 496 | | // Call the WatchAsync method with the request |
| | 1 | 497 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 498 | | } |
| | | 499 | | |
| | | 500 | | /// <summary> |
| | | 501 | | /// Watches a range of keys with a prefix and start revision asynchronously |
| | | 502 | | /// </summary> |
| | | 503 | | /// <param name="prefixKey">Prefix key to watch</param> |
| | | 504 | | /// <param name="startRevision">Start revision</param> |
| | | 505 | | /// <param name="action">Action to be executed when watch event is triggered</param> |
| | | 506 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 507 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 508 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 509 | | /// <returns>Watch ID</returns> |
| | | 510 | | public async Task<long> WatchRangeAsync(string prefixKey, long startRevision, Action<WatchEvent> action, |
| | | 511 | | Metadata? headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 512 | | { |
| | 1 | 513 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 514 | | |
| | | 515 | | // Create a watch request for the range with start revision |
| | 1 | 516 | | WatchRequest request = new() |
| | 1 | 517 | | { |
| | 1 | 518 | | CreateRequest = new WatchCreateRequest |
| | 1 | 519 | | { |
| | 1 | 520 | | Key = ByteString.CopyFromUtf8(prefixKey), |
| | 1 | 521 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(prefixKey)), |
| | 1 | 522 | | StartRevision = startRevision, |
| | 1 | 523 | | ProgressNotify = true, |
| | 1 | 524 | | PrevKv = true |
| | 1 | 525 | | } |
| | 1 | 526 | | }; |
| | | 527 | | |
| | | 528 | | // Create a wrapper callback that converts the WatchResponse to a WatchEvent |
| | 1 | 529 | | Action<WatchResponse> callback = response => |
| | 1 | 530 | | { |
| | 1 | 531 | | if (response.Events == null) |
| | 0 | 532 | | { |
| | 0 | 533 | | return; |
| | 1 | 534 | | } |
| | 1 | 535 | | |
| | 5 | 536 | | foreach (Event evt in response.Events) |
| | 1 | 537 | | { |
| | 1 | 538 | | WatchEvent watchEvent = new() |
| | 1 | 539 | | { |
| | 1 | 540 | | Key = evt.Kv.Key.ToStringUtf8(), Value = evt.Kv.Value.ToStringUtf8(), Type = evt.Type |
| | 1 | 541 | | }; |
| | 1 | 542 | | action(watchEvent); |
| | 1 | 543 | | } |
| | 2 | 544 | | }; |
| | | 545 | | |
| | | 546 | | // Call the WatchAsync method with the request |
| | 1 | 547 | | return await WatchAsync(request, callback, headers, deadline, cancellationToken).ConfigureAwait(false); |
| | 1 | 548 | | } |
| | | 549 | | |
| | | 550 | | /// <summary> |
| | | 551 | | /// Watches a key range |
| | | 552 | | /// </summary> |
| | | 553 | | /// <param name="path">The path to watch</param> |
| | | 554 | | /// <param name="callback">The callback to invoke when a watch event is received</param> |
| | | 555 | | /// <param name="headers">The initial metadata to send with the call</param> |
| | | 556 | | /// <param name="deadline">An optional deadline for the call</param> |
| | | 557 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 558 | | /// <returns>A watch ID that can be used to cancel the watch</returns> |
| | | 559 | | public long WatchRange(string path, Action<WatchResponse> callback, Metadata? headers = null, |
| | | 560 | | DateTime? deadline = null, CancellationToken cancellationToken = default) |
| | 1 | 561 | | { |
| | 1 | 562 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 563 | | |
| | | 564 | | // Create a watch request for the range |
| | 1 | 565 | | WatchRequest request = new() |
| | 1 | 566 | | { |
| | 1 | 567 | | CreateRequest = new WatchCreateRequest |
| | 1 | 568 | | { |
| | 1 | 569 | | Key = ByteString.CopyFromUtf8(path), |
| | 1 | 570 | | RangeEnd = ByteString.CopyFromUtf8(GetRangeEnd(path)), |
| | 1 | 571 | | ProgressNotify = true, |
| | 1 | 572 | | PrevKv = true |
| | 1 | 573 | | } |
| | 1 | 574 | | }; |
| | | 575 | | |
| | | 576 | | // Call the Watch method with the request |
| | 1 | 577 | | return Watch(request, callback, headers, deadline, cancellationToken); |
| | 1 | 578 | | } |
| | | 579 | | |
| | | 580 | | /// <summary> |
| | | 581 | | /// Cancels a watch request |
| | | 582 | | /// </summary> |
| | | 583 | | /// <param name="watchId">The ID of the watch to cancel</param> |
| | | 584 | | public void CancelWatch(long watchId) |
| | 2 | 585 | | { |
| | 2 | 586 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 587 | | |
| | 2 | 588 | | if (!_watches.TryRemove(watchId, out WatchCancellation? watchCancellation)) |
| | 1 | 589 | | { |
| | 1 | 590 | | return; |
| | | 591 | | } |
| | | 592 | | |
| | | 593 | | // Cancel the watch |
| | 1 | 594 | | watchCancellation.CancellationTokenSource.Cancel(); |
| | | 595 | | |
| | | 596 | | // Find the server watch ID that corresponds to our client watch ID |
| | 1 | 597 | | long serverWatchId = GetServerWatchId(watchId); |
| | | 598 | | |
| | | 599 | | // Cancel the watch on the server if we found a mapping |
| | 1 | 600 | | if (serverWatchId != -1 && _watchStream != null) |
| | 1 | 601 | | { |
| | 1 | 602 | | _watchIdMapping.TryRemove(serverWatchId, out _); |
| | 1 | 603 | | _watchStream.CancelWatchAsync(serverWatchId).ContinueWith(_ => |
| | 1 | 604 | | { |
| | 1 | 605 | | // Ignore exceptions |
| | 2 | 606 | | }); |
| | 1 | 607 | | } |
| | | 608 | | |
| | | 609 | | // Dispose the cancellation token source |
| | 1 | 610 | | watchCancellation.CancellationTokenSource.Dispose(); |
| | 2 | 611 | | } |
| | | 612 | | |
| | | 613 | | /// <summary> |
| | | 614 | | /// Disposes the watch manager |
| | | 615 | | /// </summary> |
| | | 616 | | public void Dispose() |
| | 103 | 617 | | { |
| | 103 | 618 | | if (_disposed) |
| | 1 | 619 | | { |
| | 1 | 620 | | return; |
| | | 621 | | } |
| | | 622 | | |
| | 102 | 623 | | _disposed = true; |
| | | 624 | | |
| | | 625 | | // Cancel all watches |
| | 356 | 626 | | foreach (WatchCancellation watchCancellation in _watches.Values) |
| | 25 | 627 | | { |
| | 25 | 628 | | watchCancellation.CancellationTokenSource.Cancel(); |
| | 25 | 629 | | watchCancellation.CancellationTokenSource.Dispose(); |
| | 25 | 630 | | } |
| | | 631 | | |
| | 102 | 632 | | _watches.Clear(); |
| | | 633 | | |
| | | 634 | | // Dispose the watch stream |
| | 102 | 635 | | if (_watchStream != null) |
| | 25 | 636 | | { |
| | 25 | 637 | | _watchStream.Dispose(); |
| | 25 | 638 | | _watchStream = null; |
| | 25 | 639 | | } |
| | | 640 | | |
| | 102 | 641 | | GC.SuppressFinalize(this); |
| | 103 | 642 | | } |
| | | 643 | | |
| | | 644 | | private static string GetRangeEnd(string path) |
| | 5 | 645 | | { |
| | | 646 | | // Calculate the range end for the given path |
| | | 647 | | // This is the same logic used in EtcdClient.GetRangeEnd |
| | 5 | 648 | | byte[] bytes = Encoding.UTF8.GetBytes(path); |
| | 10 | 649 | | for (int i = bytes.Length - 1; i >= 0; i--) |
| | 5 | 650 | | { |
| | 5 | 651 | | if (bytes[i] >= 0xff) |
| | 0 | 652 | | { |
| | 0 | 653 | | continue; |
| | | 654 | | } |
| | | 655 | | |
| | 5 | 656 | | bytes[i]++; |
| | 5 | 657 | | return Encoding.UTF8.GetString(bytes, 0, i + 1); |
| | | 658 | | } |
| | | 659 | | |
| | 0 | 660 | | return string.Empty; |
| | 5 | 661 | | } |
| | | 662 | | |
| | | 663 | | /// <summary> |
| | | 664 | | /// Gets the server watch ID for a client watch ID |
| | | 665 | | /// </summary> |
| | | 666 | | /// <param name="clientWatchId">The client watch ID</param> |
| | | 667 | | /// <returns>The server watch ID, or -1 if not found</returns> |
| | | 668 | | private long GetServerWatchId(long clientWatchId) |
| | 1 | 669 | | { |
| | 4 | 670 | | foreach (KeyValuePair<long, long> kvp in _watchIdMapping) |
| | 1 | 671 | | { |
| | 1 | 672 | | if (kvp.Value == clientWatchId) |
| | 1 | 673 | | { |
| | 1 | 674 | | return kvp.Key; |
| | | 675 | | } |
| | 0 | 676 | | } |
| | | 677 | | |
| | 0 | 678 | | return -1; |
| | 1 | 679 | | } |
| | | 680 | | |
| | | 681 | | /// <param name="cancellationToken">An optional token for canceling the call</param> |
| | | 682 | | private void EnsureWatchStream(Metadata? headers, DateTime? deadline, CancellationToken cancellationToken) |
| | 68 | 683 | | { |
| | 68 | 684 | | lock (_lockObject) |
| | 68 | 685 | | { |
| | 68 | 686 | | if (_watchStream != null) |
| | 13 | 687 | | { |
| | 13 | 688 | | return; |
| | | 689 | | } |
| | | 690 | | |
| | | 691 | | // Create a new watch stream |
| | 55 | 692 | | IAsyncDuplexStreamingCall<WatchRequest, WatchResponse> watchStreamCall = |
| | 55 | 693 | | _watchStreamFactory(headers, deadline, cancellationToken); |
| | 55 | 694 | | _watchStream = new Watcher(watchStreamCall, HandleConnectionFailure); |
| | 55 | 695 | | } |
| | 68 | 696 | | } |
| | | 697 | | |
| | | 698 | | private void HandleConnectionFailure() |
| | 4 | 699 | | { |
| | 4 | 700 | | lock (_lockObject) |
| | 4 | 701 | | { |
| | 4 | 702 | | _watchStream = null; |
| | 4 | 703 | | _watchIdMapping.Clear(); |
| | 4 | 704 | | } |
| | | 705 | | |
| | | 706 | | // Must run async to avoid blocking the caller (which might be the dead stream loop) |
| | 4 | 707 | | Task.Run(async () => |
| | 4 | 708 | | { |
| | 4 | 709 | | try |
| | 4 | 710 | | { |
| | 4 | 711 | | // Wait small delay to allow network to stabilize |
| | 4 | 712 | | await Task.Delay(500); |
| | 4 | 713 | | |
| | 4 | 714 | | lock (_lockObject) |
| | 4 | 715 | | { |
| | 4 | 716 | | if (_disposed) return; |
| | 4 | 717 | | EnsureWatchStream(null, null, default); |
| | 4 | 718 | | } |
| | 4 | 719 | | |
| | 20 | 720 | | foreach (var watch in _watches.Values) |
| | 4 | 721 | | { |
| | 4 | 722 | | // Resume from the revision after the last observed event so events written while |
| | 4 | 723 | | // the stream was down are replayed instead of lost. Falls back to "from now" |
| | 4 | 724 | | // (StartRevision 0) only when nothing has been observed yet. |
| | 4 | 725 | | if (watch.NextRevision > 0 && watch.Request.CreateRequest != null) |
| | 4 | 726 | | { |
| | 4 | 727 | | watch.Request.CreateRequest.StartRevision = watch.NextRevision; |
| | 4 | 728 | | } |
| | 4 | 729 | | |
| | 4 | 730 | | await _watchStream!.CreateWatchAsync(watch.Request, watch.Callback).ConfigureAwait(false); |
| | 4 | 731 | | } |
| | 4 | 732 | | } |
| | 0 | 733 | | catch (Exception ex) |
| | 0 | 734 | | { |
| | 0 | 735 | | Console.Error.WriteLine($"Watch reconnection failed: {ex.Message}"); |
| | 4 | 736 | | // Retry in 5s |
| | 0 | 737 | | _ = Task.Delay(5000).ContinueWith(_ => HandleConnectionFailure()); |
| | 0 | 738 | | } |
| | 8 | 739 | | }); |
| | 4 | 740 | | } |
| | | 741 | | |
| | | 742 | | private class WatchCancellation |
| | | 743 | | { |
| | 64 | 744 | | public long WatchId { get; set; } |
| | 116 | 745 | | public required CancellationTokenSource CancellationTokenSource { get; set; } |
| | 76 | 746 | | public required WatchRequest Request { get; set; } |
| | 68 | 747 | | public required Action<WatchResponse> Callback { get; set; } |
| | | 748 | | |
| | | 749 | | /// <summary> |
| | | 750 | | /// The revision to resume this watch from if the stream is re-established. Tracks the |
| | | 751 | | /// revision after the last event/notification observed, so a reconnect does not miss |
| | | 752 | | /// events written during the gap (mirrors the etcd clientv3 nextRev behavior). |
| | | 753 | | /// </summary> |
| | 162 | 754 | | public long NextRevision { get; set; } |
| | | 755 | | } |
| | | 756 | | } |