diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index 52cc2048..724ff1df 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -64,6 +64,7 @@ Project restored Nothing to restore Undo + This sequence has no photos yet.long Photos are being added to this sequence; wait a moment and try again.long The frames of this sequence changed on the server; get its proxies again.long This sequence is no longer in the archive.long diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index f3d7160f..403b4429 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -106,6 +106,7 @@ A system schedule cannot be deleted; turn it off instead.long You cannot do this to your own account.long A job is working on this sequence or its archive; try again when it is free.long + This sequence has no photos yet; its projects start with its first photo.long That sequence is in the library already.long The session expired; sign in again.long An environment variable sets this; change it there.long diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index 6159d8d0..fe381624 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -63,6 +63,7 @@ Progetto ripristinato Niente da ripristinare Annulla + Questa sequenza non ha ancora foto. Si stanno aggiungendo foto a questa sequenza; attendi un momento e riprova. I fotogrammi di questa sequenza sono cambiati sul server; scarica di nuovo i proxy. Questa sequenza non è più nell’archivio. diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index d5282d1c..d4df3552 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -104,6 +104,7 @@ Una pianificazione di sistema non si può eliminare; disattivala.long Non puoi farlo sul tuo account. Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera. + Questa sequenza non ha ancora foto; i suoi progetti iniziano con la prima foto. Quella sequenza è già nella libreria. La sessione è scaduta; accedi di nuovo. È impostato da una variabile d'ambiente; modificala lì. diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs index aa4acc14..17077732 100644 --- a/src/Chronos.App/Sections/SequenceViewModel.cs +++ b/src/Chronos.App/Sections/SequenceViewModel.cs @@ -791,6 +791,10 @@ public sealed class SequenceViewModel : SectionViewModel { throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex); } + catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceEmpty) + { + throw new InvalidOperationException(Loc.L("Editor.Error.Empty"), ex); + } catch (HomeUnavailableException ex) { // Said of the server, not of this PC's library. diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs index 12779dbf..4739dddb 100644 --- a/src/Chronos.App/Workspace/WorkspaceHost.cs +++ b/src/Chronos.App/Workspace/WorkspaceHost.cs @@ -418,7 +418,8 @@ public sealed class WorkspaceHost var listed = await reached.ListAsync(cancellationToken).ConfigureAwait(false); project = projectId is { } id ? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.") - : listed.First(p => p.IsMain); + // A server's sequence with no photo yet has no projects at all. + : listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet."); } // A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it. if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable) diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs index 0fc05c19..a0249ea1 100644 --- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs +++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs @@ -355,14 +355,26 @@ public sealed class ArchiveIndexer { if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row || !Directory.Exists(paths.Sequence(row.Folder).ProjectsDirectory)) return; + ProjectChangeSet? changed = null; try { await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false)) { var folder = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false); if (!SequenceFolders.Holds(folder, sequenceId) || !Directory.Exists(folder.ProjectsDirectory)) return; - await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false); + // Projects and versions another program wrote, taken in here, are told as a project call's are: the next call + // finds them in the index already and has nothing to tell. + var before = await ProjectService.WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken).ConfigureAwait(false); + try + { + await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false); + } + finally + { + if (before is not null) changed = await ProjectService.ChangesAsync(_db, sequenceId, before, settingsChanged: false).ConfigureAwait(false); + } } + if (changed is not null) await ProjectService.TellAsync(_writer.Options, changed).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) { diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index 3cc85680..0b33b41b 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -3,6 +3,7 @@ using Chronos.Core.Archiving; using Chronos.Core.Conversion; using Chronos.Core.Diagnostics; using Chronos.Core.Import; +using Chronos.Core.IO; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Naming; @@ -348,6 +349,65 @@ public sealed class ArchiveService : IJobHandlerProvider return await write(await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false); } + /// + /// Settings a caller writes into the index (: the server's PATCH, with its version checks) + /// written into the sequence's project.json too, under its lease, as every other writer of the settings does: so + /// the file never holds settings older than the index's, which the projects would take for the sequence's own when they + /// meet Main (). goes to the file first; when the index then + /// does not take it (a conflict, the sequence gone) or the edit fails, the file is put back as it was. A sequence with no + /// folder yet is edited in the index alone: its first photo writes the file from the index. + /// + /// How long the sequence's lease is waited for. + /// The sequence or its archive is not in the index. + /// The archive is offline or read-only: nothing is written. + /// Another writer held the sequence for longer than : nothing is written. + /// The sequence's folder does not hold it now: nothing is written. + /// The file cannot be written: nothing is written. + public async Task EditSettingsAsync(Guid sequenceId, string settingsJson, Func> edit, TimeSpan wait, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settingsJson); + ArgumentNullException.ThrowIfNull(edit); + var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrEmpty(sequence.Folder)) return await edit(cancellationToken).ConfigureAwait(false); + var paths = new ArchivePaths(archive.RootPath); + ArchiveVolume.EnsureWritable(paths); + await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false)) + { + var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw Unknown(sequenceId); + var folder = paths.Sequence(row.Folder); + if (string.IsNullOrEmpty(row.Folder) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException(); + var previous = File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null; + Directory.CreateDirectory(folder.MetaDirectory); + AtomicFile.WriteAllText(folder.ProjectPath, settingsJson); + SequenceEditResult result; + try + { + result = await edit(cancellationToken).ConfigureAwait(false); + } + catch + { + PutBack(folder, previous); + throw; + } + if (result.Outcome != SequenceEditOutcome.Updated) PutBack(folder, previous); + return result; + } + + static void PutBack(SequencePaths folder, string? previous) + { + try + { + if (previous is not null) AtomicFile.WriteAllText(folder.ProjectPath, previous); + else File.Delete(folder.ProjectPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("archive", $"The project.json of {folder.RelativeFolder} could not be put back after an edit the index did not take", ex); + } + } + } + public Task> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) => Maintenance.FindDuplicatesAsync(archiveId, cancellationToken); diff --git a/src/Chronos.Data/Projects/IProjectHome.cs b/src/Chronos.Data/Projects/IProjectHome.cs index 80630b23..e8bbd859 100644 --- a/src/Chronos.Data/Projects/IProjectHome.cs +++ b/src/Chronos.Data/Projects/IProjectHome.cs @@ -176,8 +176,17 @@ public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projec /// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version) /// and how many removals it keeps (a conversion's links). /// - public async Task FramesStampAsync(CancellationToken cancellationToken) + public async Task FramesStampAsync(CancellationToken cancellationToken) => + await StampOfAsync(db, sequenceId, cancellationToken).ConfigureAwait(false); + + /// + /// The stamp of a sequence's frames as an index holds them (): what a server answers for + /// its sequences too (GET …/projects/frames/stamp). + /// + /// The sequence is not in the index. + public static async Task StampOfAsync(ChronosDatabase db, Guid sequenceId, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(db); var row = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index."); var (hashed, checksum, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false); diff --git a/src/Chronos.Data/Projects/ProjectService.cs b/src/Chronos.Data/Projects/ProjectService.cs index 265badd2..bcd173be 100644 --- a/src/Chronos.Data/Projects/ProjectService.cs +++ b/src/Chronos.Data/Projects/ProjectService.cs @@ -27,6 +27,12 @@ public enum ProjectError /// The Main project cannot be deleted: it holds the sequence's own settings. MainCannotBeDeleted, + + /// + /// The sequence has no folder in its archive yet (made before its first photo, as a server's new sequence is): it keeps + /// no projects until its first photo places it. + /// + SequenceEmpty, } /// A project operation was refused; nothing was written. @@ -406,6 +412,7 @@ public sealed class ProjectService ArgumentNullException.ThrowIfNull(version); if (await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false) is not { DeletedAt: null } project) return false; var (paths, row) = await LocateAsync(project.SequenceId, cancellationToken).ConfigureAwait(false); + if (Unplaced(row)) return false; if (Availability(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline); var folder = paths.Sequence(row.Folder); if (!SequenceFolders.Holds(folder, project.SequenceId)) throw new SequenceFolderMovedException(); @@ -446,6 +453,8 @@ public sealed class ProjectService /// private async Task ReadAsync(Guid sequenceId, CancellationToken cancellationToken) { + // A sequence with no folder yet keeps no projects: nothing to catch up, and nothing may be written (its folder would be the archive's root). + if (Unplaced(await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId))) return; try { try @@ -479,6 +488,8 @@ public sealed class ProjectService { var (paths, row) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false); var folder = paths.Sequence(row.Folder); + // What the sidecars bring into the index, and a Main made in it, are told as any other call's changes. + var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false); try { if (!SequenceFolders.Holds(folder, sequenceId)) @@ -494,6 +505,11 @@ public sealed class ProjectService { Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}"); } + finally + { + if (before is not null && await ChangesAsync(sequenceId, before, settingsChanged: false).ConfigureAwait(false) is { } changed) + await TellAsync(changed).ConfigureAwait(false); + } } /// @@ -507,7 +523,10 @@ public sealed class ProjectService private async Task UnderLeaseAsync(Guid sequenceId, Func> work, CancellationToken cancellationToken, TimeSpan? wait = null) { - var (paths, _) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false); + var (paths, located) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false); + // Before the lease: the archive's root is no sequence's folder, so nothing of this sequence's projects is read from it or written into it. + if (Unplaced(located)) + throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no folder yet: it keeps no projects before its first photo."); var availability = Availability(paths); if (availability != ArchiveAvailability.Online) throw new ArchiveOfflineException(paths.Root, availability); ProjectChangeSet? changed = null; @@ -517,7 +536,7 @@ public sealed class ProjectService { var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId); var folder = paths.Sequence(row.Folder); - if (!SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException(); + if (Unplaced(row) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException(); // Taken before the reconcile: the versions another program wrote into the sidecars are told too. var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false); LeaseContext? context = null; @@ -542,21 +561,36 @@ public sealed class ProjectService } /// The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes; else null. - private async Task?> WatchedAsync(Guid sequenceId, CancellationToken cancellationToken) => - _writer.Options.ProjectsChanged is null - ? null - : (await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, cancellationToken).ConfigureAwait(false)).ToDictionary(p => p.Id); + private Task?> WatchedAsync(Guid sequenceId, CancellationToken cancellationToken) => + WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken); + + private Task ChangesAsync(Guid sequenceId, Dictionary before, bool settingsChanged) => + ChangesAsync(_db, sequenceId, before, settingsChanged); + + private Task TellAsync(ProjectChangeSet changed) => TellAsync(_writer.Options, changed); /// - /// What changed in the sequence's projects since (a project new or back, deleted, renamed, or - /// with a new head); null when nothing did. Never throws: it runs after the work, whatever became of it. + /// The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes + /// (); else null. Shared with the scans that take the sidecars back + /// outside a project call (). /// - private async Task ChangesAsync(Guid sequenceId, Dictionary before, bool settingsChanged) + internal static async Task?> WatchedAsync(ChronosDatabase db, ArchiveServiceOptions options, Guid sequenceId, + CancellationToken cancellationToken) => + options.ProjectsChanged is null + ? null + : (await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, cancellationToken).ConfigureAwait(false)).ToDictionary(p => p.Id); + + /// + /// What changed in the sequence's projects since (a project new or back, deleted, renamed or + /// made Main or no longer Main, or with a new head); null when nothing did. Never throws: it runs after the work, + /// whatever became of it. + /// + internal static async Task ChangesAsync(ChronosDatabase db, Guid sequenceId, Dictionary before, bool settingsChanged) { IReadOnlyList after; try { - after = await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, CancellationToken.None).ConfigureAwait(false); + after = await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException) { @@ -572,7 +606,8 @@ public sealed class ProjectService else if (!live && wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Deleted)); else if (live) { - if (project.Name != was!.Name) changes.Add(Change(project, Protocol.ProjectChanges.Renamed)); + // Main passed to another project (the sidecars name another one Main): told as a rename, which lists read again for. + if (project.Name != was!.Name || project.IsMain != was.IsMain) changes.Add(Change(project, Protocol.ProjectChanges.Renamed)); if (project.HeadVersionId != was.HeadVersionId) changes.Add(Change(project, Protocol.ProjectChanges.Pushed)); } } @@ -582,11 +617,11 @@ public sealed class ProjectService } /// Tells the host what a call changed; a failure is logged, never passed on. - private async Task TellAsync(ProjectChangeSet changed) + internal static async Task TellAsync(ArchiveServiceOptions options, ProjectChangeSet changed) { try { - await _writer.Options.ProjectsChanged!(changed, CancellationToken.None).ConfigureAwait(false); + await options.ProjectsChanged!(changed, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { @@ -1322,6 +1357,12 @@ public sealed class ProjectService ? project : throw new ProjectException(ProjectError.NotFound, $"Project {projectId} was deleted."); + /// + /// Whether the sequence has no folder in its archive yet (a server's sequence made before its first photo): its folder + /// would read as the archive's root, which every such sequence shares and which is no sequence's. + /// + private static bool Unplaced(Sequence row) => string.IsNullOrEmpty(row.Folder); + private static ProjectException SequenceMissing(Guid sequenceId) => new(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index."); /// The sequence as read under its lease (the mirror moves its settings version), its folder, and what its projects' reconcile met. diff --git a/src/Chronos.Data/Projects/ServerProjectHome.cs b/src/Chronos.Data/Projects/ServerProjectHome.cs index f926d611..30386207 100644 --- a/src/Chronos.Data/Projects/ServerProjectHome.cs +++ b/src/Chronos.Data/Projects/ServerProjectHome.cs @@ -92,19 +92,57 @@ public sealed class ServerProjectHome : IProjectHome ? ProjectWire.ToVersion(version) : null, cancellationToken); + /// + /// The server ends a page early when its versions' settings are large (): the + /// pages are read on until versions came or no more follow, so a short answer always means the end. + /// public Task> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) => - Reach>(async () => - [ - .. (await Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, afterNumber), limit: Page(limit), ct: cancellationToken) - .ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion), - ], cancellationToken); + Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, last?.Number ?? afterNumber), + limit: Page(limit), ct: cancellationToken)), cancellationToken); + /// Read on past a page the server ended early, as is. public Task> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) => - Reach>(async () => - [ - .. (await Client.ListProjectVersionsAsync(SequenceId, projectId, before: beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit), - ct: cancellationToken).ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion), - ], cancellationToken); + Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId, + before: last is not null ? last.Number : beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit), ct: cancellationToken)), + cancellationToken); + + /// Up to versions, page after page (each read after the last version of the one before) while more follow. + private static async Task> PagesAsync(int limit, Func> read) + { + var versions = new List(); + while (true) + { + var page = await read(versions.Count > 0 ? versions[^1] : null).ConfigureAwait(false); + versions.AddRange(page.Items.Take(limit - versions.Count).Select(ProjectWire.ToVersion)); + if (!page.More || page.Items.Count == 0 || versions.Count >= limit) return versions; + } + } + + /// + /// Read back from the version's file on the server (?stored=true: there), + /// never from its index's row: false when the file is missing or damaged, or the project was deleted. + /// + public Task HoldsAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(version); + return Reach(async () => + { + if (!ProjectContent.Verifies(version.SettingsJson, version.ContentHash)) return false; + try + { + return await Client.GetStoredProjectVersionAsync(SequenceId, projectId, version.Id, cancellationToken).ConfigureAwait(false) is { } held + && held.ProjectId == projectId && string.Equals(held.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase); + } + catch (ChronosApiException ex) when (ex is { Status: HttpStatusCode.NotFound, Error.Details: "project" }) + { + return false; + } + }, cancellationToken); + } + + /// The server's stamp of the frames (GET …/projects/frames/stamp): the frames are downloaded again only when it moved. + public Task FramesStampAsync(CancellationToken cancellationToken) => + Reach(async () => (await Client.GetProjectFramesStampAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Stamp, cancellationToken); /// The server numbers the version (head + 1) and records the account that pushed it as its author. public Task PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) @@ -174,6 +212,7 @@ public sealed class ServerProjectHome : IProjectHome (HttpStatusCode.BadRequest, ProjectErrors.InvalidName, _) => new ProjectException(ProjectError.InvalidName, ex.Message), (HttpStatusCode.Conflict, ProjectErrors.NameTaken, _) => new ProjectException(ProjectError.NameTaken, ex.Message), (HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, _) => new ProjectException(ProjectError.MainCannotBeDeleted, ex.Message), + (HttpStatusCode.Conflict, ProjectErrors.SequenceEmpty, _) => new ProjectException(ProjectError.SequenceEmpty, ex.Message), _ => null, }; diff --git a/src/Chronos.Protocol/Client/ChronosClient.cs b/src/Chronos.Protocol/Client/ChronosClient.cs index 72da8b89..9a94633b 100644 --- a/src/Chronos.Protocol/Client/ChronosClient.cs +++ b/src/Chronos.Protocol/Client/ChronosClient.cs @@ -507,7 +507,9 @@ public sealed class ChronosClient : IDisposable /// /// One page of a project's versions: newest first, numbered below (from the head when null), /// or, with , oldest first numbered above it (what a workspace pulls). : - /// 1–200 (the server's default, 50 newest first and 100 oldest first, when null). + /// 1–200 (the server's default, 50 newest first and 100 oldest first, when null). A page may hold fewer versions than + /// asked for while more follow (): the server also ends one before its settings + /// pass a few MiB (?summary=true leaves the settings out, for a list of the versions). /// public Task ListProjectVersionsAsync(Guid sequenceId, Guid projectId, int? before = null, int? after = null, int? limit = null, CancellationToken ct = default) => @@ -515,12 +517,22 @@ public sealed class ChronosClient : IDisposable ProtocolJson.Default.ProjectVersionPageDto, ct); /// A version of the project by id; null when the server has no such version of it. - public async Task GetProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default) + public Task GetProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default) => + VersionOrNullAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}", ct); + + /// + /// A version of the project the server holds durably, read back from its file now with its content hash: what a workspace + /// asks before it drops its own copy. Null when the file is missing or damaged, or the server has no such version; a + /// deleted project is a 404 project . + /// + public Task GetStoredProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default) => + VersionOrNullAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}?stored=true", ct); + + private async Task VersionOrNullAsync(string path, CancellationToken ct) { try { - return await GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}", ProtocolJson.Default.ProjectVersionDto, ct) - .ConfigureAwait(false); + return await GetAsync(path, ProtocolJson.Default.ProjectVersionDto, ct).ConfigureAwait(false); } catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound && ex.Error.Details == "version") { @@ -532,8 +544,8 @@ public sealed class ChronosClient : IDisposable /// Pushes , made in a workspace from the project's head (): /// the server stores it as the new head, numbered head + 1 (201, stored), or answers it again for a repeated push /// (200, already_stored), or refuses it, storing nothing: 409 diverged with the head, 422 - /// hash_mismatch, newer_format, too_large or invalid. These come back as - /// without throwing; any other failure (the sequence or project gone, no permission, the archive offline or the sequence + /// hash_mismatch, newer_format, too_large or invalid; a body larger than the server (or a proxy before + /// it) takes, 413, is too_large too. These come back as without throwing; any other failure (the sequence or project gone, no permission, the archive offline or the sequence /// busy: 503) throws . Safe to repeat: the version's id makes a second push a no-op. /// public async Task PushProjectVersionAsync(Guid sequenceId, Guid projectId, ProjectVersionDto version, CancellationToken ct = default) @@ -556,6 +568,8 @@ public sealed class ChronosClient : IDisposable // Not a push answer (a proxy's page): the status says what failed. } } + if (response.StatusCode == HttpStatusCode.RequestEntityTooLarge) + return new ProjectPushResultDto(ProjectPushOutcomes.TooLarge, null, null, ProjectErrors.TooLarge, response.ReasonPhrase); await EnsureSuccessAsync(response, ct).ConfigureAwait(false); throw new ChronosApiException(response.StatusCode, new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error")); } @@ -564,16 +578,27 @@ public sealed class ChronosClient : IDisposable public Task GetProjectFramesAsync(Guid sequenceId, CancellationToken ct = default) => GetAsync($"api/v1/sequences/{sequenceId}/projects/frames", ProtocolJson.Default.ProjectFramesDto, ct); + /// A cheap stamp of what answers: the frames are read again only when it moved. + public Task GetProjectFramesStampAsync(Guid sequenceId, CancellationToken ct = default) => + GetAsync($"api/v1/sequences/{sequenceId}/projects/frames/stamp", ProtocolJson.Default.ProjectFramesStampDto, ct); + // ---------------- Events ---------------- /// Server events over WebSocket until cancelled; reconnect is the caller's policy. - public async IAsyncEnumerable EventsAsync([EnumeratorCancellation] CancellationToken ct = default) + public IAsyncEnumerable EventsAsync(CancellationToken ct = default) => EventsAsync(null, ct); + + /// + /// Server events over WebSocket until cancelled, calling once the socket is open (before its + /// first event): from then on no event the server sends is missed. + /// + public async IAsyncEnumerable EventsAsync(Action? connected, [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); + connected?.Invoke(); var buffer = new byte[64 * 1024]; using var message = new MemoryStream(); while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested) diff --git a/src/Chronos.Protocol/Projects.cs b/src/Chronos.Protocol/Projects.cs index 5d83c86d..07fe5da5 100644 --- a/src/Chronos.Protocol/Projects.cs +++ b/src/Chronos.Protocol/Projects.cs @@ -87,6 +87,13 @@ public sealed record ProjectPushResultDto(string Outcome, ProjectVersionDto? Ver /// public sealed record ProjectFramesDto(Guid SequenceId, int FramesVersion, IReadOnlyList Frames, IReadOnlyList? Aliases = null); +/// +/// GET /api/v1/sequences/{sid}/projects/frames/stamp: a cheap stamp of what …/projects/frames answers, another +/// value whenever the frames, how their photos are named (a hash learnt) or the encodings conversions joined may have +/// changed, so a workspace reads the frames again only then. +/// +public sealed record ProjectFramesStampDto(Guid SequenceId, string Stamp); + /// What became of a pushed version (). public static class ProjectPushOutcomes { @@ -154,4 +161,10 @@ public static class ProjectErrors /// 409: the Main project holds the sequence's own settings and is never deleted. public const string MainCannotBeDeleted = "main_cannot_be_deleted"; + + /// 409: the sequence has no photo yet (no folder in the archive), so it keeps no projects; its list is empty. + public const string SequenceEmpty = "sequence_empty"; + + /// 413 from a push: the body is larger than the server takes; read as the outcome . + public const string TooLarge = "too_large"; } diff --git a/src/Chronos.Protocol/ProtocolJson.cs b/src/Chronos.Protocol/ProtocolJson.cs index 8372e820..d2e097ae 100644 --- a/src/Chronos.Protocol/ProtocolJson.cs +++ b/src/Chronos.Protocol/ProtocolJson.cs @@ -99,4 +99,5 @@ namespace Chronos.Protocol; [JsonSerializable(typeof(ProjectVersionPageDto))] [JsonSerializable(typeof(ProjectPushResultDto))] [JsonSerializable(typeof(ProjectFramesDto))] +[JsonSerializable(typeof(ProjectFramesStampDto))] public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Chronos.Server/Api/ProjectEndpoints.cs b/src/Chronos.Server/Api/ProjectEndpoints.cs index 4976468f..795084ef 100644 --- a/src/Chronos.Server/Api/ProjectEndpoints.cs +++ b/src/Chronos.Server/Api/ProjectEndpoints.cs @@ -25,13 +25,21 @@ public static class ProjectEndpoints { /// /// The body a push may take: a version's portable settings name each exclusion and camera keyframe by photo (about 150 - /// bytes each), so the project of a large sequence outgrows the 1 MiB of other JSON bodies. + /// bytes each), so the project of a large sequence outgrows the 1 MiB of other JSON bodies. Any version this PC's archive + /// or a workspace stores (a file up to ; the body, with its settings as one + /// JSON string, is no larger) fits, with room for the rest of the version: a server and a PC's archive take the same. /// - public const long PushBodyLimit = 16L * 1024 * 1024; + public const long PushBodyLimit = ProjectSidecars.MaxVersionBytes + (1L << 20); /// Versions one page may hold. public const int MaxPage = 200; + /// + /// The settings one page of versions carries at most (in characters): a page stops before the version that would pass it + /// (one version always goes) and says more follow, so an answer stays a few MiB however large a sequence's versions are. + /// + internal const long PageSettingsChars = 4L << 20; + private const int MaxNote = 2000; private const int MaxClientName = 200; @@ -41,6 +49,7 @@ public static class ProjectEndpoints projects.MapGet("", ListAsync); projects.MapPost("", CreateAsync).Requires(Permissions.Edit); projects.MapGet("/frames", FramesAsync); + projects.MapGet("/frames/stamp", FramesStampAsync); projects.MapGet("/{pid:guid}", GetAsync); projects.MapPatch("/{pid:guid}", RenameAsync).Requires(Permissions.Edit); projects.MapDelete("/{pid:guid}", DeleteAsync).Requires(Permissions.Delete); @@ -53,15 +62,16 @@ public static class ProjectEndpoints /// /// The sequence's live projects, Main first, each with its head's kind, author, client and time. A sequence without a Main /// project gets it now, from its settings; while that cannot be done (the archive offline, the sequence busy, its folder - /// elsewhere) the answer is 503 with the reason's code. + /// elsewhere) the answer is 503 with the reason's code. A sequence with no photo yet (no folder in the archive) has none: + /// the list is empty, and nothing is written. /// private static async Task ListAsync(HttpContext context, Guid sid, ChronosDatabase db, [FromServices] ArchiveService? archives) => await RunAsync(context, "project", async ct => { - if (await db.Sequences.GetAsync(sid, ct) is null) return ApiErrors.NotFound(context, "sequence"); + if (await db.Sequences.GetAsync(sid, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); var projects = LibraryEndpoints.Engine(archives, db).Projects; var list = await projects.ListAsync(sid, ct); - if (!list.Any(p => p.IsMain)) + if (!list.Any(p => p.IsMain) && !string.IsNullOrEmpty(sequence.Folder)) { await projects.MainAsync(sid, ct); list = await projects.ListAsync(sid, ct); @@ -73,8 +83,8 @@ public static class ProjectEndpoints /// /// A new project (201): its first version, kind imported, copies fromVersionId (a version of any project of the - /// sequence; 404 not_found version otherwise) or Main's head. 400 invalid_name, 409 name_taken. - /// Audited project_created. + /// sequence; 404 not_found version otherwise) or Main's head. 400 invalid_name, 409 name_taken, + /// sequence_empty (no photo yet). Audited project_created. /// private static async Task CreateAsync(HttpContext context, Caller caller, Guid sid, CreateProjectRequest request, ChronosDatabase db, [FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) => @@ -136,7 +146,7 @@ public static class ProjectEndpoints var project = known.Project!; if (project.DeletedAt is not null) return ApiErrors.NotFound(context, "project"); if (project.IsMain) return ApiErrors.Conflict(context, ProjectErrors.MainCannotBeDeleted); - if (!caller.IsAdmin && known.Sequence!.OwnerUserId != caller.Id && project.CreatedBy != caller.User.Username) return ApiErrors.Forbidden(context); + if (!caller.IsAdmin && known.Sequence!.OwnerUserId != caller.Id && !MadeBy(project, caller.User)) return ApiErrors.Forbidden(context); await projects.DeleteAsync(pid, lifetime.ApplicationStopping); await audit.WriteAsync(caller, context, "project_deleted", "project", pid.ToString(), $"{sid} · {project.Name}"); return Results.NoContent(); @@ -159,9 +169,11 @@ public static class ProjectEndpoints /// /// One page of the project's versions: newest first, numbered below (from the head when absent), /// or with oldest first, numbered above it. 1– (50 newest - /// first, 100 oldest first). 400 bad_request (after with before, a number below 0). + /// first, 100 oldest first); a page also ends before its settings pass , with more. + /// : the versions without their settings (settingsJson empty), what a list of them shows. + /// 400 bad_request (after with before, a number below 0). /// - private static async Task VersionsAsync(HttpContext context, Guid sid, Guid pid, int? before, int? after, int? limit, ChronosDatabase db, + private static async Task VersionsAsync(HttpContext context, Guid sid, Guid pid, int? before, int? after, int? limit, bool? summary, ChronosDatabase db, [FromServices] ArchiveService? archives) { if (before is not null && after is not null) return ApiErrors.BadRequest(context, "bad_request", "after"); @@ -178,26 +190,41 @@ public static class ProjectEndpoints : await projects.HistoryAsync(pid, before, take + 1, ct); // The head as the page was read: the call above caught the project up first. var head = (await projects.GetAsync(pid, ct))?.HeadNumber ?? known.Project!.HeadNumber; - return Results.Json(new ProjectVersionPageDto([.. page.Take(take).Select(ProjectWire.ToDto)], head, page.Count > take), - ProtocolJson.Default.ProjectVersionPageDto); + var items = new List(Math.Min(take, page.Count)); + var chars = 0L; + foreach (var version in page.Take(take)) + { + if (summary != true && items.Count > 0 && chars + version.SettingsJson.Length > PageSettingsChars) break; + chars += version.SettingsJson.Length; + var dto = ProjectWire.ToDto(version); + items.Add(summary == true ? dto with { SettingsJson = string.Empty } : dto); + } + return Results.Json(new ProjectVersionPageDto(items, head, page.Count > items.Count), ProtocolJson.Default.ProjectVersionPageDto); }); } - /// A version of the project by id; one the index does not know yet is looked for in the sequence's sidecars first. - private static async Task VersionAsync(HttpContext context, Guid sid, Guid pid, Guid vid, ChronosDatabase db, [FromServices] ArchiveService? archives) => + /// + /// A version of the project by id; one the index does not know yet is looked for in the sequence's sidecars first. With + /// , only a version the archive holds durably (: its + /// file read back now, with that content hash) of a live project: what a workspace asks before it drops its own copy; + /// 404 project for a deleted project, version for a file missing or damaged. + /// + private static async Task VersionAsync(HttpContext context, Guid sid, Guid pid, Guid vid, bool? stored, ChronosDatabase db, + [FromServices] ArchiveService? archives) => await RunAsync(context, "version", async ct => { var projects = LibraryEndpoints.Engine(archives, db).Projects; var known = await KnownAsync(context, db, projects, sid, pid, ct); if (known.Refused is { } refused) return refused; + if (stored == true && known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project"); if (await projects.GetVersionAsync(vid, ct) is not { } version) { await projects.ListAsync(sid, ct); version = await projects.GetVersionAsync(vid, ct); } - return version is not null && version.ProjectId == pid - ? Results.Json(ProjectWire.ToDto(version), ProtocolJson.Default.ProjectVersionDto) - : ApiErrors.NotFound(context, "version"); + if (version is null || version.ProjectId != pid || (stored == true && !await projects.StoredAsync(pid, version, ct))) + return ApiErrors.NotFound(context, "version"); + return Results.Json(ProjectWire.ToDto(version), ProtocolJson.Default.ProjectVersionDto); }); /// @@ -271,6 +298,30 @@ public static class ProjectEndpoints ProtocolJson.Default.ProjectFramesDto); } + /// + /// A cheap stamp of what answers (: the frames + /// version, the photos hashed and their checksum, the removals): a workspace reads the frames again only when it moved. + /// + private static async Task FramesStampAsync(HttpContext context, Guid sid, ChronosDatabase db) + { + try + { + return Results.Json(new ProjectFramesStampDto(sid, await ArchiveProjectHome.StampOfAsync(db, sid, context.RequestAborted)), + ProtocolJson.Default.ProjectFramesStampDto); + } + catch (ProjectException) + { + return ApiErrors.NotFound(context, "sequence"); + } + } + + /// + /// Whether made : the name it records, by an account that existed when + /// the project was made. An account made since under the name of a deleted one is not its maker. + /// + internal static bool MadeBy(SequenceProject project, User user) => + project.CreatedBy is { } maker && string.Equals(maker, user.Username, StringComparison.Ordinal) && user.Created <= project.CreatedAt; + /// Every frame of a sequence in index order, read a page at a time. internal static async Task> AllFramesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken) { @@ -308,7 +359,7 @@ public static class ProjectEndpoints /// /// Runs a project call with its refusals answered by their codes: 404 not_found (sequence, or /// for a project or version the engine does not know), 400 invalid_name, 409 - /// name_taken, main_cannot_be_deleted; 503 archive_offline (offline or read-only), sequence_busy + /// name_taken, main_cannot_be_deleted, sequence_empty; 503 archive_offline (offline or read-only), sequence_busy /// (another writer held it past the lease wait), folder_moved (its folder is not where the index has it), /// projects_unreadable (a project record or version this Chronos cannot read now: nothing was written); 413 /// too_large for a version file over 64 MiB; 409 folder_in_use when a project's file cannot be written. @@ -327,6 +378,7 @@ public static class ProjectEndpoints ProjectError.InvalidName => ApiErrors.BadRequest(context, ProjectErrors.InvalidName), ProjectError.NameTaken => ApiErrors.Conflict(context, ProjectErrors.NameTaken), ProjectError.MainCannotBeDeleted => ApiErrors.Conflict(context, ProjectErrors.MainCannotBeDeleted), + ProjectError.SequenceEmpty => ApiErrors.Conflict(context, ProjectErrors.SequenceEmpty), _ => ApiErrors.NotFound(context, notFound), }; } diff --git a/src/Chronos.Server/Api/SequenceEndpoints.cs b/src/Chronos.Server/Api/SequenceEndpoints.cs index ecac5cff..e85a2973 100644 --- a/src/Chronos.Server/Api/SequenceEndpoints.cs +++ b/src/Chronos.Server/Api/SequenceEndpoints.cs @@ -25,6 +25,9 @@ public static class SequenceEndpoints { private const int MaxTitle = 200; private const int MaxNotes = 2000; + + /// How long a settings edit waits for the sequence's lease (another writer filing photos or analysing it) before it answers 503 sequence_busy. + private static readonly TimeSpan SettingsLeaseWait = TimeSpan.FromSeconds(20); /// Tags a sequence may carry. internal const int MaxTags = 50; @@ -128,8 +131,15 @@ public static class SequenceEndpoints return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto); } + /// + /// Edits a sequence's title, tags, rating, notes and settings in the index (the settings version as an optional check). New + /// settings also go to the sequence's project.json, under its lease (), + /// as the archive's other writers of the settings do, so the projects never take an older file for the sequence's + /// settings (owner review 2, R8): 503 archive_offline, sequence_busy or folder_moved, and 409 + /// folder_in_use, when that cannot be done now, with nothing changed. + /// private static async Task UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, ChronosDatabase db, - AuditLog audit, EventHub events, ProjectCatchUp projects) + AuditLog audit, EventHub events, ProjectCatchUp projects, [FromServices] ArchiveService? archives) { if (request.Title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title"); if (request.Notes is { Length: > MaxNotes }) return ApiErrors.BadRequest(context, "bad_request", "notes"); @@ -150,7 +160,39 @@ public static class SequenceEndpoints HeroFrameId = request.HeroFrameId ?? (request.SettingsJson is { } settings ? await SettingsHeroAsync(db, id, settings, context.RequestAborted) : null), }; - var result = await db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, context.RequestAborted); + SequenceEditResult result; + if (request.SettingsJson is { } written && archives is not null) + { + try + { + result = await archives.EditSettingsAsync(id, written, ct => db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, ct), + SettingsLeaseWait, context.RequestAborted); + } + catch (ArgumentException) + { + return ApiErrors.NotFound(context, "sequence"); + } + catch (Chronos.Core.Archiving.ArchiveOfflineException) + { + return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"); + } + catch (Chronos.Core.Archiving.LeaseUnavailableException) + { + return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "sequence_busy"); + } + catch (SequenceFolderMovedException) + { + return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "folder_moved"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return ApiErrors.Conflict(context, "folder_in_use"); + } + } + else + { + result = await db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, context.RequestAborted); + } switch (result.Outcome) { case SequenceEditOutcome.NotFound: