Owner review 2, R8, phase 5b (client part), ported onto the final phase 5a.
A Chronos Server with the "projects" capability is now the home of
workspace projects. A server sequence is edited in the workspace like a
local one, not inside the library, and its versions sync with the server
"like git".
- Data: ServerProjectHome is an IProjectHome over ChronosClient.
- These are HomeUnavailableException, so the workspace shows Offline: a
server out of reach, an expired sign-in, a 503 (lease, offline archive,
projects_unreadable), a 409 folder_in_use, and a server without projects.
- 404 sequence/project/version and refused names are ProjectException;
other refusals keep their meaning.
- A deleted project's head is 404 project, so final 5a's HeadAsync NotFound
rule reads it as Gone. The original 5b's IsLiveAsync and
WorkspaceStatus.Gone are dropped. IProjectHome gains rename and delete.
- Data: WorkspaceJobs.CopyFromServer downloads into the workspace, through
the desktop's session, the proxies of one frames version (or the
thumbnails standing in for them), with the aliases of the server's
conversions. It is rebuilt on final 5a's copy handler:
- the copy:frame:fv:folder checkpoint, EnsureSpace (from the server's proxy
sizes), WritingMedia, and the cancelled-copy clean-up;
- the editor's current file is never overwritten;
- each file is hashed as it arrives and checked on disk, four at a time.
It never writes this PC's archive. Originals are still refused until 5c.
- Data: SyncAgent passes on the server's projectChanged events, and after a
lost event stream it reports that changes may have been missed.
- App: SyncHost gives the server home over one session client. The Server
screen offers Open in workspace, disabled with its reason on older
servers, whose sequences keep opening with proxies.
- App: Edit opens or checks out server projects with final 5a's refusals:
unreadable copies, a disabled damaged or newer Main, a refused folder. The
"sequence left the index" refusal now applies only to projects of this
PC's archive.
- App: the picker and the chip follow projectChanged (Server newer, Not on
server). Every state, conflict, delete, remove and failure text uses its
".Server" form when one exists (WorkspaceText.ForHome). That includes 5a's
newer-format conflict, the save conflict, the taken-values toast, Gone and
version-too-large.
- App: a render of a server project first offers to send what is not on the
server, then renders the version the server holds. Offline, Gone, Damaged
and missing media hold the render. Analyses and renders run as server jobs
(ServerJobs, shared with RemoteSequenceSource).
- Pruning keeps final 5a's rule: a version is pruned only after HoldsAsync
reads it back.
- Strings in en and it; ARCHITECTURE, DECISIONS and CHANGELOG.
Tests:
- ServerProjectHome error mapping, using a fake handler.
- Against the in-process server:
- two workspaces on one project: fast-forward, replay and merge, keep mine,
take server, save both, restore;
- the copy job verifying, resuming and following new frames;
- a project deleted on the server (Gone from its head; a push sends
nothing);
- an offline server.
- SyncAgent project events.
- App tests for the host, the project menu and renders of a server home.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
706 lines
41 KiB
C#
706 lines
41 KiB
C#
using System.Net;
|
||
using System.Net.Http.Headers;
|
||
using System.Net.Http.Json;
|
||
using System.Net.WebSockets;
|
||
using System.Runtime.CompilerServices;
|
||
using System.Security.Cryptography;
|
||
using System.Text.Json;
|
||
using System.Text.Json.Serialization.Metadata;
|
||
|
||
namespace Chronos.Protocol.Client;
|
||
|
||
/// <summary>Upload progress for one file.</summary>
|
||
public readonly record struct UploadProgress(long BytesSent, long BytesTotal);
|
||
|
||
/// <summary>
|
||
/// Typed client for Chronos Server API v1 (BRIEF §14.3), used by the desktop client and the uploader.
|
||
/// Thread-safe; one instance per server connection.
|
||
/// </summary>
|
||
public sealed class ChronosClient : IDisposable
|
||
{
|
||
private readonly HttpClient _http;
|
||
private readonly CertificatePinning _pinning;
|
||
|
||
/// <summary>The client made its own handler, so TLS goes through <see cref="_pinning"/> (tests pass theirs).</summary>
|
||
private readonly bool _ownsHandler;
|
||
private string? _token;
|
||
|
||
public ChronosClient(Uri baseAddress, CertificatePinning pinning, string clientName, HttpMessageHandler? handler = null)
|
||
{
|
||
_pinning = pinning;
|
||
_ownsHandler = handler is null;
|
||
ClientName = clientName;
|
||
BaseAddress = baseAddress;
|
||
var socketsHandler = handler ?? new SocketsHttpHandler
|
||
{
|
||
SslOptions = { RemoteCertificateValidationCallback = pinning.Validate },
|
||
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
|
||
ConnectTimeout = TimeSpan.FromSeconds(10),
|
||
AutomaticDecompression = DecompressionMethods.None,
|
||
};
|
||
_http = new HttpClient(socketsHandler) { BaseAddress = baseAddress, Timeout = Timeout.InfiniteTimeSpan };
|
||
_http.DefaultRequestHeaders.Add(ApiVersion.Header, ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||
_http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Chronos", typeof(ChronosClient).Assembly.GetName().Version?.ToString(3) ?? "0"));
|
||
}
|
||
|
||
public Uri BaseAddress { get; }
|
||
public string ClientName { get; }
|
||
public CertificatePinning Pinning => _pinning;
|
||
|
||
/// <summary>Bearer token; set after <see cref="LoginAsync"/> or restored from secure storage.</summary>
|
||
public string? Token
|
||
{
|
||
get => _token;
|
||
set
|
||
{
|
||
_token = value;
|
||
_http.DefaultRequestHeaders.Authorization = value is null ? null : new AuthenticationHeaderValue("Bearer", value);
|
||
}
|
||
}
|
||
|
||
/// <summary>Shared upload rate limit.</summary>
|
||
public BandwidthLimiter Bandwidth { get; } = new();
|
||
|
||
// ---------------- Server ----------------
|
||
|
||
/// <summary>
|
||
/// Reads server info; throws <see cref="UntrustedCertificateException"/> when the TLS certificate of a Chronos Server
|
||
/// needs confirmation, and <see cref="NotChronosServerException"/> when the address answers as something else (owner
|
||
/// review 3): a redirect, a page that is not JSON, JSON of another shape, or an error Chronos did not write. Behind a
|
||
/// certificate that is not trusted yet, the info is first read once more without checking the certificate and without
|
||
/// credentials: only an answer that is Chronos's leads to the fingerprint question, so the certificate of another
|
||
/// service on the host is never offered for trust. An HTTPS address whose port answers plain HTTP (the HTTP port typed
|
||
/// without a scheme) is not Chronos either. Nothing is trusted here.
|
||
/// </summary>
|
||
public async Task<ServerInfo> GetInfoAsync(CancellationToken ct = default)
|
||
{
|
||
HttpResponseMessage response;
|
||
try
|
||
{
|
||
response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, InfoPath), ct).ConfigureAwait(false);
|
||
}
|
||
catch (UntrustedCertificateException) when (_ownsHandler)
|
||
{
|
||
if (await ProbeAsync(BaseAddress, ct).ConfigureAwait(false) is { Chronos: false }) throw new NotChronosServerException(BaseAddress);
|
||
throw;
|
||
}
|
||
catch (HttpRequestException tls) when (_ownsHandler && tls.HttpRequestError == HttpRequestError.SecureConnectionError
|
||
&& BaseAddress.Scheme == Uri.UriSchemeHttps)
|
||
{
|
||
// The same authority over plain HTTP: any answer means the port is not Chronos's HTTPS port.
|
||
var plain = new UriBuilder(BaseAddress) { Scheme = Uri.UriSchemeHttp, Port = BaseAddress.Port }.Uri;
|
||
if (await ProbeAsync(plain, ct).ConfigureAwait(false) is { Answered: true }) throw new NotChronosServerException(BaseAddress, tls);
|
||
throw;
|
||
}
|
||
using (response)
|
||
{
|
||
var answer = await IdentifyAsync(response, ct).ConfigureAwait(false);
|
||
if (answer.Info is { } info) return info;
|
||
if (answer.Chronos == false) throw new NotChronosServerException(BaseAddress);
|
||
// Chronos's own error, already read (the body cannot be read twice), or busy: as any other request reports it.
|
||
if (answer.Error is { } error) throw new ChronosApiException(response.StatusCode, error);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
throw new NotChronosServerException(BaseAddress);
|
||
}
|
||
}
|
||
|
||
private const string InfoPath = "api/v1/server/info";
|
||
|
||
/// <summary>More than a server info ever holds: a larger answer is something else.</summary>
|
||
private const int MaxInfoBytes = 1 << 20;
|
||
|
||
/// <summary>What every Chronos Server's info holds; JSON of another shape reads as nulls and zeros.</summary>
|
||
private static bool IsChronos(ServerInfo? info) =>
|
||
info is { Name.Length: > 0, Version.Length: > 0, ApiVersion: > 0, Capabilities: not null, Formats: not null, Limits: not null };
|
||
|
||
/// <summary>
|
||
/// What a <c>server/info</c> answer is: Chronos's (with its info when it succeeded, or its error when it failed),
|
||
/// something else, or unknown (busy).
|
||
/// </summary>
|
||
private readonly record struct Identity(bool? Chronos, ServerInfo? Info = null, bool Answered = true, ApiError? Error = null);
|
||
|
||
/// <summary>
|
||
/// Tells a <c>server/info</c> answer of Chronos from any other. Chronos answers it anonymously with its JSON and never
|
||
/// redirects; every response of its carries <see cref="ApiVersion.Header"/>, so an error is Chronos's only with that
|
||
/// header and an error body of its own. A busy answer (408, 429, 502-504) with JSON or no body cannot tell; any answer
|
||
/// that is not JSON, or is larger than <see cref="MaxInfoBytes"/>, is something else.
|
||
/// </summary>
|
||
private static async Task<Identity> IdentifyAsync(HttpResponseMessage response, CancellationToken ct)
|
||
{
|
||
if ((int)response.StatusCode is >= 300 and < 400) return new(false);
|
||
var type = response.Content.Headers.ContentType?.MediaType;
|
||
var json = type is not null && (type.Equals("application/json", StringComparison.OrdinalIgnoreCase) || type.EndsWith("+json", StringComparison.OrdinalIgnoreCase));
|
||
if (ChronosApiException.IsTransientStatus(response.StatusCode)) return new(json || type is null ? null : false);
|
||
if (!json || response.Content.Headers.ContentLength > MaxInfoBytes) return new(false);
|
||
try
|
||
{
|
||
await response.Content.LoadIntoBufferAsync(MaxInfoBytes, ct).ConfigureAwait(false);
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false);
|
||
return IsChronos(info) ? new(true, info) : new(false);
|
||
}
|
||
if (!response.Headers.Contains(ApiVersion.Header)) return new(false);
|
||
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false);
|
||
return error is { Code.Length: > 0 } && !error.Code.StartsWith("http_", StringComparison.Ordinal) ? new(true, Error: error) : new(false);
|
||
}
|
||
catch (Exception ex) when (ex is JsonException or NotSupportedException or HttpRequestException)
|
||
{
|
||
// Not JSON after all, or more than a server info.
|
||
return new(false);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The info at <paramref name="address"/> read without checking the certificate, by a client of its own that holds no
|
||
/// token and follows no redirect; <see cref="Identity.Answered"/> is false when nothing answered (no connection, TLS
|
||
/// refused, timeout).
|
||
/// </summary>
|
||
private static async Task<Identity> ProbeAsync(Uri address, CancellationToken ct)
|
||
{
|
||
using var handler = new SocketsHttpHandler
|
||
{
|
||
SslOptions = { RemoteCertificateValidationCallback = static (_, _, _, _) => true },
|
||
ConnectTimeout = TimeSpan.FromSeconds(10),
|
||
AutomaticDecompression = DecompressionMethods.None,
|
||
AllowAutoRedirect = false,
|
||
UseCookies = false,
|
||
};
|
||
using var http = new HttpClient(handler) { BaseAddress = address, Timeout = TimeSpan.FromSeconds(20) };
|
||
http.DefaultRequestHeaders.Add(ApiVersion.Header, ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||
try
|
||
{
|
||
using var response = await http.GetAsync(InfoPath, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
||
return await IdentifyAsync(response, ct).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (ex is HttpRequestException or IOException || (ex is OperationCanceledException && !ct.IsCancellationRequested))
|
||
{
|
||
return new(null, Answered: false);
|
||
}
|
||
}
|
||
|
||
// ---------------- Auth ----------------
|
||
|
||
public async Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct = default)
|
||
{
|
||
var response = await SendAsync(HttpMethod.Post, "api/v1/auth/login", new LoginRequest(username, password, ClientName), ProtocolJson.Default.LoginRequest, ProtocolJson.Default.LoginResponse, ct).ConfigureAwait(false);
|
||
Token = response.Token;
|
||
return response;
|
||
}
|
||
|
||
public async Task LogoutAsync(CancellationToken ct = default)
|
||
{
|
||
await SendNoContentAsync(HttpMethod.Post, "api/v1/auth/logout", ct).ConfigureAwait(false);
|
||
Token = null;
|
||
}
|
||
|
||
public Task<UserDto> MeAsync(CancellationToken ct = default) => GetAsync("api/v1/auth/me", ProtocolJson.Default.UserDto, ct);
|
||
|
||
public Task ChangePasswordAsync(string current, string next, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, "api/v1/auth/password", new ChangePasswordRequest(current, next), ProtocolJson.Default.ChangePasswordRequest, ct);
|
||
|
||
// ---------------- Sequences ----------------
|
||
|
||
public Task<Page<SequenceDto>> ListSequencesAsync(string? query = null, string? cursor = null, int limit = 200, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences?limit={limit}{Q("q", query)}{Q("cursor", cursor)}", ProtocolJson.Default.PageSequenceDto, ct);
|
||
|
||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/sequences/{id}", ProtocolJson.Default.SequenceDto, ct);
|
||
|
||
public Task<SequenceDto> CreateSequenceAsync(CreateSequenceRequest request, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, "api/v1/sequences", request, ProtocolJson.Default.CreateSequenceRequest, ProtocolJson.Default.SequenceDto, ct);
|
||
|
||
/// <summary>Updates metadata/settings; a 409 <see cref="ChronosApiException"/> means the settings changed on the server.</summary>
|
||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Patch, $"api/v1/sequences/{id}", request, ProtocolJson.Default.UpdateSequenceRequest, ProtocolJson.Default.SequenceDto, ct);
|
||
|
||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{id}/manifest", ProtocolJson.Default.SequenceManifest, ct);
|
||
|
||
/// <summary>The full deep-analysis report of a sequence (<c>analysis.json</c>); null when it was never deep-analysed.</summary>
|
||
public async Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, $"api/v1/sequences/{sequenceId}/analysis/report"), ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
}
|
||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound && ex.Error.Details == "analysis")
|
||
{
|
||
return null;
|
||
}
|
||
return await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
public Task<Page<FrameDto>> ListFramesAsync(Guid sequenceId, string? cursor = null, int limit = 1000, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/frames?limit={limit}{Q("cursor", cursor)}", ProtocolJson.Default.PageFrameDto, ct);
|
||
|
||
/// <summary>Streams a frame resource (original, proxy or thumb) to <paramref name="destination"/>, resuming with Range from its current length.</summary>
|
||
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, IProgress<long>? progress = null, CancellationToken ct = default)
|
||
{
|
||
if (kind is not ("original" or "proxy" or "thumb")) throw new ArgumentOutOfRangeException(nameof(kind));
|
||
using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v1/frames/{frameId}/{kind}");
|
||
if (destination.CanSeek && destination.Length > 0)
|
||
{
|
||
destination.Seek(0, SeekOrigin.End);
|
||
request.Headers.Range = new RangeHeaderValue(destination.Length, null);
|
||
}
|
||
using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
if (response.StatusCode == HttpStatusCode.OK && destination.CanSeek) destination.SetLength(0);
|
||
await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||
var buffer = new byte[1 << 16];
|
||
long total = 0;
|
||
int read;
|
||
while ((read = await body.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0)
|
||
{
|
||
await destination.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
|
||
total += read;
|
||
progress?.Report(total);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Sends the proxy of a frame whose original the server cannot decode (<see cref="ManifestFrame.WantsProxy"/>): a JPEG
|
||
/// with the frame's capture time in its Exif, replacing the server's. A transient failure is retried.
|
||
/// </summary>
|
||
public Task UploadProxyAsync(Guid frameId, byte[] jpeg, CancellationToken ct = default)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(jpeg);
|
||
return RetryAsync(async () =>
|
||
{
|
||
await Bandwidth.AcquireAsync(jpeg.Length, ct).ConfigureAwait(false);
|
||
using var content = new ByteArrayContent(jpeg);
|
||
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||
using var response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Put, $"api/v1/frames/{frameId}/proxy") { Content = content }, ct)
|
||
.ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return true;
|
||
}, ct);
|
||
}
|
||
|
||
// ---------------- Uploads ----------------
|
||
|
||
/// <summary>
|
||
/// Uploads one file with resumable, idempotent chunks; the server verifies the SHA-256 before committing it
|
||
/// (BRIEF §14.4). Returns the committed frame id; null when the server holds the photo without a frame to name: it was
|
||
/// deleted from the target sequence, before the upload or while it was on its way (owner review 2, R6). Transient
|
||
/// failures retry with exponential backoff.
|
||
/// </summary>
|
||
public async Task<CompleteUploadResponse?> UploadFileAsync(
|
||
string path,
|
||
Guid? sequenceId,
|
||
DateTime? capturedAt,
|
||
string? sessionKey = null,
|
||
string? knownSha256 = null,
|
||
IProgress<UploadProgress>? progress = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
var info = new FileInfo(path);
|
||
var sha = knownSha256 ?? await HashFileAsync(path, ct).ConfigureAwait(false);
|
||
var start = await RetryAsync(() => SendAsync(HttpMethod.Post, "api/v1/uploads",
|
||
new StartUploadRequest(sequenceId, info.Name, info.Length, sha, capturedAt, sessionKey),
|
||
ProtocolJson.Default.StartUploadRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false);
|
||
if (start.AlreadyExists)
|
||
{
|
||
progress?.Report(new UploadProgress(info.Length, info.Length));
|
||
return start.FrameId is { } existing ? new CompleteUploadResponse(existing, sequenceId ?? Guid.Empty, -1) : null;
|
||
}
|
||
|
||
var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
|
||
await SendChunksAsync(path, info.Length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
return await RetryAsync(() => SendAsync<CompleteUploadResponse>(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct)
|
||
.ConfigureAwait(false);
|
||
}
|
||
catch (ChronosApiException ex) when (ex is { Status: HttpStatusCode.Conflict, Error.Code: UploadErrors.PhotoRemoved })
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Reports a card import this client streams into the server (started, progress, finished); the server tells every
|
||
/// connected client with a <see cref="CardEvent"/> (BRIEF §14.3).
|
||
/// </summary>
|
||
public Task ReportCardAsync(CardImportReport report, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, "api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport, ct);
|
||
|
||
/// <summary>
|
||
/// Render node: uploads the output of a claimed job in resumable chunks, then completes the job; the server verifies
|
||
/// the SHA-256 in <paramref name="result"/> and files the render under the sequence's exports (BRIEF §14.7).
|
||
/// </summary>
|
||
public async Task<RenderDto> UploadRenderResultAsync(Guid nodeId, Guid jobId, string path, RenderResultRequest result,
|
||
IProgress<UploadProgress>? progress = null, CancellationToken ct = default)
|
||
{
|
||
var length = new FileInfo(path).Length;
|
||
if (length != result.Size) throw new ArgumentException("The result size does not match the file.", nameof(result));
|
||
var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result", result,
|
||
ProtocolJson.Default.RenderResultRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false);
|
||
var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
|
||
await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
|
||
return await RetryAsync(() => SendAsync<RenderDto>(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result/complete", ProtocolJson.Default.RenderDto, ct), ct)
|
||
.ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Sends a render of <paramref name="sequenceId"/> made on this PC in resumable chunks; the server verifies the
|
||
/// SHA-256 in <paramref name="request"/> and files it under the sequence's exports with the same id. Null when the
|
||
/// server already has that render.
|
||
/// </summary>
|
||
public async Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, IProgress<UploadProgress>? progress = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
var length = new FileInfo(path).Length;
|
||
if (length != request.Size) throw new ArgumentException("The render size does not match the file.", nameof(request));
|
||
var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders", request,
|
||
ProtocolJson.Default.RenderUploadRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false);
|
||
if (start.AlreadyExists) return null;
|
||
var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
|
||
await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
|
||
return await RetryAsync(() => SendAsync<RenderDto>(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders/{uploadId}/complete",
|
||
ProtocolJson.Default.RenderDto, ct), ct).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Streams a render's file to <paramref name="destination"/>, resuming with Range from its current length; returns
|
||
/// the file name the server gives it.
|
||
/// </summary>
|
||
public async Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken ct = default)
|
||
{
|
||
using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v1/renders/{renderId}/file");
|
||
if (destination.CanSeek && destination.Length > 0)
|
||
{
|
||
destination.Seek(0, SeekOrigin.End);
|
||
request.Headers.Range = new RangeHeaderValue(destination.Length, null);
|
||
}
|
||
using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
if (response.StatusCode == HttpStatusCode.OK && destination.CanSeek) destination.SetLength(0);
|
||
await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||
await body.CopyToAsync(destination, ct).ConfigureAwait(false);
|
||
var disposition = response.Content.Headers.ContentDisposition;
|
||
return (disposition?.FileNameStar ?? disposition?.FileName)?.Trim('"');
|
||
}
|
||
|
||
/// <summary>Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors.</summary>
|
||
private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList<int> alreadyReceived,
|
||
IProgress<UploadProgress>? progress, CancellationToken ct)
|
||
{
|
||
var received = new HashSet<int>(alreadyReceived);
|
||
var chunks = (int)((length + chunkSize - 1) / chunkSize);
|
||
var buffer = new byte[chunkSize];
|
||
await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||
long sent = received.Sum(i => Math.Min(chunkSize, length - (long)i * chunkSize));
|
||
progress?.Report(new UploadProgress(sent, length));
|
||
for (var n = 0; n < chunks; n++)
|
||
{
|
||
if (received.Contains(n)) continue;
|
||
var offset = (long)n * chunkSize;
|
||
var size = (int)Math.Min(chunkSize, length - offset);
|
||
file.Position = offset;
|
||
await file.ReadExactlyAsync(buffer.AsMemory(0, size), ct).ConfigureAwait(false);
|
||
await Bandwidth.AcquireAsync(size, ct).ConfigureAwait(false);
|
||
var index = n;
|
||
await RetryAsync(async () =>
|
||
{
|
||
using var content = new ByteArrayContent(buffer, 0, size);
|
||
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||
using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{index}", content, ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return true;
|
||
}, ct).ConfigureAwait(false);
|
||
sent += size;
|
||
progress?.Report(new UploadProgress(sent, length));
|
||
}
|
||
}
|
||
|
||
/// <summary>Lower-case hex SHA-256 of a file, streamed.</summary>
|
||
public static async Task<string> HashFileAsync(string path, CancellationToken ct = default)
|
||
{
|
||
await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||
var hash = await SHA256.HashDataAsync(file, ct).ConfigureAwait(false);
|
||
return Convert.ToHexStringLower(hash);
|
||
}
|
||
|
||
// ---------------- Jobs and render nodes ----------------
|
||
|
||
public Task<Page<JobDto>> ListJobsAsync(string? state = null, string? cursor = null, CancellationToken ct = default) =>
|
||
ListJobsAsync(state, null, cursor, ct);
|
||
|
||
/// <summary>A page of jobs, newest first, in <paramref name="state"/> and of <paramref name="kind"/> (wire names; null for any).</summary>
|
||
public Task<Page<JobDto>> ListJobsAsync(string? state, string? kind, string? cursor, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/jobs?limit=200{Q("state", state)}{Q("kind", kind)}{Q("cursor", cursor)}", ProtocolJson.Default.PageJobDto, ct);
|
||
|
||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/jobs/{id}", ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken ct = default) => SendAsync<JobDto>(HttpMethod.Post, $"api/v1/jobs/{id}/cancel", ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken ct = default) => SendAsync<JobDto>(HttpMethod.Post, $"api/v1/jobs/{id}/retry", ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken ct = default) => SendAsync<JobDto>(HttpMethod.Post, $"api/v1/jobs/{id}/pause", ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken ct = default) => SendAsync<JobDto>(HttpMethod.Post, $"api/v1/jobs/{id}/resume", ProtocolJson.Default.JobDto, ct);
|
||
|
||
/// <summary>Moves a waiting job up or down the queue: <paramref name="priority"/> is background, normal or user.</summary>
|
||
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/priority", new JobPriorityRequest(priority), ProtocolJson.Default.JobPriorityRequest, ProtocolJson.Default.JobDto, ct);
|
||
|
||
public Task<List<RenderNodeDto>> ListNodesAsync(CancellationToken ct = default) => GetAsync("api/v1/nodes", ProtocolJson.Default.ListRenderNodeDto, ct);
|
||
|
||
public Task<RenderNodeDto> RegisterNodeAsync(RegisterNodeRequest request, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, "api/v1/nodes/register", request, ProtocolJson.Default.RegisterNodeRequest, ProtocolJson.Default.RenderNodeDto, ct);
|
||
|
||
public Task HeartbeatAsync(Guid nodeId, CancellationToken ct = default) => SendNoContentAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/heartbeat", ct);
|
||
|
||
/// <summary>Claims the next render job matching this node; null when there is none.</summary>
|
||
public async Task<ClaimedJob?> ClaimAsync(Guid nodeId, CancellationToken ct = default)
|
||
{
|
||
using var response = await _http.PostAsync($"api/v1/nodes/{nodeId}/claim", null, ct).ConfigureAwait(false);
|
||
if (response.StatusCode == HttpStatusCode.NoContent) return null;
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ClaimedJob, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
public Task ReportNodeProgressAsync(Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/progress", progress, ProtocolJson.Default.NodeProgress, ct);
|
||
|
||
/// <summary>Gives a claimed job back as failed; a 409 means it was cancelled or reassigned meanwhile.</summary>
|
||
public Task ReportNodeFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/failed", new NodeJobFailure(error), ProtocolJson.Default.NodeJobFailure, ct);
|
||
|
||
// ---------------- Projects (owner review 2, R8; servers with the "projects" capability) ----------------
|
||
|
||
/// <summary>The live projects of a server sequence, Main first (made from the sequence's settings the first time they are read).</summary>
|
||
public Task<List<ProjectDto>> ListProjectsAsync(Guid sequenceId, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/projects", ProtocolJson.Default.ListProjectDto, ct);
|
||
|
||
public Task<ProjectDto> GetProjectAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}", ProtocolJson.Default.ProjectDto, ct);
|
||
|
||
/// <summary>
|
||
/// A new project of the sequence, its first version copied from <see cref="CreateProjectRequest.FromVersionId"/> or from
|
||
/// Main's head; a name refused is a 400 <c>invalid_name</c> or 409 <c>name_taken</c> <see cref="ChronosApiException"/>.
|
||
/// </summary>
|
||
public Task<ProjectDto> CreateProjectAsync(Guid sequenceId, CreateProjectRequest request, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/projects", request, ProtocolJson.Default.CreateProjectRequest, ProtocolJson.Default.ProjectDto, ct);
|
||
|
||
/// <summary>Gives a project another name; a name refused is a 400 <c>invalid_name</c> or 409 <c>name_taken</c> <see cref="ChronosApiException"/>.</summary>
|
||
public Task<ProjectDto> RenameProjectAsync(Guid sequenceId, Guid projectId, string name, CancellationToken ct = default) =>
|
||
SendAsync(HttpMethod.Patch, $"api/v1/sequences/{sequenceId}/projects/{projectId}", new RenameProjectRequest(name), ProtocolJson.Default.RenameProjectRequest,
|
||
ProtocolJson.Default.ProjectDto, ct);
|
||
|
||
/// <summary>
|
||
/// Deletes a project and its versions into the sequence's projects' trash (never erased); Main is refused (409
|
||
/// <c>main_cannot_be_deleted</c>).
|
||
/// </summary>
|
||
public Task DeleteProjectAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
|
||
SendNoContentAsync(HttpMethod.Delete, $"api/v1/sequences/{sequenceId}/projects/{projectId}", ct);
|
||
|
||
/// <summary>The project's newest version.</summary>
|
||
public Task<ProjectVersionDto> GetProjectHeadAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/head", ProtocolJson.Default.ProjectVersionDto, ct);
|
||
|
||
/// <summary>
|
||
/// One page of a project's versions: newest first, numbered below <paramref name="before"/> (from the head when null),
|
||
/// or, with <paramref name="after"/>, oldest first numbered above it (what a workspace pulls). <paramref name="limit"/>:
|
||
/// 1–200 (the server's default, 50 newest first and 100 oldest first, when null).
|
||
/// </summary>
|
||
public Task<ProjectVersionPageDto> ListProjectVersionsAsync(Guid sequenceId, Guid projectId, int? before = null, int? after = null, int? limit = null,
|
||
CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions?{N("before", before)}{N("after", after)}{N("limit", limit)}".TrimEnd('&', '?'),
|
||
ProtocolJson.Default.ProjectVersionPageDto, ct);
|
||
|
||
/// <summary>A version of the project by id; null when the server has no such version of it.</summary>
|
||
public async Task<ProjectVersionDto?> GetProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default)
|
||
{
|
||
try
|
||
{
|
||
return await GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}", ProtocolJson.Default.ProjectVersionDto, ct)
|
||
.ConfigureAwait(false);
|
||
}
|
||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound && ex.Error.Details == "version")
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Pushes <paramref name="version"/>, made in a workspace from the project's head (<see cref="ProjectVersionDto.ParentId"/>):
|
||
/// the server stores it as the new head, numbered head + 1 (201, <c>stored</c>), or answers it again for a repeated push
|
||
/// (200, <c>already_stored</c>), or refuses it, storing nothing: 409 <c>diverged</c> with the head, 422
|
||
/// <c>hash_mismatch</c>, <c>newer_format</c>, <c>too_large</c> or <c>invalid</c>. These come back as <see cref="ProjectPushResultDto"/>
|
||
/// without throwing; any other failure (the sequence or project gone, no permission, the archive offline or the sequence
|
||
/// busy: 503) throws <see cref="ChronosApiException"/>. Safe to repeat: the version's id makes a second push a no-op.
|
||
/// </summary>
|
||
public async Task<ProjectPushResultDto> PushProjectVersionAsync(Guid sequenceId, Guid projectId, ProjectVersionDto version, CancellationToken ct = default)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(version);
|
||
using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/projects/{projectId}/versions")
|
||
{
|
||
Content = JsonContent.Create(version, ProtocolJson.Default.ProjectVersionDto),
|
||
};
|
||
using var response = await SendRawAsync(request, ct).ConfigureAwait(false);
|
||
if (response.StatusCode is HttpStatusCode.OK or HttpStatusCode.Created or HttpStatusCode.Conflict or HttpStatusCode.UnprocessableEntity)
|
||
{
|
||
var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (JsonSerializer.Deserialize(body, ProtocolJson.Default.ProjectPushResultDto) is { Outcome.Length: > 0 } result) return result;
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
// Not a push answer (a proxy's page): the status says what failed.
|
||
}
|
||
}
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
throw new ChronosApiException(response.StatusCode, new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error"));
|
||
}
|
||
|
||
/// <summary>The sequence's frames and photo aliases as of one frames version: what its projects' positions are placed on.</summary>
|
||
public Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken ct = default) =>
|
||
GetAsync($"api/v1/sequences/{sequenceId}/projects/frames", ProtocolJson.Default.ProjectFramesDto, ct);
|
||
|
||
// ---------------- Events ----------------
|
||
|
||
/// <summary>Server events over WebSocket until cancelled; reconnect is the caller's policy.</summary>
|
||
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||
{
|
||
using var socket = new ClientWebSocket();
|
||
socket.Options.RemoteCertificateValidationCallback = _pinning.Validate;
|
||
if (_token is not null) socket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
|
||
var ws = new UriBuilder(new Uri(BaseAddress, "api/v1/events")) { Scheme = BaseAddress.Scheme == "https" ? "wss" : "ws" }.Uri;
|
||
await socket.ConnectAsync(ws, ct).ConfigureAwait(false);
|
||
var buffer = new byte[64 * 1024];
|
||
using var message = new MemoryStream();
|
||
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||
{
|
||
var result = await socket.ReceiveAsync(buffer, ct).ConfigureAwait(false);
|
||
if (result.MessageType == WebSocketMessageType.Close) yield break;
|
||
message.Write(buffer, 0, result.Count);
|
||
if (!result.EndOfMessage) continue;
|
||
ServerEvent? e = null;
|
||
try
|
||
{
|
||
e = JsonSerializer.Deserialize(message.GetBuffer().AsSpan(0, (int)message.Length), ProtocolJson.Default.ServerEvent);
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
// Unknown event types from a newer server are ignored.
|
||
}
|
||
message.SetLength(0);
|
||
if (e is not null) yield return e;
|
||
}
|
||
}
|
||
|
||
public void Dispose() => _http.Dispose();
|
||
|
||
// ---------------- Plumbing ----------------
|
||
|
||
private async Task<T> GetAsync<T>(string url, JsonTypeInfo<T> type, CancellationToken ct)
|
||
{
|
||
using var response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, url), ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return (await response.Content.ReadFromJsonAsync(type, ct).ConfigureAwait(false))!;
|
||
}
|
||
|
||
private async Task<TResponse> SendAsync<TRequest, TResponse>(HttpMethod method, string url, TRequest body, JsonTypeInfo<TRequest> requestType, JsonTypeInfo<TResponse> responseType, CancellationToken ct)
|
||
{
|
||
using var request = new HttpRequestMessage(method, url) { Content = JsonContent.Create(body, requestType) };
|
||
using var response = await SendRawAsync(request, ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return (await response.Content.ReadFromJsonAsync(responseType, ct).ConfigureAwait(false))!;
|
||
}
|
||
|
||
private async Task SendAsync<TRequest>(HttpMethod method, string url, TRequest body, JsonTypeInfo<TRequest> requestType, CancellationToken ct)
|
||
{
|
||
using var request = new HttpRequestMessage(method, url) { Content = JsonContent.Create(body, requestType) };
|
||
using var response = await SendRawAsync(request, ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
private async Task<TResponse> SendAsync<TResponse>(HttpMethod method, string url, JsonTypeInfo<TResponse> responseType, CancellationToken ct)
|
||
{
|
||
using var response = await SendRawAsync(new HttpRequestMessage(method, url), ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
return (await response.Content.ReadFromJsonAsync(responseType, ct).ConfigureAwait(false))!;
|
||
}
|
||
|
||
private async Task SendNoContentAsync(HttpMethod method, string url, CancellationToken ct)
|
||
{
|
||
using var response = await SendRawAsync(new HttpRequestMessage(method, url), ct).ConfigureAwait(false);
|
||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
private async Task<HttpResponseMessage> SendRawAsync(HttpRequestMessage request, CancellationToken ct)
|
||
{
|
||
using (request)
|
||
{
|
||
try
|
||
{
|
||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||
timeout.CancelAfter(TimeSpan.FromSeconds(100));
|
||
return await _http.SendAsync(request, timeout.Token).ConfigureAwait(false);
|
||
}
|
||
catch (HttpRequestException) when (_pinning.LastRejectedFingerprint is { } fingerprint)
|
||
{
|
||
throw new UntrustedCertificateException(fingerprint);
|
||
}
|
||
}
|
||
}
|
||
|
||
private static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
|
||
{
|
||
if (response.IsSuccessStatusCode) return;
|
||
ApiError error;
|
||
try
|
||
{
|
||
error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false)
|
||
?? new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error");
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
error = new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error");
|
||
}
|
||
catch (NotSupportedException)
|
||
{
|
||
error = new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error");
|
||
}
|
||
throw new ChronosApiException(response.StatusCode, error);
|
||
}
|
||
|
||
/// <summary>Retries transient failures 5 times with exponential backoff (1, 2, 4, 8, 16 s).</summary>
|
||
private static async Task<T> RetryAsync<T>(Func<Task<T>> action, CancellationToken ct)
|
||
{
|
||
for (var attempt = 0; ; attempt++)
|
||
{
|
||
try
|
||
{
|
||
return await action().ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (attempt < 5 && !ct.IsCancellationRequested && IsTransient(ex))
|
||
{
|
||
await Task.Delay(TimeSpan.FromSeconds(1 << attempt), ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
}
|
||
|
||
private static bool IsTransient(Exception ex) => ex switch
|
||
{
|
||
ChronosApiException api => api.IsTransient,
|
||
HttpRequestException => true,
|
||
TaskCanceledException => true,
|
||
IOException => true,
|
||
_ => false,
|
||
};
|
||
|
||
private static string Q(string name, string? value) => string.IsNullOrEmpty(value) ? string.Empty : "&" + name + "=" + Uri.EscapeDataString(value);
|
||
|
||
/// <summary>A number of the query (<c>name=value&</c>); empty when null.</summary>
|
||
private static string N(string name, int? value) =>
|
||
value is { } n ? name + "=" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) + "&" : string.Empty;
|
||
}
|