diff --git a/docs/in-depth/client/index.md b/docs/in-depth/client/index.md index c3eb73cc..4d843c31 100644 --- a/docs/in-depth/client/index.md +++ b/docs/in-depth/client/index.md @@ -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--`. 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 => { diff --git a/src/CommunityToolkit.Datasync.Client/Offline/Operations/PullOperationManager.cs b/src/CommunityToolkit.Datasync.Client/Offline/Operations/PullOperationManager.cs index 0aecc986..ccadfdd5 100644 --- a/src/CommunityToolkit.Datasync.Client/Offline/Operations/PullOperationManager.cs +++ b/src/CommunityToolkit.Datasync.Client/Offline/Operations/PullOperationManager.cs @@ -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; @@ -233,7 +234,8 @@ public async Task ExecuteAsync(IEnumerable 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); } @@ -293,16 +295,44 @@ internal async Task> GetPageAsync(HttpClient client, Uri requestUri } } + /// + /// 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. + /// + /// The type of entity to check. + /// A to observe. + /// true if at least one entity of the type exists locally; false otherwise. + internal Task HasLocalEntitiesAsync(Type entityType, CancellationToken cancellationToken = default) + { + MethodInfo method = typeof(PullOperationManager) + .GetMethod(nameof(HasLocalEntitiesInternalAsync), BindingFlags.NonPublic | BindingFlags.Instance)! + .MakeGenericMethod(entityType); + return (Task)method.Invoke(this, [cancellationToken])!; + } + + /// + /// Typed implementation of . + /// + private Task HasLocalEntitiesInternalAsync(CancellationToken cancellationToken) where TEntity : class + => context.Set().AnyAsync(cancellationToken); + /// /// Prepares the query description for use as a pull request. /// + /// + /// 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. + /// /// The query description to modify. /// The last synchronization date/time + /// true if the local table already contains entities of the type being pulled. /// A modified query description for the actual query. - 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) { @@ -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; diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs index efbae2be..3a3d5d16 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs @@ -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"); @@ -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"); @@ -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"); @@ -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"); @@ -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"); @@ -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"); @@ -427,7 +427,7 @@ public async Task PullAsync_List_FailedRequest() pullResult.IsSuccessful.Should().BeFalse(); pullResult.FailedRequests.Should().HaveCount(1); KeyValuePair 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] diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs index e8198620..d704aa7a 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs @@ -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); } @@ -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); } @@ -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"); @@ -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 query = new(); + QueryDescription qd = new QueryTranslator(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 query = new(); + QueryDescription qd = new QueryTranslator(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 query = new(); + QueryDescription qd = new QueryTranslator(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 }