Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions .github/scripts/verify-published-packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()):
Expand All @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<RepositoryUrl>https://github.com/managedcode/Storage</RepositoryUrl>
<PackageProjectUrl>https://github.com/managedcode/Storage</PackageProjectUrl>
<Product>Managed Code - Storage</Product>
<Version>10.1.17</Version>
<Version>10.1.18</Version>

</PropertyGroup>

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Result<GoogleDriveChangesCursor>> 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<GoogleDriveChangesCursor>.Succeed(new GoogleDriveChangesCursor(
grantId, accountPermissionId, supportsAllDrives, token!));
}

internal async Task<Result<GoogleDriveChangesPage>> ReadChangesPageAsync(
GoogleDriveChangesCursor cursor, int pageSize, CancellationToken cancellationToken)
{
var accountPermissionId = await ReadChangesAccountAsync(cancellationToken).ConfigureAwait(false);
if (!string.Equals(accountPermissionId, cursor.AccountPermissionId, StringComparison.Ordinal))
{
return Result<GoogleDriveChangesPage>.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<GoogleDriveFileChange> files = [];
foreach (var change in page.Changes ?? [])
{
if (string.Equals(change?.ChangeType, DriveChangeType, StringComparison.Ordinal))
{
continue;
}

files.Add(DecodeFileChange(change));
}

return Result<GoogleDriveChangesPage>.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<string> 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.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace ManagedCode.Storage.GoogleDrive;

/// <summary>A provider-issued position for one current grant and Google Drive account.</summary>
/// <remarks>Retain this cursor on the server. Treat the page token as opaque.</remarks>
public sealed record GoogleDriveChangesCursor(
System.Guid GrantId, string AccountPermissionId, bool IncludesSharedDriveItems, string PageToken);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
using System.Collections.Generic;

namespace ManagedCode.Storage.GoogleDrive;

/// <summary>One native change page and its continuation or terminal checkpoint.</summary>
public sealed record GoogleDriveChangesPage(
IReadOnlyList<GoogleDriveFileChange> Files, GoogleDriveChangesCursor? Continuation, GoogleDriveChangesCursor? Checkpoint);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
namespace ManagedCode.Storage.GoogleDrive;

/// <summary>An item identity observed by the current grant. Unavailable includes removal from that grant's view.</summary>
public sealed record GoogleDriveFileChange(string FileId, long? Version, bool Unavailable);
Original file line number Diff line number Diff line change
@@ -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<Result<GoogleDriveChangesCursor>> GetChangesCursorAsync(
Guid currentGrantId, CancellationToken cancellationToken = default)
{
if (currentGrantId == Guid.Empty)
{
return Task.FromResult(Result<GoogleDriveChangesCursor>.FailBadRequest("A current Google Drive grant is required."));
}

return ReadChangesWithSdkAsync(client => client.GetChangesCursorAsync(
currentGrantId, StorageOptions.SupportsAllDrives, cancellationToken), cancellationToken);
}

public Task<Result<GoogleDriveChangesPage>> 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<GoogleDriveChangesPage>.FailBadRequest("The Google Drive change request is invalid."));
}

if (cursor.GrantId != currentGrantId || cursor.IncludesSharedDriveItems != StorageOptions.SupportsAllDrives)
{
return Task.FromResult(Result<GoogleDriveChangesPage>.FailNotFound("The Google Drive change cursor is unavailable."));
}

return ReadChangesWithSdkAsync(
client => client.ReadChangesPageAsync(cursor, pageSize, cancellationToken), cancellationToken);
}

private async Task<Result<T>> ReadChangesWithSdkAsync<T>(
Func<GoogleDriveClient, Task<Result<T>>> read, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (StorageClient is not GoogleDriveClient client || !string.Equals(StorageOptions.RootFolderId, "root", StringComparison.Ordinal))
{
return Result<T>.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<T>(error.HttpStatusCode);
}
catch (HttpRequestException error)
{
return ChangesFailure<T>(error.StatusCode);
}
catch (Exception error) when (error is IOException or InvalidDataException)
{
return ChangesFailure<T>(null);
}
}

private static Result<T> ChangesFailure<T>(HttpStatusCode? status) => status switch
{
HttpStatusCode.BadRequest => Result<T>.FailBadRequest("Google Drive rejected the change cursor."),
HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden or HttpStatusCode.NotFound =>
Result<T>.FailNotFound("The Google Drive change feed is unavailable."),
_ => Result<T>.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)
};
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using ManagedCode.Communication;
Expand All @@ -10,4 +11,11 @@ namespace ManagedCode.Storage.GoogleDrive;
public interface IGoogleDriveStorage : IStorage<IGoogleDriveClient, GoogleDriveStorageOptions>
{
Task<Result<GoogleDriveDocumentSnapshot>> ReadDocumentAsync(GoogleDriveDocumentRead request, CancellationToken cancellationToken = default);

/// <summary>Starts observing new changes in the current account under an already-authorized Google Drive grant.</summary>
Task<Result<GoogleDriveChangesCursor>> GetChangesCursorAsync(Guid currentGrantId, CancellationToken cancellationToken = default);

/// <summary>Reads one scoped account change page using the current grant and an existing provider position.</summary>
Task<Result<GoogleDriveChangesPage>> ReadChangesPageAsync(
Guid currentGrantId, GoogleDriveChangesCursor cursor, int pageSize, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -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!;
}
}
Loading
Loading