From 917b4b46726c890e6faf4e0f4f02c70c99f175eb Mon Sep 17 00:00:00 2001 From: ahall Date: Thu, 5 Nov 2026 17:18:41 +0000 Subject: [PATCH] feat(client): add Merged conflict resolution result that stays conditional ConflictResolutionResult.Client force-writes with no If-Match header, which can silently overwrite a concurrent update when the resolver merged the entity from the server row. Add ConflictResolutionResult.Merged, which sends If-Match with the server entity version the resolver saw, re-resolves on a further conflict (up to 5 attempts), and documents that Client is an unconditional overwrite. Fixes #579 --- docs/in-depth/client/index.md | 13 +- .../Offline/Models/ConflictResolution.cs | 14 +- .../OperationsQueue/OperationsQueueManager.cs | 38 ++++- .../Offline/ConflictResolver_Tests.cs | 152 ++++++++++++++++++ 4 files changed, 207 insertions(+), 10 deletions(-) diff --git a/docs/in-depth/client/index.md b/docs/in-depth/client/index.md index 552a719a..c3eb73cc 100644 --- a/docs/in-depth/client/index.md +++ b/docs/in-depth/client/index.md @@ -237,9 +237,16 @@ public class ClientWinsConflictResolver : IConflictResolver The `IConflictResolver` is the same as `IConflictResolver` with the notable exception that the `clientObject` and `serverObject` are typed instead of objects. The `ConflictResolution` result model consists of two parts: -* `Result` is either `ConflictResolutionResult.Client` (indicating that the client wins and the server entity should be overwritten) or `ConflictResolutionResult.Server` (indicating that the server wins and the client entity should be overwritten). +* `Result` is one of the following: + * `ConflictResolutionResult.Client` indicates that the client wins and the server entity should be overwritten. The entity is sent to the server as a "force" write with no `If-Match` header. + * `ConflictResolutionResult.Server` indicates that the server wins and the client entity should be overwritten. + * `ConflictResolutionResult.Merged` indicates that `Entity` was computed from the server entity (a merge). The entity is sent to the server with an `If-Match` header set to the version of the server entity that the resolver received. + * `ConflictResolutionResult.Default` leaves the operation in the queue marked as failed. * `Entity` is the entity that should be written. +!!! warning "A `Client` result is an unconditional overwrite" + When a resolver returns `ConflictResolutionResult.Client`, the entity is written without an `If-Match` header. If another client updates the entity after the conflict was detected but before the forced write arrives, that update is silently lost. This is fine for a plain "client wins" policy, but it is not safe when the entity is a merge of client and server values. Return `ConflictResolutionResult.Merged` for merges instead. If the server entity changes again before the merged write arrives, the service responds with another conflict and the resolver is called again with the newer server entity. After 5 attempts, the operation is left in the queue marked as failed. A `Merged` result requires the server entity to have a version; if it does not, the operation is marked as failed. + To provide another example, let's say you want to allow updates from the client for all columns except for a `Title` column. You can do this as follows: ```csharp @@ -248,12 +255,12 @@ public class CustomConflictResolver : IConflictResolver public async Task ResolverConflictAsync(Movie? clientObject, Movie? serverObject, CancellationToken cancellationToken = default) { clientObject.Movie = serverObject.Movie; - return new ConflictResolution { Result = ConflictResolutionResult.Client, Entity = clientObject }; + return new ConflictResolution { Result = ConflictResolutionResult.Merged, Entity = clientObject }; } } ``` -Here, we copy the server value of the movie title to the client before returning so that the title is preserved. +Here, we copy the server value of the movie title to the client before returning so that the title is preserved. Because the result is a merge of the client and server entities, we return `ConflictResolutionResult.Merged` so that the write is conditional on the server version we merged against. ## Pulling data from the service diff --git a/src/CommunityToolkit.Datasync.Client/Offline/Models/ConflictResolution.cs b/src/CommunityToolkit.Datasync.Client/Offline/Models/ConflictResolution.cs index 654bbe9e..b4fed26e 100644 --- a/src/CommunityToolkit.Datasync.Client/Offline/Models/ConflictResolution.cs +++ b/src/CommunityToolkit.Datasync.Client/Offline/Models/ConflictResolution.cs @@ -16,7 +16,9 @@ public enum ConflictResolutionResult /// /// The provided client object should be used. This results in a new "force" submission - /// to the server to over-write the server entity. + /// to the server (with no If-Match header) to over-write the server entity. This is an + /// unconditional overwrite: any change made on the server after the conflict was detected is lost. + /// Use when the entity was computed from the server entity. /// Client, @@ -24,7 +26,15 @@ public enum ConflictResolutionResult /// The server object should be used. This results in the client object being updated /// with whatever the server object was provided. /// - Server + Server, + + /// + /// The provided entity is a merge of the client and server objects. This results in a new submission + /// to the server that is conditional on the version of the server object that was given to the resolver + /// (an If-Match header is sent). If the server entity has changed again, the conflict is resolved + /// again, up to a fixed number of attempts, after which the operation is marked as failed. + /// + Merged } /// diff --git a/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs b/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs index b6944f68..6ffde5ea 100644 --- a/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs +++ b/src/CommunityToolkit.Datasync.Client/Offline/OperationsQueue/OperationsQueueManager.cs @@ -29,7 +29,13 @@ internal class OperationsQueueManager : IOperationsQueueManager private readonly Lock pushlock = new(); /// - /// The map of valid entities that can be synchronized to the service. + /// The maximum number of times a resolution is + /// retried when the server reports another conflict. + /// + internal const int MaxMergeAttempts = 5; + + /// + /// The context used for storing the operations queue. /// internal OfflineDbContext _context; @@ -368,15 +374,29 @@ internal async Task PushAsync(IEnumerable entityTypes, PushOpt ServiceResponse response = await op.ExecuteAsync(options, cancellationToken).ConfigureAwait(false); bool isSuccessful = response.IsSuccessful; - if (response.IsConflictStatusCode && options.ConflictResolver is not null) + int mergeAttempts = 0; + while (response.IsConflictStatusCode && options.ConflictResolver is not null) { object? serverEntity = JsonSerializer.Deserialize(response.ContentStream, entityType, DatasyncSerializer.JsonSerializerOptions); object? clientEntity = JsonSerializer.Deserialize(operation.Item, entityType, DatasyncSerializer.JsonSerializerOptions); ConflictResolution resolution = await options.ConflictResolver.ResolveConflictAsync(clientEntity, serverEntity, cancellationToken).ConfigureAwait(false); - if (resolution.Result is ConflictResolutionResult.Client) + if (resolution.Result is ConflictResolutionResult.Client or ConflictResolutionResult.Merged) { - // The client entity is the winner, so we need to update the operation and re-queue it. + bool isMerge = resolution.Result is ConflictResolutionResult.Merged; + string? mergeVersion = null; + if (isMerge) + { + // A merge must stay conditional: it is only valid against the server version that the resolver saw. + mergeVersion = serverEntity is null ? null : EntityResolver.GetEntityMetadata(serverEntity, entityType).Version; + if (string.IsNullOrEmpty(mergeVersion) || ++mergeAttempts > MaxMergeAttempts) + { + // No server version to condition on, or the server keeps changing: leave the operation failed. + break; + } + } + + // The resolved entity is the winner, so we need to update the operation and re-queue it. if (operation.Kind == OperationKind.Add) { // The server has an entity and the client is winning, so we need to replace the entity on the server. @@ -387,12 +407,18 @@ internal async Task PushAsync(IEnumerable entityTypes, PushOpt operation.State = OperationState.Pending; operation.LastAttempt = DateTimeOffset.UtcNow; operation.HttpStatusCode = response.StatusCode; - operation.EntityVersion = string.Empty; // Force the push + operation.EntityVersion = mergeVersion ?? string.Empty; // Client forces the push; Merged is conditional on the server version. operation.Version++; _ = this._context.Update(operation); ExecutableOperation resolvedOp = await ExecutableOperation.CreateAsync(operation, cancellationToken).ConfigureAwait(false); response = await resolvedOp.ExecuteAsync(options, cancellationToken).ConfigureAwait(false); isSuccessful = response.IsSuccessful; + + if (isMerge) + { + // Another conflict means the server changed again, so resolve it again (up to MaxMergeAttempts). + continue; + } } else if (resolution.Result is ConflictResolutionResult.Server) { @@ -405,6 +431,8 @@ internal async Task PushAsync(IEnumerable entityTypes, PushOpt _ = this._context.Update(operation); } } + + break; } if (!isSuccessful) diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs index cf1decd5..9c7d4317 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs @@ -651,6 +651,135 @@ public async Task PushAsync_WithNull_ConflictResolver_ShouldNotResolveConflict() op.HttpStatusCode.Should().Be(409); } + [Fact] + public async Task PushAsync_WithClientResolution_ShouldForcePushWithoutIfMatch() + { + TestDbContext context = CreateContext(); + context.Configurator = builder => builder.Entity(c => c.ConflictResolver = new ClientWinsConflictResolver()); + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N"), Title = "Client Title" }; + context.Movies.Add(clientMovie); + context.SaveChanges(acceptAllChangesOnSuccess: true, addToQueue: false); + clientMovie.Title = "Changed"; + context.Update(clientMovie); + context.SaveChanges(); + + ClientMovie serverMovie = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server Title", UpdatedAt = DateTimeOffset.UtcNow, Version = "server-v1" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(serverMovie), HttpStatusCode.PreconditionFailed); + ClientMovie finalMovie = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Changed", UpdatedAt = DateTimeOffset.UtcNow, Version = "final" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(finalMovie), HttpStatusCode.OK); + + PushResult result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + + result.IsSuccessful.Should().BeTrue(); + context.Handler.Requests.Should().HaveCount(2); + context.Handler.Requests[1].Method.Should().Be(HttpMethod.Put); + context.Handler.Requests[1].Headers.IfMatch.Should().BeEmpty(); + } + + [Fact] + public async Task PushAsync_WithMergedResolution_ShouldPushConditionalOnServerVersion() + { + TestDbContext context = CreateContext(); + MergingResolver resolver = new(); + context.Configurator = builder => builder.Entity(c => c.ConflictResolver = resolver); + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N"), Title = "Client Title", Rating = MovieRating.G }; + context.Movies.Add(clientMovie); + context.SaveChanges(); + + ClientMovie serverMovie = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server Title", Rating = MovieRating.R, UpdatedAt = DateTimeOffset.UtcNow, Version = "server-v1" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(serverMovie), HttpStatusCode.Conflict); + ClientMovie finalMovie = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server Title", Rating = MovieRating.G, UpdatedAt = DateTimeOffset.UtcNow, Version = "final" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(finalMovie), HttpStatusCode.OK); + + PushResult result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + + result.IsSuccessful.Should().BeTrue(); + result.CompletedOperations.Should().Be(1); + resolver.Calls.Should().Be(1); + context.Handler.Requests.Should().HaveCount(2); + context.Handler.Requests[1].Method.Should().Be(HttpMethod.Put); + context.Handler.Requests[1].Headers.IfMatch.Should().ContainSingle().Which.Tag.Should().Be("\"server-v1\""); + + ClientMovie saved = context.Movies.Find(clientMovie.Id)!; + saved.Title.Should().Be("Server Title"); + saved.Rating.Should().Be(MovieRating.G); + saved.Version.Should().Be("final"); + } + + [Fact] + public async Task PushAsync_WithMergedResolution_ShouldReResolveWhenServerChangesAgain() + { + TestDbContext context = CreateContext(); + MergingResolver resolver = new(); + context.Configurator = builder => builder.Entity(c => c.ConflictResolver = resolver); + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N"), Title = "Client Title", Rating = MovieRating.G }; + context.Movies.Add(clientMovie); + context.SaveChanges(); + + ClientMovie server1 = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server 1", UpdatedAt = DateTimeOffset.UtcNow, Version = "server-v1" }; + ClientMovie server2 = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server 2", UpdatedAt = DateTimeOffset.UtcNow, Version = "server-v2" }; + ClientMovie finalMovie = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server 2", Rating = MovieRating.G, UpdatedAt = DateTimeOffset.UtcNow, Version = "final" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(server1), HttpStatusCode.Conflict); + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(server2), HttpStatusCode.PreconditionFailed); + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(finalMovie), HttpStatusCode.OK); + + PushResult result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + + result.IsSuccessful.Should().BeTrue(); + resolver.Calls.Should().Be(2); + context.Handler.Requests.Should().HaveCount(3); + context.Handler.Requests[1].Headers.IfMatch.Should().ContainSingle().Which.Tag.Should().Be("\"server-v1\""); + context.Handler.Requests[2].Headers.IfMatch.Should().ContainSingle().Which.Tag.Should().Be("\"server-v2\""); + context.Movies.Find(clientMovie.Id)!.Title.Should().Be("Server 2"); + } + + [Fact] + public async Task PushAsync_WithMergedResolution_ShouldFailAfterMaxAttempts() + { + TestDbContext context = CreateContext(); + MergingResolver resolver = new(); + context.Configurator = builder => builder.Entity(c => c.ConflictResolver = resolver); + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N"), Title = "Client Title" }; + context.Movies.Add(clientMovie); + context.SaveChanges(); + + // The initial push plus every merge attempt keeps conflicting, plus one more conflict that exceeds the limit. + for (int i = 0; i <= 5 + 1; i++) + { + ClientMovie server = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = $"Server {i}", UpdatedAt = DateTimeOffset.UtcNow, Version = $"server-v{i}" }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(server), HttpStatusCode.PreconditionFailed); + } + + PushResult result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + + result.IsSuccessful.Should().BeFalse(); + result.FailedRequests.Should().HaveCount(1); + resolver.Calls.Should().Be(6); + context.Handler.Requests.Should().HaveCount(6); + context.DatasyncOperationsQueue.Single().State.Should().Be(OperationState.Failed); + context.DatasyncOperationsQueue.Single().HttpStatusCode.Should().Be(412); + } + + [Fact] + public async Task PushAsync_WithMergedResolution_AndNoServerVersion_ShouldFail() + { + TestDbContext context = CreateContext(); + MergingResolver resolver = new(); + context.Configurator = builder => builder.Entity(c => c.ConflictResolver = resolver); + ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N"), Title = "Client Title" }; + context.Movies.Add(clientMovie); + context.SaveChanges(); + + ClientMovie server = new(TestData.Movies.BlackPanther) { Id = clientMovie.Id, Title = "Server", UpdatedAt = DateTimeOffset.UtcNow, Version = null }; + context.Handler.AddResponseContent(DatasyncSerializer.Serialize(server), HttpStatusCode.Conflict); + + PushResult result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); + + result.IsSuccessful.Should().BeFalse(); + context.Handler.Requests.Should().HaveCount(1); + context.DatasyncOperationsQueue.Single().State.Should().Be(OperationState.Failed); + } + #endregion } @@ -702,3 +831,26 @@ public override Task ResolveConflictAsync(ClientMovie client }); } } + +/// +/// A resolver that merges the title from the server with the rating from the client. +/// +[ExcludeFromCodeCoverage] +public class MergingResolver : AbstractConflictResolver +{ + public int Calls { get; private set; } + + public override Task ResolveConflictAsync(ClientMovie clientObject, ClientMovie serverObject, CancellationToken cancellationToken = default) + { + Calls++; + ClientMovie merged = new(serverObject) + { + Id = serverObject.Id, + Title = serverObject.Title, + UpdatedAt = serverObject.UpdatedAt, + Version = serverObject.Version, + Rating = clientObject.Rating + }; + return Task.FromResult(new ConflictResolution { Result = ConflictResolutionResult.Merged, Entity = merged }); + } +}