From 83d8cd79bdb400cfa271fbc19c883179b2303600 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:41:20 +0000 Subject: [PATCH] feat(protocol): API v1 contract and typed client DTOs for auth, users, sequences, frames, manifests, uploads, jobs, render nodes, events and LAN discovery; TitanoClient with TOFU certificate pinning, bearer auth, resumable SHA-256-verified chunked uploads with retry/backoff, shared bandwidth limiter and the event WebSocket stream. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Protocol/Auth.cs | 31 ++ .../Client/BandwidthLimiter.cs | 45 +++ .../Client/CertificatePinning.cs | 34 ++ .../Client/TitanoApiException.cs | 23 ++ src/Titano.Protocol/Client/TitanoClient.cs | 359 ++++++++++++++++++ src/Titano.Protocol/Discovery.cs | 31 ++ src/Titano.Protocol/Dtos.cs | 11 - src/Titano.Protocol/Events.cs | 22 ++ src/Titano.Protocol/Jobs.cs | 36 ++ src/Titano.Protocol/ProtocolJson.cs | 48 +++ src/Titano.Protocol/Sequences.cs | 104 +++++ src/Titano.Protocol/Uploads.cs | 18 + 12 files changed, 751 insertions(+), 11 deletions(-) create mode 100644 src/Titano.Protocol/Auth.cs create mode 100644 src/Titano.Protocol/Client/BandwidthLimiter.cs create mode 100644 src/Titano.Protocol/Client/CertificatePinning.cs create mode 100644 src/Titano.Protocol/Client/TitanoApiException.cs create mode 100644 src/Titano.Protocol/Client/TitanoClient.cs create mode 100644 src/Titano.Protocol/Discovery.cs create mode 100644 src/Titano.Protocol/Events.cs create mode 100644 src/Titano.Protocol/Jobs.cs create mode 100644 src/Titano.Protocol/ProtocolJson.cs create mode 100644 src/Titano.Protocol/Sequences.cs create mode 100644 src/Titano.Protocol/Uploads.cs diff --git a/src/Titano.Protocol/Auth.cs b/src/Titano.Protocol/Auth.cs new file mode 100644 index 00000000..077009c1 --- /dev/null +++ b/src/Titano.Protocol/Auth.cs @@ -0,0 +1,31 @@ +namespace Titano.Protocol; + +/// POST /api/v1/auth/login. = true asks for an HttpOnly session cookie (web admin). +public sealed record LoginRequest(string Username, string Password, string ClientName, bool Cookie = false); + +public sealed record LoginResponse(string? Token, UserDto User, bool MustChangePassword, DateTimeOffset ExpiresAt); + +/// POST /api/v1/auth/password. +public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword); + +public sealed record UserDto( + Guid Id, + string Username, + string? DisplayName, + string Role, + long Permissions, + long QuotaBytes, + long UsedBytes, + bool Disabled, + bool MustChangePassword, + DateTimeOffset Created, + DateTimeOffset? LastLogin); + +/// POST /api/v1/users (admin). +public sealed record CreateUserRequest(string Username, string? DisplayName, string Role, long QuotaBytes, string? Password, bool AllowRenderNode); + +/// PATCH /api/v1/users/{id} (admin); null fields stay unchanged. +public sealed record UpdateUserRequest(string? DisplayName, string? Role, long? QuotaBytes, bool? Disabled, bool? AllowRenderNode); + +/// Response of POST /api/v1/users and /users/{id}/reset-password: a temporary password shown once. +public sealed record TemporaryPasswordResponse(UserDto User, string TemporaryPassword); diff --git a/src/Titano.Protocol/Client/BandwidthLimiter.cs b/src/Titano.Protocol/Client/BandwidthLimiter.cs new file mode 100644 index 00000000..10361151 --- /dev/null +++ b/src/Titano.Protocol/Client/BandwidthLimiter.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; + +namespace Titano.Protocol.Client; + +/// Token bucket shared by concurrent uploads (Uploader "Limit … MB/s"). 0 = unlimited. +public sealed class BandwidthLimiter +{ + private readonly Lock _gate = new(); + private readonly Stopwatch _clock = Stopwatch.StartNew(); + private double _tokens; + private double _last; + private long _bytesPerSecond; + + public BandwidthLimiter(long bytesPerSecond = 0) => BytesPerSecond = bytesPerSecond; + + public long BytesPerSecond + { + get => Interlocked.Read(ref _bytesPerSecond); + set => Interlocked.Exchange(ref _bytesPerSecond, Math.Max(0, value)); + } + + /// Waits until may be sent. + public async ValueTask AcquireAsync(int bytes, CancellationToken cancellationToken) + { + while (true) + { + var rate = BytesPerSecond; + if (rate == 0) return; + TimeSpan wait; + lock (_gate) + { + var now = _clock.Elapsed.TotalSeconds; + _tokens = Math.Min(rate, _tokens + (now - _last) * rate); + _last = now; + if (_tokens >= bytes || _tokens >= rate) + { + _tokens -= bytes; + return; + } + wait = TimeSpan.FromSeconds(Math.Min(1.0, (bytes - _tokens) / rate)); + } + await Task.Delay(wait, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Titano.Protocol/Client/CertificatePinning.cs b/src/Titano.Protocol/Client/CertificatePinning.cs new file mode 100644 index 00000000..f905b429 --- /dev/null +++ b/src/Titano.Protocol/Client/CertificatePinning.cs @@ -0,0 +1,34 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Titano.Protocol.Client; + +/// +/// Trust-on-first-use certificate validation: a certificate is accepted when it chains to a trusted root or when +/// its SHA-256 fingerprint is in the caller's trusted set. The last unknown fingerprint is remembered so the UI can +/// ask the user once and add it. +/// +public sealed class CertificatePinning(IEnumerable trustedFingerprints) +{ + private readonly HashSet _trusted = new(trustedFingerprints.Select(Normalize), StringComparer.Ordinal); + + public string? LastRejectedFingerprint { get; private set; } + + public void Trust(string fingerprint) => _trusted.Add(Normalize(fingerprint)); + + public bool Validate(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors) + { + if (certificate is null) return false; + if (errors == SslPolicyErrors.None) return true; + var fingerprint = Fingerprint(certificate); + if (_trusted.Contains(fingerprint)) return true; + LastRejectedFingerprint = fingerprint; + return false; + } + + public static string Fingerprint(X509Certificate certificate) => + string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + + private static string Normalize(string fingerprint) => fingerprint.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); +} diff --git a/src/Titano.Protocol/Client/TitanoApiException.cs b/src/Titano.Protocol/Client/TitanoApiException.cs new file mode 100644 index 00000000..03a3aef5 --- /dev/null +++ b/src/Titano.Protocol/Client/TitanoApiException.cs @@ -0,0 +1,23 @@ +using System.Net; + +namespace Titano.Protocol.Client; + +/// A non-success API response carrying the server's . +public sealed class TitanoApiException(HttpStatusCode status, ApiError error) + : Exception($"{(int)status} {error.Code}: {error.Message}") +{ + public HttpStatusCode Status { get; } = status; + public ApiError Error { get; } = error; + + /// True for errors worth retrying (server busy, gateway, timeout). + public bool IsTransient => Status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests + or HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout; +} + +/// The server presented a certificate whose fingerprint is not trusted yet (trust-on-first-use, BRIEF §12.7). +public sealed class UntrustedCertificateException(string fingerprint) + : Exception("Server certificate is not trusted: " + fingerprint) +{ + /// SHA-256 fingerprint (XX:XX:…) to show the user before trusting it. + public string Fingerprint { get; } = fingerprint; +} diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs new file mode 100644 index 00000000..d8f57f51 --- /dev/null +++ b/src/Titano.Protocol/Client/TitanoClient.cs @@ -0,0 +1,359 @@ +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 Titano.Protocol.Client; + +/// Upload progress for one file. +public readonly record struct UploadProgress(long BytesSent, long BytesTotal); + +/// +/// Typed client for Titano Server API v1 (BRIEF §14.3), used by the desktop client and the uploader. +/// Thread-safe; one instance per server connection. +/// +public sealed class TitanoClient : IDisposable +{ + private readonly HttpClient _http; + private readonly CertificatePinning _pinning; + private string? _token; + + public TitanoClient(Uri baseAddress, CertificatePinning pinning, string clientName, HttpMessageHandler? handler = null) + { + _pinning = pinning; + 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("Titano", typeof(TitanoClient).Assembly.GetName().Version?.ToString(3) ?? "0")); + } + + public Uri BaseAddress { get; } + public string ClientName { get; } + public CertificatePinning Pinning => _pinning; + + /// Bearer token; set after or restored from secure storage. + public string? Token + { + get => _token; + set + { + _token = value; + _http.DefaultRequestHeaders.Authorization = value is null ? null : new AuthenticationHeaderValue("Bearer", value); + } + } + + /// Shared upload rate limit. + public BandwidthLimiter Bandwidth { get; } = new(); + + // ---------------- Server ---------------- + + /// Reads server info; throws when the TLS certificate needs confirmation. + public Task GetInfoAsync(CancellationToken ct = default) => GetAsync("api/v1/server/info", ProtocolJson.Default.ServerInfo, ct); + + // ---------------- Auth ---------------- + + public async Task 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 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> 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 GetSequenceAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/sequences/{id}", ProtocolJson.Default.SequenceDto, ct); + + public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/sequences", request, ProtocolJson.Default.CreateSequenceRequest, ProtocolJson.Default.SequenceDto, ct); + + /// Updates metadata/settings; a 409 means the settings changed on the server. + public Task 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 GetManifestAsync(Guid id, CancellationToken ct = default) => + GetAsync($"api/v1/sequences/{id}/manifest", ProtocolJson.Default.SequenceManifest, ct); + + public Task> 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); + + /// Streams a frame resource (original, proxy or thumb) to , resuming with Range from its current length. + public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, IProgress? 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); + } + } + + // ---------------- Uploads ---------------- + + /// + /// Uploads one file with resumable, idempotent chunks; the server verifies the SHA-256 before committing it + /// (BRIEF §14.4). Returns the committed frame id. Transient failures retry with exponential backoff. + /// + public async Task UploadFileAsync( + string path, + Guid? sequenceId, + DateTime? capturedAt, + string? sessionKey = null, + string? knownSha256 = null, + IProgress? 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."); + var chunkSize = start.ChunkSize; + var received = new HashSet(start.Received); + var chunks = (int)((info.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.Count == 0 ? 0 : received.Sum(i => (long)Math.Min(chunkSize, info.Length - (long)i * chunkSize)); + progress?.Report(new UploadProgress(sent, info.Length)); + for (var n = 0; n < chunks; n++) + { + if (received.Contains(n)) continue; + var offset = (long)n * chunkSize; + var length = (int)Math.Min(chunkSize, info.Length - offset); + file.Position = offset; + await file.ReadExactlyAsync(buffer.AsMemory(0, length), ct).ConfigureAwait(false); + await Bandwidth.AcquireAsync(length, ct).ConfigureAwait(false); + await RetryAsync(async () => + { + using var content = new ByteArrayContent(buffer, 0, length); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{n}", content, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return true; + }, ct).ConfigureAwait(false); + sent += length; + progress?.Report(new UploadProgress(sent, info.Length)); + } + } + return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false); + } + + /// Lower-case hex SHA-256 of a file, streamed. + public static async Task 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> ListJobsAsync(string? state = null, string? cursor = null, CancellationToken ct = default) => + GetAsync($"api/v1/jobs?limit=200{Q("state", state)}{Q("cursor", cursor)}", ProtocolJson.Default.PageJobDto, ct); + + public Task CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct); + + public Task CancelJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/cancel", ProtocolJson.Default.JobDto, ct); + + public Task RetryJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/retry", ProtocolJson.Default.JobDto, ct); + + public Task 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); + + /// Claims the next render job matching this node; null when there is none. + public async Task 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); + + // ---------------- Events ---------------- + + /// Server events over WebSocket until cancelled; reconnect is the caller's policy. + public async IAsyncEnumerable 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 GetAsync(string url, JsonTypeInfo 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 SendAsync(HttpMethod method, string url, TRequest body, JsonTypeInfo requestType, JsonTypeInfo 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(HttpMethod method, string url, TRequest body, JsonTypeInfo 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 SendAsync(HttpMethod method, string url, JsonTypeInfo 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 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 TitanoApiException(response.StatusCode, error); + } + + /// Retries transient failures 5 times with exponential backoff (1, 2, 4, 8, 16 s). + private static async Task RetryAsync(Func> 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 + { + TitanoApiException 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); +} diff --git a/src/Titano.Protocol/Discovery.cs b/src/Titano.Protocol/Discovery.cs new file mode 100644 index 00000000..d0d63465 --- /dev/null +++ b/src/Titano.Protocol/Discovery.cs @@ -0,0 +1,31 @@ +using System.Text; +using System.Text.Json; + +namespace Titano.Protocol; + +/// +/// LAN discovery (TITANO_DISCOVERY): the server broadcasts a small UDP beacon on port 48300 every few seconds; +/// clients listen and offer "Studio NAS found on this network" on first run. +/// +public sealed record DiscoveryBeacon(string Name, string Version, int HttpPort, int HttpsPort, string? TlsFingerprint) +{ + public const int Port = 48300; + private const string Magic = "TITANO1 "; + + public byte[] ToBytes() => Encoding.UTF8.GetBytes(Magic + JsonSerializer.Serialize(this, ProtocolJson.Default.DiscoveryBeacon)); + + public static DiscoveryBeacon? TryParse(ReadOnlySpan datagram) + { + if (datagram.Length > 2048) return null; + var text = Encoding.UTF8.GetString(datagram); + if (!text.StartsWith(Magic, StringComparison.Ordinal)) return null; + try + { + return JsonSerializer.Deserialize(text[Magic.Length..], ProtocolJson.Default.DiscoveryBeacon); + } + catch (JsonException) + { + return null; + } + } +} diff --git a/src/Titano.Protocol/Dtos.cs b/src/Titano.Protocol/Dtos.cs index c2408a07..d841902d 100644 --- a/src/Titano.Protocol/Dtos.cs +++ b/src/Titano.Protocol/Dtos.cs @@ -20,14 +20,3 @@ public sealed record ServerInfo( /// GET /health. public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary Checks); - -/// Source-generated JSON contracts shared by server and clients (camelCase, enums as strings). -[JsonSourceGenerationOptions( - PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - UseStringEnumConverter = true)] -[JsonSerializable(typeof(ApiError))] -[JsonSerializable(typeof(ServerInfo))] -[JsonSerializable(typeof(HealthStatus))] -[JsonSerializable(typeof(Dictionary))] -public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Titano.Protocol/Events.cs b/src/Titano.Protocol/Events.cs new file mode 100644 index 00000000..e149000c --- /dev/null +++ b/src/Titano.Protocol/Events.cs @@ -0,0 +1,22 @@ +using System.Text.Json.Serialization; + +namespace Titano.Protocol; + +/// +/// Messages pushed on WS /api/v1/events. Each frame is one JSON object with a type discriminator: +/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState. +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")] +[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")] +[JsonDerivedType(typeof(JobStateEvent), "jobState")] +[JsonDerivedType(typeof(SequenceChangedEvent), "sequenceChanged")] +[JsonDerivedType(typeof(NodeStateEvent), "nodeState")] +public abstract record ServerEvent; + +public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent; + +public sealed record JobStateEvent(Guid JobId, string State, string? Error) : ServerEvent; + +public sealed record SequenceChangedEvent(Guid SequenceId, string Change, int FramesVersion, int SettingsVersion) : ServerEvent; + +public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State) : ServerEvent; diff --git a/src/Titano.Protocol/Jobs.cs b/src/Titano.Protocol/Jobs.cs new file mode 100644 index 00000000..e5655af4 --- /dev/null +++ b/src/Titano.Protocol/Jobs.cs @@ -0,0 +1,36 @@ +namespace Titano.Protocol; + +public sealed record JobDto( + Guid Id, + string Kind, + IReadOnlyList TargetIds, + string? TargetLabel, + string State, + string Priority, + long ProgressDone, + long ProgressTotal, + double? ItemsPerSecond, + double? EtaSeconds, + string? LogTail, + string? NodeId, + int Attempts, + string? Error, + DateTimeOffset Created, + DateTimeOffset? Started, + DateTimeOffset? Finished); + +/// POST /api/v1/jobs: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance… +public sealed record CreateJobRequest(string Kind, IReadOnlyList Target, string? ParametersJson); + +/// POST /api/v1/nodes/register: a client offers its GPU encoders (BRIEF §14.7). +public sealed record RegisterNodeRequest(string ClientName, IReadOnlyList Encoders, int MaxWidth, int MaxHeight); + +public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit); + +public sealed record RenderNodeDto(Guid Id, string ClientName, string Username, IReadOnlyList Encoders, DateTimeOffset LastHeartbeat, string State); + +/// POST /api/v1/nodes/{id}/claim: the job and everything needed to run it, or 204 when none matches. +public sealed record ClaimedJob(JobDto Job, Guid SequenceId, string SettingsJson, string PresetJson, bool UseProxies, IReadOnlyList Frames); + +/// POST /api/v1/nodes/{id}/jobs/{jobId}/progress. +public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine); diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs new file mode 100644 index 00000000..2f3dad46 --- /dev/null +++ b/src/Titano.Protocol/ProtocolJson.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization; + +namespace Titano.Protocol; + +/// Source-generated JSON contracts shared by server and clients (camelCase, enums as strings). +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNameCaseInsensitive = true, + UseStringEnumConverter = true)] +[JsonSerializable(typeof(ApiError))] +[JsonSerializable(typeof(ServerInfo))] +[JsonSerializable(typeof(HealthStatus))] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(LoginRequest))] +[JsonSerializable(typeof(LoginResponse))] +[JsonSerializable(typeof(ChangePasswordRequest))] +[JsonSerializable(typeof(UserDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(CreateUserRequest))] +[JsonSerializable(typeof(UpdateUserRequest))] +[JsonSerializable(typeof(TemporaryPasswordResponse))] +[JsonSerializable(typeof(SequenceDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(CreateSequenceRequest))] +[JsonSerializable(typeof(UpdateSequenceRequest))] +[JsonSerializable(typeof(FrameDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(SequenceManifest))] +[JsonSerializable(typeof(RenderDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(ArchiveStatsDto))] +[JsonSerializable(typeof(StartUploadRequest))] +[JsonSerializable(typeof(StartUploadResponse))] +[JsonSerializable(typeof(ChunkReceived))] +[JsonSerializable(typeof(CompleteUploadResponse))] +[JsonSerializable(typeof(UploadState))] +[JsonSerializable(typeof(JobDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(CreateJobRequest))] +[JsonSerializable(typeof(RegisterNodeRequest))] +[JsonSerializable(typeof(RenderNodeDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(ClaimedJob))] +[JsonSerializable(typeof(NodeProgress))] +[JsonSerializable(typeof(ServerEvent))] +[JsonSerializable(typeof(DiscoveryBeacon))] +public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Titano.Protocol/Sequences.cs b/src/Titano.Protocol/Sequences.cs new file mode 100644 index 00000000..ab3bb730 --- /dev/null +++ b/src/Titano.Protocol/Sequences.cs @@ -0,0 +1,104 @@ +namespace Titano.Protocol; + +/// Sequence summary for lists (BRIEF §12.2 card data). +public sealed record SequenceDto( + Guid Id, + string? Title, + string DisplayTitle, + string Folder, + string? CameraMake, + string? CameraModel, + string? Lens, + DateTime? FirstCapture, + DateTime? LastCapture, + int FrameCount, + double? MedianInterval, + long TotalBytes, + long Status, + int RenderedCount, + Guid? HeroFrameId, + IReadOnlyList Tags, + int Rating, + string? Notes, + int SettingsVersion, + int FramesVersion, + int WarningCount, + Guid? OwnerUserId, + DateTimeOffset UpdatedAt); + +/// A page of results with an opaque keyset cursor; null cursor = last page. +public sealed record Page(IReadOnlyList Items, string? NextCursor, long? Total); + +/// POST /api/v1/sequences. +public sealed record CreateSequenceRequest(string? Title, string? CameraHint); + +/// PATCH /api/v1/sequences/{id}. enables conflict detection (409). +public sealed record UpdateSequenceRequest( + string? Title, + IReadOnlyList? Tags, + int? Rating, + string? Notes, + string? SettingsJson, + int? ExpectedSettingsVersion); + +public sealed record FrameDto( + Guid Id, + Guid SequenceId, + int Index, + string FileName, + long Size, + string? Sha256, + DateTime? CapturedAt, + int? UtcOffsetMinutes, + double? ExposureTime, + double? FNumber, + int? Iso, + double? FocalLength, + int Orientation, + int Width, + int Height, + string Format, + long Flags); + +/// GET /api/v1/sequences/{id}/manifest: what a client needs to diff a sequence (BRIEF §14.5). +public sealed record SequenceManifest( + Guid SequenceId, + int FramesVersion, + int SettingsVersion, + string? SettingsJson, + IReadOnlyList Tags, + IReadOnlyList Frames, + IReadOnlyList Renders); + +public sealed record ManifestFrame(Guid Id, int Index, string FileName, long Size, string Sha256, bool HasProxy, bool HasThumb); + +public sealed record RenderDto( + Guid Id, + string PresetName, + string? Codec, + int Width, + int Height, + double Fps, + double DurationSeconds, + long Bytes, + DateTimeOffset Created, + string? ProducedBy); + +/// Aggregates for the archive dashboard and the admin panel. +public sealed record ArchiveStatsDto( + long Sequences, + long Photos, + long Bytes, + long FreeBytes, + long CapacityBytes, + int Cameras, + int? FirstYear, + int? LastYear, + IReadOnlyList ByYear, + IReadOnlyList ByMonth, + IReadOnlyList ByCamera, + IReadOnlyList ByFormat, + int SequencesWithoutProxies, + int UnverifiedSequences); + +public sealed record KeyValueCount(string Key, long Count, long Bytes); diff --git a/src/Titano.Protocol/Uploads.cs b/src/Titano.Protocol/Uploads.cs new file mode 100644 index 00000000..b2ff863c --- /dev/null +++ b/src/Titano.Protocol/Uploads.cs @@ -0,0 +1,18 @@ +namespace Titano.Protocol; + +/// +/// POST /api/v1/uploads (BRIEF §14.4). The client hashes the file first; when the server already holds that +/// SHA-256 it answers 200 with and no upload is needed. +/// +public sealed record StartUploadRequest(Guid? SequenceId, string FileName, long Size, string Sha256, DateTime? CapturedAt, string? SessionKey); + +public sealed record StartUploadResponse(Guid? UploadId, int ChunkSize, IReadOnlyList Received, bool AlreadyExists, Guid? FrameId); + +/// PUT /api/v1/uploads/{id}/chunks/{n} response. +public sealed record ChunkReceived(int Index, IReadOnlyList Received); + +/// POST /api/v1/uploads/{id}/complete response: the committed frame. +public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int Index); + +/// GET /api/v1/uploads/{id}: resume state. +public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList Received, string State);