Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/in-depth/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/server/part-2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -295,7 +296,18 @@ internal async Task<PushResult> PushAsync(IEnumerable<Type> entityTypes, PushOpt
// Push things in parallel, according to the PushOptions
QueueHandler<DatasyncOperation> 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);
Expand All @@ -310,10 +322,25 @@ internal async Task<PushResult> PushAsync(IEnumerable<Type> 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()
{
Expand Down
25 changes: 21 additions & 4 deletions src/CommunityToolkit.Datasync.Client/Threading/QueueHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -13,6 +14,7 @@ namespace CommunityToolkit.Datasync.Client.Threading;
internal class QueueHandler<T> where T : class
{
private readonly ActionBlock<T> jobs;
private ExceptionDispatchInfo? cancellation;

/// <summary>
/// Creates a new <see cref="QueueHandler{T}"/>
Expand All @@ -25,7 +27,20 @@ public QueueHandler(int maxThreads, Func<T, Task> 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);
}

/// <summary>
Expand All @@ -52,11 +67,13 @@ public void EnqueueRange(IEnumerable<T> items)
/// <summary>
/// Returns a task that resolves when all the runners are completed.
/// </summary>
/// <returns></returns>
public Task WhenComplete()
/// <returns>A task that completes when all jobs are done.</returns>
/// <exception cref="OperationCanceledException">If a job was canceled.</exception>
public async Task WhenComplete()
{
this.jobs.Complete();
return this.jobs.Completion;
await this.jobs.Completion.ConfigureAwait(false);
this.cancellation?.Throw();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Task> act = async () => _ = await this.context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken);
TimeoutException ex = (await act.Should().ThrowAsync<TimeoutException>()).Which;
ex.InnerException.Should().BeAssignableTo<OperationCanceledException>();

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<Task> act = async () => _ = await this.context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), token);
await act.Should().ThrowAsync<OperationCanceledException>();

this.context.DatasyncOperationsQueue.Should().HaveCount(1);
}

[Fact]
public async Task PushAsync_Addition_Conflict()
{
Expand Down Expand Up @@ -514,3 +560,20 @@ public async Task LLP_ModifyAfterInsertInNewContext_NoPush_ShouldUpdateOperation
}
#endregion
}

/// <summary>
/// A handler that never responds; the request only ends when its cancellation token is canceled
/// (either by <see cref="HttpClient.Timeout"/> or by the caller).
/// </summary>
[ExcludeFromCodeCoverage]
internal class TimeoutHandler : DelegatingHandler
{
public Action OnRequest { get; set; }

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
OnRequest?.Invoke();
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> processed = new();
QueueHandler<string> 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<Task> act = sut.WhenComplete;
await act.Should().ThrowAsync<OperationCanceledException>();
processed.Should().BeEquivalentTo(["el-0", "el-2"]);
}

[Theory, CombinatorialData]
public void QueueHandler_Throws_OutOfRangeMaxThreads([CombinatorialValues(-1, 0, 9, 10)] int threads)
{
Expand Down
Loading