From 4ff91ed3f09108deef6ec960b61d618426413bfc Mon Sep 17 00:00:00 2001 From: ahall Date: Thu, 5 Nov 2026 15:47:58 +0000 Subject: [PATCH 1/2] fix: throw from PushAsync when a queued operation times out TPL Dataflow treats an OperationCanceledException from an ActionBlock delegate as cooperative cancellation, silently dropping the item. A HttpClient.Timeout (TaskCanceledException) during push therefore left the operation queued while PushResult.IsSuccessful stayed true. QueueHandler now surfaces canceled jobs from WhenComplete(), and push converts a non-caller cancellation into a TimeoutException. Completed operations are still persisted before the exception is rethrown. A caller-requested cancellation still surfaces as OperationCanceledException. Closes #578 --- docs/in-depth/client/index.md | 3 + .../OperationsQueue/OperationsQueueManager.cs | 33 +++++++++- .../Threading/QueueHandler.cs | 25 ++++++-- .../Offline/OperationsQueueManager_Tests.cs | 63 +++++++++++++++++++ .../Threading/QueueHandler_Tests.cs | 22 +++++++ 5 files changed, 139 insertions(+), 7 deletions(-) diff --git a/docs/in-depth/client/index.md b/docs/in-depth/client/index.md index be1790b9..552a719a 100644 --- a/docs/in-depth/client/index.md +++ b/docs/in-depth/client/index.md @@ -201,6 +201,9 @@ When the push result is complete, the `PushResult` is returned. This has the fo In addition, the operations queue is updated. Completed operations are removed and failed operations are marked as failed. You can use the `FailedRequests` property to see the exact error that was returned by the service. +!!! note "Timeouts and network failures" + `FailedRequests` only records responses that were received from the service. If a request cannot complete (for example, the `HttpClient.Timeout` elapses or the connection is refused), `PushAsync()` throws instead of returning a result: a `TimeoutException` for a timeout, or an `HttpRequestException` for other network failures. Operations that completed before the failure are removed from the queue, and the operation that failed remains queued so it can be retried. If you cancel the push yourself through the `CancellationToken`, an `OperationCanceledException` is thrown. + ### Conflict resolution When a conflict resolver is configured, that will be used before a queued change is marked as failed. In the case of a failed request, you can process the failed requests as follows: diff --git a/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs b/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs index c278b17b..b6944f68 100644 --- a/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs +++ b/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs @@ -11,6 +11,7 @@ using Microsoft.EntityFrameworkCore.Metadata; using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Runtime.ExceptionServices; using System.Text.Json; using System.Text.Json.Serialization; @@ -295,7 +296,18 @@ internal async Task PushAsync(IEnumerable entityTypes, PushOpt // Push things in parallel, according to the PushOptions QueueHandler queueHandler = new(pushOptions.ParallelOperations, async operation => { - ServiceResponse? response = await PushOperationAsync(operation, cancellationToken).ConfigureAwait(false); + ServiceResponse? response; + try + { + response = await PushOperationAsync(operation, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested) + { + // The caller did not cancel, so this is a request timeout (HttpClient.Timeout). Don't let it be + // treated as cooperative cancellation (which drops the operation silently); fail the push instead. + throw new TimeoutException($"The push of operation '{operation.Id}' timed out.", ex); + } + pushResult.AddOperationResult(operation, response); // We can run on multiple threads, so use Interlocked to update the number of items processed. int newItemsProcessed = Interlocked.Increment(ref nrItemsProcessed); @@ -310,10 +322,25 @@ internal async Task PushAsync(IEnumerable entityTypes, PushOpt // Enqueue and process all the queued operations in scope queueHandler.EnqueueRange(queuedOperations); - await queueHandler.WhenComplete(); + Exception? pushException = null; + try + { + await queueHandler.WhenComplete().ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Operations that completed before the failure must still be persisted (removed from the queue), + // otherwise they would be pushed again. The failure is re-thrown after saving. + pushException = ex; + } // Save the changes, this time we don't update the queue. - _ = await this._context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, cancellationToken).ConfigureAwait(false); + _ = await this._context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, pushException is null ? cancellationToken : CancellationToken.None).ConfigureAwait(false); + + if (pushException is not null) + { + ExceptionDispatchInfo.Capture(pushException).Throw(); + } this._context.SendSynchronizationEvent(new SynchronizationEventArgs() { diff --git a/src/CommunityToolkit.Datasync.Client/Threading/QueueHandler.cs b/src/CommunityToolkit.Datasync.Client/Threading/QueueHandler.cs index 102ed926..4b5e3f71 100644 --- a/src/CommunityToolkit.Datasync.Client/Threading/QueueHandler.cs +++ b/src/CommunityToolkit.Datasync.Client/Threading/QueueHandler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Runtime.ExceptionServices; using System.Threading.Tasks.Dataflow; namespace CommunityToolkit.Datasync.Client.Threading; @@ -13,6 +14,7 @@ namespace CommunityToolkit.Datasync.Client.Threading; internal class QueueHandler where T : class { private readonly ActionBlock jobs; + private ExceptionDispatchInfo? cancellation; /// /// Creates a new @@ -25,7 +27,20 @@ public QueueHandler(int maxThreads, Func jobRunner) ArgumentOutOfRangeException.ThrowIfGreaterThan(maxThreads, 8); ArgumentNullException.ThrowIfNull(jobRunner); ExecutionDataflowBlockOptions options = new() { MaxDegreeOfParallelism = maxThreads }; - this.jobs = new(jobRunner, options); + this.jobs = new(async item => + { + try + { + await jobRunner(item).ConfigureAwait(false); + } + catch (OperationCanceledException ex) + { + // TPL Dataflow treats an OperationCanceledException thrown by the delegate as cooperative cancellation: + // the item is silently dropped and Completion finishes normally. Remember the first one so that + // WhenComplete() can surface it instead of reporting a clean run. + _ = Interlocked.CompareExchange(ref this.cancellation, ExceptionDispatchInfo.Capture(ex), null); + } + }, options); } /// @@ -52,11 +67,13 @@ public void EnqueueRange(IEnumerable items) /// /// Returns a task that resolves when all the runners are completed. /// - /// - public Task WhenComplete() + /// A task that completes when all jobs are done. + /// If a job was canceled. + public async Task WhenComplete() { this.jobs.Complete(); - return this.jobs.Completion; + await this.jobs.Completion.ConfigureAwait(false); + this.cancellation?.Throw(); } /// diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs index e6ba4f1a..3cf3f11a 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using CommunityToolkit.Datasync.Client.Http; using CommunityToolkit.Datasync.Client.Offline; using CommunityToolkit.Datasync.Client.Offline.OperationsQueue; using CommunityToolkit.Datasync.Client.Serialization; @@ -170,6 +171,51 @@ public async Task PushAsync_Addition_HttpError() op.LastAttempt.Should().NotBeNull().And.BeOnOrAfter(StartTime); } + [Fact] + public async Task PushAsync_Addition_Timeout_Throws_AndKeepsOperationQueued() + { + // Replace the pipeline so that the request times out (HttpClient surfaces this as a TaskCanceledException). + TimeoutHandler handler = new(); + this.context.Configurator = builder => builder.UseHttpClientOptions(new HttpClientOptions + { + Endpoint = new Uri("https://test.zumo.net"), + HttpPipeline = [handler], + Timeout = TimeSpan.FromSeconds(1) + }); + + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; + this.context.Movies.Add(clientMovie); + this.context.SaveChanges(); + + Func act = async () => _ = await this.context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + TimeoutException ex = (await act.Should().ThrowAsync()).Which; + ex.InnerException.Should().BeAssignableTo(); + + this.context.DatasyncOperationsQueue.Should().HaveCount(1); + } + + [Fact] + public async Task PushAsync_CallerCancellation_Throws_OperationCanceledException() + { + using CancellationTokenSource cts = new(); + CancellationToken token = cts.Token; + TimeoutHandler handler = new() { OnRequest = cts.Cancel }; + this.context.Configurator = builder => builder.UseHttpClientOptions(new HttpClientOptions + { + Endpoint = new Uri("https://test.zumo.net"), + HttpPipeline = [handler] + }); + + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; + this.context.Movies.Add(clientMovie); + this.context.SaveChanges(); + + Func act = async () => _ = await this.context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), token); + await act.Should().ThrowAsync(); + + this.context.DatasyncOperationsQueue.Should().HaveCount(1); + } + [Fact] public async Task PushAsync_Addition_Conflict() { @@ -514,3 +560,20 @@ public async Task LLP_ModifyAfterInsertInNewContext_NoPush_ShouldUpdateOperation } #endregion } + +/// +/// A handler that never responds; the request only ends when its cancellation token is canceled +/// (either by or by the caller). +/// +[ExcludeFromCodeCoverage] +internal class TimeoutHandler : DelegatingHandler +{ + public Action OnRequest { get; set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + OnRequest?.Invoke(); + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + return new HttpResponseMessage(HttpStatusCode.OK); + } +} diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs index 356c4a38..0e995fd4 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs @@ -88,6 +88,28 @@ public async Task QueueHandler_WithThreads_EnqueueRange(int nThreads) (endTime - startTime).TotalSeconds.Should().BeLessThanOrEqualTo(2 * (nElements / nThreads) + 5); } + [Fact(Timeout = 30000)] + public async Task QueueHandler_JobCanceled_WhenCompleteThrows() + { + ConcurrentQueue processed = new(); + QueueHandler sut = new(1, el => + { + if (el == "el-1") + { + throw new TaskCanceledException("simulated HttpClient timeout"); + } + + processed.Enqueue(el); + return Task.CompletedTask; + }); + + sut.EnqueueRange(["el-0", "el-1", "el-2"]); + + Func act = sut.WhenComplete; + await act.Should().ThrowAsync(); + processed.Should().BeEquivalentTo(["el-0", "el-2"]); + } + [Theory, CombinatorialData] public void QueueHandler_Throws_OutOfRangeMaxThreads([CombinatorialValues(-1, 0, 9, 10)] int threads) { From bb509f6fc36a8dcf6f9390a2c0eab6ee48ba36d4 Mon Sep 17 00:00:00 2001 From: ahall Date: Thu, 5 Nov 2026 17:03:44 +0000 Subject: [PATCH 2/2] docs: fix AutoMapper documentation link docs.automapper.org no longer resolves; the docs moved to docs.automapper.io. This was failing the lychee link check on the docs workflow. --- docs/tutorial/server/part-2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/server/part-2.md b/docs/tutorial/server/part-2.md index 809c0bea..669c1847 100644 --- a/docs/tutorial/server/part-2.md +++ b/docs/tutorial/server/part-2.md @@ -319,5 +319,5 @@ However, there are always those cases when one of the standard repositories does [5]: ../../in-depth/server/db/pgsql.md [6]: ../../in-depth/server/db/sqlite.md [7]: https://learn.microsoft.com/ef/core/providers/ -[8]: https://docs.automapper.org/en/stable/ +[8]: https://docs.automapper.io/en/stable/ [9]: https://www.mongodb.com/products/self-managed/community-edition