feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings #18
No files matched your search
@@ -61,7 +61,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` |
|
||||
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index, `ArchiveSettings.CheckTemplates` and `TemplateRuleException` holding a template given anew to the template rules; `UnderLeaseAsync`: a write under a sequence's lease with its row read under it), `ArchiveIndexer` (scan, rebuild; a sequence found in another folder takes its exports' paths along; a full scan or a rebuild takes the projects' sidecars back too), `ArchiveIngest` (uploads and imports, named through `FrameNaming`; content a conversion replaced is a duplicate of the frame holding its conversion; a restore or a replacement not settled yet refuses the batch), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance` (also a conversion job's staging and journals, by the job's state; those of a job this index does not know go together, by age), `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from when it changes it or names the folder or files after it), then the folder, with the sequences of the plan an earlier step left as they were inside it (taken along, their title and file names kept), every index row (the frame paths and render paths of the exports inside it, a file or an image-sequence folder, its own unless the export is still at the old place and another sequence's when it moved with it, follow it in one transaction; a sidecar that cannot be read or written then still has its row follow, and fails the step), then the files under the plan's journal in `journal/` (a sequence whose photos changed since, such as one still receiving them, or whose files are found changed or in use or have their new names taken keeps its file names, the renames being pinned by digest, and the step and the plan go on); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open, which completes any other plan an interruption left and tells each sequence changed; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceFolders` (`Holds`: the folder the index has for a sequence is there and its sidecar names no other sequence; every writer into a sequence's folder asks it), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease, `TrashKept` with its `TrashKeptReason` for each entry kept; `SequenceTrash.Replaced`: where a replaced entry's conversions are, read from the archive's sidecars (in the index's or the entry's folder, in the trash, else by one `SidecarWalk` of the archive per dry run or emptying) through their replaced tombstones, a conversion deleted only on the archive's word (a tombstone, the trash, or an `ErasureRecord` in `trash/.erased/`, written when an emptying erases a deleted sequence a replaced entry still needs), `TrashEntry.ConversionDeleted` in the dry run and its fingerprint, the erase weighed under the entry's and the sequence's leases once the sequence is settled; `BusyAsync`: what running and paused jobs hold, but the job asking, from `JobRepository.ListHoldsAsync`), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed; a replaced entry swaps back while its converted frames are unchanged (`SwapBackAsync`); `FLine truncated
|
||||
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers |
|
||||
| `Projects` | `ProjectService` (`ArchiveService.Projects`: the projects of this PC's sequences as a home, under the sequence's lease and only in a folder that holds the sequence (`SequenceFolders.Holds`; otherwise `SequenceFolderMovedException`: reads answer from the index, writes are refused); reads wait 3 s for the lease, then answer from the index; a read-only archive is read without writing (an index-only Main written back once it takes writes): list, create, rename, delete (the folder into `projects/.trash` first, then the deleted record; never Main), history, head (NotFound once deleted), `StoredAsync` (a version file read back and checked), push with fast-forward / idempotent repeat / divergence / hash, portability, strict format and 64 MiB checks; each call first catches up: the sidecars into the index, Main made from the sequence's settings, settings another path wrote appended to Main as an `external` version or, with a push whose mirror was cut short, merged into one `merge` version where they win, a mirror never written over `project.json` settings it has not taken in (`MovedSharedAsync`), records behind the index healed (`HealAsync`, `UpdatedAfter`), projects the archive lost written back (`WriteBackAsync`); a push to Main mirrored into `project.json` and the settings with the settings version check), `ProjectIndexer` (the reconcile, also run by full scans and rebuilds: the projects' trash read before the live folders, so a deletion wins and the live folder's late version files move beside it; a record that cannot be read held back, never taken for a deletion; a lost record written again from the index only once its folder settled (`RecordSettle`, 2 minutes) and no trash folder holds it back (`TrashRecordGrace`, 1 day); a creation cut before its record left as it is; a version file a push left past its record adopted, a stray one moved to `versions/.stray`; `BehindAsync`, one rule for a record behind the index; `SettleMainAsync` and `SwapMainAsync`, one Main from the records, passed in one transaction), `ProjectSidecars` (record and immutable version files, the settings as a JSON string checked against their hash, `MaxVersionBytes` 64 MiB refused before writing), `ProjectMerge` (three-way merge member by member, pending frames merged photo by photo, conflicts, `Replay` of local commits on a moved head; `NewerSettingsException` rather than merge a newer format), `IProjectHome` and `ArchiveProjectHome` (the home a workspace pushes to and pulls from: `HoldsAsync` reads a version back, `FramesStampAsync` says when the frames changed, an offline archive or busy lease is `HomeUnavailableException`; the server's comes in phase 5b), `HomePhotos` (a sequence's photos as positions name them, with the encodings its Replaced tombstones join) |
|
||||
| `Projects` | `ProjectService` (`ArchiveService.Projects`: the projects of this PC's sequences as a home, under the sequence's lease and only in a folder that holds the sequence (`SequenceFolders.Holds`; otherwise `SequenceFolderMovedException`: reads answer from the index, writes are refused); reads wait 3 s for the lease, then answer from the index; a read-only archive is read without writing (an index-only Main written back once it takes writes): list, create, rename, delete (the folder into `projects/.trash` first, then the deleted record; never Main), history, head (NotFound once deleted), `StoredAsync` (a version file read back and checked), push with fast-forward / idempotent repeat / divergence / hash, portability, strict format and 64 MiB checks; each call first catches up: the sidecars into the index, Main made from the sequence's settings, settings another path wrote appended to Main as an `external` version or, with a push whose mirror was cut short, merged into one `merge` version where they win, a mirror never written over `project.json` settings it has not taken in (`MovedSharedAsync`), records behind the index healed (`HealAsync`, `UpdatedAfter`), projects the archive lost written back (`WriteBackAsync`); a push to Main mirrored into `project.json` and the settings with the settings version check), `ProjectIndexer` (the reconcile, also run by full scans and rebuilds: the projects' trash read before the live folders, so a deletion wins and the live folder's late version files move beside it; a record that cannot be read held back, never taken for a deletion; a lost record written again from the index only once its folder settled (`RecordSettle`, 2 minutes) and no trash folder holds it back (`TrashRecordGrace`, 1 day); a creation cut before its record left as it is; a version file a push left past its record adopted, a stray one moved to `versions/.stray`; `BehindAsync`, one rule for a record behind the index; `SettleMainAsync` and `SwapMainAsync`, one Main from the records, passed in one transaction), `ProjectSidecars` (record and immutable version files, the settings as a JSON string checked against their hash, `MaxVersionBytes` 64 MiB refused before writing), `ProjectMerge` (three-way merge member by member, pending frames merged photo by photo, conflicts, `Replay` of local commits on a moved head; `NewerSettingsException` rather than merge a newer format), `IProjectHome` and `ArchiveProjectHome` (the home a workspace pushes to and pulls from: `HoldsAsync` reads a version back, `FramesStampAsync` says when the frames changed, an offline archive or busy lease is `HomeUnavailableException`; a server is the other home, phase 5b), `HomePhotos` (a sequence's photos as positions name them, with the encodings its Replaced tombstones join; the server's frames endpoint and render nodes build the same), what each call changed (`ProjectChangeSet` to `ArchiveServiceOptions.ProjectsChanged`, once the lease is let go: projects made, renamed, deleted or with a new head, compared before and after under the lease, and whether Main's head was written into the sequence's settings), `CatchUpAsync` (the catch-up alone, saying why it cannot run), `ProjectWire` (projects, versions, push outcomes and a home's frames to and from API v1 DTOs, for the server and a client of it) |
|
||||
| `Workspaces` | `WorkspaceStore` (a folder outside the library: `workspace.json` written atomically, one folder per project, no index; a leftover folder holding only stale lease files removed on listing), `WorkspaceProject` (`project.chronos` working state, `media/` with `media.json`, `proxies/<frame id>.jpg` (and `<frame id>-<sha16>.jpg` while a copy replaces one) and `analysis.json`, `versions/` with `.replaced` (versions set aside, pruned by age and count) and `.replaced.since`, `sync.json` for a conflict, a restore or the journal of a replay or a Save both, `exports/`, the lease `.lock.lease`; `UnreadableVersions`), `WorkspaceMedia` (`NamedAsAt`: the media learn the home's hashes and aliases), `WorkspaceSync` (checkout, open under the lease, save, commit, push, pull with replay and merge, the base in `project.chronos` as every write's commit point, `SettleAsync` finishing or undoing a cut push, replay or Save both, conflicts settled by keep mine, take server or save both only as shown, restore, status with Gone, Damaged and `MediaOutdated`, the home's frames read again only when their stamp moved), `WorkspaceCopyJobHandler` (`WorkspaceJobs.Copy` and `CopyFactsAsync`, registered by the desktop only: the archive only read, from a folder that holds the sequence; a workspace inside a library refused; the archive's current proxies copied, the others made in the workspace, each hash-verified, resumable from a checkpoint of its frames version and folder, free space checked against its estimate plus 512 MiB; the encodings conversions joined kept in `media.json`; the working state's positions moved by frame where frames stay, by photo where they came or went; a cancelled first copy's media cleared under the project's lease only when no other copy of the project waits or runs, through `ICancelledJobHandler` too) |
|
||||
| `Sync` | `SyncService` (sync table of one server: compare, link by content through the aliases, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, the proxies this PC can send, aliases followed; no I/O), `SyncTombstones` (photos either side removed are not offered back; the replaced tombstones of both sides join the encodings of one photo, union-find, each compared as the smallest SHA-256 among them, a deletion covering them all; immutable once made), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest, and a frame missing here whose photo the server holds in another encoding takes that file through `FrameTrash.ReplaceMissingAsync`; job log lines from the catalog), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) |
|
||||
|
||||
@@ -89,10 +89,10 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost` (`Toast.Closed` once a toast leaves the screen), `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
|
||||
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
|
||||
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
|
||||
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty (`conversionDeleted` in its dry run); `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, Convert's dry run and `convert` job, both through `PlanCache`: a dry run's plan, made apart from its request, a few at once across both kinds, kept a few minutes while what it reads from the index stays (typed keys `PlanKey<TPlan>`: `ReorganizePlanKey`, `ConvertPlanKey` from `GetConvertStampAsync`, the selection and the target with the quality that counts, not the mode), for the same dry run and its confirmation; a conversion's confirmation takes only a kept plan (`Kept`), its busy sequences and free space taken again), API errors, the WebSocket `EventHub` |
|
||||
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty (`conversionDeleted` in its dry run); `ProjectEndpoints`: `/api/v1/sequences/{sid}/projects` through the archive's `ProjectService` (list with Main first, create, rename, delete, head, versions a page at a time, one version, push with its outcome as `ProjectPushResultDto`, the frames and photo aliases a workspace places positions on); `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, Convert's dry run and `convert` job, both through `PlanCache`: a dry run's plan, made apart from its request, a few at once across both kinds, kept a few minutes while what it reads from the index stays (typed keys `PlanKey<TPlan>`: `ReorganizePlanKey`, `ConvertPlanKey` from `GetConvertStampAsync`, the selection and the target with the quality that counts, not the mode), for the same dry run and its confirmation; a conversion's confirmation takes only a kept plan (`Kept`), its busy sequences and free space taken again), API errors, the WebSocket `EventHub` |
|
||||
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
|
||||
| `Server/Storage`, `Server/Jobs` | Archive and processing modules (the archive module's `SequenceChanged` publishes `sequenceChanged` `reorganized`, `converted` and `created`; its `FreeSpace` is `VolumeSpace.WritableFree`, the tighter of the space path's volume and the folder's own), uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step; `UploadService.ReceiveAgainAsync`: a verified upload whose filing was refused for now goes back to receiving, 503), render store (files a render under the sequence's lease, where the index has the folder then; `FolderMovedException`, 503 `folder_moved`, when the sequence is not in it); `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
|
||||
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back; `convert.js` the Convert dialog of the Library's selection (`planTarget` in `library.js`, shared with Reorganize: the ids, at most 1,000, or `all`): format, JPEG quality and a mode chosen at every run (Replace or New sequence, never preselected), a debounced dry run of `POST /archive/convert` one request at a time, asked in Replace's words until a mode is chosen and again while the server is still making it (a proxy's cut-off, `plan_dropped`), per sequence photos converted, left as they are or not copied and why, blocked, size before and after, the space line; Apply that confirms Replace by a typed word and New sequence with the photos not copied, asks the dry run again and sends the shown plan's fingerprint back, never twice after no answer; `pages/library/trash.js` gives replaced entries their own Restore and lists those whose conversion was deleted first; `audit.js` reads `archive_converted` as a sentence) |
|
||||
| `Server/Storage`, `Server/Jobs` | Archive and processing modules (the archive module's `SequenceChanged` publishes `sequenceChanged` `reorganized`, `converted` and `created`; its `FreeSpace` is `VolumeSpace.WritableFree`, the tighter of the space path's volume and the folder's own), uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step; `UploadService.ReceiveAgainAsync`: a verified upload whose filing was refused for now goes back to receiving, 503), render store (files a render under the sequence's lease, where the index has the folder then, with the project and version a node's job rendered; `FolderMovedException`, 503 `folder_moved`, when the sequence is not in it); `ProjectCatchUp` (Main takes settings written outside the projects soon after a `PATCH`, an analysis or a conversion, for sequences with a Main: `projectChanged` without waiting for the next project call); the archive module's `ProjectsChanged`, published as `projectChanged` (and `sequenceChanged` `settings` when Main was mirrored); `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service (a job of a project version claimed with that version's settings placed on the frames it lists), monitor and availability |
|
||||
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `projects.js` its Projects section (Main marked, head and last change, versions on demand, Rename and Delete of the others, live on `projectChanged`; nothing that edits settings), `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back; `convert.js` the Convert dialog of the Library's selection (`planTarget` in `library.js`, shared with Reorganize: the ids, at most 1,000, or `all`): format, JPEG quality and a mode chosen at every run (Replace or New sequence, never preselected), a debounced dry run of `POST /archive/convert` one request at a time, asked in Replace's words until a mode is chosen and again while the server is still making it (a proxy's cut-off, `plan_dropped`), per sequence photos converted, left as they are or not copied and why, blocked, size before and after, the space line; Apply that confirms Replace by a typed word and New sequence with the photos not copied, asks the dry run again and sends the shown plan's fingerprint back, never twice after no answer; `pages/library/trash.js` gives replaced entries their own Restore and lists those whose conversion was deleted first; `audit.js` reads `archive_converted` as a sentence) |
|
||||
|
||||
### 2.5 Hosts
|
||||
|
||||
@@ -113,7 +113,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Thumbs`, `Proxies` | `Archiving/Jobs/ImageJobHandler` | yes | yes |
|
||||
| `Maintenance` | `Archiving/Jobs/MaintenanceJobHandler` | yes | yes |
|
||||
| `LightAnalyse`, `DeepAnalyse` | `Processing/Jobs/AnalyseJobHandler` (via `ProcessingService.CreateJobHandlers`) | yes | yes |
|
||||
| `Render` | `Processing/Jobs/RenderJobHandler` (a project version's portable settings placed on the frames first, the render recording the project and the version) | yes | managed formats, and MP4 jobs no render node can take (`RenderNodeAvailability`); render nodes claim the others (`Server/Jobs/RenderNodeService`) |
|
||||
| `Render` | `Processing/Jobs/RenderJobHandler` (a project version's portable settings placed on the frames first, the render recording the project and the version) | yes | managed formats, and MP4 jobs no render node can take (`RenderNodeAvailability`); render nodes claim the others (`Server/Jobs/RenderNodeService`, which places a project version's settings on the frames it sends, and records the project and version with the result); `POST /jobs` checks a job's project and version against the sequence and pins a project alone to its head |
|
||||
| `UploadCommit`, `Download` | `Sync/SyncJobHandler` (via `SyncService.CreateJobHandlers`): this PC's uploads to and downloads from its server | yes | no: an upload completes synchronously on the server |
|
||||
| `Duplicates`, `Orphans` | `Archiving/Jobs/ReportJobHandlers` (read-only reports into the job log, queued by schedules); the Archive screen still queries `ArchiveService` directly | yes | yes |
|
||||
| `Backup` | `Housekeeping/BackupJobHandler` (via `ArchiveService.CreateJobHandlers`; an SQLite index file only) | yes | SQLite only |
|
||||
@@ -174,7 +174,7 @@ its sidecar the sequence's (`SequenceFolders.Holds`, `SequenceWriter.ReadLocked`
|
||||
into the trash, never away. Its journals in `journal/` (`convert-<job>.json`, `.staged`, `.pins`, `.photos`) tell a resume, and
|
||||
another host's maintenance, what the job did.
|
||||
|
||||
Projects (owner review 2, R8): a sequence's home (this PC's archive; a server in phase 5b) keeps its projects as sidecars, then
|
||||
Projects (owner review 2, R8): a sequence's home (this PC's archive, or a server through `/api/v1/sequences/{sid}/projects`, phase 5b) keeps its projects as sidecars, then
|
||||
index rows. A workspace on a fast disk checks a project out (its head as the base, the proxies copied by a `WorkspaceCopy`
|
||||
job), edits the working state, saves versions locally (portable settings, positions parked by photo) and pushes them in
|
||||
order: a push whose parent is the head fast-forwards; otherwise the home's new versions are pulled, each local version is
|
||||
|
||||
@@ -499,6 +499,48 @@
|
||||
<data name="Admin.Password.Save" xml:space="preserve"><value>Change password</value></data>
|
||||
<data name="Admin.Password.Save.Tip" xml:space="preserve"><value>Replace the password and continue to the panel</value></data>
|
||||
<data name="Admin.Password.Title" xml:space="preserve"><value>Choose a new password</value></data>
|
||||
<data name="Admin.Projects.Changed" xml:space="preserve"><value>Last change</value></data>
|
||||
<data name="Admin.Projects.Count.one" xml:space="preserve"><value>{0} project</value></data>
|
||||
<data name="Admin.Projects.Count.other" xml:space="preserve"><value>{0} projects</value></data>
|
||||
<data name="Admin.Projects.Current" xml:space="preserve"><value>Newest</value></data>
|
||||
<data name="Admin.Projects.Current.Tip" xml:space="preserve"><value>The project's newest version, the one a workspace takes</value></data>
|
||||
<data name="Admin.Projects.Delete" xml:space="preserve"><value>Delete…</value></data>
|
||||
<data name="Admin.Projects.Delete.Tip" xml:space="preserve"><value>Move this project and its versions into the sequence's project trash</value></data>
|
||||
<data name="Admin.Projects.DeleteBody" xml:space="preserve"><value>The project and its versions ({0}) move into the sequence's project trash; nothing is erased.</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.DeleteConfirm" xml:space="preserve"><value>Delete project</value></data>
|
||||
<data name="Admin.Projects.DeleteConfirm.Tip" xml:space="preserve"><value>Move the project and its versions into the project trash; nothing is erased</value></data>
|
||||
<data name="Admin.Projects.DeleteTitle" xml:space="preserve"><value>Delete {0}?</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.Deleted" xml:space="preserve"><value>{0} deleted.</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.Empty" xml:space="preserve"><value>No projects yet</value></data>
|
||||
<data name="Admin.Projects.Head" xml:space="preserve"><value>Version</value></data>
|
||||
<data name="Admin.Projects.Head.Tip" xml:space="preserve"><value>The project's newest version</value></data>
|
||||
<data name="Admin.Projects.Kind.Commit" xml:space="preserve"><value>Saved</value></data>
|
||||
<data name="Admin.Projects.Kind.Commit.Tip" xml:space="preserve"><value>Saved in a workspace on a PC</value></data>
|
||||
<data name="Admin.Projects.Kind.External" xml:space="preserve"><value>Outside change</value></data>
|
||||
<data name="Admin.Projects.Kind.External.Tip" xml:space="preserve"><value>Settings written outside the projects: an older Chronos, an analysis, a desktop's sync or a conversion</value></data>
|
||||
<data name="Admin.Projects.Kind.Imported" xml:space="preserve"><value>Imported</value></data>
|
||||
<data name="Admin.Projects.Kind.Imported.Tip" xml:space="preserve"><value>The project's first version, from the settings it was made from</value></data>
|
||||
<data name="Admin.Projects.Kind.Merge" xml:space="preserve"><value>Merged</value></data>
|
||||
<data name="Admin.Projects.Kind.Merge.Tip" xml:space="preserve"><value>Changes made on two PCs, merged setting by setting</value></data>
|
||||
<data name="Admin.Projects.Kind.Restore" xml:space="preserve"><value>Restored</value></data>
|
||||
<data name="Admin.Projects.Kind.Restore.Tip" xml:space="preserve"><value>An earlier version brought back</value></data>
|
||||
<data name="Admin.Projects.Main" xml:space="preserve"><value>Main</value></data>
|
||||
<data name="Admin.Projects.Main.Tip" xml:space="preserve"><value>The sequence's own settings: renders and older Chronos versions use them, and it is never deleted</value></data>
|
||||
<data name="Admin.Projects.Name" xml:space="preserve"><value>Project</value></data>
|
||||
<data name="Admin.Projects.NameInvalid" xml:space="preserve"><value>Type a name of 1 to 60 characters.</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.NewName" xml:space="preserve"><value>Name</value></data>
|
||||
<data name="Admin.Projects.NewName.Tip" xml:space="preserve"><value>1 to 60 characters, not used by another project of this sequence</value></data>
|
||||
<data name="Admin.Projects.NoVersions" xml:space="preserve"><value>No versions yet</value></data>
|
||||
<data name="Admin.Projects.Number" xml:space="preserve"><value>Version {0}</value></data>
|
||||
<data name="Admin.Projects.Rename" xml:space="preserve"><value>Rename…</value></data>
|
||||
<data name="Admin.Projects.Rename.Tip" xml:space="preserve"><value>Give this project another name</value></data>
|
||||
<data name="Admin.Projects.RenameConfirm" xml:space="preserve"><value>Rename</value></data>
|
||||
<data name="Admin.Projects.RenameConfirm.Tip" xml:space="preserve"><value>Save the new name</value></data>
|
||||
<data name="Admin.Projects.RenameTitle" xml:space="preserve"><value>Rename {0}</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.Renamed" xml:space="preserve"><value>Renamed to {0}.</value><comment>long</comment></data>
|
||||
<data name="Admin.Projects.Title" xml:space="preserve"><value>Projects</value></data>
|
||||
<data name="Admin.Projects.Versions.Tip" xml:space="preserve"><value>Show or hide this project's versions</value></data>
|
||||
<data name="Admin.Projects.VersionsOf" xml:space="preserve"><value>Versions of {0}</value><comment>long</comment></data>
|
||||
<data name="Admin.Reorganize.Action" xml:space="preserve"><value>Reorganize…</value></data>
|
||||
<data name="Admin.Reorganize.Action.Tip" xml:space="preserve"><value>Apply folder, file and title templates to the selected sequences; a preview shows every change first</value></data>
|
||||
<data name="Admin.Reorganize.After" xml:space="preserve"><value>After:</value></data>
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
<data name="Server.Error.InvalidFilter" xml:space="preserve"><value>A filter value is not valid.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidHash" xml:space="preserve"><value>The SHA-256 must be 64 hexadecimal characters.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidJobKind" xml:space="preserve"><value>This job kind cannot be started here.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidName" xml:space="preserve"><value>A project name has 1 to 60 characters and no control characters.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidParameters" xml:space="preserve"><value>The job parameters are not valid.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidPriority" xml:space="preserve"><value>The priority must be background, normal or user.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidProxy" xml:space="preserve"><value>The proxy is not a JPEG the server can read.</value><comment>long</comment></data>
|
||||
@@ -70,12 +71,16 @@
|
||||
<data name="Server.Error.InvalidState" xml:space="preserve"><value>The job cannot do that in its current state.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidTemplate" xml:space="preserve"><value>The naming template is not valid.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidUsername" xml:space="preserve"><value>Use letters, digits, dot, dash or underscore.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.InvalidVersion" xml:space="preserve"><value>The version is not one of this project: its positions are not by photo, or its id is another version's.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.JobNotAssigned" xml:space="preserve"><value>This job is no longer assigned to this node.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.JobUnavailable" xml:space="preserve"><value>This server cannot run that kind of job.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.LastAdmin" xml:space="preserve"><value>The last administrator cannot be removed or disabled.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.MainCannotBeDeleted" xml:space="preserve"><value>The Main project holds the sequence's own settings and is never deleted.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.MethodNotAllowed" xml:space="preserve"><value>This method is not allowed here.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NameTaken" xml:space="preserve"><value>Another project of this sequence has that name.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NestedTarget" xml:space="preserve"><value>A new folder would lie inside the folder of another sequence.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotChronosAt" xml:space="preserve"><value>No Chronos server answers at {0}; check the port (the admin panel's Settings › Network and TLS shows the client address).</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NewerFormat" xml:space="preserve"><value>The version was made by a newer Chronos; update the server to keep it.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotEnoughSpace" xml:space="preserve"><value>The archive's volume lacks the space the conversion needs.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotChronos" xml:space="preserve"><value>That address is not a Chronos Server.</value><comment>long</comment></data>
|
||||
@@ -85,6 +90,8 @@
|
||||
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>{0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PlanChanged" xml:space="preserve"><value>The archive changed after the dry run; review the plan again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PlanDropped" xml:space="preserve"><value>The server stopped making this plan: it took too long, or too many were asked at once; try again shortly.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProjectDiverged" xml:space="preserve"><value>The project has newer versions on the server; take them, then send yours again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProjectsUnreadable" xml:space="preserve"><value>A project of this sequence cannot be read now; nothing was changed. Try again shortly.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>This page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to CHRONOS_TRUSTED_PROXIES.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxiesDisabled" xml:space="preserve"><value>This archive makes no proxies.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxyMismatch" xml:space="preserve"><value>The proxy was made from another photo.</value><comment>long</comment></data>
|
||||
@@ -114,6 +121,7 @@
|
||||
<data name="Server.Error.Untrusted" xml:space="preserve"><value>The certificate was not trusted, so nothing was sent.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.UploadState" xml:space="preserve"><value>This upload is not accepting that request now.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.UsernameTaken" xml:space="preserve"><value>That user name is taken.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.VersionHashMismatch" xml:space="preserve"><value>The version arrived damaged; send it again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.WeakPassword" xml:space="preserve"><value>Use at least {0} characters.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.WebsocketRequired" xml:space="preserve"><value>Connect with a WebSocket.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.WouldEmpty" xml:space="preserve"><value>Every photo of the sequence would go; delete the sequence instead.</value><comment>long</comment></data>
|
||||
|
||||
@@ -493,6 +493,48 @@
|
||||
<data name="Admin.Password.Save" xml:space="preserve"><value>Cambia password</value></data>
|
||||
<data name="Admin.Password.Save.Tip" xml:space="preserve"><value>Sostituisci la password e continua nel pannello</value></data>
|
||||
<data name="Admin.Password.Title" xml:space="preserve"><value>Scegli una nuova password</value></data>
|
||||
<data name="Admin.Projects.Changed" xml:space="preserve"><value>Ultima modifica</value></data>
|
||||
<data name="Admin.Projects.Count.one" xml:space="preserve"><value>{0} progetto</value></data>
|
||||
<data name="Admin.Projects.Count.other" xml:space="preserve"><value>{0} progetti</value></data>
|
||||
<data name="Admin.Projects.Current" xml:space="preserve"><value>Più recente</value></data>
|
||||
<data name="Admin.Projects.Current.Tip" xml:space="preserve"><value>La versione più recente del progetto, quella che prende uno spazio di lavoro</value></data>
|
||||
<data name="Admin.Projects.Delete" xml:space="preserve"><value>Elimina…</value></data>
|
||||
<data name="Admin.Projects.Delete.Tip" xml:space="preserve"><value>Sposta questo progetto e le sue versioni nel cestino dei progetti della sequenza</value></data>
|
||||
<data name="Admin.Projects.DeleteBody" xml:space="preserve"><value>Il progetto e le sue versioni ({0}) vanno nel cestino dei progetti della sequenza; non si cancella nulla.</value></data>
|
||||
<data name="Admin.Projects.DeleteConfirm" xml:space="preserve"><value>Elimina progetto</value></data>
|
||||
<data name="Admin.Projects.DeleteConfirm.Tip" xml:space="preserve"><value>Sposta il progetto e le sue versioni nel cestino dei progetti; non si cancella nulla</value></data>
|
||||
<data name="Admin.Projects.DeleteTitle" xml:space="preserve"><value>Eliminare {0}?</value></data>
|
||||
<data name="Admin.Projects.Deleted" xml:space="preserve"><value>{0} eliminato.</value></data>
|
||||
<data name="Admin.Projects.Empty" xml:space="preserve"><value>Ancora nessun progetto</value></data>
|
||||
<data name="Admin.Projects.Head" xml:space="preserve"><value>Versione</value></data>
|
||||
<data name="Admin.Projects.Head.Tip" xml:space="preserve"><value>La versione più recente del progetto</value></data>
|
||||
<data name="Admin.Projects.Kind.Commit" xml:space="preserve"><value>Salvata</value></data>
|
||||
<data name="Admin.Projects.Kind.Commit.Tip" xml:space="preserve"><value>Salvata in uno spazio di lavoro su un PC</value></data>
|
||||
<data name="Admin.Projects.Kind.External" xml:space="preserve"><value>Modifica esterna</value></data>
|
||||
<data name="Admin.Projects.Kind.External.Tip" xml:space="preserve"><value>Impostazioni scritte fuori dai progetti: un Chronos precedente, un'analisi, la sincronizzazione di un desktop o una conversione</value></data>
|
||||
<data name="Admin.Projects.Kind.Imported" xml:space="preserve"><value>Importata</value></data>
|
||||
<data name="Admin.Projects.Kind.Imported.Tip" xml:space="preserve"><value>La prima versione del progetto, dalle impostazioni da cui è nato</value></data>
|
||||
<data name="Admin.Projects.Kind.Merge" xml:space="preserve"><value>Unita</value></data>
|
||||
<data name="Admin.Projects.Kind.Merge.Tip" xml:space="preserve"><value>Modifiche fatte su due PC, unite impostazione per impostazione</value></data>
|
||||
<data name="Admin.Projects.Kind.Restore" xml:space="preserve"><value>Ripristinata</value></data>
|
||||
<data name="Admin.Projects.Kind.Restore.Tip" xml:space="preserve"><value>Una versione precedente riportata</value></data>
|
||||
<data name="Admin.Projects.Main" xml:space="preserve"><value>Principale</value></data>
|
||||
<data name="Admin.Projects.Main.Tip" xml:space="preserve"><value>Le impostazioni della sequenza: le usano i render e le versioni precedenti di Chronos, e non si elimina mai</value></data>
|
||||
<data name="Admin.Projects.Name" xml:space="preserve"><value>Progetto</value></data>
|
||||
<data name="Admin.Projects.NameInvalid" xml:space="preserve"><value>Scrivi un nome da 1 a 60 caratteri.</value></data>
|
||||
<data name="Admin.Projects.NewName" xml:space="preserve"><value>Nome</value></data>
|
||||
<data name="Admin.Projects.NewName.Tip" xml:space="preserve"><value>Da 1 a 60 caratteri, non usato da un altro progetto di questa sequenza</value></data>
|
||||
<data name="Admin.Projects.NoVersions" xml:space="preserve"><value>Ancora nessuna versione</value></data>
|
||||
<data name="Admin.Projects.Number" xml:space="preserve"><value>Versione {0}</value></data>
|
||||
<data name="Admin.Projects.Rename" xml:space="preserve"><value>Rinomina…</value></data>
|
||||
<data name="Admin.Projects.Rename.Tip" xml:space="preserve"><value>Dai a questo progetto un altro nome</value></data>
|
||||
<data name="Admin.Projects.RenameConfirm" xml:space="preserve"><value>Rinomina</value></data>
|
||||
<data name="Admin.Projects.RenameConfirm.Tip" xml:space="preserve"><value>Salva il nuovo nome</value></data>
|
||||
<data name="Admin.Projects.RenameTitle" xml:space="preserve"><value>Rinomina {0}</value></data>
|
||||
<data name="Admin.Projects.Renamed" xml:space="preserve"><value>Rinominato in {0}.</value></data>
|
||||
<data name="Admin.Projects.Title" xml:space="preserve"><value>Progetti</value></data>
|
||||
<data name="Admin.Projects.Versions.Tip" xml:space="preserve"><value>Mostra o nascondi le versioni di questo progetto</value></data>
|
||||
<data name="Admin.Projects.VersionsOf" xml:space="preserve"><value>Versioni di {0}</value></data>
|
||||
<data name="Admin.Reorganize.Action" xml:space="preserve"><value>Riorganizza…</value></data>
|
||||
<data name="Admin.Reorganize.Action.Tip" xml:space="preserve"><value>Applica modelli di cartelle, file e titoli alle sequenze selezionate; un'anteprima mostra prima ogni modifica</value></data>
|
||||
<data name="Admin.Reorganize.After" xml:space="preserve"><value>Dopo:</value></data>
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
<data name="Server.Error.InvalidFilter" xml:space="preserve"><value>Un valore di filtro non è valido.</value></data>
|
||||
<data name="Server.Error.InvalidHash" xml:space="preserve"><value>Lo SHA-256 deve avere 64 caratteri esadecimali.</value></data>
|
||||
<data name="Server.Error.InvalidJobKind" xml:space="preserve"><value>Questo tipo di job non si può avviare qui.</value></data>
|
||||
<data name="Server.Error.InvalidName" xml:space="preserve"><value>Il nome di un progetto ha da 1 a 60 caratteri, senza caratteri di controllo.</value></data>
|
||||
<data name="Server.Error.InvalidParameters" xml:space="preserve"><value>I parametri del job non sono validi.</value></data>
|
||||
<data name="Server.Error.InvalidPriority" xml:space="preserve"><value>La priorità deve essere background, normal o user.</value></data>
|
||||
<data name="Server.Error.InvalidProxy" xml:space="preserve"><value>Il proxy non è un JPEG che il server sa leggere.</value></data>
|
||||
@@ -68,12 +69,16 @@
|
||||
<data name="Server.Error.InvalidState" xml:space="preserve"><value>Il job non può farlo nello stato attuale.</value></data>
|
||||
<data name="Server.Error.InvalidTemplate" xml:space="preserve"><value>Il modello dei nomi non è valido.</value></data>
|
||||
<data name="Server.Error.InvalidUsername" xml:space="preserve"><value>Usa lettere, cifre, punto, trattino o trattino basso.</value></data>
|
||||
<data name="Server.Error.InvalidVersion" xml:space="preserve"><value>La versione non è di questo progetto: le sue posizioni non sono per foto, o il suo id è di un'altra versione.</value></data>
|
||||
<data name="Server.Error.JobNotAssigned" xml:space="preserve"><value>Questo job non è più assegnato a questo nodo.</value></data>
|
||||
<data name="Server.Error.JobUnavailable" xml:space="preserve"><value>Questo server non può eseguire quel tipo di job.</value></data>
|
||||
<data name="Server.Error.LastAdmin" xml:space="preserve"><value>L'ultimo amministratore non può essere rimosso o disattivato.</value></data>
|
||||
<data name="Server.Error.MainCannotBeDeleted" xml:space="preserve"><value>Il progetto Principale contiene le impostazioni della sequenza e non si elimina mai.</value></data>
|
||||
<data name="Server.Error.MethodNotAllowed" xml:space="preserve"><value>Metodo non consentito qui.</value></data>
|
||||
<data name="Server.Error.NameTaken" xml:space="preserve"><value>Un altro progetto di questa sequenza ha già quel nome.</value></data>
|
||||
<data name="Server.Error.NestedTarget" xml:space="preserve"><value>Una nuova cartella finirebbe dentro la cartella di un'altra sequenza.</value></data>
|
||||
<data name="Server.Error.NotChronosAt" xml:space="preserve"><value>Nessun server Chronos risponde a {0}; controlla la porta (l'indirizzo client è nel pannello di amministrazione, Impostazioni › Rete e TLS).</value></data>
|
||||
<data name="Server.Error.NewerFormat" xml:space="preserve"><value>La versione è stata creata da un Chronos più recente; aggiorna il server per conservarla.</value></data>
|
||||
<data name="Server.Error.NotEnoughSpace" xml:space="preserve"><value>Il volume dell'archivio non ha lo spazio che serve alla conversione.</value></data>
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
|
||||
<data name="Server.Error.NotChronos" xml:space="preserve"><value>Questo indirizzo non è un Chronos Server.</value></data>
|
||||
@@ -83,6 +88,8 @@
|
||||
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova.</value></data>
|
||||
<data name="Server.Error.PlanChanged" xml:space="preserve"><value>L'archivio è cambiato dopo la simulazione; rivedi di nuovo il piano.</value></data>
|
||||
<data name="Server.Error.PlanDropped" xml:space="preserve"><value>Il server ha smesso di preparare questo piano: richiedeva troppo tempo, o ne sono stati chiesti troppi insieme; riprova tra poco.</value></data>
|
||||
<data name="Server.Error.ProjectDiverged" xml:space="preserve"><value>Il progetto ha versioni più recenti sul server; prendile, poi invia di nuovo le tue.</value></data>
|
||||
<data name="Server.Error.ProjectsUnreadable" xml:space="preserve"><value>Un progetto di questa sequenza non si può leggere ora; non è cambiato nulla. Riprova tra poco.</value></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a CHRONOS_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Server.Error.ProxiesDisabled" xml:space="preserve"><value>Questo archivio non crea proxy.</value></data>
|
||||
<data name="Server.Error.ProxyMismatch" xml:space="preserve"><value>Il proxy è stato creato da un'altra foto.</value></data>
|
||||
@@ -112,6 +119,7 @@
|
||||
<data name="Server.Error.Untrusted" xml:space="preserve"><value>Il certificato non è stato accettato, quindi non è stato inviato nulla.</value></data>
|
||||
<data name="Server.Error.UploadState" xml:space="preserve"><value>Questo caricamento ora non accetta la richiesta.</value></data>
|
||||
<data name="Server.Error.UsernameTaken" xml:space="preserve"><value>Questo nome utente è già in uso.</value></data>
|
||||
<data name="Server.Error.VersionHashMismatch" xml:space="preserve"><value>La versione è arrivata danneggiata; inviala di nuovo.</value></data>
|
||||
<data name="Server.Error.WeakPassword" xml:space="preserve"><value>Usa almeno {0} caratteri.</value></data>
|
||||
<data name="Server.Error.WebsocketRequired" xml:space="preserve"><value>Connettiti con un WebSocket.</value></data>
|
||||
<data name="Server.Error.WouldEmpty" xml:space="preserve"><value>Se ne andrebbero tutte le foto della sequenza; elimina invece la sequenza.</value></data>
|
||||
|
||||
@@ -62,6 +62,15 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Told after a call of <see cref="Projects.ProjectService"/> changed a sequence's projects (owner review 2, R8): a project
|
||||
/// made, renamed or deleted, a new head (a push, settings another path wrote taken as Main's external version, a merge, the
|
||||
/// versions another program sharing the archive wrote found in the sidecars), and whether the call wrote Main's head into
|
||||
/// the sequence's settings. Told once per call, after the sequence's lease is let go. A server tells its connected clients
|
||||
/// (BRIEF §14.3); a failure is logged and never fails the call.
|
||||
/// </summary>
|
||||
public Func<Projects.ProjectChangeSet, CancellationToken, Task>? ProjectsChanged { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes a write under a folder of an archive (its root, its staging folder) may count on, as the host counts
|
||||
/// them: a server takes the tighter of its space volume (owner review 2, R2) and the folder's own volume, the desktop asks
|
||||
|
||||
@@ -7,9 +7,9 @@ namespace Chronos.Data.Projects;
|
||||
/// <summary>
|
||||
/// The photos of a sequence's frames at its home as project positions name them (owner review 2, R8), with the encodings
|
||||
/// a conversion joined (R7): a version parked on a photo before its file was converted, or after a conversion was undone,
|
||||
/// still finds its frame.
|
||||
/// still finds its frame. A server builds the same for a sequence it is the home of, and sends its aliases to workspaces.
|
||||
/// </summary>
|
||||
internal static class HomePhotos
|
||||
public static class HomePhotos
|
||||
{
|
||||
/// <summary>The links between encodings of the sequence's photos: its tombstones of reason "replaced".</summary>
|
||||
public static async Task<IReadOnlyList<PhotoAlias>> AliasesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -79,6 +79,19 @@ public sealed record PushResult(PushOutcome Outcome, ProjectVersion? Version, Pr
|
||||
/// </summary>
|
||||
public sealed record HomeFrames(int FramesVersion, IReadOnlyList<Frame> Frames, FramePhotos Photos);
|
||||
|
||||
/// <summary>
|
||||
/// One project a <see cref="ProjectService"/> call changed: <see cref="Change"/> is one of <see cref="Protocol.ProjectChanges"/>
|
||||
/// (<c>created</c>, <c>renamed</c>, <c>deleted</c>, <c>pushed</c>: a new head), with the project's head after the call.
|
||||
/// </summary>
|
||||
public sealed record ProjectChange(Guid ProjectId, string Change, int HeadNumber, Guid? HeadVersionId);
|
||||
|
||||
/// <summary>
|
||||
/// What one <see cref="ProjectService"/> call changed in a sequence's projects (<see cref="ArchiveServiceOptions.ProjectsChanged"/>):
|
||||
/// the projects, in index order, and whether it wrote Main's head into the sequence's settings (<see cref="SettingsChanged"/>:
|
||||
/// the sequence's settings version moved, which the code paths that read the sequence's settings want to know).
|
||||
/// </summary>
|
||||
public sealed record ProjectChangeSet(Guid SequenceId, IReadOnlyList<ProjectChange> Changes, bool SettingsChanged);
|
||||
|
||||
/// <summary>
|
||||
/// The projects of the sequences of this PC's archives (owner review 2, R8): the home side of a workspace's push and pull.
|
||||
/// Every operation runs under the sequence's lease and first catches up: the sidecars into the index
|
||||
@@ -412,6 +425,20 @@ public sealed class ProjectService
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings the sequence's projects in step now (see the class remarks: the sidecars into the index, Main made, settings
|
||||
/// another path wrote appended to Main), as every call does first, but saying why when it cannot: what a host runs soon
|
||||
/// after it wrote a sequence's settings outside the projects, so Main takes them (and is told, <see
|
||||
/// cref="ArchiveServiceOptions.ProjectsChanged"/>) before anyone asks.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than a read waits.</exception>
|
||||
/// <exception cref="SequenceFolderMovedException">The sequence's folder does not hold it.</exception>
|
||||
/// <exception cref="ProjectsUnreadableException">The index has no Main and a project record cannot be read now (it may be Main's).</exception>
|
||||
public Task CatchUpAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||||
UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait);
|
||||
|
||||
/// <summary>
|
||||
/// Catches the sequence's projects up under its lease (see the class remarks) before a read; the index alone answers while
|
||||
/// the archive is offline, the sequence busy for longer than the lease wait, or a project of it cannot be read now. A
|
||||
@@ -483,14 +510,87 @@ public sealed class ProjectService
|
||||
var (paths, _) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
var availability = Availability(paths);
|
||||
if (availability != ArchiveAvailability.Online) throw new ArchiveOfflineException(paths.Root, availability);
|
||||
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
|
||||
ProjectChangeSet? changed = null;
|
||||
try
|
||||
{
|
||||
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();
|
||||
var context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
|
||||
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
return await work(context, cancellationToken).ConfigureAwait(false);
|
||||
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
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();
|
||||
// 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;
|
||||
try
|
||||
{
|
||||
context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
|
||||
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
return await work(context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// What the reconcile, the catch-up and the work wrote stays written even when the work then refused or failed.
|
||||
if (before is not null)
|
||||
changed = await ChangesAsync(sequenceId, before, context is not null && row.SettingsVersion != context.Row.SettingsVersion).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (changed is not null) await TellAsync(changed).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes; else null.</summary>
|
||||
private async Task<Dictionary<Guid, SequenceProject>?> 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);
|
||||
|
||||
/// <summary>
|
||||
/// What changed in the sequence's projects since <paramref name="before"/> (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.
|
||||
/// </summary>
|
||||
private async Task<ProjectChangeSet?> ChangesAsync(Guid sequenceId, Dictionary<Guid, SequenceProject> before, bool settingsChanged)
|
||||
{
|
||||
IReadOnlyList<SequenceProject> after;
|
||||
try
|
||||
{
|
||||
after = await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("projects", $"The project changes of sequence {sequenceId} cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
var changes = new List<ProjectChange>();
|
||||
foreach (var project in after)
|
||||
{
|
||||
before.TryGetValue(project.Id, out var was);
|
||||
var (live, wasLive) = (project.DeletedAt is null, was is { DeletedAt: null });
|
||||
if (live && !wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Created));
|
||||
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));
|
||||
if (project.HeadVersionId != was.HeadVersionId) changes.Add(Change(project, Protocol.ProjectChanges.Pushed));
|
||||
}
|
||||
}
|
||||
return changes.Count == 0 && !settingsChanged ? null : new ProjectChangeSet(sequenceId, changes, settingsChanged);
|
||||
|
||||
static ProjectChange Change(SequenceProject project, string change) => new(project.Id, change, project.HeadNumber, project.HeadVersionId);
|
||||
}
|
||||
|
||||
/// <summary>Tells the host what a call changed; a failure is logged, never passed on.</summary>
|
||||
private async Task TellAsync(ProjectChangeSet changed)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _writer.Options.ProjectsChanged!(changed, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("projects", $"The project changes of sequence {changed.SequenceId} were not told", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>
|
||||
/// Projects and their versions on the wire (owner review 2, R8): what a server answers from its index, and how a client
|
||||
/// reads it back into the model a workspace works with, so a server is a project home like this PC's archive; with the
|
||||
/// wire names of the push outcomes.
|
||||
/// </summary>
|
||||
public static class ProjectWire
|
||||
{
|
||||
/// <summary>A project as the API shows it; <paramref name="head"/> (its head version) says who changed it last, and when.</summary>
|
||||
public static ProjectDto ToDto(SequenceProject project, ProjectVersion? head = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return new ProjectDto(project.Id, project.SequenceId, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.CreatedBy,
|
||||
project.CreatedAt, project.UpdatedAt, head is null ? null : ProjectVersionKinds.Name(head.Kind), head?.Author, head?.ClientName, head?.StoredAt);
|
||||
}
|
||||
|
||||
public static ProjectVersionDto ToDto(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
return new ProjectVersionDto(version.Id, version.ProjectId, version.ParentId, version.Number, ProjectVersionKinds.Name(version.Kind), version.Author,
|
||||
version.ClientName, version.Note, version.SettingsJson, version.ContentHash, version.SettingsFormat, version.FramesVersion, version.RestoredFrom,
|
||||
version.CreatedAt, version.StoredAt);
|
||||
}
|
||||
|
||||
/// <summary>A project of a server sequence as the model knows it (the mirror fields stay the server's own).</summary>
|
||||
public static SequenceProject ToProject(ProjectDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
return new SequenceProject
|
||||
{
|
||||
Id = dto.Id,
|
||||
SequenceId = dto.SequenceId,
|
||||
Name = dto.Name,
|
||||
IsMain = dto.IsMain,
|
||||
HeadVersionId = dto.HeadVersionId,
|
||||
HeadNumber = dto.HeadNumber,
|
||||
CreatedBy = dto.CreatedBy,
|
||||
CreatedAt = dto.CreatedAt,
|
||||
UpdatedAt = dto.UpdatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A version as the model knows it; a kind this build does not know reads as a commit (<see cref="ProjectVersionKinds.Parse"/>).</summary>
|
||||
public static ProjectVersion ToVersion(ProjectVersionDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
return new ProjectVersion
|
||||
{
|
||||
Id = dto.Id,
|
||||
ProjectId = dto.ProjectId,
|
||||
ParentId = dto.ParentId,
|
||||
Number = dto.Number,
|
||||
Kind = ProjectVersionKinds.Parse(dto.Kind),
|
||||
Author = dto.Author,
|
||||
ClientName = dto.ClientName,
|
||||
Note = dto.Note,
|
||||
SettingsJson = dto.SettingsJson,
|
||||
ContentHash = dto.ContentHash,
|
||||
SettingsFormat = dto.SettingsFormat,
|
||||
FramesVersion = dto.FramesVersion,
|
||||
RestoredFrom = dto.RestoredFrom,
|
||||
CreatedAt = dto.CreatedAt,
|
||||
StoredAt = dto.StoredAt,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The wire name of <paramref name="outcome"/> (<see cref="ProjectPushOutcomes"/>).</summary>
|
||||
public static string Outcome(PushOutcome outcome) => outcome switch
|
||||
{
|
||||
PushOutcome.Stored => ProjectPushOutcomes.Stored,
|
||||
PushOutcome.AlreadyStored => ProjectPushOutcomes.AlreadyStored,
|
||||
PushOutcome.Diverged => ProjectPushOutcomes.Diverged,
|
||||
PushOutcome.HashMismatch => ProjectPushOutcomes.HashMismatch,
|
||||
PushOutcome.NewerFormat => ProjectPushOutcomes.NewerFormat,
|
||||
PushOutcome.TooLarge => ProjectPushOutcomes.TooLarge,
|
||||
_ => ProjectPushOutcomes.Invalid,
|
||||
};
|
||||
|
||||
/// <summary>The outcome a wire name stands for; one this build does not know is a refusal (<see cref="PushOutcome.Invalid"/>).</summary>
|
||||
public static PushOutcome ParseOutcome(string? name) => name switch
|
||||
{
|
||||
ProjectPushOutcomes.Stored => PushOutcome.Stored,
|
||||
ProjectPushOutcomes.AlreadyStored => PushOutcome.AlreadyStored,
|
||||
ProjectPushOutcomes.Diverged => PushOutcome.Diverged,
|
||||
ProjectPushOutcomes.HashMismatch => PushOutcome.HashMismatch,
|
||||
ProjectPushOutcomes.NewerFormat => PushOutcome.NewerFormat,
|
||||
ProjectPushOutcomes.TooLarge => PushOutcome.TooLarge,
|
||||
_ => PushOutcome.Invalid,
|
||||
};
|
||||
|
||||
/// <summary>A push's answer as <see cref="ProjectService.PushAsync"/> gives it on this PC's archive.</summary>
|
||||
public static PushResult ToResult(ProjectPushResultDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
return new PushResult(ParseOutcome(dto.Outcome), dto.Version is null ? null : ToVersion(dto.Version), dto.Head is null ? null : ToVersion(dto.Head));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The links a server sends with a sequence's frames (<see cref="ProjectFramesDto.Aliases"/>): its tombstones of reason
|
||||
/// <c>replaced</c> with their replacement.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<RemovedPhotoDto> Aliases(IEnumerable<FrameRemoval> removals) =>
|
||||
Sync.SyncTombstones.ToDto(removals.Where(r => r.Reason == RemovalReason.Replaced && !string.IsNullOrEmpty(r.ReplacementSha256)));
|
||||
|
||||
/// <summary>
|
||||
/// The frames a server sequence's project positions are placed on, as <see cref="ProjectService.FramesAsync"/> gives a
|
||||
/// sequence of this PC's archive: rows in index order and their photos, with the encodings its conversions joined.
|
||||
/// </summary>
|
||||
public static HomeFrames ToHomeFrames(ProjectFramesDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
var frames = dto.Frames.Select(RenderNodeClient.ToFrame).OrderBy(f => f.Index).ToList();
|
||||
var aliases = (dto.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
|
||||
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
|
||||
return new HomeFrames(dto.FramesVersion, frames, HomePhotos.Of(frames, aliases));
|
||||
}
|
||||
}
|
||||
@@ -472,6 +472,98 @@ public sealed class ChronosClient : IDisposable
|
||||
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> 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>
|
||||
@@ -606,4 +698,8 @@ public sealed class ChronosClient : IDisposable
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -23,5 +23,15 @@ public sealed record ServerInfo(
|
||||
ServerLimits Limits,
|
||||
IReadOnlyList<string>? Extensions = null);
|
||||
|
||||
/// <summary>Names of <see cref="ServerInfo.Capabilities"/> that clients act on.</summary>
|
||||
public static class ServerCapabilities
|
||||
{
|
||||
/// <summary>
|
||||
/// The server keeps its sequences' projects (owner review 2, R8): <c>/api/v1/sequences/{sid}/projects</c>, the
|
||||
/// <c>projectChanged</c> event, renders of a project version. A server without it knows only the sequence's settings.
|
||||
/// </summary>
|
||||
public const string Projects = "projects";
|
||||
}
|
||||
|
||||
/// <summary><c>GET /health</c>.</summary>
|
||||
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
|
||||
@@ -4,7 +4,8 @@ namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// Messages pushed on <c>WS /api/v1/events</c>. Each frame is one JSON object with a <c>type</c> discriminator:
|
||||
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState, scheduleChanged.
|
||||
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState, scheduleChanged, projectChanged. A client ignores the types it
|
||||
/// does not know (an older client those of a newer server).
|
||||
/// </summary>
|
||||
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
|
||||
[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")]
|
||||
@@ -13,6 +14,7 @@ namespace Chronos.Protocol;
|
||||
[JsonDerivedType(typeof(CardEvent), "cardEvent")]
|
||||
[JsonDerivedType(typeof(NodeStateEvent), "nodeState")]
|
||||
[JsonDerivedType(typeof(ScheduleChangedEvent), "scheduleChanged")]
|
||||
[JsonDerivedType(typeof(ProjectChangedEvent), "projectChanged")]
|
||||
public abstract record ServerEvent;
|
||||
|
||||
public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent;
|
||||
@@ -48,3 +50,12 @@ public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State
|
||||
/// included, or its next run moved (owner review 2, R10): the admin panel's Scheduled tab reads the list again.
|
||||
/// </summary>
|
||||
public sealed record ScheduleChangedEvent(Guid ScheduleId, bool Deleted) : ServerEvent;
|
||||
|
||||
/// <summary>
|
||||
/// A project of a sequence changed (owner review 2, R8): <see cref="Change"/> is one of <see cref="ProjectChanges"/>
|
||||
/// (<c>created</c>, <c>renamed</c>, <c>deleted</c>, <c>pushed</c>), <see cref="HeadNumber"/> and <see cref="HeadVersionId"/>
|
||||
/// its head after the change. Sent for the API's own changes and when Main takes settings another path wrote (a
|
||||
/// <c>PATCH</c> of the sequence's settings, an analysis, the sync of a desktop's copy, a conversion); a workspace with that
|
||||
/// project checked out knows its home moved, and the admin panel reads the projects again.
|
||||
/// </summary>
|
||||
public sealed record ProjectChangedEvent(Guid SequenceId, Guid ProjectId, string Change, int HeadNumber, Guid? HeadVersionId) : ServerEvent;
|
||||
@@ -0,0 +1,157 @@
|
||||
namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// A project of a server sequence (owner review 2, R8; <c>/api/v1/sequences/{sid}/projects</c>): a named set of render
|
||||
/// settings ("4K landscape", "Vertical social") with a linear history of versions. Every sequence has one Main project
|
||||
/// (<see cref="IsMain"/>, listed first), whose head is the sequence's own settings: an old client's <c>PATCH
|
||||
/// /sequences/{id}</c> of the settings becomes a version of it. <see cref="HeadKind"/>, <see cref="HeadAuthor"/>,
|
||||
/// <see cref="HeadClientName"/> and <see cref="HeadStoredAt"/> describe the head version: who changed the project last,
|
||||
/// and when. <see cref="CreatedBy"/> is the account that made the project (null for Main, made from the settings).
|
||||
/// </summary>
|
||||
public sealed record ProjectDto(
|
||||
Guid Id,
|
||||
Guid SequenceId,
|
||||
string Name,
|
||||
bool IsMain,
|
||||
Guid? HeadVersionId,
|
||||
int HeadNumber,
|
||||
string? CreatedBy,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset UpdatedAt,
|
||||
string? HeadKind = null,
|
||||
string? HeadAuthor = null,
|
||||
string? HeadClientName = null,
|
||||
DateTimeOffset? HeadStoredAt = null);
|
||||
|
||||
/// <summary>
|
||||
/// One version of a project, immutable once stored (owner review 2, R8). <see cref="SettingsJson"/> is the portable form of
|
||||
/// the settings (every frame position parked by photo, canonical text) and <see cref="ContentHash"/> the lower-case hex
|
||||
/// SHA-256 of its UTF-8 bytes, which every side checks. <see cref="Kind"/> is <c>commit</c>, <c>merge</c>, <c>restore</c>,
|
||||
/// <c>imported</c> or <c>external</c> (Main only: settings written outside the projects). <see cref="SettingsFormat"/> is the
|
||||
/// settings' format (a newer one opens read-only), <see cref="FramesVersion"/> the frames version they were made against,
|
||||
/// <see cref="RestoredFrom"/> the version a restore brought back. <see cref="StoredAt"/> is null for a version a workspace
|
||||
/// has not pushed. A push (<c>POST …/versions</c>) sends the version as the workspace made it, its parent the head it knew:
|
||||
/// the server numbers it (head + 1), records the account that pushed it as its <see cref="Author"/> and stores it.
|
||||
/// </summary>
|
||||
public sealed record ProjectVersionDto(
|
||||
Guid Id,
|
||||
Guid ProjectId,
|
||||
Guid? ParentId,
|
||||
int Number,
|
||||
string Kind,
|
||||
string? Author,
|
||||
string? ClientName,
|
||||
string? Note,
|
||||
string SettingsJson,
|
||||
string ContentHash,
|
||||
int SettingsFormat,
|
||||
int FramesVersion,
|
||||
Guid? RestoredFrom,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset? StoredAt);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/sequences/{sid}/projects</c>: a new project named <see cref="Name"/> (1–60 characters, unique among the
|
||||
/// sequence's projects whatever the case), whose first version (kind <c>imported</c>) holds the settings of
|
||||
/// <see cref="FromVersionId"/> (a version of any project of the sequence), or of Main's head.
|
||||
/// </summary>
|
||||
public sealed record CreateProjectRequest(string Name, Guid? FromVersionId = null);
|
||||
|
||||
/// <summary><c>PATCH /api/v1/sequences/{sid}/projects/{pid}</c>: the project's new name (1–60 characters, unique among the sequence's projects).</summary>
|
||||
public sealed record RenameProjectRequest(string Name);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/sequences/{sid}/projects/{pid}/versions</c>: one page of a project's versions, newest first (below
|
||||
/// <c>before</c>, from the head when absent) or oldest first with <c>after</c> (what a workspace pulls). <see cref="More"/>:
|
||||
/// versions follow this page in its order. <see cref="HeadNumber"/> is the project's head as the page was read.
|
||||
/// </summary>
|
||||
public sealed record ProjectVersionPageDto(IReadOnlyList<ProjectVersionDto> Items, int HeadNumber, bool More);
|
||||
|
||||
/// <summary>
|
||||
/// The answer to a push (<c>POST /api/v1/sequences/{sid}/projects/{pid}/versions</c>): <see cref="Outcome"/> (one of
|
||||
/// <see cref="ProjectPushOutcomes"/>), the version as stored (<c>stored</c>: 201, <c>already_stored</c>: 200, a push repeated
|
||||
/// after its answer was lost) and the project's head. A refusal stores nothing and carries the error's <see cref="Code"/>
|
||||
/// and its sentence in the request's language (<see cref="Message"/>), so the body also reads as an <see cref="ApiError"/>:
|
||||
/// 409 <c>project_diverged</c> (<c>diverged</c>: the head moved past the version's parent; pull the head, replay the version
|
||||
/// on it and push again), 422 <c>hash_mismatch</c> (the settings do not match the content hash), <c>newer_format</c>
|
||||
/// (settings of a newer format than the server reads), <c>invalid_version</c> (<c>invalid</c>: positions not parked by
|
||||
/// photo, or the id is another project's version).
|
||||
/// </summary>
|
||||
public sealed record ProjectPushResultDto(string Outcome, ProjectVersionDto? Version, ProjectVersionDto? Head, string? Code = null, string? Message = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/sequences/{sid}/projects/frames</c>: what a workspace places a server sequence's project positions on, as
|
||||
/// of one frames version: every frame in index order (as <c>GET /sequences/{id}/frames</c> gives them) and the links between
|
||||
/// encodings of one photo, the sequence's tombstones of reason <c>replaced</c> (a conversion's original and its replacement;
|
||||
/// a position parked on either finds the frame that holds the other). <see cref="Aliases"/> is null when there are none.
|
||||
/// </summary>
|
||||
public sealed record ProjectFramesDto(Guid SequenceId, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<RemovedPhotoDto>? Aliases = null);
|
||||
|
||||
/// <summary>What became of a pushed version (<see cref="ProjectPushResultDto.Outcome"/>).</summary>
|
||||
public static class ProjectPushOutcomes
|
||||
{
|
||||
/// <summary>Stored as the new head: its parent was the head (a fast-forward). 201.</summary>
|
||||
public const string Stored = "stored";
|
||||
|
||||
/// <summary>A version with that id and content is stored already (a repeated push): nothing changed. 200.</summary>
|
||||
public const string AlreadyStored = "already_stored";
|
||||
|
||||
/// <summary>The head moved past the version's parent. 409 <c>project_diverged</c>.</summary>
|
||||
public const string Diverged = "diverged";
|
||||
|
||||
/// <summary>The settings do not match the content hash. 422 <c>hash_mismatch</c>.</summary>
|
||||
public const string HashMismatch = "hash_mismatch";
|
||||
|
||||
/// <summary>Settings of a newer format than the server reads. 422 <c>newer_format</c>.</summary>
|
||||
public const string NewerFormat = "newer_format";
|
||||
|
||||
/// <summary>Not a version of this project (positions not parked by photo, or another project's id). 422 <c>invalid_version</c>.</summary>
|
||||
public const string Invalid = "invalid";
|
||||
|
||||
/// <summary>The version's file would be larger than a version may be (64 MiB). 422 <c>too_large</c>.</summary>
|
||||
public const string TooLarge = "too_large";
|
||||
}
|
||||
|
||||
/// <summary>Changes of a project a <see cref="ProjectChangedEvent"/> tells.</summary>
|
||||
public static class ProjectChanges
|
||||
{
|
||||
/// <summary>A project was made (Main too, the first time the sequence's projects are read).</summary>
|
||||
public const string Created = "created";
|
||||
|
||||
public const string Renamed = "renamed";
|
||||
|
||||
/// <summary>A project left the sequence (into its projects' trash).</summary>
|
||||
public const string Deleted = "deleted";
|
||||
|
||||
/// <summary>
|
||||
/// The project has a new head: a version pushed, settings written outside the projects taken as Main's external version
|
||||
/// (an older client, an analysis, the sync of a desktop's copy), a merge, or versions another program sharing the archive
|
||||
/// wrote.
|
||||
/// </summary>
|
||||
public const string Pushed = "pushed";
|
||||
}
|
||||
|
||||
/// <summary>Error codes of the project calls that clients act on (owner review 2, R8).</summary>
|
||||
public static class ProjectErrors
|
||||
{
|
||||
/// <summary>409 from a push: the head moved past the version's parent (the answer carries the head).</summary>
|
||||
public const string Diverged = "project_diverged";
|
||||
|
||||
/// <summary>422 from a push: the settings do not match their content hash.</summary>
|
||||
public const string HashMismatch = "hash_mismatch";
|
||||
|
||||
/// <summary>422 from a push: settings of a newer format than the server reads.</summary>
|
||||
public const string NewerFormat = "newer_format";
|
||||
|
||||
/// <summary>422 from a push: not a version of this project.</summary>
|
||||
public const string InvalidVersion = "invalid_version";
|
||||
|
||||
/// <summary>400: a project name is blank, longer than 60 characters or holds a control character.</summary>
|
||||
public const string InvalidName = "invalid_name";
|
||||
|
||||
/// <summary>409: another project of the sequence has that name (case does not count).</summary>
|
||||
public const string NameTaken = "name_taken";
|
||||
|
||||
/// <summary>409: the Main project holds the sequence's own settings and is never deleted.</summary>
|
||||
public const string MainCannotBeDeleted = "main_cannot_be_deleted";
|
||||
}
|
||||
@@ -91,4 +91,12 @@ namespace Chronos.Protocol;
|
||||
[JsonSerializable(typeof(ReorganizePlanDto))]
|
||||
[JsonSerializable(typeof(ConvertRequest))]
|
||||
[JsonSerializable(typeof(ConvertPlanDto))]
|
||||
[JsonSerializable(typeof(ProjectDto))]
|
||||
[JsonSerializable(typeof(List<ProjectDto>))]
|
||||
[JsonSerializable(typeof(ProjectVersionDto))]
|
||||
[JsonSerializable(typeof(CreateProjectRequest))]
|
||||
[JsonSerializable(typeof(RenameProjectRequest))]
|
||||
[JsonSerializable(typeof(ProjectVersionPageDto))]
|
||||
[JsonSerializable(typeof(ProjectPushResultDto))]
|
||||
[JsonSerializable(typeof(ProjectFramesDto))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -387,6 +387,13 @@ textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize
|
||||
.frame-badge.hero { color: var(--sun); }
|
||||
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
|
||||
/* A sequence's projects (owner review 2, R8) and, under one opened, its versions. */
|
||||
.table.projects { grid-template-columns: minmax(120px, 1.4fr) max-content minmax(120px, 1.2fr) max-content; }
|
||||
.table.projects.fit-1 { grid-template-columns: minmax(120px, 1fr) max-content max-content; }
|
||||
.table.projects.fit-1 .col-changed { display: none; }
|
||||
.versions { display: grid; grid-template-columns: max-content max-content minmax(0, max-content) minmax(0, 1fr) max-content; gap: 6px 18px; align-items: center; padding: 10px 18px; background: var(--bg); border-top: 1px solid var(--stroke); }
|
||||
.versions .version { display: contents; }
|
||||
.versions .more { grid-column: 1 / -1; justify-self: start; }
|
||||
.table.trash { grid-template-columns: max-content minmax(140px, 2fr) max-content max-content minmax(60px, 1fr) max-content max-content; }
|
||||
.table.trash.fit-1 { grid-template-columns: max-content minmax(120px, 2fr) max-content max-content max-content max-content; }
|
||||
.table.trash.fit-1 .col-by { display: none; }
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
// The projects of a sequence on the panel (owner review 2, R8): each project's name, Main marked, its newest version and who
|
||||
// changed it last, its versions on demand, and Rename and Delete for the projects other than Main. Nothing here edits a
|
||||
// project's settings: the desktop does, in its workspace, and pushes its versions here. The list follows projectChanged.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatNumber, formatDateTime, toast, errorText, confirmDialog, formDialog, emptyState, markInvalid, redraw, fitColumns } from "../../ui.js";
|
||||
|
||||
/** Versions read at a time when a project is opened, and with each Load more. */
|
||||
const VERSION_PAGE = 20;
|
||||
/** A project name, as the server takes it (ProjectService.MaxNameLength). */
|
||||
const MAX_NAME = 60;
|
||||
/** The name every sequence's Main project is made with; shown in the panel's language. */
|
||||
const MAIN_NAME = "Main";
|
||||
/** How long after a projectChanged the projects are read again; one read covers every change meanwhile. */
|
||||
const AFTER_CHANGE_MS = 500;
|
||||
/** Version kinds the panel names (ProjectVersionKinds). */
|
||||
const KINDS = { commit: "Commit", merge: "Merge", restore: "Restore", imported: "Imported", external: "External" };
|
||||
|
||||
/**
|
||||
* Draws the Projects section of sequence sequenceId into host (its count into meta) and keeps it current. Returns
|
||||
* onEvent(e), which the sequence page passes every server event to.
|
||||
*/
|
||||
export function projectsSection(host, meta, { api, sequenceId }) {
|
||||
const base = `/api/v1/sequences/${encodeURIComponent(sequenceId)}/projects`;
|
||||
let projects = [];
|
||||
/** The versions read of each project opened: { items, more }. */
|
||||
const versions = new Map();
|
||||
const expanded = new Set();
|
||||
let timer = null;
|
||||
let failed = null;
|
||||
|
||||
host.innerHTML = `
|
||||
<div class="table projects" data-levels="1" role="table" aria-labelledby="projects-title">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Projects.Name"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Projects.Head"></span>
|
||||
<span role="columnheader" class="col-changed" data-i18n="Admin.Projects.Changed"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div role="rowgroup" id="project-rows"></div>
|
||||
</div>`;
|
||||
applyStrings(host);
|
||||
const table = host.querySelector(".table");
|
||||
const rows = host.querySelector("#project-rows");
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
projects = await api.get(base);
|
||||
failed = null;
|
||||
// A project deleted meanwhile (here or elsewhere) closes; the others' versions are read again.
|
||||
for (const id of expanded) {
|
||||
if (!projects.some((p) => p.id === id)) forget(id);
|
||||
}
|
||||
await Promise.all([...expanded].map((id) => loadVersions(id).catch(() => forget(id))));
|
||||
} catch (err) {
|
||||
projects = [];
|
||||
failed = errorText(err);
|
||||
}
|
||||
if (!host.isConnected) return;
|
||||
meta.textContent = failed ? "" : plural("Admin.Projects.Count", projects.length);
|
||||
draw();
|
||||
}
|
||||
|
||||
/** The newest versions of a project, or with more the next page after those shown. */
|
||||
async function loadVersions(id, more = false) {
|
||||
const known = versions.get(id);
|
||||
const before = more && known?.items.length ? `&before=${known.items[known.items.length - 1].number}` : "";
|
||||
const page = await api.get(`${base}/${encodeURIComponent(id)}/versions?limit=${VERSION_PAGE}${before}`);
|
||||
versions.set(id, { items: more && known ? known.items.concat(page.items) : page.items, more: page.more });
|
||||
}
|
||||
|
||||
function forget(id) {
|
||||
expanded.delete(id);
|
||||
versions.delete(id);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
redraw(rows, () => {
|
||||
rows.innerHTML = failed
|
||||
? `<div class="row" role="row"><div class="wide empty" role="cell">${escapeHtml(failed)}</div></div>`
|
||||
: projects.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Projects.Empty")}</div></div>`;
|
||||
applyStrings(rows);
|
||||
});
|
||||
rows.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => toggle(b.dataset.toggle)));
|
||||
rows.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.dataset.act, find(b.closest("[data-key]").dataset.key))));
|
||||
rows.querySelectorAll("[data-more-versions]").forEach((b) => b.addEventListener("click", () => moreVersions(b.dataset.moreVersions)));
|
||||
fitColumns(table);
|
||||
}
|
||||
|
||||
function find(id) {
|
||||
return projects.find((p) => p.id === id);
|
||||
}
|
||||
|
||||
/** Main keeps the name it was made with in the panel's language; a Main renamed shows its name and the Main mark. */
|
||||
function projectName(p) {
|
||||
return p.isMain && p.name === MAIN_NAME ? t("Admin.Projects.Main") : p.name;
|
||||
}
|
||||
|
||||
function rowHtml(p) {
|
||||
const name = projectName(p);
|
||||
const mark = p.isMain && p.name !== MAIN_NAME
|
||||
? `<span class="pill" data-i18n="Admin.Projects.Main" data-i18n-title="Admin.Projects.Main.Tip"></span>` : "";
|
||||
const who = p.headAuthor ?? p.headClientName ?? "";
|
||||
const when = p.headStoredAt ?? p.updatedAt;
|
||||
const actions = p.isMain ? "" : `
|
||||
<button class="btn small" data-act="rename" data-i18n="Admin.Projects.Rename" data-i18n-title="Admin.Projects.Rename.Tip"></button>
|
||||
<button class="btn small destructive" data-act="delete" data-i18n="Admin.Projects.Delete" data-i18n-title="Admin.Projects.Delete.Tip"></button>`;
|
||||
return `
|
||||
<div class="row" role="row" data-key="${attr(p.id)}">
|
||||
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(p.id)}" aria-expanded="${expanded.has(p.id)}"
|
||||
aria-controls="versions-${attr(p.id)}" dir="auto" title="${attr(p.isMain ? `${t("Admin.Projects.Main.Tip")}\n${t("Admin.Projects.Versions.Tip")}` : t("Admin.Projects.Versions.Tip"))}">${escapeHtml(name)}</button>${mark}</span>
|
||||
<span class="num end nowrap" role="cell" title="${attr(t("Admin.Projects.Head.Tip"))}">${escapeHtml(formatNumber(p.headNumber))}</span>
|
||||
<span class="col-changed ellipsis" role="cell" title="${attr([kindTip(p.headKind), p.headClientName].filter(Boolean).join("\n"))}"><span dir="auto">${escapeHtml(who)}</span>${who ? " · " : ""}<span class="muted nowrap">${escapeHtml(formatDateTime(when))}</span></span>
|
||||
<span class="row-actions" role="cell">${actions}</span>
|
||||
</div>
|
||||
${expanded.has(p.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="versions-${attr(p.id)}">${versionsHtml(p)}</div></div>` : ""}`;
|
||||
}
|
||||
|
||||
function versionsHtml(p) {
|
||||
const page = versions.get(p.id);
|
||||
if (!page) return "";
|
||||
if (page.items.length === 0) return emptyState("Admin.Projects.NoVersions");
|
||||
return `<div class="versions" role="list" aria-label="${attr(t("Admin.Projects.VersionsOf", projectName(p)))}">${page.items.map((v) => `
|
||||
<div class="version" role="listitem">
|
||||
<span class="num nowrap">${escapeHtml(t("Admin.Projects.Number", formatNumber(v.number)))}${v.id === p.headVersionId
|
||||
? ` <span class="pill" data-i18n="Admin.Projects.Current" data-i18n-title="Admin.Projects.Current.Tip"></span>` : ""}</span>
|
||||
<span class="nowrap" title="${attr(kindTip(v.kind))}">${escapeHtml(kindLabel(v.kind))}</span>
|
||||
<span class="ellipsis" dir="auto" title="${attr([v.author, v.clientName].filter(Boolean).join(" · "))}">${escapeHtml(v.author ?? v.clientName ?? "")}</span>
|
||||
<span class="ellipsis muted" dir="auto" title="${attr(v.note ?? "")}">${escapeHtml(v.note ?? "")}</span>
|
||||
<span class="muted nowrap num">${escapeHtml(formatDateTime(v.storedAt ?? v.createdAt))}</span>
|
||||
</div>`).join("")}
|
||||
${page.more ? `<button class="btn small more" data-more-versions="${attr(p.id)}" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button>` : ""}</div>`;
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return KINDS[kind] ? t(`Admin.Projects.Kind.${KINDS[kind]}`) : String(kind ?? "");
|
||||
}
|
||||
|
||||
function kindTip(kind) {
|
||||
return KINDS[kind] ? t(`Admin.Projects.Kind.${KINDS[kind]}.Tip`) : "";
|
||||
}
|
||||
|
||||
async function toggle(id) {
|
||||
if (expanded.delete(id)) {
|
||||
versions.delete(id);
|
||||
draw();
|
||||
return;
|
||||
}
|
||||
expanded.add(id);
|
||||
try {
|
||||
await loadVersions(id);
|
||||
} catch (err) {
|
||||
forget(id);
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
draw();
|
||||
}
|
||||
|
||||
async function moreVersions(id) {
|
||||
try {
|
||||
await loadVersions(id, true);
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
draw();
|
||||
}
|
||||
|
||||
async function act(action, project) {
|
||||
if (!project || project.isMain) return;
|
||||
if (action === "rename") return rename(project);
|
||||
if (action === "delete") return remove(project);
|
||||
}
|
||||
|
||||
async function rename(project) {
|
||||
const data = await formDialog({
|
||||
title: t("Admin.Projects.RenameTitle", project.name),
|
||||
fields: `<label><span data-i18n="Admin.Projects.NewName"></span><input class="input" name="name" dir="auto" maxlength="${MAX_NAME}" autocomplete="off"
|
||||
value="${attr(project.name)}" data-i18n-title="Admin.Projects.NewName.Tip"></label>`,
|
||||
confirm: t("Admin.Projects.RenameConfirm"),
|
||||
confirmTip: t("Admin.Projects.RenameConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Cancel"),
|
||||
cancelTip: t("Admin.Common.Cancel.Tip"),
|
||||
check: (form) => {
|
||||
const name = form.elements.name.value.trim();
|
||||
if (name.length > 0 && name.length <= MAX_NAME) return true;
|
||||
markInvalid(form.elements.name, t("Admin.Projects.NameInvalid"));
|
||||
form.elements.name.focus();
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const name = String(data?.get("name") ?? "").trim();
|
||||
if (!data || name === project.name) return;
|
||||
try {
|
||||
await api.patch(`${base}/${encodeURIComponent(project.id)}`, { name });
|
||||
toast(t("Admin.Projects.Renamed", name));
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
await load();
|
||||
}
|
||||
|
||||
/** Delete, after a confirmation that names the project: it and its versions move to the sequence's project trash. */
|
||||
async function remove(project) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Projects.DeleteTitle", project.name),
|
||||
body: t("Admin.Projects.DeleteBody", formatNumber(project.headNumber)),
|
||||
confirm: t("Admin.Projects.DeleteConfirm"),
|
||||
confirmTip: t("Admin.Projects.DeleteConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
try {
|
||||
await api.del(`${base}/${encodeURIComponent(project.id)}`);
|
||||
toast(t("Admin.Projects.Deleted", project.name));
|
||||
forget(project.id);
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
await load();
|
||||
}
|
||||
|
||||
load();
|
||||
return {
|
||||
onEvent(e) {
|
||||
if ((e.type === "projectChanged" && e.sequenceId === sequenceId) || e.type === "reconnected") {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
if (host.isConnected) load();
|
||||
}, AFTER_CHANGE_MS);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
|
||||
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, the originals and the renders
|
||||
// to download. Nothing here edits the video: its settings and its renders are the desktop editor's.
|
||||
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, its projects (R8: listed,
|
||||
// renamed and deleted, projects.js), the originals and the renders to download. Nothing here edits the video: its settings,
|
||||
// its projects' versions and its renders are the desktop editor's.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js";
|
||||
import { projectsSection } from "./projects.js";
|
||||
|
||||
const FRAME_PAGE = 500;
|
||||
/** Deleting more photos than this asks for their number to be typed. */
|
||||
@@ -80,11 +82,16 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
<div class="table-foot" id="frames-foot" hidden><span class="muted" id="frames-shown"></span><span class="spacer"></span>
|
||||
<button class="btn small" id="frames-more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Sequence.MorePhotos.Tip"></button></div>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="projects-title">
|
||||
<div class="panel-head padded"><h2 id="projects-title" data-i18n="Admin.Projects.Title"></h2><span class="muted ellipsis" id="projects-meta"></span></div>
|
||||
<div id="projects"></div>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="renders-title">
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
|
||||
<div id="renders"></div>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
const projects = projectsSection(root.querySelector("#projects"), root.querySelector("#projects-meta"), { api, sequenceId: id });
|
||||
const form = root.querySelector("form");
|
||||
const framesHost = root.querySelector("#frames");
|
||||
escapeReverts(form);
|
||||
@@ -573,6 +580,7 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
}
|
||||
|
||||
onEvent((e) => {
|
||||
projects.onEvent(e);
|
||||
if (e.type === "jobState") {
|
||||
// The event names neither the job's kind nor its targets: any job that ended may have worked on this one. The timer
|
||||
// is not pushed back by the next one, so a busy queue still refreshes the page every AFTER_JOB_MS; a refresh that
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
@@ -11,8 +14,9 @@ using Chronos.Server.Storage;
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset), cancel,
|
||||
/// pause, resume, retry and priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
|
||||
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset; a render of a
|
||||
/// project version is checked against the sequence's projects, owner review 2, R8), cancel, pause, resume, retry and
|
||||
/// priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
|
||||
/// </summary>
|
||||
public static class JobEndpoints
|
||||
{
|
||||
@@ -62,7 +66,7 @@ public static class JobEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
|
||||
ServerArchive archive, AuditLog audit)
|
||||
ServerArchive archive, AuditLog audit, [FromServices] ArchiveService? archives)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (!JobWire.TryParseKind(request.Kind, out var kind) || !(kind == JobKind.Render || SequenceKinds.Contains(kind) || ArchiveKinds.Contains(kind)))
|
||||
@@ -94,7 +98,11 @@ public static class JobEndpoints
|
||||
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
|
||||
if (kind == JobKind.Render)
|
||||
{
|
||||
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
if (ParseRender(request.ParametersJson) is not { } parsed) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
// A render of a project version (owner review 2, R8): of the sequence's projects, a project alone pinned to its head.
|
||||
var (render, missing) = await ProjectRenderAsync(db, archives, targets[0], parsed, ct);
|
||||
if (missing is not null) return ApiErrors.NotFound(context, missing);
|
||||
var parametersJson = render == parsed ? request.ParametersJson : JsonSerializer.Serialize(render, ProtocolJson.Default.RenderJobParameters);
|
||||
// A batch becomes one job per preset: a render node uploads one file per job (BRIEF §14.7).
|
||||
IReadOnlyList<RenderJobParameters> each;
|
||||
try
|
||||
@@ -107,7 +115,7 @@ public static class JobEndpoints
|
||||
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
}
|
||||
queue = each.Count == 1
|
||||
? [(ProcessingJobs.RenderLabel(label, render.PresetName), request.ParametersJson)]
|
||||
? [(ProcessingJobs.RenderLabel(label, render.PresetName), parametersJson)]
|
||||
: [.. each.Select(p => (ProcessingJobs.RenderLabel(label, p.PresetName), (string?)JsonSerializer.Serialize(p, ProtocolJson.Default.RenderJobParameters)))];
|
||||
}
|
||||
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
|
||||
@@ -133,6 +141,51 @@ public static class JobEndpoints
|
||||
return Results.Json(Dto.Job(first!), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The render of a project version (owner review 2, R8), checked against the sequence: <see cref="RenderJobParameters.ProjectVersionId"/>
|
||||
/// must be a version of one of its projects (that project, when <see cref="RenderJobParameters.ProjectId"/> names one too) and
|
||||
/// fills in the project; a live project alone, without settings of its own, renders its head as it is now, which the job then
|
||||
/// names, so the render records the version it rendered; embedded settings with a project render as they are, recording
|
||||
/// the project. A deleted project's versions still render (they are kept). Without either, the parameters as they are.
|
||||
/// Returns what is missing (<c>project</c>, <c>version</c>) instead of the parameters when they do not hold.
|
||||
/// </summary>
|
||||
internal static async Task<(RenderJobParameters Parameters, string? Missing)> ProjectRenderAsync(ChronosDatabase db, ArchiveService? archives, Guid sequenceId,
|
||||
RenderJobParameters render, CancellationToken ct)
|
||||
{
|
||||
if (render.ProjectId is null && render.ProjectVersionId is null) return (render, null);
|
||||
var projects = LibraryEndpoints.Engine(archives, db).Projects;
|
||||
ProjectVersion? version = null;
|
||||
if (render.ProjectVersionId is { } versionId && (version = await KnownVersionAsync(versionId)) is null) return (render, "version");
|
||||
var projectId = render.ProjectId ?? version!.ProjectId;
|
||||
if (await db.Projects.GetAsync(projectId, ct) is not { } project)
|
||||
{
|
||||
// A project the index does not know yet may be in the sequence's sidecars: listing reads them first.
|
||||
await projects.ListAsync(sequenceId, ct);
|
||||
project = await db.Projects.GetAsync(projectId, ct);
|
||||
}
|
||||
if (project is null || project.SequenceId != sequenceId) return (render, "project");
|
||||
if (version is not null) return version.ProjectId == project.Id ? (render with { ProjectId = project.Id }, null) : (render, "version");
|
||||
if (render.SettingsJson is not null) return (render with { ProjectId = project.Id }, null);
|
||||
try
|
||||
{
|
||||
// Caught up first: Main's head is the sequence's settings as they are now.
|
||||
var head = await projects.HeadAsync(project.Id, ct);
|
||||
return (render with { ProjectId = project.Id, ProjectVersionId = head.Id }, null);
|
||||
}
|
||||
catch (ProjectException)
|
||||
{
|
||||
// A deleted project has no head to render; its versions, named by id, still render (they are kept).
|
||||
return (render, project.DeletedAt is null ? "version" : "project");
|
||||
}
|
||||
|
||||
async Task<ProjectVersion?> KnownVersionAsync(Guid id)
|
||||
{
|
||||
if (await db.Projects.GetVersionAsync(id, ct) is { } known) return known;
|
||||
await projects.ListAsync(sequenceId, ct);
|
||||
return await db.Projects.GetVersionAsync(id, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The oriented size of the sequence's first frame (what a preset without a fixed size renders at), else the job's size.</summary>
|
||||
private static async Task<(int Width, int Height)> SourceSizeAsync(ChronosDatabase db, Guid sequenceId, RenderJobParameters render, CancellationToken ct) =>
|
||||
(await db.Frames.ListBySequenceAsync(sequenceId, limit: 1, cancellationToken: ct)).FirstOrDefault() is { Width: > 0, Height: > 0 } frame
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
using Microsoft.AspNetCore.Http.Metadata;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Security;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/sequences/{sid}/projects</c> (owner review 2, R8): the server as the home of its sequences' projects, through
|
||||
/// the archive engine's <see cref="ProjectService"/> as a desktop's archive is (its sidecars first, then the index, under the
|
||||
/// sequence's lease). The live projects with Main first (made from the sequence's settings when first read), a new project
|
||||
/// from a version or from Main's head, rename, delete into the sequence's projects' trash (never Main), the head, the versions
|
||||
/// a page at a time and one by id, the push of a version made in a workspace (a fast-forward, a repeated push answered again,
|
||||
/// a divergence, a hash, format or portability refusal), and the frames a workspace places the positions on. Reading needs
|
||||
/// Read; making, renaming and pushing Edit; deleting Delete, and the sequence's owner, the project's maker or an admin.
|
||||
/// Every change is told to connected clients as <c>projectChanged</c> (the archive module, from what each call changed) and
|
||||
/// creations, renames and deletions are audited. Nothing here edits a video on the admin panel: it lists and manages.
|
||||
/// </summary>
|
||||
public static class ProjectEndpoints
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const long PushBodyLimit = 16L * 1024 * 1024;
|
||||
|
||||
/// <summary>Versions one page may hold.</summary>
|
||||
public const int MaxPage = 200;
|
||||
|
||||
private const int MaxNote = 2000;
|
||||
private const int MaxClientName = 200;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var projects = api.MapGroup("/sequences/{sid:guid}/projects").Requires(Permissions.Read);
|
||||
projects.MapGet("", ListAsync);
|
||||
projects.MapPost("", CreateAsync).Requires(Permissions.Edit);
|
||||
projects.MapGet("/frames", FramesAsync);
|
||||
projects.MapGet("/{pid:guid}", GetAsync);
|
||||
projects.MapPatch("/{pid:guid}", RenameAsync).Requires(Permissions.Edit);
|
||||
projects.MapDelete("/{pid:guid}", DeleteAsync).Requires(Permissions.Delete);
|
||||
projects.MapGet("/{pid:guid}/head", HeadAsync);
|
||||
projects.MapGet("/{pid:guid}/versions", VersionsAsync);
|
||||
projects.MapGet("/{pid:guid}/versions/{vid:guid}", VersionAsync);
|
||||
projects.MapPost("/{pid:guid}/versions", PushAsync).Requires(Permissions.Edit).WithMetadata(new PushBodyLimitMetadata());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static async Task<IResult> 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");
|
||||
var projects = LibraryEndpoints.Engine(archives, db).Projects;
|
||||
var list = await projects.ListAsync(sid, ct);
|
||||
if (!list.Any(p => p.IsMain))
|
||||
{
|
||||
await projects.MainAsync(sid, ct);
|
||||
list = await projects.ListAsync(sid, ct);
|
||||
}
|
||||
var items = new List<ProjectDto>(list.Count);
|
||||
foreach (var project in list) items.Add(ProjectWire.ToDto(project, await HeadOfAsync(projects, project, ct)));
|
||||
return Results.Json(items, ProtocolJson.Default.ListProjectDto);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A new project (201): its first version, kind <c>imported</c>, copies <c>fromVersionId</c> (a version of any project of the
|
||||
/// sequence; 404 <c>not_found</c> <c>version</c> otherwise) or Main's head. 400 <c>invalid_name</c>, 409 <c>name_taken</c>.
|
||||
/// Audited <c>project_created</c>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, Guid sid, CreateProjectRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
|
||||
await RunAsync(context, "version", async ct =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sid, ct) is null) return ApiErrors.NotFound(context, "sequence");
|
||||
var projects = LibraryEndpoints.Engine(archives, db).Projects;
|
||||
// Once asked for, the project is made even if the client goes away meanwhile.
|
||||
var created = await projects.CreateAsync(sid, request.Name ?? string.Empty, request.FromVersionId, caller.User.Username, lifetime.ApplicationStopping);
|
||||
await audit.WriteAsync(caller, context, "project_created", "project", created.Id.ToString(), $"{sid} · {created.Name}");
|
||||
return Results.Json(ProjectWire.ToDto(created, await HeadOfAsync(projects, created, ct)), ProtocolJson.Default.ProjectDto,
|
||||
statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
|
||||
/// <summary>A live project of the sequence; 404 <c>not_found</c> <c>project</c> for one deleted or of another sequence.</summary>
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid sid, Guid pid, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
|
||||
await RunAsync(context, "project", 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;
|
||||
var project = known.Project!;
|
||||
if (project.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
|
||||
return Results.Json(ProjectWire.ToDto(project, await HeadOfAsync(projects, project, ct)), ProtocolJson.Default.ProjectDto);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Gives a project another name (Main too: the desktop shows Main in its own language either way). 400 <c>invalid_name</c>,
|
||||
/// 409 <c>name_taken</c>. Audited <c>project_renamed</c> when the name changed.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RenameAsync(HttpContext context, Caller caller, Guid sid, Guid pid, RenameProjectRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
|
||||
await RunAsync(context, "project", 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;
|
||||
var before = known.Project!;
|
||||
if (before.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
|
||||
var renamed = await projects.RenameAsync(pid, request.Name ?? string.Empty, lifetime.ApplicationStopping);
|
||||
if (renamed.Name != before.Name)
|
||||
await audit.WriteAsync(caller, context, "project_renamed", "project", pid.ToString(), $"{sid} · {before.Name} → {renamed.Name}");
|
||||
return Results.Json(ProjectWire.ToDto(renamed, await HeadOfAsync(projects, renamed, ct)), ProtocolJson.Default.ProjectDto);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a project (204): its record says so and its folder, with every version, moves to the sequence's
|
||||
/// <c>.chronos/projects/.trash</c>, kept and never erased by Chronos. The Main project is refused (409
|
||||
/// <c>main_cannot_be_deleted</c>); so is another account's project of another account's sequence, for anyone but an admin
|
||||
/// (403). Audited <c>project_deleted</c>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid sid, Guid pid, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
|
||||
await RunAsync(context, "project", 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;
|
||||
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);
|
||||
await projects.DeleteAsync(pid, lifetime.ApplicationStopping);
|
||||
await audit.WriteAsync(caller, context, "project_deleted", "project", pid.ToString(), $"{sid} · {project.Name}");
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The newest version of a live project; 404 <c>not_found</c> <c>project</c> once it is deleted (its versions are still
|
||||
/// listed: a workspace's copy of it reads as gone, never as in step), <c>version</c> when it has none.
|
||||
/// </summary>
|
||||
private static async Task<IResult> HeadAsync(HttpContext context, Guid sid, Guid pid, 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 (known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
|
||||
return Results.Json(ProjectWire.ToDto(await projects.HeadAsync(pid, ct)), ProtocolJson.Default.ProjectVersionDto);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// One page of the project's versions: newest first, numbered below <paramref name="before"/> (from the head when absent),
|
||||
/// or with <paramref name="after"/> oldest first, numbered above it. <paramref name="limit"/> 1–<see cref="MaxPage"/> (50 newest
|
||||
/// first, 100 oldest first). 400 <c>bad_request</c> (<c>after</c> with <c>before</c>, a number below 0).
|
||||
/// </summary>
|
||||
private static async Task<IResult> VersionsAsync(HttpContext context, Guid sid, Guid pid, int? before, int? after, int? limit, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives)
|
||||
{
|
||||
if (before is not null && after is not null) return ApiErrors.BadRequest(context, "bad_request", "after");
|
||||
if (before is < 0) return ApiErrors.BadRequest(context, "bad_request", "before");
|
||||
if (after is < 0) return ApiErrors.BadRequest(context, "bad_request", "after");
|
||||
var take = Math.Clamp(limit ?? (after is null ? 50 : 100), 1, MaxPage);
|
||||
return await RunAsync(context, "project", 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;
|
||||
var page = after is { } from
|
||||
? await projects.VersionsAfterAsync(pid, from, take + 1, ct)
|
||||
: 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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>A version of the project by id; one the index does not know yet is looked for in the sequence's sidecars first.</summary>
|
||||
private static async Task<IResult> VersionAsync(HttpContext context, Guid sid, Guid pid, Guid vid, 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 (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");
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Stores a version made in a workspace from the project's head (<see cref="ProjectService.PushAsync"/>), recording the
|
||||
/// account that pushed it as its author: 201 <c>stored</c> (a fast-forward: numbered head + 1, Main's mirrored into the
|
||||
/// sequence's settings), 200 <c>already_stored</c> (the same id and content stored before: a push repeated after its
|
||||
/// answer was lost), 409 <c>project_diverged</c> (the head moved past its parent; the answer carries the head), 422
|
||||
/// <c>hash_mismatch</c>, <c>newer_format</c>, <c>invalid_version</c> or <c>too_large</c> (a version file over 64 MiB), each answered as a
|
||||
/// <see cref="ProjectPushResultDto"/> and logged. 400 <c>bad_request</c> (<c>id</c>, <c>settingsJson</c>, <c>contentHash</c>,
|
||||
/// <c>note</c>, <c>clientName</c>); 413 <c>too_large</c> above <see cref="PushBodyLimit"/>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> PushAsync(HttpContext context, Caller caller, Guid sid, Guid pid, ProjectVersionDto request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, ILoggerFactory loggers, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (request is null) return ApiErrors.BadRequest(context, "bad_request");
|
||||
if (request.Id == Guid.Empty) return ApiErrors.BadRequest(context, "bad_request", "id");
|
||||
if (string.IsNullOrEmpty(request.SettingsJson)) return ApiErrors.BadRequest(context, "bad_request", "settingsJson");
|
||||
if (string.IsNullOrEmpty(request.ContentHash)) return ApiErrors.BadRequest(context, "bad_request", "contentHash");
|
||||
if (request.Note is { Length: > MaxNote }) return ApiErrors.BadRequest(context, "bad_request", "note");
|
||||
if (request.ClientName is { Length: > MaxClientName }) return ApiErrors.BadRequest(context, "bad_request", "clientName");
|
||||
return await RunAsync(context, "project", 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 (known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
|
||||
var client = string.IsNullOrWhiteSpace(request.ClientName) ? caller.ClientName : request.ClientName.Trim();
|
||||
var version = ProjectWire.ToVersion(request) with
|
||||
{
|
||||
ProjectId = pid,
|
||||
Author = caller.User.Username,
|
||||
ClientName = client,
|
||||
Note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim(),
|
||||
CreatedAt = request.CreatedAt == default ? DateTimeOffset.UtcNow : request.CreatedAt,
|
||||
StoredAt = null,
|
||||
};
|
||||
// Once sent, the version is stored even if the client goes away meanwhile; a client that asks again is answered already_stored.
|
||||
var result = await projects.PushAsync(pid, version, lifetime.ApplicationStopping);
|
||||
var outcome = ProjectWire.Outcome(result.Outcome);
|
||||
loggers.CreateLogger("Chronos.Server.Projects").LogInformation(
|
||||
"Version {Version} of project {Project} ({Name}) of sequence {Sequence} pushed by {User} from {Client}: {Outcome}{Number}", request.Id, pid,
|
||||
known.Project.Name, sid, caller.User.Username, client ?? "-", outcome, result.Version is { } stored ? $" as number {stored.Number}" : string.Empty);
|
||||
var (status, code, message) = result.Outcome switch
|
||||
{
|
||||
PushOutcome.Stored => (StatusCodes.Status201Created, (string?)null, (string?)null),
|
||||
PushOutcome.AlreadyStored => (StatusCodes.Status200OK, null, null),
|
||||
PushOutcome.Diverged => (StatusCodes.Status409Conflict, ProjectErrors.Diverged, ApiErrors.Message(context, ProjectErrors.Diverged)),
|
||||
PushOutcome.HashMismatch => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.HashMismatch, ApiErrors.Message(context, "version_hash_mismatch")),
|
||||
PushOutcome.NewerFormat => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.NewerFormat, ApiErrors.Message(context, ProjectErrors.NewerFormat)),
|
||||
PushOutcome.TooLarge => (StatusCodes.Status422UnprocessableEntity, "too_large", ApiErrors.Message(context, "too_large")),
|
||||
_ => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.InvalidVersion, ApiErrors.Message(context, ProjectErrors.InvalidVersion)),
|
||||
};
|
||||
return Results.Json(new ProjectPushResultDto(outcome, result.Version is { } v ? ProjectWire.ToDto(v) : null,
|
||||
result.Head is { } h ? ProjectWire.ToDto(h) : null, code, message), ProtocolJson.Default.ProjectPushResultDto, statusCode: status);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence's frames in index order and the photo aliases of its conversions, as of one frames version
|
||||
/// (<see cref="SequenceEndpoints.SnapshotOfAsync"/>): what a workspace places a version's positions on.
|
||||
/// </summary>
|
||||
private static async Task<IResult> FramesAsync(HttpContext context, Guid sid, ChronosDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await SequenceEndpoints.SnapshotOfAsync(db, sid, async (on, sequence, c) =>
|
||||
(Frames: await AllFramesAsync(on, sequence.Id, c), Removals: await on.FrameRemovals.ListBySequenceAsync(sequence.Id, c)), ct) is not { } snapshot)
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
var (row, (frames, removals)) = snapshot;
|
||||
var aliases = ProjectWire.Aliases(removals);
|
||||
return Results.Json(new ProjectFramesDto(sid, row.FramesVersion, [.. frames.Select(Dto.Frame)], aliases.Count == 0 ? null : aliases),
|
||||
ProtocolJson.Default.ProjectFramesDto);
|
||||
}
|
||||
|
||||
/// <summary>Every frame of a sequence in index order, read a page at a time.</summary>
|
||||
internal static async Task<List<Frame>> AllFramesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
const int pageSize = 1000;
|
||||
var frames = new List<Frame>();
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, pageSize, cancellationToken);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < pageSize) return frames;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence and a project of it (deleted ones too, whose versions are kept); one the index does not know yet (an index
|
||||
/// taken back from a backup, a project another program sharing the archive made) is looked for in the sequence's sidecars
|
||||
/// first. Otherwise the refusal: 404 <c>not_found</c> <c>sequence</c> or <c>project</c>.
|
||||
/// </summary>
|
||||
private static async Task<(Sequence? Sequence, SequenceProject? Project, IResult? Refused)> KnownAsync(HttpContext context, ChronosDatabase db,
|
||||
ProjectService projects, Guid sid, Guid pid, CancellationToken ct)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sid, ct) is not { } sequence) return (null, null, ApiErrors.NotFound(context, "sequence"));
|
||||
if (await projects.GetAsync(pid, ct) is not { } project)
|
||||
{
|
||||
await projects.ListAsync(sid, ct);
|
||||
project = await projects.GetAsync(pid, ct);
|
||||
}
|
||||
return project is not null && project.SequenceId == sid ? (sequence, project, null) : (sequence, null, ApiErrors.NotFound(context, "project"));
|
||||
}
|
||||
|
||||
private static async Task<ProjectVersion?> HeadOfAsync(ProjectService projects, SequenceProject project, CancellationToken ct) =>
|
||||
project.HeadVersionId is { } id ? await projects.GetVersionAsync(id, ct) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Runs a project call with its refusals answered by their codes: 404 <c>not_found</c> (<c>sequence</c>, or
|
||||
/// <paramref name="notFound"/> for a project or version the engine does not know), 400 <c>invalid_name</c>, 409
|
||||
/// <c>name_taken</c>, <c>main_cannot_be_deleted</c>; 503 <c>archive_offline</c> (offline or read-only), <c>sequence_busy</c>
|
||||
/// (another writer held it past the lease wait), <c>folder_moved</c> (its folder is not where the index has it),
|
||||
/// <c>projects_unreadable</c> (a project record or version this Chronos cannot read now: nothing was written); 413
|
||||
/// <c>too_large</c> for a version file over 64 MiB; 409 <c>folder_in_use</c> when a project's file cannot be written.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RunAsync(HttpContext context, string notFound, Func<CancellationToken, Task<IResult>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await call(context.RequestAborted);
|
||||
}
|
||||
catch (ProjectException ex)
|
||||
{
|
||||
return ex.Reason switch
|
||||
{
|
||||
ProjectError.SequenceNotFound => ApiErrors.NotFound(context, "sequence"),
|
||||
ProjectError.InvalidName => ApiErrors.BadRequest(context, ProjectErrors.InvalidName),
|
||||
ProjectError.NameTaken => ApiErrors.Conflict(context, ProjectErrors.NameTaken),
|
||||
ProjectError.MainCannotBeDeleted => ApiErrors.Conflict(context, ProjectErrors.MainCannotBeDeleted),
|
||||
_ => ApiErrors.NotFound(context, notFound),
|
||||
};
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "sequence_busy");
|
||||
}
|
||||
catch (SequenceFolderMovedException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "folder_moved");
|
||||
}
|
||||
catch (ProjectsUnreadableException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "projects_unreadable");
|
||||
}
|
||||
catch (ProjectVersionTooLargeException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status413PayloadTooLarge, "too_large");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The push route's body limit (<see cref="PushBodyLimit"/>), applied by routing as it selects the endpoint.</summary>
|
||||
private sealed class PushBodyLimitMetadata : IRequestSizeLimitMetadata
|
||||
{
|
||||
public long? MaxRequestBodySize => PushBodyLimit;
|
||||
}
|
||||
}
|
||||
@@ -129,7 +129,7 @@ public static class SequenceEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, ChronosDatabase db,
|
||||
AuditLog audit, EventHub events)
|
||||
AuditLog audit, EventHub events, ProjectCatchUp projects)
|
||||
{
|
||||
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");
|
||||
@@ -166,6 +166,9 @@ public static class SequenceEndpoints
|
||||
var sequence = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request));
|
||||
events.Publish(new SequenceChangedEvent(id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
// Settings written outside the projects (an older client, the sync of a desktop's copy) become Main's next version now,
|
||||
// so a workspace with Main checked out hears that its home moved (owner review 2, R8).
|
||||
if (request.SettingsJson is not null) projects.Touch(id);
|
||||
context.Response.Headers.ETag = ETag(sequence);
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
@@ -266,19 +269,28 @@ public static class SequenceEndpoints
|
||||
/// the sequence is gone.
|
||||
/// </summary>
|
||||
internal static async Task<(Sequence Sequence, List<ManifestFrame> Frames)?> SnapshotAsync(ChronosDatabase db, Guid id,
|
||||
Func<ChronosRepositories, Sequence, CancellationToken, Task<List<ManifestFrame>>> listFrames, CancellationToken cancellationToken)
|
||||
Func<ChronosRepositories, Sequence, CancellationToken, Task<List<ManifestFrame>>> listFrames, CancellationToken cancellationToken) =>
|
||||
await SnapshotOfAsync(db, id, listFrames, cancellationToken) is { } snapshot ? (snapshot.Sequence, snapshot.Value) : null;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="SnapshotAsync"/> for anything read from the sequence's frames (the frames a render node renders and the photos
|
||||
/// a project version is placed on, the frames and photo aliases of a project home): <paramref name="read"/> runs again while
|
||||
/// the frames version moved during it, then inside the transaction holding the sequence's row. Null when the sequence is gone.
|
||||
/// </summary>
|
||||
internal static async Task<(Sequence Sequence, T Value)?> SnapshotOfAsync<T>(ChronosDatabase db, Guid id,
|
||||
Func<ChronosRepositories, Sequence, CancellationToken, Task<T>> read, CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 0; attempt < SnapshotAttempts; attempt++)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } sequence) return null;
|
||||
var frames = await listFrames(db, sequence, cancellationToken);
|
||||
var value = await read(db, sequence, cancellationToken);
|
||||
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } after) return null;
|
||||
if (after.FramesVersion == sequence.FramesVersion) return (sequence, frames);
|
||||
if (after.FramesVersion == sequence.FramesVersion) return (sequence, value);
|
||||
}
|
||||
// Commits keep landing (an upload of earlier photos): the frames are listed while none can.
|
||||
await using var tx = await db.BeginAsync(cancellationToken);
|
||||
if (await tx.Sequences.GetForUpdateAsync(id, cancellationToken) is not { } locked) return null;
|
||||
return (locked, await listFrames(tx, locked, cancellationToken));
|
||||
return (locked, await read(tx, locked, cancellationToken));
|
||||
}
|
||||
|
||||
private static async Task<IResult> FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, ChronosDatabase db)
|
||||
|
||||
@@ -104,7 +104,8 @@ public sealed class ServerState
|
||||
/// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary>
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
|
||||
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -163,6 +163,9 @@ public static class ServerHost
|
||||
services.AddSingleton<UploadMaintenance>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
||||
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
|
||||
// Main takes settings written outside the projects soon after they are (owner review 2, R8).
|
||||
services.AddSingleton<ProjectCatchUp>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>());
|
||||
services.AddSingleton<DiscoveryBeaconService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
||||
}
|
||||
@@ -181,6 +184,7 @@ public static class ServerHost
|
||||
AuthEndpoints.Map(api);
|
||||
UserEndpoints.Map(api);
|
||||
SequenceEndpoints.Map(api);
|
||||
ProjectEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
@@ -20,7 +23,9 @@ namespace Chronos.Server.Jobs;
|
||||
/// render jobs they can encode, report progress, and upload the output in resumable chunks that become a render of
|
||||
/// the sequence. A claimed job lists every frame with its flags (a node renders none missing, corrupt or excluded) and
|
||||
/// the proxies the server asks for (<see cref="ServerProxies"/>), which the node sends from the originals it fetched.
|
||||
/// A node that stops heart-beating loses its jobs to the queue (<see cref="RenderNodeMonitor"/>).
|
||||
/// A node that stops heart-beating loses its jobs to the queue (<see cref="RenderNodeMonitor"/>). A job of a project version
|
||||
/// (owner review 2, R8) gets that version's settings placed on the frames it lists, and its render records the project and
|
||||
/// the version.
|
||||
/// </summary>
|
||||
public sealed class RenderNodeService(
|
||||
ChronosDatabase db,
|
||||
@@ -90,14 +95,62 @@ public sealed class RenderNodeService(
|
||||
continue;
|
||||
}
|
||||
await TouchAsync(node, cancellationToken);
|
||||
if (await SettingsAsync(parameters, sequence, cancellationToken) is not { } settings)
|
||||
{
|
||||
await FinishAsync(node, job, JobState.Failed, Loc.L("Errors.Render.ProjectVersion"), cancellationToken);
|
||||
continue;
|
||||
}
|
||||
var spec = ServerProxies.Spec(archive.Current);
|
||||
return new ClaimedJob(Dto.Job(job), sequence.Id, parameters.SettingsJson ?? sequence.SettingsJson ?? "{}", parameters.PresetJson,
|
||||
parameters.UseProxies, await ServerProxies.FramesAsync(db, archive.Current, sequence, spec, cancellationToken), spec);
|
||||
// The frames the node renders and the photos a project version's positions are placed on, of one frames version.
|
||||
var snapshot = await SequenceEndpoints.SnapshotOfAsync(db, sequence.Id, async (on, row, ct) => (
|
||||
Frames: await ServerProxies.FramesAsync(on, archive.Current, row, spec, ct),
|
||||
Photos: settings.Portable ? HomePhotos.Of(await ProjectEndpoints.AllFramesAsync(on, row.Id, ct), await HomePhotos.AliasesAsync(on, row.Id, ct)) : null),
|
||||
cancellationToken);
|
||||
if (snapshot is not { } taken)
|
||||
{
|
||||
await FinishAsync(node, job, JobState.Failed, "The sequence no longer exists.", cancellationToken);
|
||||
continue;
|
||||
}
|
||||
var (frames, photos) = taken.Value;
|
||||
return new ClaimedJob(Dto.Job(job), sequence.Id, photos is null ? settings.Json : Placed(settings.Json, photos), parameters.PresetJson,
|
||||
parameters.UseProxies, frames, spec);
|
||||
}
|
||||
await TouchAsync(node, cancellationToken);
|
||||
return (ClaimedJob?)null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings a node renders: the job's own (a project version's portable form among them, whose positions are placed on
|
||||
/// the frames the node gets), else those of the project version the job names (owner review 2, R8), else the sequence's.
|
||||
/// Null when the job names a version that is not one of the sequence's projects'.
|
||||
/// </summary>
|
||||
private async Task<(string Json, bool Portable)?> SettingsAsync(RenderJobParameters parameters, Sequence sequence, CancellationToken cancellationToken)
|
||||
{
|
||||
if (parameters.SettingsJson is { } embedded) return (embedded, Waits(embedded));
|
||||
if (parameters.ProjectVersionId is not { } versionId) return (sequence.SettingsJson ?? "{}", false);
|
||||
return await db.Projects.GetVersionAsync(versionId, cancellationToken) is { } version
|
||||
&& await db.Projects.GetAsync(version.ProjectId, cancellationToken) is { } project && project.SequenceId == sequence.Id
|
||||
? (version.SettingsJson, Waits(version.SettingsJson))
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Settings with positions that wait for their photos (a project version's portable form, settings synced from another copy).</summary>
|
||||
private static bool Waits(string settingsJson) => settingsJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The settings with their waiting positions placed on <paramref name="photos"/>, as the server's own render does; others as they are.</summary>
|
||||
private static string Placed(string settingsJson, FramePhotos photos)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProjectContent.Place(settingsJson, photos);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not a project: the node says so as it reads it.
|
||||
return settingsJson;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Outcome<bool>> ProgressAsync(Caller caller, Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome<bool>.Fail(404, "not_found", "node");
|
||||
@@ -176,10 +229,15 @@ public sealed class RenderNodeService(
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var output = JsonSerializer.Deserialize(upload.RenderJson, ProtocolJson.Default.RenderResultRequest)!;
|
||||
var sequence = await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken);
|
||||
// The render records the project and the version its job rendered (owner review 2, R8).
|
||||
var rendered = JobEndpoints.ParseRender(job.ParametersJson);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
|
||||
render = sequence is null
|
||||
? null
|
||||
: await renders.CommitAsync(sequence, staged, output, node.ClientName, Guid.CreateVersion7(), rendered?.ProjectId, rendered?.ProjectVersionId,
|
||||
cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException or FolderMovedException)
|
||||
{
|
||||
|
||||
@@ -14,13 +14,17 @@ namespace Chronos.Server.Storage;
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, Reorganize's
|
||||
/// <c>move</c> jobs and the <c>convert</c> jobs, which tell connected clients of the sequences they change or make, and check
|
||||
/// their space against the space volume's free bytes, <see cref="VolumeSpace.Report"/>); a scan
|
||||
/// their space against the space volume's free bytes, <see cref="VolumeSpace.Report"/>); the projects of its sequences, every
|
||||
/// change of them told to connected clients as <c>projectChanged</c> (owner review 2, R8); a scan
|
||||
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
|
||||
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
|
||||
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
|
||||
/// </summary>
|
||||
public static class ArchiveModule
|
||||
{
|
||||
/// <summary>The change a conversion's Replace tells about a sequence (<c>sequenceChanged</c>).</summary>
|
||||
private const string ConvertedChange = "converted";
|
||||
|
||||
/// <summary>Name the server writes into the archive's lease files.</summary>
|
||||
public static string Owner { get; } = "server@" + Environment.MachineName;
|
||||
|
||||
@@ -40,6 +44,18 @@ public static class ArchiveModule
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
// A conversion may leave settings Main has not taken yet (owner review 2, R8).
|
||||
if (change == ConvertedChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
|
||||
},
|
||||
// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that
|
||||
// project checked out knows its home moved, the admin panel lists the projects again. Main's head written into the
|
||||
// sequence's settings is a settings change for the clients that read those (an older client, a desktop's sync).
|
||||
ProjectsChanged = async (changed, ct) =>
|
||||
{
|
||||
foreach (var change in changed.Changes)
|
||||
events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
|
||||
if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
},
|
||||
Decoder = DecoderFactory.CreateServer(),
|
||||
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
|
||||
|
||||
@@ -18,7 +18,8 @@ namespace Chronos.Server.Storage;
|
||||
/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
|
||||
/// jobs wait for render nodes until none can take them (<see cref="RenderNodeAvailability"/>), and then render here as
|
||||
/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
|
||||
/// clients as <c>sequenceChanged</c> events (§14.3).
|
||||
/// clients as <c>sequenceChanged</c> events (§14.3); Auto values changed become Main's next version (owner review 2, R8). A
|
||||
/// render of a project version places that version's settings on the sequence's frames and records the project and the version.
|
||||
/// </summary>
|
||||
public static class ProcessingModule
|
||||
{
|
||||
@@ -48,6 +49,8 @@ public static class ProcessingModule
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
// Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
|
||||
if (change == ProcessingOptions.SettingsChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Channels;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Projects;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Brings a sequence's projects in step soon after its settings were written outside the projects (owner review 2, R8): an
|
||||
/// older client's or a desktop sync's <c>PATCH /sequences/{id}</c>, an analysis's Auto values, a conversion. Main takes them
|
||||
/// as an external version at once (<see cref="ProjectService.CatchUpAsync"/>), and connected clients hear
|
||||
/// <c>projectChanged</c> without waiting for the next project call, which would catch up all the same. Only a sequence that
|
||||
/// has its Main project already: Main is made when the projects are first read, never for every sequence an analysis or a
|
||||
/// sync touches. One sequence at a time in the background; a sequence asked for again while it waits is caught up once; one
|
||||
/// another writer holds is tried again a few times, then left to that next call. Nothing happens without the archive engine
|
||||
/// (a test host without it).
|
||||
/// </summary>
|
||||
public sealed class ProjectCatchUp(IServiceProvider services, ILogger<ProjectCatchUp> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>The waits before each new try of a sequence another writer holds.</summary>
|
||||
private static readonly TimeSpan[] Retries = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2)];
|
||||
|
||||
private readonly Channel<(Guid Id, int Attempt)> _queue = Channel.CreateUnbounded<(Guid Id, int Attempt)>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly ConcurrentDictionary<Guid, byte> _waiting = new();
|
||||
private CancellationToken _stopping;
|
||||
|
||||
/// <summary>Catches the projects of <paramref name="sequenceId"/> up soon (at once when nothing waits).</summary>
|
||||
public void Touch(Guid sequenceId) => Enqueue(sequenceId, 0);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_stopping = stoppingToken;
|
||||
try
|
||||
{
|
||||
await foreach (var (id, attempt) in _queue.Reader.ReadAllAsync(stoppingToken))
|
||||
{
|
||||
_waiting.TryRemove(id, out _);
|
||||
await CatchUpAsync(id, attempt, stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// The server stops: what waits is caught up by the next project call.
|
||||
}
|
||||
}
|
||||
|
||||
private void Enqueue(Guid id, int attempt)
|
||||
{
|
||||
if (_waiting.TryAdd(id, 0)) _queue.Writer.TryWrite((id, attempt));
|
||||
}
|
||||
|
||||
private async Task CatchUpAsync(Guid id, int attempt, CancellationToken cancellationToken)
|
||||
{
|
||||
if (services.GetService<ArchiveService>() is not { } archives) return;
|
||||
try
|
||||
{
|
||||
if (await services.GetRequiredService<ChronosDatabase>().Projects.GetMainAsync(id, cancellationToken) is null) return;
|
||||
await archives.Projects.CatchUpAsync(id, cancellationToken);
|
||||
}
|
||||
catch (LeaseUnavailableException) when (attempt < Retries.Length)
|
||||
{
|
||||
_ = RetryLaterAsync(id, attempt);
|
||||
}
|
||||
catch (Exception ex) when (ex is ProjectException or ArchiveOfflineException or SequenceFolderMovedException or LeaseUnavailableException)
|
||||
{
|
||||
// The sequence is gone, its archive offline or its folder elsewhere, or it stayed busy: the next project call catches up.
|
||||
logger.LogDebug("The projects of sequence {Sequence} are caught up later: {Reason}", id, ex.Message);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(ex, "The projects of sequence {Sequence} could not be caught up", id);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RetryLaterAsync(Guid id, int attempt)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(Retries[attempt], _stopping);
|
||||
Enqueue(id, attempt + 1);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Stopping.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,15 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
|
||||
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has.</exception>
|
||||
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
|
||||
CancellationToken cancellationToken) =>
|
||||
CommitAsync(sequence, stagedFile, output, producedBy, id, null, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// As above, recording the project and the version rendered (owner review 2, R8: a render node's output of a job that names
|
||||
/// them); null for a render of the sequence's own settings.
|
||||
/// </summary>
|
||||
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has.</exception>
|
||||
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id, Guid? projectId,
|
||||
Guid? projectVersionId, CancellationToken cancellationToken) =>
|
||||
_archives.UnderLeaseAsync(sequence, async row =>
|
||||
{
|
||||
if (row is null || string.IsNullOrEmpty(row.Folder) || ArchivePathGuard.Resolve(archive.Root, row.Folder.TrimEnd('/') + "/exports") is not { } exports)
|
||||
@@ -55,6 +64,8 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
|
||||
Bytes = output.Size,
|
||||
Created = time.GetUtcNow(),
|
||||
ProducedBy = producedBy,
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return (Render?)render;
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Server.Tests.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The server as the home of its sequences' projects (owner review 2, R8): <c>/api/v1/sequences/{sid}/projects</c> through
|
||||
/// the protocol client, as a desktop's workspace uses it (list, create, rename, delete, head, versions, push and the frames
|
||||
/// positions are placed on), two clients pushing to one project, the permissions, the audit, the <c>projectChanged</c>
|
||||
/// event (Main taking settings a <c>PATCH</c> wrote among them), the capability, and the leases and offline archive.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ProjectTests(TestContext context)
|
||||
{
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
[Test]
|
||||
public async Task ProjectsAreListedMadeRenamedAndDeleted()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 3);
|
||||
|
||||
// Main comes first, made from the sequence's settings the first time the projects are read.
|
||||
var main = Assert.NotNull((await client.ListProjectsAsync(sid, context.Cancellation)).SingleOrDefault());
|
||||
Assert.Equal((true, "Main", 1, sid), (main.IsMain, main.Name, main.HeadNumber, main.SequenceId));
|
||||
var mainHead = await client.GetProjectHeadAsync(sid, main.Id, context.Cancellation);
|
||||
Assert.Equal(("imported", "imported", (Guid?)mainHead.Id), (main.HeadKind, mainHead.Kind, main.HeadVersionId));
|
||||
|
||||
var vertical = await client.CreateProjectAsync(sid, new CreateProjectRequest(" Vertical social "), context.Cancellation);
|
||||
Assert.Equal(("Vertical social", false, 1, "alberto"), (vertical.Name, vertical.IsMain, vertical.HeadNumber, vertical.CreatedBy));
|
||||
var first = await client.GetProjectHeadAsync(sid, vertical.Id, context.Cancellation);
|
||||
Assert.Equal(("imported", mainHead.ContentHash), (first.Kind, first.ContentHash));
|
||||
Assert.SequenceEqual([main.Id, vertical.Id], (await client.ListProjectsAsync(sid, context.Cancellation)).Select(p => p.Id));
|
||||
// The sidecars are the truth: the project's record and its first version are in the sequence's folder.
|
||||
var folder = new ArchivePaths(server.Options.ArchivePath).Sequence((await server.Database.Sequences.GetAsync(sid))!.Folder);
|
||||
Assert.FileExists(folder.ProjectRecordPath(vertical.Id));
|
||||
Assert.FileExists(folder.VersionPath(vertical.Id, 1, first.Id));
|
||||
|
||||
await RefusedAsync(HttpStatusCode.Conflict, ProjectErrors.NameTaken, () => client.CreateProjectAsync(sid, new CreateProjectRequest("VERTICAL SOCIAL")));
|
||||
await RefusedAsync(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, () => client.CreateProjectAsync(sid, new CreateProjectRequest(" ")));
|
||||
await RefusedAsync(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, () => client.CreateProjectAsync(sid, new CreateProjectRequest(new string('x', 61))));
|
||||
Assert.Equal("version", (await RefusedAsync(HttpStatusCode.NotFound, "not_found",
|
||||
() => client.CreateProjectAsync(sid, new CreateProjectRequest("Copy", Guid.CreateVersion7())))).Error.Details);
|
||||
Assert.Equal("sequence", (await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.ListProjectsAsync(Guid.CreateVersion7()))).Error.Details);
|
||||
|
||||
// A project made from a version holds that version's settings.
|
||||
var copy = await client.CreateProjectAsync(sid, new CreateProjectRequest("4K landscape", first.Id), context.Cancellation);
|
||||
Assert.Equal(first.ContentHash, (await client.GetProjectHeadAsync(sid, copy.Id, context.Cancellation)).ContentHash);
|
||||
|
||||
var renamed = await client.RenameProjectAsync(sid, vertical.Id, "Vertical", context.Cancellation);
|
||||
Assert.Equal(("Vertical", vertical.Id), (renamed.Name, renamed.Id));
|
||||
await RefusedAsync(HttpStatusCode.Conflict, ProjectErrors.NameTaken, () => client.RenameProjectAsync(sid, copy.Id, "vertical"));
|
||||
await RefusedAsync(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, () => client.DeleteProjectAsync(sid, main.Id));
|
||||
|
||||
await client.DeleteProjectAsync(sid, copy.Id, context.Cancellation);
|
||||
Assert.SequenceEqual([main.Id, vertical.Id], (await client.ListProjectsAsync(sid, context.Cancellation)).Select(p => p.Id));
|
||||
Assert.Equal("project", (await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.GetProjectAsync(sid, copy.Id))).Error.Details);
|
||||
await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.RenameProjectAsync(sid, copy.Id, "Back"));
|
||||
// Deleted into the sequence's projects' trash with its versions, never erased; they can still be read, while it has no
|
||||
// head: a workspace's copy of it reads as gone.
|
||||
Assert.False(Directory.Exists(folder.ProjectDirectory(copy.Id)), "the project's folder left");
|
||||
Assert.Contains(Directory.EnumerateDirectories(folder.ProjectsTrashDirectory), d => Path.GetFileName(d).StartsWith(copy.Id.ToString("N"), StringComparison.Ordinal));
|
||||
Assert.Equal("project", (await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.GetProjectHeadAsync(sid, copy.Id))).Error.Details);
|
||||
Assert.Equal(1, (await client.ListProjectVersionsAsync(sid, copy.Id, ct: context.Cancellation)).Items.Single().Number);
|
||||
// The name of a deleted project is free again.
|
||||
Assert.Equal("4K landscape", (await client.CreateProjectAsync(sid, new CreateProjectRequest("4K landscape"), context.Cancellation)).Name);
|
||||
|
||||
// A project of another sequence is not this one's.
|
||||
var other = await SequenceAsync(server, token, 1, "other");
|
||||
Assert.Equal("project", (await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.GetProjectHeadAsync(other, vertical.Id))).Error.Details);
|
||||
|
||||
// Creations, renames and deletions are audited, by whom and on what.
|
||||
var audit = (await server.Database.Audit.ListAsync(null, 100)).Items;
|
||||
Assert.Contains(audit, a => a is { Action: "project_created", Username: "alberto" } && a.TargetId == vertical.Id.ToString());
|
||||
Assert.Contains(audit, a => a.Action == "project_renamed" && a.TargetId == vertical.Id.ToString() && a.Details!.EndsWith("Vertical social → Vertical", StringComparison.Ordinal));
|
||||
Assert.Contains(audit, a => a.Action == "project_deleted" && a.TargetId == copy.Id.ToString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TwoClientsPushToOneProject()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
await PushesAsync(server);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two PCs push to Main (also run on PostgreSQL): a fast-forward, the same push again, a divergence answered with the head
|
||||
/// and then replayed, the refusals that store nothing, the history a page at a time, and Main's mirror into the sequence.
|
||||
/// </summary>
|
||||
internal static async Task PushesAsync(TestServer server)
|
||||
{
|
||||
var (_, _, albertoToken) = await server.UserAsync("alberto", "editor");
|
||||
var (giuliaHttp, _, giuliaToken) = await server.UserAsync("giulia", "editor");
|
||||
using var alberto = Client(server, albertoToken);
|
||||
using var giulia = Client(server, giuliaToken);
|
||||
var sid = await SequenceAsync(server, albertoToken, 3);
|
||||
var main = (await alberto.ListProjectsAsync(sid)).Single(p => p.IsMain);
|
||||
var head = await alberto.GetProjectHeadAsync(sid, main.Id);
|
||||
var home = ProjectWire.ToHomeFrames(await alberto.GetProjectFramesAsync(sid));
|
||||
Assert.Equal(3, home.Frames.Count);
|
||||
|
||||
// A fast-forward: numbered head + 1, by the account that pushed it, as the workspace made it.
|
||||
var mine = Version(head, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.3 }, ExcludedFrames = [1] }, home, "warmer");
|
||||
var stored = await alberto.PushProjectVersionAsync(sid, main.Id, mine);
|
||||
var v2 = Assert.NotNull(stored.Version);
|
||||
Assert.Equal((ProjectPushOutcomes.Stored, 2, "alberto", "Chronos on PC-A", "warmer"), (stored.Outcome, v2.Number, v2.Author, v2.ClientName, v2.Note));
|
||||
Assert.Equal((mine.Id, mine.ContentHash, (Guid?)head.Id, (Guid?)v2.Id), (v2.Id, v2.ContentHash, v2.ParentId, stored.Head?.Id));
|
||||
Assert.Null(stored.Code);
|
||||
Assert.NotNull(v2.StoredAt);
|
||||
Assert.True(ProjectContent.Verifies(v2.SettingsJson, v2.ContentHash), "the stored settings match their hash");
|
||||
|
||||
// The same push again (its answer was lost): answered as the first time, nothing new.
|
||||
var again = await alberto.PushProjectVersionAsync(sid, main.Id, mine);
|
||||
Assert.Equal((ProjectPushOutcomes.AlreadyStored, v2.Id, 2), (again.Outcome, again.Version?.Id, again.Version?.Number));
|
||||
|
||||
// The other PC pushed from version 1: diverged, with the head to replay on; stored once replayed.
|
||||
var theirs = Version(head, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = -0.5 } }, home);
|
||||
var diverged = await giulia.PushProjectVersionAsync(sid, main.Id, theirs);
|
||||
Assert.Equal((ProjectPushOutcomes.Diverged, ProjectErrors.Diverged, (Guid?)v2.Id), (diverged.Outcome, diverged.Code, diverged.Head?.Id));
|
||||
Assert.Null(diverged.Version);
|
||||
Assert.False(string.IsNullOrWhiteSpace(diverged.Message), "the refusal says why");
|
||||
using (var raw = await giuliaHttp.PostAsJsonAsync($"/api/v1/sequences/{sid}/projects/{main.Id}/versions", theirs, ProtocolJson.Default.ProjectVersionDto))
|
||||
await raw.ExpectErrorAsync(HttpStatusCode.Conflict, ProjectErrors.Diverged);
|
||||
var replayed = theirs with { Id = Guid.CreateVersion7(), ParentId = v2.Id };
|
||||
var v3 = Assert.NotNull((await giulia.PushProjectVersionAsync(sid, main.Id, replayed)).Version);
|
||||
Assert.Equal((3, "giulia"), (v3.Number, v3.Author));
|
||||
|
||||
// Refused, nothing stored: settings that do not match their hash, of a newer format, or not portable; another project's id.
|
||||
var damaged = Version(v3, new ProjectSettings(), home) with { ContentHash = new string('0', 64) };
|
||||
var mismatch = await alberto.PushProjectVersionAsync(sid, main.Id, damaged);
|
||||
Assert.Equal((ProjectPushOutcomes.HashMismatch, ProjectErrors.HashMismatch, 3), (mismatch.Outcome, mismatch.Code, mismatch.Head?.Number));
|
||||
using (var raw = await giuliaHttp.PostAsJsonAsync($"/api/v1/sequences/{sid}/projects/{main.Id}/versions", damaged, ProtocolJson.Default.ProjectVersionDto))
|
||||
await raw.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, ProjectErrors.HashMismatch);
|
||||
const string future = """{"version":99,"exposure":{"exposureOffsetEv":1}}""";
|
||||
var newer = await alberto.PushProjectVersionAsync(sid, main.Id, Version(v3, new ProjectSettings(), home) with { SettingsJson = future, ContentHash = ProjectContent.Hash(future) });
|
||||
Assert.Equal((ProjectPushOutcomes.NewerFormat, ProjectErrors.NewerFormat), (newer.Outcome, newer.Code));
|
||||
var positional = new ProjectSettings { ExcludedFrames = [0] }.ToJson();
|
||||
var invalid = await alberto.PushProjectVersionAsync(sid, main.Id, Version(v3, new ProjectSettings(), home) with { SettingsJson = positional, ContentHash = ProjectContent.Hash(positional) });
|
||||
Assert.Equal((ProjectPushOutcomes.Invalid, ProjectErrors.InvalidVersion), (invalid.Outcome, invalid.Code));
|
||||
var vertical = await alberto.CreateProjectAsync(sid, new CreateProjectRequest("Vertical"));
|
||||
var foreign = await alberto.PushProjectVersionAsync(sid, vertical.Id, mine with { ParentId = vertical.HeadVersionId });
|
||||
Assert.Equal(ProjectPushOutcomes.Invalid, foreign.Outcome);
|
||||
Assert.Equal(3, (await alberto.GetProjectAsync(sid, main.Id)).HeadNumber);
|
||||
await RefusedAsync(HttpStatusCode.BadRequest, "bad_request", () => alberto.PushProjectVersionAsync(sid, main.Id, mine with { Id = Guid.Empty }));
|
||||
|
||||
// The history, newest first a page at a time, and oldest first above a number (what a workspace pulls).
|
||||
var page = await alberto.ListProjectVersionsAsync(sid, main.Id, limit: 2);
|
||||
Assert.SequenceEqual([3, 2], page.Items.Select(v => v.Number), "newest first");
|
||||
Assert.Equal((true, 3), (page.More, page.HeadNumber));
|
||||
var rest = await alberto.ListProjectVersionsAsync(sid, main.Id, before: 2, limit: 2);
|
||||
Assert.SequenceEqual([1], rest.Items.Select(v => v.Number));
|
||||
Assert.False(rest.More);
|
||||
var pulled = await giulia.ListProjectVersionsAsync(sid, main.Id, after: 1);
|
||||
Assert.SequenceEqual([v2.Id, v3.Id], pulled.Items.Select(v => v.Id));
|
||||
var read = Assert.NotNull(await giulia.GetProjectVersionAsync(sid, main.Id, v2.Id));
|
||||
Assert.Equal((v2.Number, v2.ContentHash, v2.SettingsJson, v2.Author), (read.Number, read.ContentHash, read.SettingsJson, read.Author));
|
||||
Assert.Null(await giulia.GetProjectVersionAsync(sid, main.Id, Guid.CreateVersion7()));
|
||||
Assert.Null(await giulia.GetProjectVersionAsync(sid, vertical.Id, v2.Id));
|
||||
await RefusedAsync(HttpStatusCode.BadRequest, "bad_request", () => giulia.ListProjectVersionsAsync(sid, main.Id, before: 2, after: 1));
|
||||
|
||||
// Main's head is the sequence's settings: version 3's, placed on its frames (an older client reads them there).
|
||||
var sequence = await alberto.GetSequenceAsync(sid);
|
||||
var settings = ProjectSettings.FromJson(Assert.NotNull((await server.Database.Sequences.GetAsync(sid))!.SettingsJson));
|
||||
Assert.Equal(-0.5, settings.Exposure.ExposureOffsetEv);
|
||||
Assert.Empty(settings.ExcludedFrames);
|
||||
Assert.True(sequence.SettingsVersion > 1, "the settings version moved with the mirror");
|
||||
var listed = (await alberto.ListProjectsAsync(sid)).Single(p => p.IsMain);
|
||||
Assert.Equal((3, (Guid?)v3.Id, "commit", "giulia", "Chronos on PC-A"), (listed.HeadNumber, listed.HeadVersionId, listed.HeadKind, listed.HeadAuthor, listed.HeadClientName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadersReadEditorsChangeAndDeletingNeedsTheOwner()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, ownerToken) = await server.UserAsync("alberto", "editor");
|
||||
var (_, _, otherToken) = await server.UserAsync("giulia", "editor");
|
||||
var (viewerHttp, _, viewerToken) = await server.UserAsync("ospite", "viewer");
|
||||
var (uploaderHttp, _, _) = await server.UserAsync("studio-pc", "uploader");
|
||||
var admin = await server.AdminAsync();
|
||||
using var owner = Client(server, ownerToken);
|
||||
using var other = Client(server, otherToken);
|
||||
using var viewer = Client(server, viewerToken);
|
||||
var sid = await SequenceAsync(server, ownerToken, 2);
|
||||
var main = (await owner.ListProjectsAsync(sid)).Single();
|
||||
var head = await owner.GetProjectHeadAsync(sid, main.Id);
|
||||
|
||||
// Read to read; Edit to make, rename and push; uploaders read nothing.
|
||||
Assert.Equal(main.Id, (await viewer.ListProjectsAsync(sid)).Single().Id);
|
||||
Assert.Equal(head.Id, (await viewer.GetProjectHeadAsync(sid, main.Id)).Id);
|
||||
await RefusedAsync(HttpStatusCode.Forbidden, "forbidden", () => viewer.CreateProjectAsync(sid, new CreateProjectRequest("Mine")));
|
||||
var home = ProjectWire.ToHomeFrames(await viewer.GetProjectFramesAsync(sid));
|
||||
await RefusedAsync(HttpStatusCode.Forbidden, "forbidden", () => viewer.PushProjectVersionAsync(sid, main.Id, Version(head, new ProjectSettings(), home)));
|
||||
using (var refused = await uploaderHttp.GetAsync($"/api/v1/sequences/{sid}/projects")) await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var gone = await viewerHttp.DeleteAsync($"/api/v1/sequences/{sid}/projects/{main.Id}")) await gone.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
|
||||
// Deleting: the sequence's owner, the project's maker or an admin.
|
||||
var byOwner = await owner.CreateProjectAsync(sid, new CreateProjectRequest("Owner's"));
|
||||
var byOther = await other.CreateProjectAsync(sid, new CreateProjectRequest("Giulia's"));
|
||||
var third = await owner.CreateProjectAsync(sid, new CreateProjectRequest("Third"));
|
||||
await RefusedAsync(HttpStatusCode.Forbidden, "forbidden", () => other.DeleteProjectAsync(sid, byOwner.Id));
|
||||
await other.DeleteProjectAsync(sid, byOther.Id);
|
||||
await owner.DeleteProjectAsync(sid, byOwner.Id);
|
||||
using (var deleted = await admin.DeleteAsync($"/api/v1/sequences/{sid}/projects/{third.Id}")) await deleted.ExpectAsync(HttpStatusCode.NoContent);
|
||||
Assert.SequenceEqual([main.Id], (await viewer.ListProjectsAsync(sid)).Select(p => p.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EveryChangeIsToldAndMainTakesSettingsAPatchWrote()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 2);
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
|
||||
// Main made at the first read.
|
||||
var main = (await client.ListProjectsAsync(sid)).Single();
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == main.Id && e is { Change: ProjectChanges.Created, HeadNumber: 1 } && e.SequenceId == sid);
|
||||
|
||||
// The API's own changes.
|
||||
var vertical = await client.CreateProjectAsync(sid, new CreateProjectRequest("Vertical"));
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == vertical.Id && e.Change == ProjectChanges.Created && e.HeadVersionId == vertical.HeadVersionId);
|
||||
await client.RenameProjectAsync(sid, vertical.Id, "Vertical social");
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == vertical.Id && e.Change == ProjectChanges.Renamed);
|
||||
var home = ProjectWire.ToHomeFrames(await client.GetProjectFramesAsync(sid));
|
||||
var pushed = Assert.NotNull((await client.PushProjectVersionAsync(sid, vertical.Id,
|
||||
Version(await client.GetProjectHeadAsync(sid, vertical.Id), new ProjectSettings { HeroFrame = 1 }, home))).Version);
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == vertical.Id && e.Change == ProjectChanges.Pushed && e.HeadVersionId == pushed.Id && e.HeadNumber == 2);
|
||||
await client.DeleteProjectAsync(sid, vertical.Id);
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == vertical.Id && e.Change == ProjectChanges.Deleted);
|
||||
|
||||
// A push to Main is a settings change too, for the clients that read the sequence's settings.
|
||||
var toMain = Assert.NotNull((await client.PushProjectVersionAsync(sid, main.Id,
|
||||
Version(await client.GetProjectHeadAsync(sid, main.Id), new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.2 } }, home))).Version);
|
||||
await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == main.Id && e.Change == ProjectChanges.Pushed && e.HeadVersionId == toMain.Id);
|
||||
var mirrored = await NextAsync<SequenceChangedEvent>(events, e => e.SequenceId == sid && e.Change == "settings");
|
||||
Assert.Equal((await client.GetSequenceAsync(sid)).SettingsVersion, mirrored.SettingsVersion);
|
||||
|
||||
// An older client (or a desktop's sync) PATCHes the settings: Main takes them as an external version at once, told
|
||||
// without anyone reading the projects.
|
||||
var sequence = await client.GetSequenceAsync(sid);
|
||||
var patched = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.7 } }.ToJson();
|
||||
await client.UpdateSequenceAsync(sid, new UpdateSequenceRequest(null, null, null, null, patched, sequence.SettingsVersion));
|
||||
var external = await NextAsync<ProjectChangedEvent>(events, e => e.ProjectId == main.Id && e.Change == ProjectChanges.Pushed && e.HeadNumber == 3);
|
||||
var head = await client.GetProjectHeadAsync(sid, main.Id);
|
||||
Assert.Equal(("external", 3, external.HeadVersionId), (head.Kind, head.Number, (Guid?)head.Id));
|
||||
Assert.Equal(0.7, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv);
|
||||
// A tags edit changes no settings: no new version.
|
||||
sequence = await client.GetSequenceAsync(sid);
|
||||
await client.UpdateSequenceAsync(sid, new UpdateSequenceRequest(null, ["harbour"], null, null, null, sequence.SettingsVersion));
|
||||
Assert.Equal(3, (await client.GetProjectHeadAsync(sid, main.Id)).Number);
|
||||
|
||||
// The event reaches a client over the WebSocket like the others.
|
||||
using var listening = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
listening.CancelAfter(Wait);
|
||||
var received = new TaskCompletionSource<ProjectChangedEvent>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var connected = new TaskCompletionSource();
|
||||
var reader = Task.Run(async () =>
|
||||
{
|
||||
var stream = client.EventsAsync(listening.Token).GetAsyncEnumerator(listening.Token);
|
||||
var first = stream.MoveNextAsync();
|
||||
connected.TrySetResult();
|
||||
try
|
||||
{
|
||||
for (var more = await first; more; more = await stream.MoveNextAsync())
|
||||
{
|
||||
if (stream.Current is ProjectChangedEvent { Change: ProjectChanges.Created } e && e.SequenceId == sid) received.TrySetResult(e);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stream.DisposeAsync();
|
||||
}
|
||||
});
|
||||
await connected.Task;
|
||||
await WaitForSubscribersAsync(server, 2);
|
||||
var landscape = await client.CreateProjectAsync(sid, new CreateProjectRequest("4K landscape"));
|
||||
var told = await received.Task.WaitAsync(Wait);
|
||||
Assert.Equal((landscape.Id, 1, landscape.HeadVersionId), (told.ProjectId, told.HeadNumber, told.HeadVersionId));
|
||||
await listening.CancelAsync();
|
||||
await reader;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerSaysItKeepsProjects()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests");
|
||||
Assert.Contains(ServerCapabilities.Projects, (await client.GetInfoAsync(context.Cancellation)).Capabilities);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheFramesOfAHomeAreOfOneFramesVersionWithTheAliasesOfItsConversions()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 3);
|
||||
var frames = await client.GetProjectFramesAsync(sid, context.Cancellation);
|
||||
var sequence = await client.GetSequenceAsync(sid, context.Cancellation);
|
||||
Assert.Equal((sid, sequence.FramesVersion, 3), (frames.SequenceId, frames.FramesVersion, frames.Frames.Count));
|
||||
Assert.SequenceEqual([0, 1, 2], frames.Frames.Select(f => f.Index));
|
||||
Assert.Null(frames.Aliases);
|
||||
await RefusedAsync(HttpStatusCode.NotFound, "not_found", () => client.GetProjectFramesAsync(Guid.CreateVersion7()));
|
||||
|
||||
// A conversion's tombstones join the original's encoding to its replacement's; deletions join nothing.
|
||||
var replaced = new string('a', 64);
|
||||
await server.Database.FrameRemovals.SyncSequenceAsync(sid,
|
||||
[
|
||||
new FrameRemoval(sid, replaced, frames.Frames[1].Sha256, RemovalReason.Replaced, DateTimeOffset.UtcNow),
|
||||
new FrameRemoval(sid, new string('b', 64), null, RemovalReason.Deleted, DateTimeOffset.UtcNow),
|
||||
]);
|
||||
frames = await client.GetProjectFramesAsync(sid, context.Cancellation);
|
||||
var alias = Assert.NotNull(frames.Aliases).Single();
|
||||
Assert.Equal((replaced, frames.Frames[1].Sha256, "replaced"), (alias.Sha256, alias.Replacement, alias.Reason));
|
||||
// A position parked on the encoding a conversion replaced finds the frame that holds its replacement.
|
||||
var home = ProjectWire.ToHomeFrames(frames);
|
||||
Assert.Equal(1, home.Photos.IndexOf(new FramePhoto(replaced, 1, null)));
|
||||
Assert.SequenceEqual(frames.Frames.Select(f => f.Id), home.Frames.Select(f => f.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ABusyOfflineOrMovedSequenceRefusesChangesAndStillLists()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
ArchiveModule.Register(s);
|
||||
// A short lease wait: a sequence another writer holds refuses at once.
|
||||
s.AddSingleton(sp => new ArchiveService(sp.GetRequiredService<ChronosDatabase>(),
|
||||
new ArchiveServiceOptions { Owner = ArchiveModule.Owner, LeaseWait = TimeSpan.FromMilliseconds(200) }));
|
||||
});
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 2);
|
||||
var main = (await client.ListProjectsAsync(sid)).Single();
|
||||
var head = await client.GetProjectHeadAsync(sid, main.Id);
|
||||
var home = ProjectWire.ToHomeFrames(await client.GetProjectFramesAsync(sid));
|
||||
var version = Version(head, new ProjectSettings { HeroFrame = 0 }, home);
|
||||
var paths = new ArchivePaths(server.Options.ArchivePath);
|
||||
|
||||
async Task RefusedNowAsync(string code)
|
||||
{
|
||||
await RefusedAsync(HttpStatusCode.ServiceUnavailable, code, () => client.PushProjectVersionAsync(sid, main.Id, version));
|
||||
await RefusedAsync(HttpStatusCode.ServiceUnavailable, code, () => client.CreateProjectAsync(sid, new CreateProjectRequest("Later")));
|
||||
// Reads answer from the index meanwhile.
|
||||
Assert.Equal(main.Id, (await client.ListProjectsAsync(sid)).Single().Id);
|
||||
Assert.Equal(head.Id, (await client.GetProjectHeadAsync(sid, main.Id)).Id);
|
||||
}
|
||||
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(paths.LocksDirectory, $"seq-{sid:N}", "tests")))
|
||||
await RefusedNowAsync("sequence_busy");
|
||||
File.Move(paths.ManifestPath, paths.ManifestPath + ".away");
|
||||
try
|
||||
{
|
||||
await RefusedNowAsync("archive_offline");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Move(paths.ManifestPath + ".away", paths.ManifestPath);
|
||||
}
|
||||
var folder = (await server.Database.Sequences.GetAsync(sid))!.Folder;
|
||||
Directory.Move(paths.FromRelative(folder), paths.FromRelative(folder + " moved"));
|
||||
try
|
||||
{
|
||||
await RefusedNowAsync("folder_moved");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Move(paths.FromRelative(folder + " moved"), paths.FromRelative(folder));
|
||||
}
|
||||
// Nothing was lost: the same push is stored now.
|
||||
Assert.Equal(ProjectPushOutcomes.Stored, (await client.PushProjectVersionAsync(sid, main.Id, version)).Outcome);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderNodeGetsAProjectVersionPlacedAndItsRenderRecordsIt()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
|
||||
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 3);
|
||||
var other = await SequenceAsync(server, token, 1, "other");
|
||||
var vertical = await client.CreateProjectAsync(sid, new CreateProjectRequest("Vertical"));
|
||||
var home = ProjectWire.ToHomeFrames(await client.GetProjectFramesAsync(sid));
|
||||
// The second photo left out, parked by photo in the version.
|
||||
var excluding = Version(await client.GetProjectHeadAsync(sid, vertical.Id), new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }, home);
|
||||
Assert.Contains("pendingFrames", excluding.SettingsJson);
|
||||
var v2 = Assert.NotNull((await client.PushProjectVersionAsync(sid, vertical.Id, excluding)).Version);
|
||||
|
||||
var node = await client.RegisterNodeAsync(new RegisterNodeRequest("studio-pc", [new NodeEncoder("h264", "Media Foundation H.264", true, false)], 4096, 4096));
|
||||
var job = await JobApiTests.CreateAsync(editor, "render", sid, H264(vertical.Id, v2.Id));
|
||||
var claimed = Assert.NotNull(await client.ClaimAsync(node.Id));
|
||||
Assert.Equal((job.Id, sid, 3), (claimed.Job.Id, claimed.SequenceId, claimed.Frames.Count));
|
||||
// The node renders the version's settings with their positions placed on the frames it was sent.
|
||||
var placed = ProjectSettings.FromJson(claimed.SettingsJson);
|
||||
Assert.SequenceEqual([1], placed.ExcludedFrames);
|
||||
Assert.Equal(2, placed.HeroFrame);
|
||||
Assert.True(placed.PendingFrames is null or { Count: 0 }, "nothing waits");
|
||||
|
||||
var output = Path.Combine(context.CreateTempDirectory("render"), "Vertical.mp4");
|
||||
var video = Uploads.Photo(100_000, 61);
|
||||
await File.WriteAllBytesAsync(output, video);
|
||||
var render = await client.UploadRenderResultAsync(node.Id, job.Id, output,
|
||||
new RenderResultRequest("Vertical.mp4", video.Length, Uploads.Sha(video), "1080p", "h264", 1920, 1080, 25, 4));
|
||||
var row = Assert.NotNull(await server.Database.Renders.GetAsync(render.Id));
|
||||
Assert.Equal(((Guid?)vertical.Id, (Guid?)v2.Id), (row.ProjectId, row.ProjectVersionId));
|
||||
|
||||
// A project alone renders its head as it is when the job is queued: the job names that version.
|
||||
var pinned = await JobApiTests.CreateAsync(editor, "render", sid, H264(vertical.Id, null));
|
||||
var parameters = JsonSerializer.Deserialize((await server.Database.Jobs.GetAsync(pinned.Id))!.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
|
||||
Assert.Equal(((Guid?)vertical.Id, (Guid?)v2.Id), (parameters.ProjectId, parameters.ProjectVersionId));
|
||||
// A version alone names its project.
|
||||
var named = await JobApiTests.CreateAsync(editor, "render", sid, H264(null, v2.Id));
|
||||
Assert.Equal((Guid?)vertical.Id, JsonSerializer.Deserialize((await server.Database.Jobs.GetAsync(named.Id))!.ParametersJson!,
|
||||
ProtocolJson.Default.RenderJobParameters)!.ProjectId);
|
||||
// What is not the sequence's is refused; an old client naming neither renders the sequence's settings as before.
|
||||
using (var unknown = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [sid], H264(null, Guid.CreateVersion7())), ProtocolJson.Default.CreateJobRequest))
|
||||
Assert.Equal("version", (await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
using (var foreign = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [other], H264(vertical.Id, v2.Id)), ProtocolJson.Default.CreateJobRequest))
|
||||
Assert.Equal("project", (await foreign.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
var main = (await client.ListProjectsAsync(sid)).Single(p => p.IsMain);
|
||||
using (var mismatched = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [sid], H264(main.Id, v2.Id)), ProtocolJson.Default.CreateJobRequest))
|
||||
Assert.Equal("version", (await mismatched.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
var plain = await JobApiTests.CreateAsync(editor, "render", sid, H264(null, null));
|
||||
Assert.Equal(H264(null, null), (await server.Database.Jobs.GetAsync(plain.Id))!.ParametersJson);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerRendersAProjectVersionAndRecordsIt()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
ArchiveModule.Register(s);
|
||||
ProcessingModule.Register(s);
|
||||
});
|
||||
var (editor, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var client = Client(server, token);
|
||||
var sid = await SequenceAsync(server, token, 4);
|
||||
var vertical = await client.CreateProjectAsync(sid, new CreateProjectRequest("Vertical"));
|
||||
var home = ProjectWire.ToHomeFrames(await client.GetProjectFramesAsync(sid));
|
||||
var v2 = Assert.NotNull((await client.PushProjectVersionAsync(sid, vertical.Id,
|
||||
Version(await client.GetProjectHeadAsync(sid, vertical.Id), new ProjectSettings { ExcludedFrames = [2] }, home))).Version);
|
||||
|
||||
const string avi = """{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"overrides":{"width":96,"height":64},"nameTemplate":"vertical"}""";
|
||||
var job = await JobApiTests.CreateAsync(editor, "render", sid,
|
||||
JsonSerializer.Serialize(new RenderJobParameters("MJPEG", avi, "mjpeg", 96, 64, false, null, vertical.Id, v2.Id), ProtocolJson.Default.RenderJobParameters));
|
||||
await JobApiTests.WaitForAsync(editor, job.Id, "done");
|
||||
var render = (await server.Database.Renders.ListBySequenceAsync(sid)).Single();
|
||||
Assert.Equal(((Guid?)vertical.Id, (Guid?)v2.Id), (render.ProjectId, render.ProjectVersionId));
|
||||
// Rendered with the version's settings, its positions placed on the sequence's frames.
|
||||
Assert.SequenceEqual([2], ProjectSettings.FromJson(Assert.NotNull(render.SettingsJson)).ExcludedFrames);
|
||||
}
|
||||
|
||||
/// <summary>A render job's parameters for an H.264 render node, naming a project and a version.</summary>
|
||||
private static string H264(Guid? projectId, Guid? versionId) =>
|
||||
JsonSerializer.Serialize(new RenderJobParameters("1080p", """{"codec":"h264","bitrate":20}""", "h264", 1920, 1080, false, null, projectId, versionId),
|
||||
ProtocolJson.Default.RenderJobParameters);
|
||||
|
||||
/// <summary>A version made from <paramref name="parent"/> with <paramref name="settings"/> in portable form, as a workspace commits it.</summary>
|
||||
private static ProjectVersionDto Version(ProjectVersionDto parent, ProjectSettings settings, HomeFrames home, string? note = null)
|
||||
{
|
||||
var portable = ProjectContent.ToPortable(settings, home.Photos);
|
||||
return new ProjectVersionDto(Guid.CreateVersion7(), parent.ProjectId, parent.Id, parent.Number + 1, "commit", null, "Chronos on PC-A", note, portable,
|
||||
ProjectContent.Hash(portable), ProjectContent.FormatOf(portable), home.FramesVersion, null, DateTimeOffset.UtcNow, null);
|
||||
}
|
||||
|
||||
private static ChronosClient Client(TestServer server, string token) => new(server.HttpBase, new CertificatePinning([]), "tests") { Token = token };
|
||||
|
||||
/// <summary>A call the server refuses with <paramref name="status"/> and <paramref name="code"/>.</summary>
|
||||
private static async Task<ChronosApiException> RefusedAsync(HttpStatusCode status, string code, Func<Task> call)
|
||||
{
|
||||
var refused = await Assert.ThrowsAsync<ChronosApiException>(call);
|
||||
Assert.Equal((status, code), (refused.Status, refused.Error.Code), refused.Message);
|
||||
Assert.False(string.IsNullOrWhiteSpace(refused.Error.Message), "the refusal says why");
|
||||
return refused;
|
||||
}
|
||||
|
||||
/// <summary>The first event of <typeparamref name="T"/> that <paramref name="match"/> takes, those before it passed over.</summary>
|
||||
private static async Task<T> NextAsync<T>(EventHub.Subscription events, Func<T, bool> match) where T : ServerEvent
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(Wait);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (await events.Reader.ReadAsync(timeout.Token) is T typed && match(typed)) return typed;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Assert.Fail($"No {typeof(T).Name} as expected within {Wait.TotalSeconds} s");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitForSubscribersAsync(TestServer server, int count)
|
||||
{
|
||||
var hub = server.Services.GetRequiredService<EventHub>();
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (hub.SubscriberCount < count)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "the WebSocket did not subscribe");
|
||||
await Task.Delay(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A sequence of <paramref name="photos"/> JPEG photos a minute apart, filed by the archive engine, once its jobs are done.</summary>
|
||||
private static async Task<Guid> SequenceAsync(TestServer server, string token, int photos, string session = "harbour")
|
||||
{
|
||||
var uploader = server.NewClient(token);
|
||||
Guid id = default;
|
||||
for (var i = 0; i < photos; i++)
|
||||
{
|
||||
id = (await Uploads.UploadAsync(uploader, Photo(i + session.Length * 10), $"IMG_{i + 1:0000}.JPG", sessionKey: session,
|
||||
capturedAt: new DateTime(2026, 9, 28, 18, i, 11))).SequenceId;
|
||||
}
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
||||
{
|
||||
while ((await server.Database.Jobs.ListAsync(state)).Items.Any(j => j.Kind != JobKind.Render))
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The projects of a sequence on the admin panel (owner review 2, R8; <c>Admin/web/pages/library/projects.js</c>): the
|
||||
/// sequence page's Projects section, what it lists and offers (Rename and Delete, never for Main, nothing that edits
|
||||
/// settings), its strings, and the requests it writes, sent through the cookie session as <c>api.js</c> sends them and read
|
||||
/// back by the names the page reads.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed partial class AdminProjectsTests(TestContext context)
|
||||
{
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
[Test]
|
||||
public async Task TheSequencePageListsItsProjectsAndManagesThoseOtherThanMain()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
Assert.Contains(@"import { projectsSection } from ""./projects.js"";", page);
|
||||
Assert.Contains(@"<h2 id=""projects-title"" data-i18n=""Admin.Projects.Title""></h2>", page);
|
||||
Assert.Contains("projects.onEvent(e);", page);
|
||||
|
||||
using var response = await server.Client.GetAsync("/admin/pages/library/projects.js");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
|
||||
var projects = await response.Content.ReadAsStringAsync();
|
||||
Assert.True(Regex.IsMatch(projects, @"export function projectsSection\(host, meta, \{ api, sequenceId \}\)"), "projects.js exports projectsSection");
|
||||
var imports = StaticImport().Matches(projects).Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.SequenceEqual(["../../i18n.js", "../../ui.js"], imports);
|
||||
Assert.True(!Regex.IsMatch(projects, @"\son[a-z]+="""), "inline handler");
|
||||
// It lists, opens versions, renames and deletes: no push, no restore, no settings (R6: the panel manages, never edits).
|
||||
Assert.Contains("projects = await api.get(base);", projects);
|
||||
Assert.Contains("api.get(`${base}/${encodeURIComponent(id)}/versions?limit=${VERSION_PAGE}${before}`)", projects);
|
||||
Assert.Contains("await api.patch(`${base}/${encodeURIComponent(project.id)}`, { name });", projects);
|
||||
Assert.Contains("await api.del(`${base}/${encodeURIComponent(project.id)}`);", projects);
|
||||
Assert.False(projects.Contains("api.post(", StringComparison.Ordinal), "the panel pushes or makes nothing");
|
||||
Assert.False(projects.Contains("settingsJson", StringComparison.Ordinal), "the panel reads no settings");
|
||||
// Main is marked and never renamed or deleted here.
|
||||
Assert.Contains(@"const actions = p.isMain ? """" : `", projects);
|
||||
Assert.Contains("if (!project || project.isMain) return;", projects);
|
||||
Assert.Contains("p.isMain && p.name === MAIN_NAME ? t(\"Admin.Projects.Main\") : p.name", projects);
|
||||
// A deletion is confirmed first, naming the project.
|
||||
Assert.Contains("title: t(\"Admin.Projects.DeleteTitle\", project.name),", projects);
|
||||
Assert.Contains("const confirmed = await confirmDialog({", projects);
|
||||
// The list follows projectChanged of this sequence, and a reconnection.
|
||||
Assert.Contains(@"(e.type === ""projectChanged"" && e.sequenceId === sequenceId) || e.type === ""reconnected""", projects);
|
||||
|
||||
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
|
||||
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
||||
var keys = Regex.Matches(projects + page, @"""(Admin\.Projects\.[A-Za-z.]+)""").Select(m => m.Groups[1].Value).Distinct().ToList();
|
||||
Assert.True(keys.Count > 20, $"{keys.Count} keys");
|
||||
foreach (var kind in new[] { "Commit", "Merge", "Restore", "Imported", "External" }) keys.AddRange([$"Admin.Projects.Kind.{kind}", $"Admin.Projects.Kind.{kind}.Tip"]);
|
||||
foreach (var key in keys)
|
||||
{
|
||||
var name = en.ContainsKey(key) ? key : key + ".other";
|
||||
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
|
||||
}
|
||||
Assert.Equal("Principale", it["Admin.Projects.Main"]);
|
||||
Assert.Equal("Modifica esterna", it["Admin.Projects.Kind.External"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThePagesRequestsListRenameAndDeleteProjects()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
Guid sid = default;
|
||||
for (var i = 0; i < 2; i++) sid = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "pier")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var browser = await Browser.SignInAsync(server);
|
||||
var url = $"/api/v1/sequences/{sid}/projects";
|
||||
|
||||
// Made on a PC (the panel makes none): a project the page lists after Main.
|
||||
using (var created = await editor.PostAsJsonAsync(url, new CreateProjectRequest("Vertical social"), ProtocolJson.Default.CreateProjectRequest))
|
||||
await created.ExpectAsync(HttpStatusCode.Created);
|
||||
Guid vertical;
|
||||
using (var list = await browser.SendAsync(HttpMethod.Get, url))
|
||||
{
|
||||
await list.ExpectAsync(HttpStatusCode.OK);
|
||||
using var json = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
|
||||
var items = json.RootElement.EnumerateArray().ToList();
|
||||
Assert.Count(2, items);
|
||||
var main = items[0];
|
||||
Assert.Equal((true, "Main", 1), (main.GetProperty("isMain").GetBoolean(), main.GetProperty("name").GetString(), main.GetProperty("headNumber").GetInt32()));
|
||||
var project = items[1];
|
||||
Assert.False(project.GetProperty("isMain").GetBoolean());
|
||||
vertical = project.GetProperty("id").GetGuid();
|
||||
// The names the page reads for the last change.
|
||||
Assert.Equal(("imported", "alberto"), (project.GetProperty("headKind").GetString(), project.GetProperty("headAuthor").GetString()));
|
||||
Assert.True(project.TryGetProperty("headStoredAt", out _) && project.TryGetProperty("updatedAt", out _) && project.TryGetProperty("headVersionId", out _));
|
||||
}
|
||||
using (var versions = await browser.SendAsync(HttpMethod.Get, $"{url}/{vertical}/versions?limit=20"))
|
||||
{
|
||||
await versions.ExpectAsync(HttpStatusCode.OK);
|
||||
using var json = JsonDocument.Parse(await versions.Content.ReadAsStringAsync());
|
||||
var first = json.RootElement.GetProperty("items").EnumerateArray().Single();
|
||||
Assert.Equal((1, "imported"), (first.GetProperty("number").GetInt32(), first.GetProperty("kind").GetString()));
|
||||
Assert.True(first.TryGetProperty("storedAt", out _) && first.TryGetProperty("createdAt", out _) && first.TryGetProperty("clientName", out _));
|
||||
Assert.False(json.RootElement.GetProperty("more").GetBoolean());
|
||||
}
|
||||
|
||||
using (var renamed = await browser.SendAsync(HttpMethod.Patch, $"{url}/{vertical}", Json("""{"name":"Vertical"}""")))
|
||||
{
|
||||
await renamed.ExpectAsync(HttpStatusCode.OK);
|
||||
using var json = JsonDocument.Parse(await renamed.Content.ReadAsStringAsync());
|
||||
Assert.Equal("Vertical", json.RootElement.GetProperty("name").GetString());
|
||||
}
|
||||
// Refusals carry the page's language, which its toast shows.
|
||||
using (var taken = await browser.SendAsync(HttpMethod.Patch, $"{url}/{vertical}", Json("""{"name":"main"}""")))
|
||||
Assert.Equal(Loc.Get("Server.Error.NameTaken", CultureInfo.GetCultureInfo("it")), (await taken.ExpectErrorAsync(HttpStatusCode.Conflict, "name_taken")).Message);
|
||||
var mainId = (await server.Database.Projects.GetMainAsync(sid))!.Id;
|
||||
using (var kept = await browser.SendAsync(HttpMethod.Delete, $"{url}/{mainId}"))
|
||||
await kept.ExpectErrorAsync(HttpStatusCode.Conflict, "main_cannot_be_deleted");
|
||||
using (var deleted = await browser.SendAsync(HttpMethod.Delete, $"{url}/{vertical}")) await deleted.ExpectAsync(HttpStatusCode.NoContent);
|
||||
using (var list = await browser.SendAsync(HttpMethod.Get, url))
|
||||
{
|
||||
using var json = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
|
||||
Assert.SequenceEqual([mainId], json.RootElement.EnumerateArray().Select(p => p.GetProperty("id").GetGuid()));
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
||||
private static partial Regex StaticImport();
|
||||
|
||||
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
|
||||
|
||||
private static async Task UntilIdleAsync(TestServer server)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
||||
{
|
||||
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
|
||||
private sealed class Browser(HttpClient client, string csrfToken)
|
||||
{
|
||||
public static async Task<Browser> SignInAsync(TestServer server)
|
||||
{
|
||||
await server.AdminAsync();
|
||||
var cookies = new CookieContainer();
|
||||
var client = server.NewCookieClient(cookies);
|
||||
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
|
||||
ProtocolJson.Default.LoginRequest);
|
||||
await login.ExpectAsync(HttpStatusCode.OK);
|
||||
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
|
||||
}
|
||||
|
||||
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
request.Headers.Accept.ParseAdd("application/json");
|
||||
request.Headers.AcceptLanguage.ParseAdd("it");
|
||||
if (method != HttpMethod.Get) request.Headers.Add("X-CSRF-Token", csrfToken);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,20 @@ public sealed class PostgresServerTests(TestContext context)
|
||||
await JobApiTests.WaitForAsync(admin, ran.JobId!.Value, "done");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProjectsArePushedAndListedOnPostgres()
|
||||
{
|
||||
await using var schema = await Schema.CreateAsync(context);
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.Database = DatabaseKind.Postgres;
|
||||
o.DbConnectionString = schema.ConnectionString;
|
||||
}, Chronos.Server.Storage.ArchiveModule.Register);
|
||||
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
|
||||
// Owner review 2, R8: the server as a project home, two clients pushing to one project.
|
||||
await Api.ProjectTests.PushesAsync(server);
|
||||
}
|
||||
|
||||
/// <summary>A throw-away schema on the test server, selected through <c>Search Path</c>.</summary>
|
||||
private sealed class Schema : IAsyncDisposable
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user