From c167842ec217cf733aecd9141f9f760b5c0b1c9c Mon Sep 17 00:00:00 2001 From: ksemenenko Date: Fri, 4 Dec 2026 08:35:21 +0100 Subject: [PATCH 1/2] Add scoped Google Drive and OneDrive change feeds --- .github/scripts/verify-published-packages.py | 17 +- Directory.Build.props | 2 +- README.md | 2 + .../Clients/GoogleDriveClient.Changes.cs | 126 ++++++++++ .../GoogleDriveChangesCursor.cs | 6 + .../GoogleDriveChangesPage.cs | 7 + .../GoogleDriveFileChange.cs | 4 + .../GoogleDriveStorage.Changes.cs | 83 +++++++ .../IGoogleDriveStorage.cs | 8 + .../GraphOneDriveClient.Continuation.cs | 36 +++ .../Clients/GraphOneDriveClient.Delta.cs | 186 ++++++++++++++ .../Clients/GraphOneDriveClient.cs | 62 +++-- .../IOneDriveStorage.cs | 9 + .../OneDriveDeltaCursor.cs | 7 + .../OneDriveDeltaPage.cs | 8 + .../OneDriveDeltaReset.cs | 4 + .../OneDriveDeltaStart.cs | 8 + .../OneDriveItemChange.cs | 4 + .../OneDriveStorage.Delta.cs | 42 ++++ .../OneDriveStorage.ItemRevisions.cs | 2 +- .../CloudDrive/GoogleDriveChangesTests.cs | 168 +++++++++++++ .../GraphOneDriveChildrenPagingTests.cs | 115 +++++++++ .../CloudDrive/GraphOneDriveDeltaTests.cs | 232 ++++++++++++++++++ docs/ADR/0008-cloud-drive-clients-and-auth.md | 1 + docs/Architecture.md | 5 + docs/Features/cloud-drive-change-feeds.md | 33 +++ docs/Features/index.md | 1 + 27 files changed, 1156 insertions(+), 22 deletions(-) create mode 100644 Storages/ManagedCode.Storage.GoogleDrive/Clients/GoogleDriveClient.Changes.cs create mode 100644 Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesCursor.cs create mode 100644 Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesPage.cs create mode 100644 Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveFileChange.cs create mode 100644 Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveStorage.Changes.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Continuation.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Delta.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaCursor.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaPage.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaReset.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaStart.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveItemChange.cs create mode 100644 Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.Delta.cs create mode 100644 Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs create mode 100644 Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs create mode 100644 Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs create mode 100644 docs/Features/cloud-drive-change-feeds.md diff --git a/.github/scripts/verify-published-packages.py b/.github/scripts/verify-published-packages.py index 05817015..2f4b5d1c 100644 --- a/.github/scripts/verify-published-packages.py +++ b/.github/scripts/verify-published-packages.py @@ -43,6 +43,7 @@ def packed_metadata(directory, commit, expected_version): def verify(pending, commit, timeout): package_count = len(pending) + failures = {} deadline = time.monotonic() + timeout while pending: for package_id, identity in list(pending.items()): @@ -51,19 +52,27 @@ def verify(pending, commit, timeout): url = f"https://api.nuget.org/v3-flatcontainer/{name}/{version}/{name}.{version}.nupkg" try: response = subprocess.run(["curl", "--fail", "--silent", "--show-error", "--max-time", "15", - "--header", "Cache-Control: no-cache", url], + "--header", "Cache-Control: no-cache", + "--write-out", "%{stderr}%{http_code}", url], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20) published = metadata(response.stdout) if published != identity: raise ValueError(f"{package_id}: published identity/version/commit differs from the packed artifact") print(f"Verified {package_id} {version} at {commit}", flush=True) del pending[package_id] - except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: - print(f"Waiting for {package_id}: {type(error).__name__}", flush=True) + except subprocess.CalledProcessError as error: + http_code = (error.stderr or b"")[-3:] + status = http_code.decode("ascii") if http_code.isdigit() else "unknown" + failures[package_id] = f"curl exit {error.returncode}, HTTP {status}" + except subprocess.TimeoutExpired: + failures[package_id] = "transport timed out" + if package_id in pending: + print(f"Waiting for {package_id}: {failures[package_id]}", flush=True) if not pending: break if time.monotonic() >= deadline: - raise TimeoutError("Packages unavailable before the publication deadline: " + ", ".join(pending)) + waiting = "; ".join(f"{name} ({failures[name]})" for name in pending) + raise TimeoutError("Packages unavailable before the publication deadline: " + waiting) time.sleep(min(20, max(0, deadline - time.monotonic()))) print(f"Verified all {package_count} published packages", flush=True) diff --git a/Directory.Build.props b/Directory.Build.props index 8c87ab3f..8ceca8b6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -29,7 +29,7 @@ https://github.com/managedcode/Storage https://github.com/managedcode/Storage Managed Code - Storage - 10.1.17 + 10.1.18 diff --git a/README.md b/README.md index 105e36db..a0255b7d 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,8 @@ For a Google Workspace document use `IGoogleDriveStorage.ReadDocumentAsync` with For a known OneDrive file, `IOneDriveStorage.GetItemRevisionAsync` returns the exact item ID, drive ID and current ETag. `CaptureItemRevisionAsync` reads that selected revision within a caller-supplied byte limit and returns its SHA-256. `ReadItemRevisionAsync` rechecks the revision and a trusted SHA-256. [OneDrive revision reads](docs/Features/provider-onedrive.md) +Google Drive Changes and OneDrive delta provide incremental item identities for a current grant. The provider cursor stays on the server, and an exact file read verifies current access and revision before content is used. [Cloud drive change feeds](docs/Features/cloud-drive-change-feeds.md) + ### Configuring OneDrive, Google Drive, Dropbox, and CloudKit > iCloud Drive does not expose a public server-side file API. `ManagedCode.Storage.CloudKit` targets CloudKit Web Services (iCloud app data), not iCloud Drive. diff --git a/Storages/ManagedCode.Storage.GoogleDrive/Clients/GoogleDriveClient.Changes.cs b/Storages/ManagedCode.Storage.GoogleDrive/Clients/GoogleDriveClient.Changes.cs new file mode 100644 index 00000000..5122c517 --- /dev/null +++ b/Storages/ManagedCode.Storage.GoogleDrive/Clients/GoogleDriveClient.Changes.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Google.Apis.Drive.v3.Data; +using ManagedCode.Communication; + +namespace ManagedCode.Storage.GoogleDrive.Clients; + +public partial class GoogleDriveClient +{ + private const int MaximumChangesTokenLength = 16 * 1024; + private const int MaximumChangesItemIdLength = 256; + private const string FileChangeType = "file"; + private const string DriveChangeType = "drive"; + + internal async Task> GetChangesCursorAsync( + Guid grantId, bool supportsAllDrives, CancellationToken cancellationToken) + { + var accountPermissionId = await ReadChangesAccountAsync(cancellationToken).ConfigureAwait(false); + var request = _driveService.Changes.GetStartPageToken(); + request.SupportsAllDrives = supportsAllDrives; + request.Fields = "startPageToken"; + request.ModifyRequest = RequireFreshChangeRead; + var token = (await request.ExecuteAsync(cancellationToken).ConfigureAwait(false))?.StartPageTokenValue; + if (!IsChangesToken(token)) + { + throw new InvalidDataException("Google Drive returned no start token."); + } + + return Result.Succeed(new GoogleDriveChangesCursor( + grantId, accountPermissionId, supportsAllDrives, token!)); + } + + internal async Task> ReadChangesPageAsync( + GoogleDriveChangesCursor cursor, int pageSize, CancellationToken cancellationToken) + { + var accountPermissionId = await ReadChangesAccountAsync(cancellationToken).ConfigureAwait(false); + if (!string.Equals(accountPermissionId, cursor.AccountPermissionId, StringComparison.Ordinal)) + { + return Result.FailNotFound("The Google Drive change cursor is unavailable."); + } + + var request = _driveService.Changes.List(cursor.PageToken); + request.SupportsAllDrives = cursor.IncludesSharedDriveItems; + request.IncludeItemsFromAllDrives = cursor.IncludesSharedDriveItems; + request.IncludeRemoved = true; + request.IncludeCorpusRemovals = true; + request.PageSize = pageSize; + request.Fields = "nextPageToken,newStartPageToken,changes(changeType,fileId,removed,file(id,version,trashed))"; + request.ModifyRequest = RequireFreshChangeRead; + var page = await request.ExecuteAsync(cancellationToken).ConfigureAwait(false) + ?? throw new InvalidDataException("Google Drive returned no change page."); + var next = page.NextPageToken; + var checkpoint = page.NewStartPageToken; + if ((next is null) == (checkpoint is null) || + (next is not null && (!IsChangesToken(next) || string.Equals(next, cursor.PageToken, StringComparison.Ordinal))) || + (checkpoint is not null && !IsChangesToken(checkpoint)) || page.Changes?.Count > pageSize) + { + throw new InvalidDataException("Google Drive returned an invalid change position."); + } + + List files = []; + foreach (var change in page.Changes ?? []) + { + if (string.Equals(change?.ChangeType, DriveChangeType, StringComparison.Ordinal)) + { + continue; + } + + files.Add(DecodeFileChange(change)); + } + + return Result.Succeed(new GoogleDriveChangesPage( + files, next is null ? null : cursor with { PageToken = next }, + checkpoint is null ? null : cursor with { PageToken = checkpoint })); + } + + internal static bool IsChangesToken(string? value) => + value is { Length: > 0 and <= MaximumChangesTokenLength } && !value.Any(char.IsControl) && + !string.IsNullOrWhiteSpace(value); + + private async Task ReadChangesAccountAsync(CancellationToken cancellationToken) + { + var request = _driveService.About.Get(); + request.Fields = "user(permissionId)"; + request.ModifyRequest = RequireFreshChangeRead; + var accountPermissionId = (await request.ExecuteAsync(cancellationToken).ConfigureAwait(false))?.User?.PermissionId; + if (string.IsNullOrWhiteSpace(accountPermissionId)) + { + throw new InvalidDataException("Google Drive returned no account identity."); + } + + return accountPermissionId; + } + + private static void RequireFreshChangeRead(HttpRequestMessage request) => + request.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true }; + + private static GoogleDriveFileChange DecodeFileChange(Change? change) + { + if (change is null || !string.Equals(change.ChangeType, FileChangeType, StringComparison.Ordinal) || + change.FileId is not { Length: > 0 and <= MaximumChangesItemIdLength } fileId || + !fileId.All(static value => char.IsAsciiLetterOrDigit(value) || value is '-' or '_') || + (change.File?.Id is { } nestedId && !string.Equals(fileId, nestedId, StringComparison.Ordinal))) + { + throw new InvalidDataException("Google Drive returned an invalid file change."); + } + + if (change.Removed == true || change.File?.Trashed == true) + { + return new GoogleDriveFileChange(fileId, null, true); + } + + if (change.File is { Id: not null, Version: > 0 } file) + { + return new GoogleDriveFileChange(fileId, file.Version, false); + } + + throw new InvalidDataException("Google Drive returned a file change without its revision."); + } +} diff --git a/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesCursor.cs b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesCursor.cs new file mode 100644 index 00000000..e6204c8d --- /dev/null +++ b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesCursor.cs @@ -0,0 +1,6 @@ +namespace ManagedCode.Storage.GoogleDrive; + +/// A provider-issued position for one current grant and Google Drive account. +/// Retain this cursor on the server. Treat the page token as opaque. +public sealed record GoogleDriveChangesCursor( + System.Guid GrantId, string AccountPermissionId, bool IncludesSharedDriveItems, string PageToken); diff --git a/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesPage.cs b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesPage.cs new file mode 100644 index 00000000..e552047b --- /dev/null +++ b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveChangesPage.cs @@ -0,0 +1,7 @@ +using System.Collections.Generic; + +namespace ManagedCode.Storage.GoogleDrive; + +/// One native change page and its continuation or terminal checkpoint. +public sealed record GoogleDriveChangesPage( + IReadOnlyList Files, GoogleDriveChangesCursor? Continuation, GoogleDriveChangesCursor? Checkpoint); diff --git a/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveFileChange.cs b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveFileChange.cs new file mode 100644 index 00000000..83ce7d4e --- /dev/null +++ b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveFileChange.cs @@ -0,0 +1,4 @@ +namespace ManagedCode.Storage.GoogleDrive; + +/// An item identity observed by the current grant. Unavailable includes removal from that grant's view. +public sealed record GoogleDriveFileChange(string FileId, long? Version, bool Unavailable); diff --git a/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveStorage.Changes.cs b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveStorage.Changes.cs new file mode 100644 index 00000000..347a3187 --- /dev/null +++ b/Storages/ManagedCode.Storage.GoogleDrive/GoogleDriveStorage.Changes.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Google; +using ManagedCode.Communication; +using ManagedCode.Storage.GoogleDrive.Clients; + +namespace ManagedCode.Storage.GoogleDrive; + +public partial class GoogleDriveStorage +{ + private const int MaximumChangesPageSize = 1000; + + public Task> GetChangesCursorAsync( + Guid currentGrantId, CancellationToken cancellationToken = default) + { + if (currentGrantId == Guid.Empty) + { + return Task.FromResult(Result.FailBadRequest("A current Google Drive grant is required.")); + } + + return ReadChangesWithSdkAsync(client => client.GetChangesCursorAsync( + currentGrantId, StorageOptions.SupportsAllDrives, cancellationToken), cancellationToken); + } + + public Task> ReadChangesPageAsync( + Guid currentGrantId, GoogleDriveChangesCursor cursor, int pageSize, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(cursor); + if (currentGrantId == Guid.Empty || !GoogleDriveClient.IsChangesToken(cursor.PageToken) || + pageSize is < 1 or > MaximumChangesPageSize) + { + return Task.FromResult(Result.FailBadRequest("The Google Drive change request is invalid.")); + } + + if (cursor.GrantId != currentGrantId || cursor.IncludesSharedDriveItems != StorageOptions.SupportsAllDrives) + { + return Task.FromResult(Result.FailNotFound("The Google Drive change cursor is unavailable.")); + } + + return ReadChangesWithSdkAsync( + client => client.ReadChangesPageAsync(cursor, pageSize, cancellationToken), cancellationToken); + } + + private async Task> ReadChangesWithSdkAsync( + Func>> read, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (StorageClient is not GoogleDriveClient client || !string.Equals(StorageOptions.RootFolderId, "root", StringComparison.Ordinal)) + { + return Result.FailBadRequest("The Google Drive change feed requires the SDK client and account root."); + } + + try + { + return await read(client).ConfigureAwait(false); + } + catch (GoogleApiException error) + { + return ChangesFailure(error.HttpStatusCode); + } + catch (HttpRequestException error) + { + return ChangesFailure(error.StatusCode); + } + catch (Exception error) when (error is IOException or InvalidDataException) + { + return ChangesFailure(null); + } + } + + private static Result ChangesFailure(HttpStatusCode? status) => status switch + { + HttpStatusCode.BadRequest => Result.FailBadRequest("Google Drive rejected the change cursor."), + HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden or HttpStatusCode.NotFound => + Result.FailNotFound("The Google Drive change feed is unavailable."), + _ => Result.Fail("Google Drive change read failed.", "Google Drive could not complete the change read.", + (int)status.GetValueOrDefault() is >= 400 and <= 599 ? status.GetValueOrDefault() : HttpStatusCode.BadGateway) + }; +} diff --git a/Storages/ManagedCode.Storage.GoogleDrive/IGoogleDriveStorage.cs b/Storages/ManagedCode.Storage.GoogleDrive/IGoogleDriveStorage.cs index a39f4f95..e790f80a 100644 --- a/Storages/ManagedCode.Storage.GoogleDrive/IGoogleDriveStorage.cs +++ b/Storages/ManagedCode.Storage.GoogleDrive/IGoogleDriveStorage.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using System.Threading.Tasks; using ManagedCode.Communication; @@ -10,4 +11,11 @@ namespace ManagedCode.Storage.GoogleDrive; public interface IGoogleDriveStorage : IStorage { Task> ReadDocumentAsync(GoogleDriveDocumentRead request, CancellationToken cancellationToken = default); + + /// Starts observing new changes in the current account under an already-authorized Google Drive grant. + Task> GetChangesCursorAsync(Guid currentGrantId, CancellationToken cancellationToken = default); + + /// Reads one scoped account change page using the current grant and an existing provider position. + Task> ReadChangesPageAsync( + Guid currentGrantId, GoogleDriveChangesCursor cursor, int pageSize, CancellationToken cancellationToken = default); } diff --git a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Continuation.cs b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Continuation.cs new file mode 100644 index 00000000..ec3f30f8 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Continuation.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; + +namespace ManagedCode.Storage.OneDrive.Clients; + +public partial class GraphOneDriveClient +{ + private const int MaximumContinuationLength = 16 * 1024; + + private static bool TryGetGraphContinuation(string? value, Uri operationUri, out Uri? continuation) + { + continuation = null; + if (value is not { Length: > 0 and <= MaximumContinuationLength } || + !Uri.TryCreate(value, UriKind.Absolute, out var link) || + !string.Equals(link.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) || + !string.Equals(link.IdnHost, operationUri.IdnHost, StringComparison.OrdinalIgnoreCase) || + link.Port != operationUri.Port || link.UserInfo.Length != 0 || link.Fragment.Length != 0) + { + return false; + } + + continuation = link; + return true; + } + + private static Uri RequireChildrenContinuation(string value, Uri operationUri) + { + if (!TryGetGraphContinuation(value, operationUri, out var link) || + !string.Equals(link!.AbsolutePath, operationUri.AbsolutePath, StringComparison.Ordinal)) + { + throw new InvalidDataException("Microsoft Graph returned a continuation outside the current folder."); + } + + return link!; + } +} diff --git a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Delta.cs b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Delta.cs new file mode 100644 index 00000000..2f6779b9 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.Delta.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using ManagedCode.Communication; +using Microsoft.Graph.Drives.Item.Items.Item.Delta; +using Microsoft.Graph.Models; +using Microsoft.Kiota.Abstractions; + +namespace ManagedCode.Storage.OneDrive.Clients; + +public partial class GraphOneDriveClient +{ + private const string EmptyDeltaFunction = "()"; + private const string LatestDeltaToken = "latest"; + private const string ResyncLocationHeader = "Location"; + + internal async Task> StartDeltaAsync( + string configuredDriveId, Guid grantId, OneDriveDeltaStart start, CancellationToken cancellationToken) + { + var scope = await ReadDeltaScopeAsync(configuredDriveId, cancellationToken).ConfigureAwait(false); + if (scope is null) + { + return MissingDeltaScope(); + } + + if (start == OneDriveDeltaStart.FromNow) + { + var latest = await _graphServiceClient.Drives[scope.DriveId].Items[scope.RootItemId] + .DeltaWithToken(LatestDeltaToken).GetAsDeltaWithTokenGetResponseAsync( + config => config.Headers.Add("Cache-Control", "no-cache"), cancellationToken) + .ConfigureAwait(false); + if (latest is not { Value.Count: 0, OdataNextLink: null, OdataDeltaLink: { } latestCheckpoint }) + { + throw new InvalidDataException("Microsoft Graph returned no latest delta checkpoint."); + } + + return BuildDeltaPage(scope, grantId, latest.Value, null, latestCheckpoint, null); + } + + var first = await scope.Builder.GetAsDeltaGetResponseAsync( + config => config.Headers.Add("Cache-Control", "no-cache"), cancellationToken).ConfigureAwait(false); + return BuildDeltaPage(scope, grantId, first?.Value, first?.OdataNextLink, first?.OdataDeltaLink, null); + } + + internal async Task> ReadDeltaPageAsync( + string configuredDriveId, OneDriveDeltaCursor cursor, CancellationToken cancellationToken) + { + var scope = await ReadDeltaScopeAsync(configuredDriveId, cancellationToken).ConfigureAwait(false); + if (scope is null || !string.Equals(scope.DriveId, cursor.DriveId, StringComparison.Ordinal) || + !string.Equals(scope.RootItemId, cursor.RootItemId, StringComparison.Ordinal) || + !IsDeltaLink(scope, cursor.ProviderLink)) + { + return MissingDeltaScope(); + } + + try + { + var page = await scope.Builder.WithUrl(cursor.ProviderLink).GetAsDeltaGetResponseAsync( + config => config.Headers.Add("Cache-Control", "no-cache"), cancellationToken).ConfigureAwait(false); + return BuildDeltaPage(scope, cursor.GrantId, page?.Value, page?.OdataNextLink, page?.OdataDeltaLink, cursor.ProviderLink); + } + catch (ApiException error) when (error.ResponseStatusCode == (int)HttpStatusCode.Gone) + { + var locations = error.ResponseHeaders?.Where(header => string.Equals(header.Key, ResyncLocationHeader, StringComparison.OrdinalIgnoreCase)) + .SelectMany(static header => header.Value) + .Take(2) + .ToArray(); + var restart = locations is { Length: 1 } && IsDeltaLink(scope, locations[0]) && + !string.Equals(locations[0], cursor.ProviderLink, StringComparison.Ordinal) + ? cursor with { ProviderLink = locations[0] } + : null; + return Result.Succeed(new OneDriveDeltaPage([], null, null, new OneDriveDeltaReset(restart))); + } + } + + private async Task ReadDeltaScopeAsync(string configuredDriveId, CancellationToken cancellationToken) + { + // The delegated default drive proves both the current owner's drive and the meaning of Graph's /me aliases. + var drive = await _graphServiceClient.Me.Drive.GetAsync(config => + { + config.QueryParameters.Select = ["id"]; + config.Headers.Add("Cache-Control", "no-cache"); + }, cancellationToken).ConfigureAwait(false); + if (drive?.Id is not { Length: > 0 } driveId || + (!string.Equals(configuredDriveId, "me", StringComparison.OrdinalIgnoreCase) && + !string.Equals(configuredDriveId, driveId, StringComparison.Ordinal))) + { + return null; + } + + var root = await _graphServiceClient.Drives[driveId].Root.GetAsync(config => + { + config.QueryParameters.Select = ["id"]; + config.Headers.Add("Cache-Control", "no-cache"); + }, cancellationToken).ConfigureAwait(false); + if (root?.Id is not { Length: > 0 } rootId) + { + return null; + } + + var builder = _graphServiceClient.Drives[driveId].Items[rootId].Delta; + var operation = builder.ToGetRequestInformation().URI; + var baseUrl = _graphServiceClient.RequestAdapter.BaseUrl; + if (string.IsNullOrWhiteSpace(baseUrl)) + { + throw new InvalidDataException("Microsoft Graph requires a configured base URL."); + } + + var baseUri = new Uri(baseUrl.TrimEnd('/') + "/", UriKind.Absolute); + return new GraphDeltaScope(driveId, rootId, builder, operation, + new Uri(baseUri, $"drives/{Uri.EscapeDataString(driveId)}/root/delta").AbsolutePath, + new Uri(baseUri, "me/drive/root/delta").AbsolutePath, + new Uri(baseUri, "me/drive/delta").AbsolutePath); + } + + private static Result BuildDeltaPage( + GraphDeltaScope scope, Guid grantId, IReadOnlyList? items, string? next, string? checkpoint, string? inputLink) + { + if (items is null || (next is null) == (checkpoint is null) || + (next is not null && (!IsDeltaLink(scope, next) || string.Equals(inputLink, next, StringComparison.Ordinal))) || + (checkpoint is not null && !IsDeltaLink(scope, checkpoint))) + { + throw new InvalidDataException("Microsoft Graph returned an invalid delta page."); + } + + List changes = []; + foreach (var item in items) + { + if (item?.Id is not { Length: > 0 } itemId) + { + throw new InvalidDataException("Microsoft Graph returned a delta item without an ID."); + } + + if (item.RemoteItem is not null || + (item.ParentReference?.DriveId is { } parentDrive && + !string.Equals(parentDrive, scope.DriveId, StringComparison.Ordinal))) + { + continue; + } + + changes.Add(new OneDriveItemChange(itemId, item.ETag, item.Deleted is not null)); + } + + return Result.Succeed(new OneDriveDeltaPage( + changes, next is null ? null : new OneDriveDeltaCursor(grantId, scope.DriveId, scope.RootItemId, next), + checkpoint is null ? null : new OneDriveDeltaCursor(grantId, scope.DriveId, scope.RootItemId, checkpoint), + null)); + } + + private static bool IsDeltaLink(GraphDeltaScope scope, string link) => + TryGetGraphContinuation(link, scope.Operation, out var target) && + (IsDeltaOperation(target!.AbsolutePath, scope.Operation.AbsolutePath) || + IsDeltaOperation(target.AbsolutePath, scope.DriveRootPath) || + IsDeltaOperation(target.AbsolutePath, scope.CurrentDriveRootPath) || + IsDeltaOperation(target.AbsolutePath, scope.CurrentDrivePath)); + + private static bool IsDeltaOperation(string path, string operation) + { + // The SDK request template uses delta(), and Graph also issues plain delta links. + var operationPath = operation.EndsWith(EmptyDeltaFunction, StringComparison.Ordinal) + ? operation[..^EmptyDeltaFunction.Length] + : operation; + if (string.Equals(path, operationPath, StringComparison.Ordinal) || + string.Equals(path, operationPath + EmptyDeltaFunction, StringComparison.Ordinal)) + { + return true; + } + + const string tokenParameter = "(token="; + var openingLength = operationPath.Length + tokenParameter.Length; + return path.StartsWith(operationPath + tokenParameter, StringComparison.Ordinal) && + path.EndsWith(')') && path.Length > openingLength + 1 && + path.AsSpan(openingLength, path.Length - openingLength - 1).IndexOfAny('/', '(', ')') < 0; + } + + private static Result MissingDeltaScope() => + Result.FailNotFound("The OneDrive delta scope is unavailable."); + + private sealed record GraphDeltaScope( + string DriveId, string RootItemId, DeltaRequestBuilder Builder, Uri Operation, + string DriveRootPath, string CurrentDriveRootPath, string CurrentDrivePath); +} diff --git a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs index adf94847..cb4ad469 100644 --- a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs +++ b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Graph; +using Microsoft.Graph.Drives.Item.Items.Item.Children; using Microsoft.Graph.Models; using Microsoft.Graph.Models.ODataErrors; @@ -159,19 +159,9 @@ private async IAsyncEnumerable ListInternalAsync(string driveId, stri } var builder = _graphServiceClient.Drives[resolvedDriveId].Items[parent.Id].Children; - var page = await builder.GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - if (page?.Value == null) + await foreach (var item in EnumerateChildrenAsync(builder, cancellationToken).ConfigureAwait(false)) { - yield break; - } - - foreach (var item in page.Value) - { - cancellationToken.ThrowIfCancellationRequested(); - if (item != null) - { - yield return item; - } + yield return item; } } @@ -181,7 +171,7 @@ private async IAsyncEnumerable ListInternalAsync(string driveId, stri return _graphServiceClient.Drives[resolvedDriveId].Root; } - private async Task GetChildrenBuilderAsync(string driveId, string parentId, CancellationToken cancellationToken) + private async Task GetChildrenBuilderAsync(string driveId, string parentId, CancellationToken cancellationToken) { var resolvedDriveId = await ResolveDriveIdAsync(driveId, cancellationToken).ConfigureAwait(false); return _graphServiceClient.Drives[resolvedDriveId].Items[parentId].Children; @@ -208,9 +198,49 @@ private async Task ResolveDriveIdAsync(string driveId, CancellationToken private async Task FindChildAsync(string driveId, string parentId, string name, CancellationToken cancellationToken) { var childrenBuilder = await GetChildrenBuilderAsync(driveId, parentId, cancellationToken).ConfigureAwait(false); - var children = await childrenBuilder.GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + await foreach (var child in EnumerateChildrenAsync(childrenBuilder, cancellationToken).ConfigureAwait(false)) + { + if (string.Equals(child.Name, name, StringComparison.OrdinalIgnoreCase)) + { + return child; + } + } + + return null; + } - return children?.Value?.FirstOrDefault(c => string.Equals(c?.Name, name, StringComparison.OrdinalIgnoreCase)); + private static async IAsyncEnumerable EnumerateChildrenAsync( + ChildrenRequestBuilder builder, [EnumeratorCancellation] CancellationToken cancellationToken) + { + var requestUri = builder.ToGetRequestInformation().URI; + var page = await builder.GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + var seen = new HashSet(StringComparer.Ordinal) { requestUri.AbsoluteUri }; + while (page is not null) + { + foreach (var child in page.Value ?? []) + { + cancellationToken.ThrowIfCancellationRequested(); + if (child is not null) + { + yield return child; + } + } + + var next = page.OdataNextLink; + if (next is null) + { + yield break; + } + + var link = RequireChildrenContinuation(next, requestUri); + if (!seen.Add(link.AbsoluteUri)) + { + throw new InvalidDataException("Microsoft Graph repeated a folder continuation."); + } + + page = await builder.WithUrl(next).GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false) + ?? throw new InvalidDataException("Microsoft Graph returned no folder continuation page."); + } } private static string NormalizePath(string path) diff --git a/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs b/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs index 6c72ace7..8f6c49ab 100644 --- a/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs +++ b/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -20,4 +21,12 @@ public interface IOneDriveStorage : IStorageReads verified bytes of one file using a previously observed drive, item and revision. /// The returned stream belongs to the caller. Task> ReadItemRevisionAsync(OneDriveItemRead request, CancellationToken cancellationToken = default); + + /// Starts a delta enumeration or reads the latest checkpoint for the granted user's default drive. + Task> StartDeltaAsync( + Guid currentGrantId, OneDriveDeltaStart start, CancellationToken cancellationToken = default); + + /// Reads one native delta position using the current delegated grant and resolved drive root. + Task> ReadDeltaPageAsync( + Guid currentGrantId, OneDriveDeltaCursor cursor, CancellationToken cancellationToken = default); } diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaCursor.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaCursor.cs new file mode 100644 index 00000000..25ad21a2 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaCursor.cs @@ -0,0 +1,7 @@ +using System; + +namespace ManagedCode.Storage.OneDrive; + +/// A provider-issued position for one current delegated grant, drive and root. +/// Retain this cursor on the server. Treat the provider link as opaque. +public sealed record OneDriveDeltaCursor(Guid GrantId, string DriveId, string RootItemId, string ProviderLink); diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaPage.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaPage.cs new file mode 100644 index 00000000..ed9c49ef --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaPage.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace ManagedCode.Storage.OneDrive; + +/// One native delta page, a terminal checkpoint, or a request to resynchronize. +public sealed record OneDriveDeltaPage( + IReadOnlyList Items, OneDriveDeltaCursor? Continuation, + OneDriveDeltaCursor? Checkpoint, OneDriveDeltaReset? Reset); diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaReset.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaReset.cs new file mode 100644 index 00000000..98ca3999 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaReset.cs @@ -0,0 +1,4 @@ +namespace ManagedCode.Storage.OneDrive; + +/// Graph expired a position. A provider restart link may be available for full enumeration. +public sealed record OneDriveDeltaReset(OneDriveDeltaCursor? Restart); diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaStart.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaStart.cs new file mode 100644 index 00000000..a0d36d02 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveDeltaStart.cs @@ -0,0 +1,8 @@ +namespace ManagedCode.Storage.OneDrive; + +/// Whether to enumerate the current drive before consuming future changes. +public enum OneDriveDeltaStart +{ + FromNow, + FullEnumeration +} diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveItemChange.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveItemChange.cs new file mode 100644 index 00000000..6f6ac4f2 --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveItemChange.cs @@ -0,0 +1,4 @@ +namespace ManagedCode.Storage.OneDrive; + +/// An item identity in the scoped drive. An ETag is present only when Graph provides it. +public sealed record OneDriveItemChange(string ItemId, string? ETag, bool Deleted); diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.Delta.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.Delta.cs new file mode 100644 index 00000000..6e9e622c --- /dev/null +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.Delta.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using ManagedCode.Communication; + +namespace ManagedCode.Storage.OneDrive; + +public partial class OneDriveStorage +{ + public Task> StartDeltaAsync( + Guid currentGrantId, OneDriveDeltaStart start, CancellationToken cancellationToken = default) + { + if (currentGrantId == Guid.Empty || start is not (OneDriveDeltaStart.FromNow or OneDriveDeltaStart.FullEnumeration) || + NormalizeRelativePath(StorageOptions.RootPath).Length != 0) + { + return Task.FromResult(Result.FailBadRequest( + "OneDrive delta requires a current delegated grant and a drive root.")); + } + + return ReadGraphAsync((client, drive, _) => client.StartDeltaAsync(drive, currentGrantId, start, cancellationToken), + cancellationToken); + } + + public Task> ReadDeltaPageAsync( + Guid currentGrantId, OneDriveDeltaCursor cursor, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(cursor); + if (currentGrantId == Guid.Empty || !IsValidNativeIdentifier(cursor.DriveId) || + !IsValidNativeIdentifier(cursor.RootItemId) || NormalizeRelativePath(StorageOptions.RootPath).Length != 0) + { + return Task.FromResult(Result.FailBadRequest("The OneDrive delta request is invalid.")); + } + + if (cursor.GrantId != currentGrantId) + { + return Task.FromResult(Result.FailNotFound("The OneDrive delta cursor is unavailable.")); + } + + return ReadGraphAsync((client, drive, _) => client.ReadDeltaPageAsync(drive, cursor, cancellationToken), + cancellationToken); + } +} diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs index 8a0fcce3..831bf132 100644 --- a/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs +++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs @@ -74,7 +74,7 @@ private async Task> ReadGraphAsync( { return GraphReadFailure(error.StatusCode); } - catch (IOException) + catch (Exception error) when (error is IOException or InvalidDataException) { return GraphReadFailure(null); } diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs new file mode 100644 index 00000000..b759600f --- /dev/null +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ManagedCode.Storage.GoogleDrive; +using Shouldly; +using Xunit; + +namespace ManagedCode.Storage.Tests.Storages.CloudDrive; + +public sealed class GoogleDriveChangesTests +{ + [Fact] + public async Task CurrentGrantConsumesEmptyAndNonemptyPagesBeforeAdvancingCheckpointAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport(); + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + + var start = await storage.GetChangesCursorAsync(grant, cancellation); + start.IsSuccess.ShouldBeTrue(); + start.Value.ShouldBe(new GoogleDriveChangesCursor(grant, "authorized-person", true, "start+opaque/position=")); + var empty = await storage.ReadChangesPageAsync(grant, start.Value, 50, cancellation); + empty.IsSuccess.ShouldBeTrue(); + empty.Value.Files.ShouldBeEmpty(); + empty.Value.Checkpoint.ShouldBeNull(); + var continuation = empty.Value.Continuation.ShouldNotBeNull(); + continuation.PageToken.ShouldBe("next+opaque/position="); + + var complete = await storage.ReadChangesPageAsync(grant, continuation, 50, cancellation); + complete.IsSuccess.ShouldBeTrue(); + complete.Value.Continuation.ShouldBeNull(); + complete.Value.Checkpoint.ShouldBe(start.Value with { PageToken = "terminal+opaque/position=" }); + complete.Value.Files.ShouldBe(new[] + { + new GoogleDriveFileChange("paper_123", 8, false), + new GoogleDriveFileChange("removed_1", null, true), + new GoogleDriveFileChange("trashed_1", null, true) + }); + + var retry = await storage.ReadChangesPageAsync(grant, continuation, 50, cancellation); + retry.IsSuccess.ShouldBeTrue(); + retry.Value.Files.ShouldBe(complete.Value.Files); + retry.Value.Checkpoint.ShouldBe(complete.Value.Checkpoint); + transport.FeedTokens.ShouldBe(new string?[] { null, "start+opaque/position=", "next+opaque/position=", "next+opaque/position=" }); + } + + [Fact] + public async Task ChangedGrantAndProviderAccountCannotReadRetainedGooglePositionAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport(); + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + var opened = await storage.GetChangesCursorAsync(grant, cancellation); + opened.IsSuccess.ShouldBeTrue(); + var start = opened.Value; + + var wrongGrant = await storage.ReadChangesPageAsync(Guid.NewGuid(), start, 50, cancellation); + wrongGrant.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.AboutReads.ShouldBe(1); + + transport.AccountPermissionId = "different-person"; + var wrongAccount = await storage.ReadChangesPageAsync(grant, start, 50, cancellation); + wrongAccount.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.AboutReads.ShouldBe(2); + transport.FeedTokens.ShouldBe(new string?[] { null }); + } + + [Theory] + [InlineData(HttpStatusCode.Forbidden, "", HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.BadRequest, "", HttpStatusCode.BadRequest)] + [InlineData(HttpStatusCode.OK, """{"nextPageToken":"a","newStartPageToken":"b","changes":[]}""", HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.OK, """{"newStartPageToken":"b","changes":[{"changeType":"file","fileId":"one","file":{"id":"another","version":"2"}}]}""", + HttpStatusCode.BadGateway)] + public async Task DeniedOrInvalidGooglePageDoesNotAdvanceThePositionAsync( + HttpStatusCode providerStatus, string body, HttpStatusCode expectedStatus) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport { PageResponse = (providerStatus, body) }; + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + var opened = await storage.GetChangesCursorAsync(grant, cancellation); + opened.IsSuccess.ShouldBeTrue(); + var start = opened.Value; + + var denied = await storage.ReadChangesPageAsync(grant, start, 50, cancellation); + denied.IsFailed.ShouldBeTrue(); + denied.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)expectedStatus); + + transport.PageResponse = null; + var retried = await storage.ReadChangesPageAsync(grant, start, 50, cancellation); + retried.IsSuccess.ShouldBeTrue(); + retried.Value.Continuation.ShouldNotBeNull().PageToken.ShouldBe("next+opaque/position="); + transport.FeedTokens.ShouldBe(new string?[] { null, "start+opaque/position=", "start+opaque/position=" }); + } + + private sealed class ChangesTransport : HttpMessageHandler + { + public string AccountPermissionId { get; set; } = "authorized-person"; + public List FeedTokens { get; } = []; + public int AboutReads { get; private set; } + public (HttpStatusCode Status, string Body)? PageResponse { get; set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + request.Method.ShouldBe(HttpMethod.Get); + var target = request.RequestUri.ShouldNotBeNull(); + target.Host.ShouldBe("www.googleapis.com"); + request.Headers.CacheControl.ShouldNotBeNull().NoCache.ShouldBeTrue(); + if (target.AbsolutePath == "/drive/v3/about") + { + Uri.UnescapeDataString(target.Query).ShouldContain("fields=user(permissionId)"); + AboutReads++; + return Task.FromResult(Json(HttpStatusCode.OK, $$$"""{"user":{"permissionId":"{{{AccountPermissionId}}}"}}""")); + } + + var query = Uri.UnescapeDataString(target.Query); + query.ShouldContain("supportsAllDrives=true"); + if (target.AbsolutePath == "/drive/v3/changes/startPageToken") + { + FeedTokens.Add(null); + return Task.FromResult(Json(HttpStatusCode.OK, """{"startPageToken":"start+opaque/position="}""")); + } + + target.AbsolutePath.ShouldBe("/drive/v3/changes"); + query.ShouldContain("includeItemsFromAllDrives=true"); + query.ShouldContain("includeCorpusRemovals=true"); + query.ShouldContain("pageSize=50"); + const string pageTokenParameter = "pageToken="; + const string includeRemovedParameter = "includeRemoved="; + var parameters = target.Query.TrimStart('?').Split('&'); + // The Google discovery contract enables removals when this parameter is absent. + var removalParameter = Array.Find(parameters, + value => value.StartsWith(includeRemovedParameter, StringComparison.Ordinal)); + (removalParameter ?? "includeRemoved=true").ShouldBe("includeRemoved=true"); + var tokenParameter = Array.Find(parameters, + value => value.StartsWith(pageTokenParameter, StringComparison.Ordinal)).ShouldNotBeNull(); + var pageToken = Uri.UnescapeDataString(tokenParameter[pageTokenParameter.Length..]); + FeedTokens.Add(pageToken); + if (PageResponse is { } response) + { + return Task.FromResult(Json(response.Status, response.Body)); + } + + return Task.FromResult(pageToken switch + { + "start+opaque/position=" => Json(HttpStatusCode.OK, """{"nextPageToken":"next+opaque/position=","changes":[]}"""), + "next+opaque/position=" => Json(HttpStatusCode.OK, """ + {"newStartPageToken":"terminal+opaque/position=","changes":[ + {"changeType":"file","fileId":"paper_123","file":{"id":"paper_123","version":"8"}}, + {"changeType":"file","fileId":"removed_1","removed":true}, + {"changeType":"file","fileId":"trashed_1","file":{"id":"trashed_1","version":"9","trashed":true}}, + {"changeType":"drive","removed":true}]} + """), + _ => throw new InvalidOperationException("Unexpected Google Drive position.") + }); + } + + private static HttpResponseMessage Json(HttpStatusCode status, string body) => + new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + } +} diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs new file mode 100644 index 00000000..4c738339 --- /dev/null +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ManagedCode.Storage.OneDrive; +using ManagedCode.Storage.OneDrive.Clients; +using ManagedCode.Storage.OneDrive.Options; +using Shouldly; +using Xunit; + +namespace ManagedCode.Storage.Tests.Storages.CloudDrive; + +public partial class GraphOneDriveClientTests +{ + private const string ChildrenPath = "/v1.0/drives/drive/items/root/children"; + private const string ChildrenPageTwo = "https://graph.microsoft.com" + ChildrenPath + "?%24skiptoken=empty"; + private const string ChildrenPageThree = "https://graph.microsoft.com" + ChildrenPath + "?%24skiptoken=last"; + + [Fact] + public async Task OneDriveListKeepsItsFileProjectionAcrossEveryNativeChildPageAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var transport = new ChildrenPagingTransport(); + using var storage = new OneDriveStorage(new OneDriveStorageOptions + { + GraphClient = CreateGraphClient(transport), + DriveId = "drive" + }); + var files = new List(); + await foreach (var item in storage.GetBlobMetadataListAsync(cancellationToken: cancellation)) + { + files.Add(item.FullName); + } + + files.ShouldBe(new[] { "first.txt", "last.txt" }); + transport.ChildrenQueries.ShouldBe(new[] { "", "?%24skiptoken=empty", "?%24skiptoken=last" }); + } + + [Fact] + public async Task ExistingOneDriveFolderOnLaterPageDoesNotRequireAnotherFolderAsync() + { + var transport = new ChildrenPagingTransport(); + var client = new GraphOneDriveClient(CreateGraphClient(transport)); + await client.EnsureRootAsync("drive", "saved", false, TestContext.Current.CancellationToken); + + transport.ChildrenQueries.ShouldBe(new[] { "", "?%24skiptoken=empty", "?%24skiptoken=last" }); + } + + [Theory] + [InlineData("https://other.invalid/v1.0/drives/drive/items/root/children?%24skiptoken=other", 1)] + [InlineData("https://graph.microsoft.com/v1.0/drives/drive/items/other/children?%24skiptoken=other", 1)] + [InlineData(ChildrenPageTwo, 2)] + public async Task OneDriveListNeverFollowsForeignOrRepeatedChildLinksAsync(string next, int expectedRequests) + { + var cancellation = TestContext.Current.CancellationToken; + var transport = new ChildrenPagingTransport { RepeatedOrForeign = next }; + using var storage = new OneDriveStorage(new OneDriveStorageOptions + { + GraphClient = CreateGraphClient(transport), + DriveId = "drive" + }); + var files = new List(); + await Should.ThrowAsync(async () => + { + await foreach (var item in storage.GetBlobMetadataListAsync(cancellationToken: cancellation)) + { + files.Add(item.FullName); + } + }); + + files.ShouldBe(new[] { "first.txt" }); + transport.ChildrenQueries.Count.ShouldBe(expectedRequests); + } + + private sealed class ChildrenPagingTransport : HttpMessageHandler + { + public string? RepeatedOrForeign { get; set; } + public List ChildrenQueries { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + request.Method.ShouldBe(HttpMethod.Get); + var target = request.RequestUri.ShouldNotBeNull(); + target.Host.ShouldBe("graph.microsoft.com"); + if (target.AbsolutePath == "/v1.0/drives/drive/root") + { + return Task.FromResult(Json("""{"id":"root","folder":{}}""")); + } + + target.AbsolutePath.ShouldBe(ChildrenPath); + ChildrenQueries.Add(target.Query); + return Task.FromResult(target.Query switch + { + "" => Json($$$""" + {"value":[{"id":"one","name":"first.txt","file":{"mimeType":"text/plain"}}], + "@odata.nextLink":"{{{RepeatedOrForeign ?? ChildrenPageTwo}}}"} + """), + "?%24skiptoken=empty" => Json($$$"""{"value":[],"@odata.nextLink":"{{{RepeatedOrForeign ?? ChildrenPageThree}}}"}"""), + "?%24skiptoken=last" => Json(""" + {"value":[{"id":"last","name":"last.txt","file":{"mimeType":"text/plain"}}, + {"id":"existing","name":"saved","folder":{}}]} + """), + _ => throw new InvalidOperationException("Unexpected Microsoft Graph folder continuation.") + }); + } + + private static HttpResponseMessage Json(string body) => + new(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + } +} diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs new file mode 100644 index 00000000..b7300b41 --- /dev/null +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ManagedCode.Storage.OneDrive; +using ManagedCode.Storage.OneDrive.Clients; +using ManagedCode.Storage.OneDrive.Options; +using Shouldly; +using Xunit; + +namespace ManagedCode.Storage.Tests.Storages.CloudDrive; + +public partial class GraphOneDriveClientTests +{ + private const string GraphBase = "https://graph.microsoft.com/v1.0"; + private const string DeltaRoot = "/drives/drive/items/root/delta"; + private const string FullEnumerationPosition = GraphBase + DeltaRoot + "()"; + private const string LatestPosition = GraphBase + "/me/drive/root/delta?token=issued%2Bcheckpoint"; + private const string EmptyContinuation = GraphBase + "/me/drive/delta(token=empty-page)"; + private const string TerminalPosition = GraphBase + DeltaRoot + "?token=terminal"; + private const string RestartPosition = GraphBase + "/drives/drive/root/delta?token=restart"; + + [Fact] + public async Task DelegatedDeltaUsesProviderContinuationAndRetainsChangeOrderAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport(); + using var storage = CreateDeltaStorage(transport); + var latest = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); + latest.IsSuccess.ShouldBeTrue(); + latest.Value.Items.ShouldBeEmpty(); + latest.Value.Continuation.ShouldBeNull(); + var checkpoint = latest.Value.Checkpoint.ShouldNotBeNull(); + checkpoint.ShouldBe(new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition)); + + var empty = await storage.ReadDeltaPageAsync(grant, checkpoint, cancellation); + empty.IsSuccess.ShouldBeTrue(); + empty.Value.Items.ShouldBeEmpty(); + empty.Value.Checkpoint.ShouldBeNull(); + var continuation = empty.Value.Continuation.ShouldNotBeNull(); + continuation.ProviderLink.ShouldBe(EmptyContinuation); + + var updates = await storage.ReadDeltaPageAsync(grant, continuation, cancellation); + updates.IsSuccess.ShouldBeTrue(); + updates.Value.Checkpoint.ShouldBe(checkpoint with { ProviderLink = TerminalPosition }); + updates.Value.Continuation.ShouldBeNull(); + updates.Value.Reset.ShouldBeNull(); + updates.Value.Items.ShouldBe(new[] + { + new OneDriveItemChange("native-item", "first", false), + new OneDriveItemChange("native-item", "second", false), + new OneDriveItemChange("native-deleted", null, true) + }); + transport.DeltaRequests.Count.ShouldBe(3); + transport.DeltaRequests[1].ShouldBe(LatestPosition); + transport.DeltaRequests[2].ShouldBe(EmptyContinuation); + } + + [Fact] + public async Task DelegatedDeltaRejectsWrongGrantDriveRootAndForeignReadBeforeForwardingAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport(); + using var storage = CreateDeltaStorage(transport); + var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); + + var wrongGrant = await storage.ReadDeltaPageAsync(Guid.NewGuid(), cursor, cancellation); + wrongGrant.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.ScopeReads.ShouldBe(0); + foreach (var untrusted in new[] + { + cursor with { RootItemId = "other" }, + cursor with { ProviderLink = GraphBase + "/drives/another/root/delta?token=issued" }, + cursor with { ProviderLink = "https://other.invalid/v1.0/me/drive/root/delta?token=issued" }, + cursor with { ProviderLink = GraphBase + "/drives/drive/items/private/content?token=issued" } + }) + { + var denied = await storage.ReadDeltaPageAsync(grant, untrusted, cancellation); + denied.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + } + + transport.CurrentDrive = "another"; + var oldAccount = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + oldAccount.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.DeltaRequests.ShouldBeEmpty(); + } + + [Theory] + [InlineData(RestartPosition, true)] + [InlineData("https://other.invalid/v1.0/me/drive/root/delta?token=restart", false)] + [InlineData(null, false)] + public async Task ExpiredOneDrivePositionRequiresExplicitResynchronizationAsync(string? providerLocation, bool forwardsRestart) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport { Expired = true, RestartLocation = providerLocation }; + using var storage = CreateDeltaStorage(transport); + var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); + + var expired = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + expired.IsSuccess.ShouldBeTrue(); + expired.Value.Items.ShouldBeEmpty(); + expired.Value.Continuation.ShouldBeNull(); + expired.Value.Checkpoint.ShouldBeNull(); + var restart = expired.Value.Reset.ShouldNotBeNull().Restart; + transport.DeltaRequests.ShouldBe(new[] { LatestPosition }); + if (forwardsRestart) + { + restart.ShouldBe(cursor with { ProviderLink = RestartPosition }); + } + else + { + restart.ShouldBeNull(); + } + + var resync = restart is not null + ? await storage.ReadDeltaPageAsync(grant, restart, cancellation) + : await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FullEnumeration, cancellation); + resync.IsSuccess.ShouldBeTrue(); + resync.Value.Items.ShouldBe(new[] { new OneDriveItemChange("current-item", "current", false) }); + resync.Value.Checkpoint.ShouldBe(cursor with { ProviderLink = TerminalPosition }); + transport.DeltaRequests.Count.ShouldBe(2); + transport.DeltaRequests[1].ShouldBe(forwardsRestart ? RestartPosition : FullEnumerationPosition); + } + + [Theory] + [InlineData(HttpStatusCode.Forbidden, null, HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.OK, "https://other.invalid/v1.0/me/drive/root/delta?token=issued", HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.OK, LatestPosition, HttpStatusCode.BadGateway)] + public async Task DeniedOrUnsafeOneDrivePageDoesNotAdvanceThePositionAsync( + HttpStatusCode providerStatus, string? next, HttpStatusCode expectedStatus) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport { ReadStatus = providerStatus, ReadContinuation = next }; + using var storage = CreateDeltaStorage(transport); + var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); + + var denied = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + denied.IsFailed.ShouldBeTrue(); + denied.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)expectedStatus); + transport.ReadStatus = HttpStatusCode.OK; + transport.ReadContinuation = EmptyContinuation; + var retry = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + retry.IsSuccess.ShouldBeTrue(); + retry.Value.Continuation.ShouldNotBeNull().ProviderLink.ShouldBe(EmptyContinuation); + transport.DeltaRequests.ShouldBe(new[] { LatestPosition, LatestPosition }); + } + + private static OneDriveStorage CreateDeltaStorage(DeltaTransport transport) => + new(new OneDriveStorageOptions { GraphClient = CreateGraphClient(transport), DriveId = "drive" }); + + private sealed class DeltaTransport : HttpMessageHandler + { + public List DeltaRequests { get; } = []; + public int ScopeReads { get; private set; } + public string CurrentDrive { get; set; } = "drive"; + public bool Expired { get; set; } + public string? RestartLocation { get; set; } + public HttpStatusCode ReadStatus { get; set; } = HttpStatusCode.OK; + public string? ReadContinuation { get; set; } = EmptyContinuation; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + request.Method.ShouldBe(HttpMethod.Get); + var target = request.RequestUri.ShouldNotBeNull(); + target.Host.ShouldBe("graph.microsoft.com"); + request.Headers.CacheControl.ShouldNotBeNull().NoCache.ShouldBeTrue(); + if (target.AbsolutePath is "/v1.0/me/drive" or "/v1.0/drives/drive/root") + { + ScopeReads++; + Uri.UnescapeDataString(target.Query).ShouldContain("$select=id"); + var id = target.AbsolutePath == "/v1.0/me/drive" ? CurrentDrive : "root"; + return Task.FromResult(Json(HttpStatusCode.OK, $$$"""{"id":"{{{id}}}"}""")); + } + + DeltaRequests.Add(target.OriginalString); + return Task.FromResult(AnswerDelta(target)); + } + + private HttpResponseMessage AnswerDelta(Uri target) + { + if (Uri.UnescapeDataString(target.AbsolutePath).StartsWith("/v1.0" + DeltaRoot + "(token=", StringComparison.Ordinal)) + { + target.AbsolutePath.ShouldContain("latest"); + return Json(HttpStatusCode.OK, $$$"""{"value":[],"@odata.deltaLink":"{{{LatestPosition}}}"}"""); + } + + return target.OriginalString switch + { + LatestPosition => AnswerCheckpoint(), + EmptyContinuation => Json(HttpStatusCode.OK, $$$""" + {"value":[{"id":"native-item","eTag":"first","file":{}}, + {"id":"native-item","eTag":"second","file":{}}, + {"id":"native-deleted","deleted":{}}, + {"id":"other-drive-item","parentReference":{"driveId":"elsewhere"},"file":{}}], + "@odata.deltaLink":"{{{TerminalPosition}}}"} + """), + RestartPosition or FullEnumerationPosition => Json(HttpStatusCode.OK, $$$""" + {"value":[{"id":"current-item","eTag":"current","file":{}}],"@odata.deltaLink":"{{{TerminalPosition}}}"} + """), + _ => throw new InvalidOperationException("Unexpected Microsoft Graph delta position.") + }; + } + + private HttpResponseMessage AnswerCheckpoint() + { + if (Expired) + { + var response = Json(HttpStatusCode.Gone, """{"error":{"code":"resyncChangesApplyDifferences","message":"Expired"}}"""); + if (RestartLocation is not null) + { + response.Headers.Location = new Uri(RestartLocation); + } + return response; + } + + return ReadStatus == HttpStatusCode.OK + ? Json(ReadStatus, $$$"""{"value":[],"@odata.nextLink":"{{{ReadContinuation}}}"}""") + : Json(ReadStatus, """{"error":{"code":"accessDenied","message":"Grant withdrawn"}}"""); + } + + private static HttpResponseMessage Json(HttpStatusCode status, string body) => + new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + } +} diff --git a/docs/ADR/0008-cloud-drive-clients-and-auth.md b/docs/ADR/0008-cloud-drive-clients-and-auth.md index 51944961..fa057ff3 100644 --- a/docs/ADR/0008-cloud-drive-clients-and-auth.md +++ b/docs/ADR/0008-cloud-drive-clients-and-auth.md @@ -78,6 +78,7 @@ flowchart LR - Minimal consumer boilerplate (options can build clients when possible). - Clean test seams: fake HTTP through official SDK plumbing without mocking SDK methods. - Providers can evolve without exposing vendor SDK types everywhere. +- The [Google Drive and OneDrive change feeds](../Features/cloud-drive-change-feeds.md) use the same authorized SDK clients and return provider-specific item identities and positions without putting vendor models in Core. ### Negative diff --git a/docs/Architecture.md b/docs/Architecture.md index 9a0e6959..b3c85f8e 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -77,6 +77,11 @@ OneDrive initial revision capture uses the same bounded content snapshot to comp SHA-256 between two checks of the selected Graph item and ETag. The verified read for a revision with an independently known digest remains available. +The Google Drive and OneDrive providers also own their SDK change feeds and opaque +provider positions. The application owns the current OAuth grant and the durable +point at which it has finished applying an entire page. See +[Cloud drive change feeds](Features/cloud-drive-change-feeds.md). + ## Cartograph artifact provider `ManagedCode.Storage.Cartograph` is a separate provider for reading catalogued files diff --git a/docs/Features/cloud-drive-change-feeds.md b/docs/Features/cloud-drive-change-feeds.md new file mode 100644 index 00000000..403f3ab8 --- /dev/null +++ b/docs/Features/cloud-drive-change-feeds.md @@ -0,0 +1,33 @@ +# Cloud drive change feeds + +Use the provider-specific storage interface with the current authorized SDK client. Pass the server-owned identifier of the exact OAuth grant used by that client. Resolve the grant and the delegated credential before each call. Retain the returned position alongside the same member, provider and connection. Treat the position as private server data and keep the provider token or link opaque. + +## Google Drive + +Use `IGoogleDriveStorage.GetChangesCursorAsync` to begin watching new changes in the configured account root, then call `ReadChangesPageAsync` with that grant. Storage checks the native Google account permission ID on each call. `SupportsAllDrives` also governs whether this account feed includes Shared Drive items available to the grant. The position is bound to that setting. An application can use the existing `drive.file` consent for the files that account granted to that application. + +Continue with `Continuation` even when the file list is empty. Persist the terminal `Checkpoint` after applying the page's changes. Google documents the tokens as nonexpiring. A rejected or malformed position returns a failure and leaves the application in control of reconciliation. A Google removal or trashed item is unavailable through this observation. A removal can mean that the grant lost access. Match the exact retained file ID and verify current access before using it again. [Google Drive start position](https://developers.google.com/workspace/drive/api/reference/rest/v3/changes/getStartPageToken), [Google Drive changes](https://developers.google.com/workspace/drive/api/reference/rest/v3/changes/list), [Google Drive account identity](https://developers.google.com/workspace/drive/api/reference/rest/v3/about/get). + +## OneDrive + +Use `IOneDriveStorage.StartDeltaAsync` under the current delegated `Files.Read` connection, at its default drive root. Choose `FromNow` to obtain the provider's current checkpoint or `FullEnumeration` to obtain its current hierarchy page by page. Subsequent `ReadDeltaPageAsync` requests check the current grant and resolve the same drive and root before following a native Graph link. Configured subfolders and other drives require their own feed contract. + +Follow `Continuation` through the end, including from an empty page. Preserve order and use the last observed occurrence of an item when reconciling duplicate native IDs. `Checkpoint` marks the next round. A Graph `410 Gone` returns `Reset`: explicitly reconcile via its scoped `Restart` cursor when present, or start a full enumeration. Complete the reconciliation before replacing the old checkpoint. Authorization failures return a failed result without a new position. [Microsoft Graph drive delta](https://learn.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0). + +Ordinary OneDrive listings follow each native child-page link within the same folder and retain their existing file metadata projection. [Microsoft Graph list children](https://learn.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0). + +## Applying a change page + +```mermaid +sequenceDiagram + participant Consumer + participant Storage + participant Provider + Consumer->>Storage: Read one page under the current grant + Storage->>Provider: Verify account and read the scoped position + Provider-->>Storage: Item changes and next position + Storage-->>Consumer: Changes, continuation, checkpoint, or reset + Consumer->>Consumer: Reconcile exact items and retain the position +``` + +A change is an observation of an item ID and optional provider revision. Apply it only to an exact source the caller can currently use. Recheck the item, revision and content rights through `ReadDocumentAsync`, `CaptureItemRevisionAsync` or `ReadItemRevisionAsync` before indexing or presenting content. Preserve existing independent access checks when presenting a citation. Apply a page and its position durably in the caller's existing owner so retrying the same page cannot duplicate effects. Keep previous data subject to its existing access and retention rules while reconciling a reset. diff --git a/docs/Features/index.md b/docs/Features/index.md index aa6e2114..4d78c3f0 100644 --- a/docs/Features/index.md +++ b/docs/Features/index.md @@ -51,5 +51,6 @@ flowchart LR - [SFTP](provider-sftp.md) - [OneDrive (Microsoft Graph)](provider-onedrive.md) - [Google Drive](provider-googledrive.md) +- [Cloud drive change feeds](cloud-drive-change-feeds.md) - [Dropbox](provider-dropbox.md) - [CloudKit (iCloud app data)](provider-cloudkit.md) From d4f798beb5a3f90f59673e082895c0634ce52bc6 Mon Sep 17 00:00:00 2001 From: ksemenenko Date: Fri, 4 Dec 2026 08:59:48 +0100 Subject: [PATCH 2/2] Cover incomplete Google Drive and OneDrive responses --- .../Clients/GraphOneDriveClient.cs | 12 +- .../CloudDrive/GoogleDriveChangesTests.cs | 93 +++++++++++++- .../GraphOneDriveChildrenPagingTests.cs | 52 ++++++++ .../GraphOneDriveDeltaRejectionTests.cs | 119 ++++++++++++++++++ .../CloudDrive/GraphOneDriveDeltaTests.cs | 54 +++++--- docs/Features/cloud-drive-change-feeds.md | 2 +- 6 files changed, 309 insertions(+), 23 deletions(-) create mode 100644 Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaRejectionTests.cs diff --git a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs index cb4ad469..8eb0e075 100644 --- a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs +++ b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.cs @@ -215,9 +215,14 @@ private static async IAsyncEnumerable EnumerateChildrenAsync( var requestUri = builder.ToGetRequestInformation().URI; var page = await builder.GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false); var seen = new HashSet(StringComparer.Ordinal) { requestUri.AbsoluteUri }; - while (page is not null) + while (true) { - foreach (var child in page.Value ?? []) + if (page?.Value is not { } items) + { + throw new InvalidDataException("Microsoft Graph did not return a folder children collection."); + } + + foreach (var child in items) { cancellationToken.ThrowIfCancellationRequested(); if (child is not null) @@ -238,8 +243,7 @@ private static async IAsyncEnumerable EnumerateChildrenAsync( throw new InvalidDataException("Microsoft Graph repeated a folder continuation."); } - page = await builder.WithUrl(next).GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false) - ?? throw new InvalidDataException("Microsoft Graph returned no folder continuation page."); + page = await builder.WithUrl(next).GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs index b759600f..f23ea31a 100644 --- a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GoogleDriveChangesTests.cs @@ -75,8 +75,12 @@ public async Task ChangedGrantAndProviderAccountCannotReadRetainedGooglePosition [InlineData(HttpStatusCode.Forbidden, "", HttpStatusCode.NotFound)] [InlineData(HttpStatusCode.BadRequest, "", HttpStatusCode.BadRequest)] [InlineData(HttpStatusCode.OK, """{"nextPageToken":"a","newStartPageToken":"b","changes":[]}""", HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.OK, """{"nextPageToken":"start+opaque/position=","changes":[]}""", HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.OK, """{"changes":[]}""", HttpStatusCode.BadGateway)] [InlineData(HttpStatusCode.OK, """{"newStartPageToken":"b","changes":[{"changeType":"file","fileId":"one","file":{"id":"another","version":"2"}}]}""", HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.OK, """{"newStartPageToken":"b","changes":[{"changeType":"file","fileId":"one","file":{"id":"one"}}]}""", + HttpStatusCode.BadGateway)] public async Task DeniedOrInvalidGooglePageDoesNotAdvanceThePositionAsync( HttpStatusCode providerStatus, string body, HttpStatusCode expectedStatus) { @@ -99,9 +103,91 @@ public async Task DeniedOrInvalidGooglePageDoesNotAdvanceThePositionAsync( transport.FeedTokens.ShouldBe(new string?[] { null, "start+opaque/position=", "start+opaque/position=" }); } + [Fact] + public async Task InvalidLocalPositionsAreRejectedBeforeGoogleReadsAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport(); + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + + var missingGrant = await storage.GetChangesCursorAsync(Guid.Empty, cancellation); + missingGrant.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadRequest); + transport.AboutReads.ShouldBe(0); + transport.FeedTokens.ShouldBeEmpty(); + + var opened = await storage.GetChangesCursorAsync(grant, cancellation); + opened.IsSuccess.ShouldBeTrue(); + var cursor = opened.Value; + var malformedToken = await storage.ReadChangesPageAsync(grant, cursor with { PageToken = "" }, 50, cancellation); + malformedToken.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadRequest); + var invalidPageSize = await storage.ReadChangesPageAsync(grant, cursor, 0, cancellation); + invalidPageSize.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadRequest); + var wrongDriveVisibility = await storage.ReadChangesPageAsync(grant, + cursor with { IncludesSharedDriveItems = false }, 50, cancellation); + wrongDriveVisibility.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.AboutReads.ShouldBe(1); + transport.FeedTokens.ShouldBe(new string?[] { null }); + + var accepted = await storage.ReadChangesPageAsync(grant, cursor, 50, cancellation); + accepted.IsSuccess.ShouldBeTrue(); + accepted.Value.Continuation.ShouldNotBeNull().PageToken.ShouldBe("next+opaque/position="); + transport.FeedTokens.ShouldBe(new string?[] { null, "start+opaque/position=" }); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task IncompleteGoogleStartEvidenceDoesNotIssueAPositionAsync(bool accountMissing) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport + { + AccountPermissionId = accountMissing ? "" : "authorized-person", + StartBody = "{}" + }; + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + + var rejected = await storage.GetChangesCursorAsync(grant, cancellation); + rejected.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadGateway); + transport.AboutReads.ShouldBe(1); + transport.FeedTokens.Count.ShouldBe(accountMissing ? 0 : 1); + + transport.AccountPermissionId = "authorized-person"; + transport.StartBody = null; + var recovered = await storage.GetChangesCursorAsync(grant, cancellation); + recovered.IsSuccess.ShouldBeTrue(); + recovered.Value.ShouldBe(new GoogleDriveChangesCursor(grant, "authorized-person", true, "start+opaque/position=")); + } + + [Fact] + public async Task InterruptedGoogleAccountReadLeavesTheCheckpointReusableAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new ChangesTransport(); + using var storage = GoogleDriveStorage.FromTransport(transport, supportsAllDrives: true); + var opened = await storage.GetChangesCursorAsync(grant, cancellation); + opened.IsSuccess.ShouldBeTrue(); + + transport.AccountReadInterrupted = true; + var denied = await storage.ReadChangesPageAsync(grant, opened.Value, 50, cancellation); + denied.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadGateway); + transport.FeedTokens.ShouldBe(new string?[] { null }); + + transport.AccountReadInterrupted = false; + var retried = await storage.ReadChangesPageAsync(grant, opened.Value, 50, cancellation); + retried.IsSuccess.ShouldBeTrue(); + retried.Value.Continuation.ShouldNotBeNull().PageToken.ShouldBe("next+opaque/position="); + transport.FeedTokens.ShouldBe(new string?[] { null, "start+opaque/position=" }); + } + private sealed class ChangesTransport : HttpMessageHandler { public string AccountPermissionId { get; set; } = "authorized-person"; + public string? StartBody { get; set; } + public bool AccountReadInterrupted { get; set; } public List FeedTokens { get; } = []; public int AboutReads { get; private set; } public (HttpStatusCode Status, string Body)? PageResponse { get; set; } @@ -117,6 +203,10 @@ protected override Task SendAsync(HttpRequestMessage reques { Uri.UnescapeDataString(target.Query).ShouldContain("fields=user(permissionId)"); AboutReads++; + if (AccountReadInterrupted) + { + throw new HttpRequestException("The account transport was interrupted."); + } return Task.FromResult(Json(HttpStatusCode.OK, $$$"""{"user":{"permissionId":"{{{AccountPermissionId}}}"}}""")); } @@ -125,7 +215,8 @@ protected override Task SendAsync(HttpRequestMessage reques if (target.AbsolutePath == "/drive/v3/changes/startPageToken") { FeedTokens.Add(null); - return Task.FromResult(Json(HttpStatusCode.OK, """{"startPageToken":"start+opaque/position="}""")); + return Task.FromResult(Json(HttpStatusCode.OK, + StartBody ?? """{"startPageToken":"start+opaque/position="}""")); } target.AbsolutePath.ShouldBe("/drive/v3/changes"); diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs index 4c738339..e5faa889 100644 --- a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveChildrenPagingTests.cs @@ -51,6 +51,12 @@ public async Task ExistingOneDriveFolderOnLaterPageDoesNotRequireAnotherFolderAs } [Theory] + [InlineData("", 1)] + [InlineData("/v1.0/drives/drive/items/root/children?%24skiptoken=relative", 1)] + [InlineData("http://graph.microsoft.com/v1.0/drives/drive/items/root/children?%24skiptoken=insecure", 1)] + [InlineData("https://graph.microsoft.com:444/v1.0/drives/drive/items/root/children?%24skiptoken=port", 1)] + [InlineData("https://account@graph.microsoft.com/v1.0/drives/drive/items/root/children?%24skiptoken=identity", 1)] + [InlineData("https://graph.microsoft.com/v1.0/drives/drive/items/root/children?%24skiptoken=fragment#part", 1)] [InlineData("https://other.invalid/v1.0/drives/drive/items/root/children?%24skiptoken=other", 1)] [InlineData("https://graph.microsoft.com/v1.0/drives/drive/items/other/children?%24skiptoken=other", 1)] [InlineData(ChildrenPageTwo, 2)] @@ -76,9 +82,47 @@ await Should.ThrowAsync(async () => transport.ChildrenQueries.Count.ShouldBe(expectedRequests); } + [Theory] + [InlineData("", true)] + [InlineData("", false)] + [InlineData("?%24skiptoken=empty", true)] + [InlineData("?%24skiptoken=empty", false)] + public async Task OneDriveListFailsWhenAPageHasNoChildrenCollectionAsync(string invalidQuery, bool omitBody) + { + var cancellation = TestContext.Current.CancellationToken; + var transport = new ChildrenPagingTransport { InvalidPageQuery = invalidQuery, OmitInvalidPageBody = omitBody }; + using var storage = new OneDriveStorage(new OneDriveStorageOptions + { + GraphClient = CreateGraphClient(transport), + DriveId = "drive" + }); + var files = new List(); + var missing = await Should.ThrowAsync(ReadFilesAsync); + missing.Message.ShouldBe("Microsoft Graph did not return a folder children collection."); + files.ShouldBe(invalidQuery.Length == 0 ? Array.Empty() : new[] { "first.txt" }); + transport.ChildrenQueries.ShouldBe(invalidQuery.Length == 0 ? new[] { "" } : new[] { "", invalidQuery }); + + transport.InvalidPageQuery = null; + transport.ChildrenQueries.Clear(); + files.Clear(); + await ReadFilesAsync(); + files.ShouldBe(new[] { "first.txt", "last.txt" }); + transport.ChildrenQueries.ShouldBe(new[] { "", "?%24skiptoken=empty", "?%24skiptoken=last" }); + + async Task ReadFilesAsync() + { + await foreach (var item in storage.GetBlobMetadataListAsync(cancellationToken: cancellation)) + { + files.Add(item.FullName); + } + } + } + private sealed class ChildrenPagingTransport : HttpMessageHandler { public string? RepeatedOrForeign { get; set; } + public string? InvalidPageQuery { get; set; } + public bool OmitInvalidPageBody { get; set; } public List ChildrenQueries { get; } = []; protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) @@ -94,6 +138,14 @@ protected override Task SendAsync(HttpRequestMessage reques target.AbsolutePath.ShouldBe(ChildrenPath); ChildrenQueries.Add(target.Query); + if (target.Query == InvalidPageQuery) + { + var next = target.Query.Length == 0 ? ChildrenPageTwo : ChildrenPageThree; + return Task.FromResult(OmitInvalidPageBody + ? new HttpResponseMessage(HttpStatusCode.NoContent) + : Json($$$"""{"@odata.nextLink":"{{{next}}}"}""")); + } + return Task.FromResult(target.Query switch { "" => Json($$$""" diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaRejectionTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaRejectionTests.cs new file mode 100644 index 00000000..dad4ca04 --- /dev/null +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaRejectionTests.cs @@ -0,0 +1,119 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using ManagedCode.Storage.OneDrive; +using Shouldly; +using Xunit; + +namespace ManagedCode.Storage.Tests.Storages.CloudDrive; + +public partial class GraphOneDriveClientTests +{ + [Fact] + public async Task OneDriveDeltaRequiresTheRootAndValidGrantAndNativeIdentifiersAsync() + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); + var transport = new DeltaTransport(); + using var root = CreateDeltaStorage(transport); + using var folder = CreateDeltaStorage(transport, "/scoped-folder"); + + var start = await root.StartDeltaAsync(Guid.Empty, OneDriveDeltaStart.FromNow, cancellation); + var unknownMode = await root.StartDeltaAsync(grant, (OneDriveDeltaStart)int.MaxValue, cancellation); + var folderStart = await folder.StartDeltaAsync(grant, OneDriveDeltaStart.FullEnumeration, cancellation); + var invalidGrant = await root.ReadDeltaPageAsync(Guid.Empty, cursor, cancellation); + var invalidDrive = await root.ReadDeltaPageAsync(grant, cursor with { DriveId = "drive/other" }, cancellation); + var invalidRoot = await root.ReadDeltaPageAsync(grant, cursor with { RootItemId = ".." }, cancellation); + var folderRead = await folder.ReadDeltaPageAsync(grant, cursor, cancellation); + foreach (var rejected in new[] { start, unknownMode, folderStart, invalidGrant, invalidDrive, invalidRoot, folderRead }) + { + rejected.IsFailed.ShouldBeTrue(); + rejected.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadRequest); + } + + transport.ScopeReads.ShouldBe(0); + transport.DeltaRequests.ShouldBeEmpty(); + var accepted = await root.ReadDeltaPageAsync(grant, cursor, cancellation); + accepted.IsSuccess.ShouldBeTrue(); + accepted.Value.Continuation.ShouldNotBeNull().ProviderLink.ShouldBe(EmptyContinuation); + transport.DeltaRequests.ShouldBe(new[] { LatestPosition }); + } + + [Theory] + [InlineData(null, "root", 1)] + [InlineData("other-drive", "root", 1)] + [InlineData("drive", null, 2)] + public async Task OneDriveDeltaCannotStartWithoutTheCurrentDriveAndRootAsync(string? drive, string? root, int expectedScopeReads) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport { CurrentDrive = drive, CurrentRoot = root }; + using var storage = CreateDeltaStorage(transport); + + var missing = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); + missing.IsFailed.ShouldBeTrue(); + missing.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.NotFound); + transport.ScopeReads.ShouldBe(expectedScopeReads); + transport.DeltaRequests.ShouldBeEmpty(); + + transport.CurrentDrive = "drive"; + transport.CurrentRoot = "root"; + var restored = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); + restored.IsSuccess.ShouldBeTrue(); + restored.Value.Checkpoint.ShouldBe(new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition)); + transport.DeltaRequests.Count.ShouldBe(1); + } + + [Theory] + [InlineData(null)] + [InlineData("""{"value":[]}""")] + [InlineData($$$"""{"@odata.deltaLink":"{{{LatestPosition}}}"}""")] + [InlineData($$$"""{"value":[{"id":"old"}],"@odata.deltaLink":"{{{LatestPosition}}}"}""")] + [InlineData($$$"""{"value":[],"@odata.nextLink":"{{{EmptyContinuation}}}","@odata.deltaLink":"{{{LatestPosition}}}"}""")] + public async Task OneDriveDeltaCannotStartFromAnIncompleteLatestCheckpointAsync(string? response) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var transport = new DeltaTransport { LatestResponse = response, OmitLatestPage = response is null }; + using var storage = CreateDeltaStorage(transport); + + var rejected = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); + rejected.IsFailed.ShouldBeTrue(); + rejected.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadGateway); + transport.DeltaRequests.Count.ShouldBe(1); + var requested = transport.DeltaRequests[0]; + + transport.LatestResponse = null; + transport.OmitLatestPage = false; + var retry = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); + retry.IsSuccess.ShouldBeTrue(); + retry.Value.Checkpoint.ShouldBe(new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition)); + transport.DeltaRequests.ShouldBe(new[] { requested, requested }); + } + + [Theory] + [InlineData($$$"""{"value":[{"id":"first"},{"file":{}}],"@odata.deltaLink":"{{{TerminalPosition}}}"}""")] + [InlineData($$$"""{"@odata.deltaLink":"{{{TerminalPosition}}}"}""")] + [InlineData("""{"value":[],"@odata.deltaLink":"https://other.invalid/v1.0/me/drive/root/delta?token=wrong"}""")] + [InlineData($$$"""{"value":[],"@odata.nextLink":"{{{EmptyContinuation}}}","@odata.deltaLink":"{{{TerminalPosition}}}"}""")] + public async Task OneDriveDeltaRejectsAnIncompletePageBeforePublishingChangesAsync(string response) + { + var cancellation = TestContext.Current.CancellationToken; + var grant = Guid.NewGuid(); + var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); + var transport = new DeltaTransport { CheckpointResponse = response }; + using var storage = CreateDeltaStorage(transport); + + var rejected = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + rejected.IsFailed.ShouldBeTrue(); + rejected.Problem.ShouldNotBeNull().StatusCode.ShouldBe((int)HttpStatusCode.BadGateway); + + transport.CheckpointResponse = $$$"""{"value":[{"id":"first"}],"@odata.deltaLink":"{{{TerminalPosition}}}"}"""; + var retry = await storage.ReadDeltaPageAsync(grant, cursor, cancellation); + retry.IsSuccess.ShouldBeTrue(); + retry.Value.Items.ShouldBe(new[] { new OneDriveItemChange("first", null, false) }); + retry.Value.Checkpoint.ShouldBe(cursor with { ProviderLink = TerminalPosition }); + transport.DeltaRequests.ShouldBe(new[] { LatestPosition, LatestPosition }); + } +} diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs index b7300b41..1f3e683a 100644 --- a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs +++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveDeltaTests.cs @@ -23,13 +23,15 @@ public partial class GraphOneDriveClientTests private const string TerminalPosition = GraphBase + DeltaRoot + "?token=terminal"; private const string RestartPosition = GraphBase + "/drives/drive/root/delta?token=restart"; - [Fact] - public async Task DelegatedDeltaUsesProviderContinuationAndRetainsChangeOrderAsync() + [Theory] + [InlineData("drive")] + [InlineData("me")] + public async Task DelegatedDeltaUsesProviderContinuationAndRetainsChangeOrderAsync(string driveId) { var cancellation = TestContext.Current.CancellationToken; var grant = Guid.NewGuid(); var transport = new DeltaTransport(); - using var storage = CreateDeltaStorage(transport); + using var storage = CreateDeltaStorage(transport, driveId: driveId); var latest = await storage.StartDeltaAsync(grant, OneDriveDeltaStart.FromNow, cancellation); latest.IsSuccess.ShouldBeTrue(); latest.Value.Items.ShouldBeEmpty(); @@ -91,14 +93,16 @@ public async Task DelegatedDeltaRejectsWrongGrantDriveRootAndForeignReadBeforeFo } [Theory] - [InlineData(RestartPosition, true)] - [InlineData("https://other.invalid/v1.0/me/drive/root/delta?token=restart", false)] - [InlineData(null, false)] - public async Task ExpiredOneDrivePositionRequiresExplicitResynchronizationAsync(string? providerLocation, bool forwardsRestart) + [InlineData(RestartPosition, false, true)] + [InlineData("https://other.invalid/v1.0/me/drive/root/delta?token=restart", false, false)] + [InlineData(LatestPosition, false, false)] + [InlineData(RestartPosition, true, false)] + [InlineData(null, false, false)] + public async Task ExpiredOneDrivePositionRequiresExplicitResynchronizationAsync(string? providerLocation, bool repeatedLocation, bool forwardsRestart) { var cancellation = TestContext.Current.CancellationToken; var grant = Guid.NewGuid(); - var transport = new DeltaTransport { Expired = true, RestartLocation = providerLocation }; + var transport = new DeltaTransport { Expired = true, RestartLocation = providerLocation, RepeatedRestartLocation = repeatedLocation }; using var storage = CreateDeltaStorage(transport); var cursor = new OneDriveDeltaCursor(grant, "drive", "root", LatestPosition); @@ -152,16 +156,21 @@ public async Task DeniedOrUnsafeOneDrivePageDoesNotAdvanceThePositionAsync( transport.DeltaRequests.ShouldBe(new[] { LatestPosition, LatestPosition }); } - private static OneDriveStorage CreateDeltaStorage(DeltaTransport transport) => - new(new OneDriveStorageOptions { GraphClient = CreateGraphClient(transport), DriveId = "drive" }); + private static OneDriveStorage CreateDeltaStorage(DeltaTransport transport, string rootPath = "/", string driveId = "drive") => + new(new OneDriveStorageOptions { GraphClient = CreateGraphClient(transport), DriveId = driveId, RootPath = rootPath }); private sealed class DeltaTransport : HttpMessageHandler { public List DeltaRequests { get; } = []; public int ScopeReads { get; private set; } - public string CurrentDrive { get; set; } = "drive"; + public string? CurrentDrive { get; set; } = "drive"; + public string? CurrentRoot { get; set; } = "root"; public bool Expired { get; set; } public string? RestartLocation { get; set; } + public bool RepeatedRestartLocation { get; set; } + public bool OmitLatestPage { get; set; } + public string? LatestResponse { get; set; } + public string? CheckpointResponse { get; set; } public HttpStatusCode ReadStatus { get; set; } = HttpStatusCode.OK; public string? ReadContinuation { get; set; } = EmptyContinuation; @@ -176,8 +185,9 @@ protected override Task SendAsync(HttpRequestMessage reques { ScopeReads++; Uri.UnescapeDataString(target.Query).ShouldContain("$select=id"); - var id = target.AbsolutePath == "/v1.0/me/drive" ? CurrentDrive : "root"; - return Task.FromResult(Json(HttpStatusCode.OK, $$$"""{"id":"{{{id}}}"}""")); + var id = target.AbsolutePath == "/v1.0/me/drive" ? CurrentDrive : CurrentRoot; + var body = id is null ? "{}" : $$$"""{"id":"{{{id}}}"}"""; + return Task.FromResult(Json(HttpStatusCode.OK, body)); } DeltaRequests.Add(target.OriginalString); @@ -189,7 +199,9 @@ private HttpResponseMessage AnswerDelta(Uri target) if (Uri.UnescapeDataString(target.AbsolutePath).StartsWith("/v1.0" + DeltaRoot + "(token=", StringComparison.Ordinal)) { target.AbsolutePath.ShouldContain("latest"); - return Json(HttpStatusCode.OK, $$$"""{"value":[],"@odata.deltaLink":"{{{LatestPosition}}}"}"""); + return LatestResponse is null && OmitLatestPage + ? new HttpResponseMessage(HttpStatusCode.NoContent) + : Json(HttpStatusCode.OK, LatestResponse ?? $$$"""{"value":[],"@odata.deltaLink":"{{{LatestPosition}}}"}"""); } return target.OriginalString switch @@ -199,6 +211,7 @@ private HttpResponseMessage AnswerDelta(Uri target) {"value":[{"id":"native-item","eTag":"first","file":{}}, {"id":"native-item","eTag":"second","file":{}}, {"id":"native-deleted","deleted":{}}, + {"id":"shared-placeholder","remoteItem":{"id":"foreign-item"},"file":{}}, {"id":"other-drive-item","parentReference":{"driveId":"elsewhere"},"file":{}}], "@odata.deltaLink":"{{{TerminalPosition}}}"} """), @@ -214,15 +227,22 @@ private HttpResponseMessage AnswerCheckpoint() if (Expired) { var response = Json(HttpStatusCode.Gone, """{"error":{"code":"resyncChangesApplyDifferences","message":"Expired"}}"""); - if (RestartLocation is not null) + if (RestartLocation is { } location) { - response.Headers.Location = new Uri(RestartLocation); + if (RepeatedRestartLocation) + { + response.Headers.TryAddWithoutValidation("Location", new[] { location, location }).ShouldBeTrue(); + } + else + { + response.Headers.Location = new Uri(location); + } } return response; } return ReadStatus == HttpStatusCode.OK - ? Json(ReadStatus, $$$"""{"value":[],"@odata.nextLink":"{{{ReadContinuation}}}"}""") + ? Json(ReadStatus, CheckpointResponse ?? $$$"""{"value":[],"@odata.nextLink":"{{{ReadContinuation}}}"}""") : Json(ReadStatus, """{"error":{"code":"accessDenied","message":"Grant withdrawn"}}"""); } diff --git a/docs/Features/cloud-drive-change-feeds.md b/docs/Features/cloud-drive-change-feeds.md index 403f3ab8..a8297418 100644 --- a/docs/Features/cloud-drive-change-feeds.md +++ b/docs/Features/cloud-drive-change-feeds.md @@ -14,7 +14,7 @@ Use `IOneDriveStorage.StartDeltaAsync` under the current delegated `Files.Read` Follow `Continuation` through the end, including from an empty page. Preserve order and use the last observed occurrence of an item when reconciling duplicate native IDs. `Checkpoint` marks the next round. A Graph `410 Gone` returns `Reset`: explicitly reconcile via its scoped `Restart` cursor when present, or start a full enumeration. Complete the reconciliation before replacing the old checkpoint. Authorization failures return a failed result without a new position. [Microsoft Graph drive delta](https://learn.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0). -Ordinary OneDrive listings follow each native child-page link within the same folder and retain their existing file metadata projection. [Microsoft Graph list children](https://learn.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0). +Ordinary OneDrive listings follow each native child-page link within the same folder and retain their existing file metadata projection. Graph must provide a children collection on the first page and each continuation. An empty collection is valid. An absent collection fails the listing so the caller can retry. [Microsoft Graph list children](https://learn.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0). ## Applying a change page