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
2 changes: 2 additions & 0 deletions docs/in-depth/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,8 @@ As with the push operations, you can optionally specify a `PullOptions` object f

Service requests are paged and each page contains a link to the next page of results. This means that consecutive service requests for a single entity are serialized, but service requests for different entities can be parallelized. After each service request, the delta-token for the request is updated. The delta-token is stored in the `DatasyncDeltaTokens` DbSet on the database context. For normal requests, the Id is the full name of the entity type. If a query ID is used (see below), then the Id is `q-<entityType>-<queryId>`. The `Value` property of the delta-token is the maximum value of the `UpdatedAt` property for the entity data set, expressed as the number of milliseconds since the UNIX epoch.

Soft-deleted entities are only requested from the service (using `__includedeleted=true`) when they could result in a local deletion: that is, when a delta-token exists for the request, or when the local table already contains entities. On an initial pull into an empty table, soft-deleted entities are not requested, which reduces the amount of data transferred when the service holds a large number of soft-deleted entities. This also means the total count reported in synchronization events for an initial pull only includes entities that are not deleted.

If you need to pull data from the same entity using different searches, you need to use a pull configurator.

PullResult result = await context.PullAsync(cfg => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using CommunityToolkit.Datasync.Client.Query.OData;
using CommunityToolkit.Datasync.Client.Serialization;
using CommunityToolkit.Datasync.Client.Threading;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Diagnostics.CodeAnalysis;
Expand Down Expand Up @@ -233,7 +234,8 @@ public async Task<PullResult> ExecuteAsync(IEnumerable<PullRequest> requests, Pu
foreach (PullRequest request in requests)
{
DateTimeOffset lastSynchronization = await context.DeltaTokenStore.GetDeltaTokenAsync(request.QueryId, cancellationToken).ConfigureAwait(false);
request.QueryDescription = PrepareQueryDescription(request.QueryDescription, lastSynchronization);
bool hasLocalEntities = lastSynchronization.ToUnixTimeMilliseconds() > 0L || await HasLocalEntitiesAsync(request.EntityType, cancellationToken).ConfigureAwait(false);
request.QueryDescription = PrepareQueryDescription(request.QueryDescription, lastSynchronization, hasLocalEntities);
requestsToEnqueue.Add(request);
}

Expand Down Expand Up @@ -293,16 +295,44 @@ internal async Task<Page<object>> GetPageAsync(HttpClient client, Uri requestUri
}
}

/// <summary>
/// Determines whether the local table for the entity type contains any entities. This is used to decide
/// if soft-deleted entities need to be requested from the service on an initial pull.
/// </summary>
/// <param name="entityType">The type of entity to check.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe.</param>
/// <returns><c>true</c> if at least one entity of the type exists locally; <c>false</c> otherwise.</returns>
internal Task<bool> HasLocalEntitiesAsync(Type entityType, CancellationToken cancellationToken = default)
{
MethodInfo method = typeof(PullOperationManager)
.GetMethod(nameof(HasLocalEntitiesInternalAsync), BindingFlags.NonPublic | BindingFlags.Instance)!
.MakeGenericMethod(entityType);
return (Task<bool>)method.Invoke(this, [cancellationToken])!;
}

/// <summary>
/// Typed implementation of <see cref="HasLocalEntitiesAsync(Type, CancellationToken)"/>.
/// </summary>
private Task<bool> HasLocalEntitiesInternalAsync<TEntity>(CancellationToken cancellationToken) where TEntity : class
=> context.Set<TEntity>().AnyAsync(cancellationToken);

/// <summary>
/// Prepares the query description for use as a pull request.
/// </summary>
/// <remarks>
/// Soft-deleted entities are only requested when they could result in a local deletion; that is,
/// when this is an incremental pull (a delta-token exists) or when the local table already contains
/// entities. On an initial pull into an empty table, they are not requested.
/// </remarks>
/// <param name="source">The query description to modify.</param>
/// <param name="lastSynchronization">The last synchronization date/time</param>
/// <param name="hasLocalEntities"><c>true</c> if the local table already contains entities of the type being pulled.</param>
/// <returns>A modified query description for the actual query.</returns>
internal static QueryDescription PrepareQueryDescription(QueryDescription source, DateTimeOffset lastSynchronization)
internal static QueryDescription PrepareQueryDescription(QueryDescription source, DateTimeOffset lastSynchronization, bool hasLocalEntities)
{
QueryDescription query = new(source);
if (lastSynchronization.ToUnixTimeMilliseconds() > 0L)
bool isIncremental = lastSynchronization.ToUnixTimeMilliseconds() > 0L;
if (isIncremental)
{
BinaryOperatorNode deltaTokenFilter = new(BinaryOperatorKind.GreaterThan)
{
Expand All @@ -312,7 +342,15 @@ internal static QueryDescription PrepareQueryDescription(QueryDescription source
query.Filter = query.Filter is null ? deltaTokenFilter : new BinaryOperatorNode(BinaryOperatorKind.And, query.Filter, deltaTokenFilter);
}

query.QueryParameters[ODataQueryParameters.IncludeDeleted] = "true";
if (isIncremental || hasLocalEntities)
{
query.QueryParameters[ODataQueryParameters.IncludeDeleted] = "true";
}
else
{
_ = query.QueryParameters.Remove(ODataQueryParameters.IncludeDeleted);
}

query.RequestTotalCount = true;
query.Top = null;
query.Skip = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public async Task PullAsync_List_Works_InitialSync()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -104,7 +104,7 @@ public async Task PullAsync_DbSet_Works_InitialSync()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -148,7 +148,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver1()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -192,7 +192,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver2()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -243,7 +243,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver3()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$filter=startswith%28title%2C%27abc%27%29&$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -282,7 +282,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver4()
actual.Should().BeEquivalentTo(expected);

this.context.Handler.Requests.Should().HaveCount(4);
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true&__includedeleted=true");
this.context.Handler.Requests[0].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true");
this.context.Handler.Requests[1].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=5");
this.context.Handler.Requests[2].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=10");
this.context.Handler.Requests[3].RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies?$skip=15");
Expand Down Expand Up @@ -427,7 +427,7 @@ public async Task PullAsync_List_FailedRequest()
pullResult.IsSuccessful.Should().BeFalse();
pullResult.FailedRequests.Should().HaveCount(1);
KeyValuePair<Uri, ServiceResponse> kv = pullResult.FailedRequests.Single();
kv.Key.Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true&__includedeleted=true");
kv.Key.Should().Be("https://test.zumo.net/tables/movies?$orderby=updatedAt&$count=true");
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,10 @@ public void PrepareQueryDescription_NQ_NS()
string expected = qd.ToODataQueryString();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeSeconds(0L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, false);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$orderby=updatedAt&$count=true&__includedeleted=true");
actual.Should().Be("$orderby=updatedAt&$count=true");
qd.ToODataQueryString().Should().Be(expected);
}

Expand All @@ -202,10 +202,10 @@ public void PrepareQueryDescription_Q_NS()
string expected = qd.ToODataQueryString();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeSeconds(0L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, false);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$filter=(rating eq 'G')&$orderby=updatedAt&$count=true&__includedeleted=true");
actual.Should().Be("$filter=(rating eq 'G')&$orderby=updatedAt&$count=true");
qd.ToODataQueryString().Should().Be(expected);
}

Expand All @@ -217,7 +217,7 @@ public void PrepareQueryDescription_NQ_S()
string expected = qd.ToODataQueryString();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeMilliseconds(1724444574291L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, true);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$filter=(updatedAt gt cast(2024-08-23T20:22:54.291Z,Edm.DateTimeOffset))&$orderby=updatedAt&$count=true&__includedeleted=true");
Expand All @@ -233,11 +233,71 @@ public void PrepareQueryDescription_Q_S()
string expected = qd.ToODataQueryString();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeMilliseconds(1724444574291L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, true);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$filter=((rating eq 'G') and (updatedAt gt cast(2024-08-23T20:22:54.291Z,Edm.DateTimeOffset)))&$orderby=updatedAt&$count=true&__includedeleted=true");
qd.ToODataQueryString().Should().Be(expected);
}

[Fact]
public void PrepareQueryDescription_NQ_NS_LocalEntities_IncludesDeleted()
{
DatasyncPullQuery<ClientMovie> query = new();
QueryDescription qd = new QueryTranslator<ClientMovie>(query).Translate();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeSeconds(0L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, true);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$orderby=updatedAt&$count=true&__includedeleted=true");
}

[Fact]
public void PrepareQueryDescription_NS_RemovesExistingIncludeDeleted()
{
DatasyncPullQuery<ClientMovie> query = new();
QueryDescription qd = new QueryTranslator<ClientMovie>(query).Translate();
qd.QueryParameters[ODataQueryParameters.IncludeDeleted] = "true";

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeSeconds(0L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, false);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Be("$orderby=updatedAt&$count=true");
}

[Fact]
public void PrepareQueryDescription_S_NoLocalEntities_IncludesDeleted()
{
DatasyncPullQuery<ClientMovie> query = new();
QueryDescription qd = new QueryTranslator<ClientMovie>(query).Translate();

DateTimeOffset lastSynchronization = DateTimeOffset.FromUnixTimeMilliseconds(1724444574291L);
QueryDescription actualQD = PullOperationManager.PrepareQueryDescription(qd, lastSynchronization, false);

string actual = Uri.UnescapeDataString(actualQD.ToODataQueryString());
actual.Should().Contain("__includedeleted=true");
}
#endregion

#region HasLocalEntitiesAsync
[Fact]
public async Task HasLocalEntitiesAsync_EmptyTable_ReturnsFalse()
{
bool actual = await operationManager.HasLocalEntitiesAsync(typeof(ClientMovie), TestContext.Current.CancellationToken);
actual.Should().BeFalse();
}

[Fact]
public async Task HasLocalEntitiesAsync_WithEntities_ReturnsTrue()
{
ClientMovie movie = new() { Id = Guid.NewGuid().ToString("N"), Title = "Test Movie" };
_ = this.context.Movies.Add(movie);
_ = await this.context.SaveChangesAsync(true, false, TestContext.Current.CancellationToken);

bool actual = await operationManager.HasLocalEntitiesAsync(typeof(ClientMovie), TestContext.Current.CancellationToken);
actual.Should().BeTrue();
}
#endregion
}
Loading