using System.Globalization; using System.Text.Json; using Chronos.Data; using Chronos.Data.Repositories; using Chronos.Protocol; using Chronos.Server.Api; using Chronos.Server.Configuration; using Chronos.Server.Events; using Chronos.Server.Security; using UploadState = Chronos.Data.Repositories.UploadState; namespace Chronos.Server.Storage; /// /// Renders a client sends on request (BRIEF ยง14.5): chunked like frame uploads (same store, chunk endpoint and /// retention), verified against their SHA-256 at completion and filed by under the /// sequence's exports with the client's render id, so both sides recognise the same render. /// public sealed class RenderUploads( ChronosDatabase db, ServerOptions options, UploadService uploads, UploadStore store, RenderStore renders, EventHub events, TimeProvider time) { public async Task> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken) { if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is null) return Outcome.Fail(404, "not_found", "sequence"); if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome.Fail(400, "invalid_file_name"); if (!UploadRules.IsSha256(request.Sha256)) return Outcome.Fail(400, "invalid_hash"); if (request.Size <= 0) return Outcome.Fail(400, "bad_request", "size"); if (request.Size > options.MaxUploadBytes) return Outcome.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture)); if (string.IsNullOrWhiteSpace(request.PresetName) || request.PresetName.Length > 200) return Outcome.Fail(400, "bad_request", "presetName"); if (request.RenderId == Guid.Empty) return Outcome.Fail(400, "bad_request", "renderId"); if (await db.Renders.GetAsync(request.RenderId, cancellationToken) is { } known) { return known.SequenceId == sequenceId ? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null) : Outcome.Fail(409, "render_exists"); } var sha = request.Sha256.ToLowerInvariant(); if (await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken) is { } open && open.SequenceId == sequenceId && open.Size == request.Size && Read(open)?.RenderId == request.RenderId && store.Exists(open.Id)) return Started(open); if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome.Fail(507, "insufficient_storage"); var now = time.GetUtcNow(); var upload = await db.Uploads.CreateAsync(new Upload { Id = Guid.CreateVersion7(), UserId = caller.Id, SequenceId = sequenceId, FileName = fileName, Size = request.Size, Sha256 = sha, ChunkSize = options.ChunkSizeBytes, State = UploadState.Receiving, Created = now, UpdatedAt = now, RenderJson = JsonSerializer.Serialize(request with { FileName = fileName, Sha256 = sha }, ProtocolJson.Default.RenderUploadRequest), }, cancellationToken); store.Create(upload.Id, upload.Size); return Started(upload); } /// Verifies a fully received render and files it; completing a committed one answers it again (a lost response). public async Task> CompleteAsync(Caller caller, Guid sequenceId, Guid uploadId, CancellationToken cancellationToken) { var upload = await db.Uploads.GetAsync(uploadId, cancellationToken); if (upload is null || upload.UserId != caller.Id || upload.SequenceId != sequenceId || upload.JobId is not null || Read(upload) is not { } output) return Outcome.Fail(404, "not_found", "upload"); if (upload.State == UploadState.Committed && await db.Renders.GetAsync(output.RenderId, cancellationToken) is { } done) return Dto.Render(done); if (upload.State != UploadState.Receiving) return Outcome.Fail(409, "upload_state"); if (!upload.IsComplete) return Outcome.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture)); if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken)) return Outcome.Fail(409, "upload_state"); if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome.Fail(422, "hash_mismatch"); var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken); var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps, output.DurationSeconds); var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username, output.RenderId, cancellationToken); if (render is null) { UploadStore.TryDelete(staged); await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None); store.Delete(upload.Id); return Outcome.Fail(409, "upload_state", "sequence"); } await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, cancellationToken: CancellationToken.None); store.Delete(upload.Id); if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } updated) events.Publish(new SequenceChangedEvent(updated.Id, "renders", updated.FramesVersion, updated.SettingsVersion)); return Dto.Render(render); } private static RenderUploadRequest? Read(Upload upload) { if (upload.RenderJson is not { } json) return null; try { return JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest) is { RenderId: var id } request && id != Guid.Empty ? request : null; } catch (JsonException) { return null; } } private static StartUploadResponse Started(Upload upload) => new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null); }