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
13 changes: 10 additions & 3 deletions docs/in-depth/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,16 @@ public class ClientWinsConflictResolver : IConflictResolver

The `IConflictResolver<T>` 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
Expand All @@ -248,12 +255,12 @@ public class CustomConflictResolver : IConflictResolver<Movie>
public async Task<ConflictResolution> 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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,25 @@ public enum ConflictResolutionResult

/// <summary>
/// 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 <c>If-Match</c> 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 <see cref="Merged"/> when the entity was computed from the server entity.
/// </summary>
Client,

/// <summary>
/// The server object should be used. This results in the client object being updated
/// with whatever the server object was provided.
/// </summary>
Server
Server,

/// <summary>
/// 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 <c>If-Match</c> 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.
/// </summary>
Merged
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@ internal class OperationsQueueManager : IOperationsQueueManager
private readonly Lock pushlock = new();

/// <summary>
/// The map of valid entities that can be synchronized to the service.
/// The maximum number of times a <see cref="ConflictResolutionResult.Merged"/> resolution is
/// retried when the server reports another conflict.
/// </summary>
internal const int MaxMergeAttempts = 5;

/// <summary>
/// The context used for storing the operations queue.
/// </summary>
internal OfflineDbContext _context;

Expand Down Expand Up @@ -368,15 +374,29 @@ internal async Task<PushResult> PushAsync(IEnumerable<Type> 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.
Expand All @@ -387,12 +407,18 @@ internal async Task<PushResult> PushAsync(IEnumerable<Type> 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)
{
Expand All @@ -405,6 +431,8 @@ internal async Task<PushResult> PushAsync(IEnumerable<Type> entityTypes, PushOpt
_ = this._context.Update(operation);
}
}

break;
}

if (!isSuccessful)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ClientMovie>(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<ClientMovie>(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<ClientMovie>(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<ClientMovie>(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<ClientMovie>(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
}

Expand Down Expand Up @@ -702,3 +831,26 @@ public override Task<ConflictResolution> ResolveConflictAsync(ClientMovie client
});
}
}

/// <summary>
/// A resolver that merges the title from the server with the rating from the client.
/// </summary>
[ExcludeFromCodeCoverage]
public class MergingResolver : AbstractConflictResolver<ClientMovie>
{
public int Calls { get; private set; }

public override Task<ConflictResolution> 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 });
}
}
Loading