From 8d41992d84c3734530d34a184eccaf5cb0f6708b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sun, 15 Nov 2026 14:55:50 +0100 Subject: [PATCH] feat: Chronos Desktop shares its library on the LAN (owner review 5 P4) Chronos Server for Windows is replaced by Settings > Server > Share this library: Chronos Desktop hosts the server engine in its own process over its own index, archive and processing services, job engine and scheduler, so a second PC, the Uploader and render nodes use this PC's library without a Windows service or a second index. - Chronos.Server is a library; Chronos.Server.Host is the console exe that Docker and development runs start. The App references the library and the ASP.NET Core shared framework (no package). - ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and never creates, starts or disposes them; no static log sink, no console lifetime; server.json plus desktop-owned values locked "Set in Chronos Desktop"; only upload-cleanup and audit-cleanup schedules are added. - Both modes: by-id endpoints scoped to the served archive, a client's render export folder dropped; hosted mode exposes server job kinds only. - Desktop: LibraryShare (start after the schedules, stop first, port in use named), Settings > Server sharing rows, Server > This library panel (state, addresses with Copy, ports, fingerprint, temporary admin password, clients, admin panel), own library refused by ConnectFlow and dropped from LAN discovery, the uploads sweep step, thumbnails after scans while sharing, capture scenes server-share and server-share-failed. - Removed: the Windows service hosting of Chronos.Server, its switches and its tests. Refs #67 Co-Authored-By: Claude Opus 5.5 --- Chronos.slnx | 1 + deploy/docker/Dockerfile | 5 +- deploy/docker/entrypoint.sh | 6 +- i18n/en/Admin.resx | 1 + i18n/en/Errors.resx | 4 + i18n/en/Server.resx | 24 + i18n/en/Settings.resx | 10 + i18n/en/Tooltips.resx | 22 +- i18n/it/Admin.it.resx | 1 + i18n/it/Errors.it.resx | 4 + i18n/it/Server.it.resx | 24 + i18n/it/Settings.it.resx | 10 + i18n/it/Tooltips.it.resx | 22 +- src/Chronos.App/Chronos.App.csproj | 5 + src/Chronos.App/DesignTime/SampleData.cs | 30 ++ .../Infrastructure/AppEnvironment.cs | 10 + src/Chronos.App/Infrastructure/AppServices.cs | 27 +- src/Chronos.App/Infrastructure/AppSettings.cs | 37 ++ src/Chronos.App/Jobs/DesktopScheduleHost.cs | 2 + src/Chronos.App/Sections/ServerView.xaml | 82 ++- src/Chronos.App/Sections/ServerViewModel.cs | 5 + src/Chronos.App/Sections/SettingsView.xaml | 41 ++ src/Chronos.App/Sections/SettingsViewModel.cs | 11 +- .../Sections/SharePanelViewModel.cs | 171 ++++++ src/Chronos.App/Server/ConnectFlow.cs | 11 + src/Chronos.App/Server/LibraryShare.cs | 495 ++++++++++++++++++ src/Chronos.App/Server/ServerApi.cs | 5 +- src/Chronos.App/Server/ServerSession.cs | 9 + src/Chronos.App/Settings/ShareSettingsRows.cs | 117 +++++ src/Chronos.App/Shell/ScreenCapture.cs | 6 + src/Chronos.Data/Archiving/ArchiveIndexer.cs | 2 +- src/Chronos.Data/Archiving/ArchiveService.cs | 6 +- src/Chronos.Data/Archiving/FrameTrash.cs | 2 +- .../Archiving/Jobs/ScanJobHandler.cs | 6 +- src/Chronos.Data/Archiving/SequenceWriter.cs | 10 + .../Chronos.Server.Host.csproj | 17 + src/Chronos.Server.Host/Program.cs | 30 ++ .../Admin/web/pages/settings.js | 4 +- src/Chronos.Server/Api/JobEndpoints.cs | 36 +- src/Chronos.Server/Api/LibraryEndpoints.cs | 6 +- src/Chronos.Server/Api/ServedItems.cs | 90 ++++ src/Chronos.Server/Api/VideoEndpoints.cs | 21 +- src/Chronos.Server/Chronos.Server.csproj | 6 +- .../Configuration/ServerOptions.cs | 140 +++++ src/Chronos.Server/Hosting/HealthProbe.cs | 2 +- src/Chronos.Server/Hosting/HostedServer.cs | 168 ++++++ .../Hosting/ServerCommandLine.cs | 16 +- src/Chronos.Server/Hosting/ServerHost.cs | 126 ++++- src/Chronos.Server/Hosting/ServerLogging.cs | 13 +- .../Hosting/Windows/ServiceEventLog.cs | 58 -- .../Hosting/Windows/ServiceInstaller.cs | 160 ------ .../Hosting/Windows/ServiceNative.cs | 107 ---- .../Hosting/Windows/ServiceStatusTracker.cs | 68 --- .../Hosting/Windows/WindowsServiceHost.cs | 121 ----- src/Chronos.Server/Jobs/JobEngineHost.cs | 76 ++- src/Chronos.Server/Jobs/SchedulerHost.cs | 64 ++- src/Chronos.Server/Jobs/ServerScheduleHost.cs | 23 +- src/Chronos.Server/Program.cs | 62 --- src/Chronos.Server/Security/AdminBootstrap.cs | 3 +- .../Security/AuthenticationMiddleware.cs | 9 +- src/Chronos.Server/Security/ClientActivity.cs | 42 ++ src/Chronos.Server/Storage/ArchiveModule.cs | 24 +- .../Storage/ProcessingModule.cs | 9 +- src/Chronos.Server/Storage/ServerArchive.cs | 18 + .../Storage/ServerEventBridge.cs | 48 ++ .../Server/ConnectFlowTests.cs | 21 + .../Server/LibraryShareTests.cs | 192 +++++++ .../Hosting/HostedServerTests.cs | 336 ++++++++++++ .../Hosting/WindowsServiceTests.cs | 152 ------ 69 files changed, 2633 insertions(+), 859 deletions(-) create mode 100644 src/Chronos.App/Sections/SharePanelViewModel.cs create mode 100644 src/Chronos.App/Server/LibraryShare.cs create mode 100644 src/Chronos.App/Settings/ShareSettingsRows.cs create mode 100644 src/Chronos.Server.Host/Chronos.Server.Host.csproj create mode 100644 src/Chronos.Server.Host/Program.cs create mode 100644 src/Chronos.Server/Api/ServedItems.cs create mode 100644 src/Chronos.Server/Hosting/HostedServer.cs delete mode 100644 src/Chronos.Server/Hosting/Windows/ServiceEventLog.cs delete mode 100644 src/Chronos.Server/Hosting/Windows/ServiceInstaller.cs delete mode 100644 src/Chronos.Server/Hosting/Windows/ServiceNative.cs delete mode 100644 src/Chronos.Server/Hosting/Windows/ServiceStatusTracker.cs delete mode 100644 src/Chronos.Server/Hosting/Windows/WindowsServiceHost.cs delete mode 100644 src/Chronos.Server/Program.cs create mode 100644 src/Chronos.Server/Security/ClientActivity.cs create mode 100644 src/Chronos.Server/Storage/ServerEventBridge.cs create mode 100644 tests/Chronos.App.Tests/Server/LibraryShareTests.cs create mode 100644 tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs delete mode 100644 tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs diff --git a/Chronos.slnx b/Chronos.slnx index 58d06039..a81cf613 100644 --- a/Chronos.slnx +++ b/Chronos.slnx @@ -5,6 +5,7 @@ + diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 898fcb85..98104d1c 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -10,7 +10,8 @@ COPY src/Chronos.Core/ src/Chronos.Core/ COPY src/Chronos.Data/ src/Chronos.Data/ COPY src/Chronos.Protocol/ src/Chronos.Protocol/ COPY src/Chronos.Server/ src/Chronos.Server/ -RUN dotnet publish src/Chronos.Server/Chronos.Server.csproj \ +COPY src/Chronos.Server.Host/ src/Chronos.Server.Host/ +RUN dotnet publish src/Chronos.Server.Host/Chronos.Server.Host.csproj \ -c Release -a "$TARGETARCH" --no-self-contained \ -p:ChronosVersion="$CHRONOS_VERSION" -o /out \ && rm -f /out/*.pdb @@ -43,5 +44,5 @@ RUN chmod 0755 /usr/local/bin/chronos-entrypoint && mkdir -p /archive /data /vid VOLUME ["/archive", "/data"] EXPOSE 8080 8443 HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \ - CMD ["dotnet", "/app/Chronos.Server.dll", "--healthcheck"] + CMD ["dotnet", "/app/Chronos.Server.Host.dll", "--healthcheck"] ENTRYPOINT ["/usr/local/bin/chronos-entrypoint"] diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index 2bd812cd..5575060b 100755 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -14,7 +14,7 @@ umask 002 # Help and the health probe touch neither folder. case "${1:-}" in - --help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.dll "$@" ;; + --help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.Host.dll "$@" ;; esac as_user() { @@ -62,7 +62,7 @@ if [ "$(id -u)" = "0" ]; then fi fi fi - exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.dll "$@" + exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.Host.dll "$@" fi -exec dotnet /app/Chronos.Server.dll "$@" +exec dotnet /app/Chronos.Server.Host.dll "$@" diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 019960a6..588d9922 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -869,6 +869,7 @@ Warning Limits and retention Set by the environment variable {0}; remove the variable to change it here + Set in Chronos Desktop; change it in Settings on the PC that shares this library File level Least severe level written to the log files; Debug and Trace help find problems but fill the files fast File size (MB) diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 6b0eb1c2..da8fa47a 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -29,6 +29,10 @@ The sequence to render is no longer in the archive. Enter a server address such as nas.local:8443 or https://chronos.example.com. This file does not contain Chronos settings. + Sharing could not start: {0} + Open or create an archive before sharing it. + The library is not open yet; sharing starts once it is. + Port {0} is used by another program. Choose another one in Settings › Server. This PC or the server changed the sequence again; compare and choose again. The disk needs {0} GB more for this download.{0} gigabytes missing {0} render is no longer on this PC; the others were sent.{0} count diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 16dd7563..74fa448d 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -85,6 +85,7 @@ Not found.long That address is not a Chronos Server.long The plan converts nothing: every photo is skipped or every sequence is blocked.long + This address is this PC's own shared library, already open here.long Change your password first.long The photo was deleted from the sequence while it was being uploaded, so it was not added.long {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.long @@ -134,6 +135,7 @@ Server Status {0} ms + Sharing off: nothing swept.long Uploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}long: job log line Cancel Password @@ -197,6 +199,28 @@ Trail length Transitions WB smoothing + Addresses + Admin panel + Admin password + {0} client + {0} clients + {0} · {1} · {2} + Clients + Copy + Fingerprint + Hide + None + Ports + HTTPS {0} · HTTP {1} + Render node + Restart + Sharing settings + Show + Not started + Not shared + Sharing + Starting… + This library Sign out Connected Connecting… diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx index 38ce56ae..5a0a26d3 100644 --- a/i18n/en/Settings.resx +++ b/i18n/en/Settings.resx @@ -178,17 +178,27 @@ testing… Reset section Search settings + Announce on LAN Server cache Trusted certificates Default server + LAN discovery Forget: {0} + HTTP port + HTTPS port Known servers None Offer this PC Offline Originals folder + Public HTTP port + Public HTTPS port Render node Server ID + Sharing + Server data + Share this library + Library name Signed in Clear Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.long diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index ba8ca96d..a215375f 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -706,6 +706,18 @@ Editors import, edit and render; only admins manage users Uploaders send photos; editing needs an editor Viewers browse and download + Open the admin panel in your browser to manage accounts; the browser warns once about the self-signed certificate: compare its fingerprint with the one here + Temporary password of the account admin; change it at the first sign-in, then this row goes + Programs that used this library in the last 5 minutes, and the render nodes online + Copy this address for the Uploader or another Chronos + Copy the fingerprint + Copy the temporary password + Clients see this fingerprint the first time they connect; it must match + The ports the shared library listens on + Try to start sharing again + Open Settings › Server to share this library + Show or hide the password + Whether other PCs and the Uploader can use this PC's library now Sign in; the token is stored encrypted for this Windows user · Enter Sign out; the token is removed from this PC Connection to the server @@ -778,10 +790,13 @@ Server Chronos connects to at start; changing it signs out · Enter applies, Esc reverts Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out How much of the end of each log file the diagnostics bundle includes + Announce this library to Chronos programs on the local network Open the data this portable copy kept beside it before it ran from OneDrive. Chronos no longer uses it and leaves it as it is Save every setting as JSON, without the session token File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts + Port the shared library listens on for HTTP (8080 by default); a change restarts sharing · Enter applies, Esc reverts + Port the shared library listens on for HTTPS (8443 by default); a change restarts sharing · Enter applies, Esc reverts Load settings from a JSON file; the session and the window layout stay as they are Open the Microsoft Store page of this free or paid extension; Re-detect after installing it While Chronos is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses @@ -804,7 +819,9 @@ Without this extension some formats are read only from their embedded preview, or not at all, on this PC Frames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc reverts Open the data folder in Explorer + Open the shared library's data folder in Explorer Show the workspace folder in Explorer + Port clients reach when a router forwards another port to this PC; empty: the one above · Enter applies, Esc reverts This server's proxies, render-node files and staged imports, inside the cache folder Servers this PC has signed in to, with the folders kept for each Not signed in: its projects open from the workspace and wait to sync @@ -822,7 +839,7 @@ Session rules, verification, duplicates, after-import actions While Chronos is minimised or in the background, inserted cards, finished jobs and server messages also appear as Windows notifications Quality profile, memory budget, parallelism, encoders - Default server, render node, trusted certificates + Sharing, default server, render node, trusted certificates Cache folder, thumbnails in memory, cache limit Update check on start Where projects are edited on this PC: the folder, sync and versions kept @@ -851,6 +868,9 @@ Find a setting by name Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute Speed on the synthetic 1280×720 test clip + Certificate, server settings, partial uploads and logs of the shared library; its accounts are in the index and its backups + Other PCs and the Uploader on your network use this PC's library as a Chronos Server, while Chronos runs and you are signed in + The name clients see on sign-in and in LAN discovery; empty: this PC's name · Enter applies, Esc reverts Always the Microsoft software H.264 encoder; slower, identical everywhere Remember the folder and leave it as it is Stars per megapixel from which a night frame counts as a star field · Enter applies, Esc reverts diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index e7032d65..aadfe0e3 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -862,6 +862,7 @@ Avviso Limiti e conservazione Impostato dalla variabile d'ambiente {0}; rimuovi la variabile per cambiarlo qui + Impostato in Chronos Desktop; cambialo nelle Impostazioni del PC che condivide questa libreria Livello file Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta Dimensione file (MB) diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index 2000a8d5..d7d36ff4 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -29,6 +29,10 @@ La sequenza da renderizzare non è più nell'archivio. Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://chronos.example.com. Questo file non contiene impostazioni di Chronos. + Impossibile avviare la condivisione: {0} + Apri o crea un archivio prima di condividerlo. + La libreria non è ancora aperta; la condivisione parte appena lo è. + La porta {0} è usata da un altro programma. Scegline un'altra in Impostazioni › Server. La sequenza è cambiata di nuovo su questo PC o sul server; confronta e scegli di nuovo. Al disco servono altri {0} GB per questo scaricamento. {0} render non è più su questo PC; gli altri sono stati inviati. diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 7002d187..3d48946c 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -83,6 +83,7 @@ Non trovato. Questo indirizzo non è un Chronos Server. Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata. + Questo indirizzo è la libreria condivisa di questo PC, già aperta qui.long Cambia prima la password. La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.long 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. @@ -132,6 +133,7 @@ Server Stato {0} ms + Condivisione spenta: nulla da ripulire.long Caricamenti scaduti: {0}, file rimossi: {1}, record rimossi: {2}, token rimossi: {3}long: job log line Annulla Password @@ -195,6 +197,28 @@ Lunghezza scie Transizioni Livellamento WB + Indirizzi + Pannello admin + Password admin + {0} client + {0} client + {0} · {1} · {2} + Client + Copia + Impronta + Nascondi + Nessuno + Porte + HTTPS {0} · HTTP {1} + Nodo di rendering + Riavvia + Impostazioni condivisione + Mostra + Non avviata + Non condivisa + In condivisione + Avvio… + Questa libreria Esci Connesso Connessione… diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx index 0a78d616..ce776c93 100644 --- a/i18n/it/Settings.it.resx +++ b/i18n/it/Settings.it.resx @@ -175,17 +175,27 @@ in prova… Ripristina sezione Cerca impostazioni + Annuncia in LAN Cache del server Certificati attendibili Server predefinito + Rilevamento LAN Dimentica: {0} + Porta HTTP + Porta HTTPS Server noti Nessuno Offri questo PC Non in linea Cartella originali + Porta HTTP pubblica + Porta HTTPS pubblica Nodo di rendering ID server + Condivisione + Dati server + Condividi questa libreria + Nome libreria Connesso Svuota I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti. diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 3ab4112f..11cd5543 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -777,6 +777,18 @@ Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti I caricatori inviano foto; per modificare serve un editor I visualizzatori sfogliano e scaricano + Apri il pannello admin nel browser per gestire gli account; il browser avvisa una volta del certificato autofirmato: confronta l'impronta con quella qui + Password temporanea dell'account admin; cambiala al primo accesso, poi questa riga sparisce + Programmi che hanno usato questa libreria negli ultimi 5 minuti, e i nodi di rendering online + Copia questo indirizzo per l'Uploader o un altro Chronos + Copia l'impronta + Copia la password temporanea + I client vedono questa impronta la prima volta che si connettono; deve coincidere + Le porte su cui ascolta la libreria condivisa + Riprova ad avviare la condivisione + Apri Impostazioni › Server per condividere questa libreria + Mostra o nascondi la password + Se altri PC e l'Uploader possono usare ora la libreria di questo PC Accedi; il token viene salvato cifrato per questo utente di Windows · Invio Esci; il token viene rimosso da questo PC Connessione al server @@ -849,10 +861,13 @@ Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori Quanta parte finale di ogni file di log include il pacchetto di diagnostica + Annuncia questa libreria ai programmi Chronos della rete locale Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Chronos non li usa più e li lascia com'erano Salva tutte le impostazioni in JSON, senza il token di sessione Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla + Porta su cui la libreria condivisa ascolta in HTTP (8080 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla + Porta su cui la libreria condivisa ascolta in HTTPS (8443 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate Apri la pagina del Microsoft Store di questa estensione, gratuita o a pagamento; dopo averla installata premi Rileva di nuovo Mentre Chronos è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi @@ -875,7 +890,9 @@ Senza questa estensione alcuni formati si leggono solo dall'anteprima incorporata, o per niente, su questo PC I fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annulla Apri la cartella dati in Esplora file + Apri in Esplora risorse la cartella dati della libreria condivisa Mostra la cartella dello spazio di lavoro in Esplora file + Porta che i client raggiungono quando un router inoltra un'altra porta a questo PC; vuoto: quella sopra · Invio applica, Esc annulla Proxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cache I server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascuno Accesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione @@ -893,7 +910,7 @@ Lingua, tema, avvio, notifiche Regole delle sessioni, verifica, duplicati, azioni dopo l'importazione Profilo di qualità, memoria, parallelismo, encoder - Server predefinito, nodo di rendering, certificati attendibili + Condivisione, server predefinito, nodo di rendering, certificati attendibili Cartella della cache, miniature in memoria, limite della cache Controllo degli aggiornamenti all'avvio Dove si modificano i progetti su questo PC: cartella, sincronizzazione e versioni tenute @@ -922,6 +939,9 @@ Trova un'impostazione per nome Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto Velocità sulla clip di prova sintetica 1280×720 + Certificato, impostazioni del server, upload parziali e log della libreria condivisa; i suoi account sono nell'indice e nei suoi backup + Altri PC e l'Uploader della tua rete usano la libreria di questo PC come Chronos Server, finché Chronos è aperto e hai effettuato l'accesso + Il nome che i client vedono all'accesso e nel rilevamento LAN; vuoto: il nome di questo PC · Invio applica, Esc annulla Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque Ricorda la cartella e lasciala com'è Stelle per megapixel da cui un fotogramma notturno conta come campo stellare · Invio applica, Esc annulla diff --git a/src/Chronos.App/Chronos.App.csproj b/src/Chronos.App/Chronos.App.csproj index be99345b..855311af 100644 --- a/src/Chronos.App/Chronos.App.csproj +++ b/src/Chronos.App/Chronos.App.csproj @@ -13,8 +13,13 @@ + + + + + diff --git a/src/Chronos.App/DesignTime/SampleData.cs b/src/Chronos.App/DesignTime/SampleData.cs index 27577fb2..5a42e65f 100644 --- a/src/Chronos.App/DesignTime/SampleData.cs +++ b/src/Chronos.App/DesignTime/SampleData.cs @@ -69,6 +69,36 @@ public sealed class SampleData /// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga). public Guid ProxiedSequenceId => _sunrise; + /// The certificate fingerprint of this PC's shared library in the captures. + public const string ShareFingerprint = "4F:0B:E2:91:7C:3A:D5:68:B0:1E:29:C7:83:5D:F4:A6:12:9E:7B:40:D8:6C:35:E1:A9:52:0F:BD:74:C3:86:2E"; + + /// Server › This library shared (owner review 5, #67): sample addresses, two clients, the temporary password. + public static void ShowShare(AppServices services) + { + ArgumentNullException.ThrowIfNull(services); + var pc = AppEnvironment.SamplePcName; + services.Share.ShowSample(ShareState.On, null, + [$"https://{pc}:8443", $"https://{pc}.studio.lan:8443", "https://192.168.1.20:8443", "https://100.88.14.3:8443"], 8443, 8080, ShareFingerprint, + "kT7p-Qm2x-Wf9r", [ + new ShareClient("anna", "Chronos Uploader (ANNA-LAPTOP)", "192.168.1.31", Now.AddMinutes(-1)), + new ShareClient("admin", Chronos.Server.Security.ClientActivity.AdminPanel, "127.0.0.1", Now.AddMinutes(-3)), + ]); + } + + /// Server › This library that could not start: the port is taken. + public static void ShowShareFailed(AppServices services) + { + ArgumentNullException.ThrowIfNull(services); + services.Share.ShowSample(ShareState.Failed, Loc.L("Errors.Share.PortInUse", 8443), [], 0, 0, null, null, []); + } + + /// Server › This library not shared, as before . + public static void HideShare(AppServices services) + { + ArgumentNullException.ThrowIfNull(services); + services.Share.ShowSample(ShareState.Off, null, [], 0, 0, null, null, []); + } + /// Points the services at fakes (server, encoders, update check) for an empty first-run state. public static SampleData Configure(AppServices services) { diff --git a/src/Chronos.App/Infrastructure/AppEnvironment.cs b/src/Chronos.App/Infrastructure/AppEnvironment.cs index d97520bf..4edd9582 100644 --- a/src/Chronos.App/Infrastructure/AppEnvironment.cs +++ b/src/Chronos.App/Infrastructure/AppEnvironment.cs @@ -44,6 +44,16 @@ public sealed class AppEnvironment public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string CacheDirectory => Path.Combine(DataDirectory, "cache"); public string BackupDirectory => Path.Combine(DataDirectory, "backups"); + + /// The private folder of the server this PC runs while it shares its library: certificate, settings, uploads, logs. + public string ShareDirectory => Path.Combine(DataDirectory, "server"); + + /// The PC's name as the screens show it: a capture shows . + public string PcName => IsCapture ? SamplePcName : Environment.MachineName; + + /// The PC name captures show. + public const string SamplePcName = "STUDIO-PC"; + public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName); public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName); diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs index c88ee52b..98da75b6 100644 --- a/src/Chronos.App/Infrastructure/AppServices.cs +++ b/src/Chronos.App/Infrastructure/AppServices.cs @@ -74,6 +74,7 @@ public sealed class AppServices : IAsyncDisposable // The editor's open and closed groups survive a restart (owner review 1, R3). Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings); _renderNode = new RenderNodeHost(StartRenderNode); + Share = new LibraryShare(this); ArchiveSetup = new EngineArchiveSetup(this); Sync = new SyncHost(this); ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives); @@ -114,6 +115,7 @@ public sealed class AppServices : IAsyncDisposable { if (_server is not null) _server.PropertyChanged -= OnServerChanged; _server = value; + _server.IsOwnLibrary = Share.IsOwn; _server.PropertyChanged += OnServerChanged; UpdateRenderNode(); Sync.Update(); @@ -123,6 +125,9 @@ public sealed class AppServices : IAsyncDisposable /// Sync with the signed-in server: engine, job connection, background comparison. public SyncHost Sync { get; } + /// Settings › Server › Share this library: this PC's library served to the LAN while Chronos runs (owner review 5, #67). + public LibraryShare Share { get; } + /// /// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), or replaced its /// frames' files (a conversion), with the sequence's id (any thread): an open editor reads it again where and as it is now. @@ -239,6 +244,7 @@ public sealed class AppServices : IAsyncDisposable SaveSettingsAction(); UpdateRenderNode(); ApplyJobSettings(); + if (!Environment.IsCapture) Share.Apply(); } /// Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last). @@ -329,6 +335,8 @@ public sealed class AppServices : IAsyncDisposable { await _stopping.CancelAsync().ConfigureAwait(false); await _schedules.ConfigureAwait(false); + // First: the shared library's clients and its subscriptions to the engine and the scheduler go before they do. + await Share.DisposeAsync().ConfigureAwait(false); _schedulerReady.TrySetResult(false); if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false); _stopping.Dispose(); @@ -361,6 +369,7 @@ public sealed class AppServices : IAsyncDisposable await StartSchedulerAsync(ct).ConfigureAwait(false); if (reopen is null) { + await Share.StartAsync(ct).ConfigureAwait(false); await ScanNowAsync(started, ct).ConfigureAwait(false); return; } @@ -369,6 +378,7 @@ public sealed class AppServices : IAsyncDisposable { if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return; if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue; + await Share.StartAsync(ct).ConfigureAwait(false); await ScanNowAsync(null, ct).ConfigureAwait(false); Scheduler?.Wake(); return; @@ -559,19 +569,24 @@ public sealed class AppServices : IAsyncDisposable MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes), // The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10). // The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c). + // The shared library's upload-cleanup schedule runs on this PC's scheduler (owner review 5, #67). CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)), - new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)], + new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace), new ShareUploadsStep(() => Share)], BackupDirectory = Environment.BackupDirectory, - // Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs. - SequenceChanged = (id, _, _) => + // While the library is shared, its clients see thumbnails and proxies of what a scan finds, as a server's do. + ImagesAfterScanWhen = () => Share.IsOn, + // Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job + // runs; the shared library's clients are told too. + SequenceChanged = (id, change, token) => { SequenceReorganized?.Invoke(id); - return Task.CompletedTask; + return Share.SequenceChangedAsync(id, change, token); }, + ProjectsChanged = (changed, token) => Share.ProjectsChangedAsync(changed, token), }; Archives = new ArchiveService(database, archive); // The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5). - Archives.Videos.ProtectedFolders = () => [Workspace.Root]; + Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder]; Archives.Videos.Servers = Sync; Processing = new ProcessingService(database, ProcessingOptions(archive)); Sync.Open(database, Archives, archive); @@ -602,6 +617,8 @@ public sealed class AppServices : IAsyncDisposable AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId), Host = EncoderHost.Client, ProducedBy = System.Environment.MachineName, + // A render or an advice recorded on this PC reaches the shared library's clients (owner review 5, #67). + SequenceChanged = (id, change, token) => Share.SequenceChangedAsync(id, change, token), Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount, CacheStore.Folder(Environment, Settings)), }; diff --git a/src/Chronos.App/Infrastructure/AppSettings.cs b/src/Chronos.App/Infrastructure/AppSettings.cs index 0e41bd62..b4a56044 100644 --- a/src/Chronos.App/Infrastructure/AppSettings.cs +++ b/src/Chronos.App/Infrastructure/AppSettings.cs @@ -88,6 +88,40 @@ public sealed class KnownServer public DateTimeOffset LastSeen { get; set; } } +/// +/// Settings › Server › Sharing (owner review 5, #67): this PC's library served to the LAN by the server Chronos hosts +/// while it runs. Absent in a 1.0 settings file: off, on Docker's ports. +/// +public sealed class ShareSettings +{ + public const int DefaultHttpsPort = 8443; + public const int DefaultHttpPort = 8080; + + public bool Enabled { get; set; } + + /// The name clients see; empty: this PC's name. + public string? Name { get; set; } + + public int HttpsPort { get; set; } = DefaultHttpsPort; + public int HttpPort { get; set; } = DefaultHttpPort; + + /// The ports clients reach when a router forwards others to this PC; null: the ones above. + public int? PublicHttpsPort { get; set; } + + public int? PublicHttpPort { get; set; } + + /// Announce the library to Chronos programs on the local network. + public bool Discovery { get; set; } = true; + + /// What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live. + public bool SameEndpoint(ShareSettings other) + { + ArgumentNullException.ThrowIfNull(other); + return string.Equals(Name?.Trim() ?? string.Empty, other.Name?.Trim() ?? string.Empty, StringComparison.Ordinal) && HttpsPort == other.HttpsPort && + HttpPort == other.HttpPort && PublicHttpsPort == other.PublicHttpsPort && PublicHttpPort == other.PublicHttpPort && Discovery == other.Discovery; + } +} + /// /// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in /// settings.json next to the database and written atomically, because language and theme apply before the @@ -292,6 +326,9 @@ public sealed class AppSettings /// The known server of ; null when this PC has none. public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id); + /// Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67). + public ShareSettings Share { get; set; } = new(); + /// Let the server send render jobs to this PC (BRIEF §14.7). public bool RenderNodeOptIn { get; set; } diff --git a/src/Chronos.App/Jobs/DesktopScheduleHost.cs b/src/Chronos.App/Jobs/DesktopScheduleHost.cs index 3a378ce3..25f622f8 100644 --- a/src/Chronos.App/Jobs/DesktopScheduleHost.cs +++ b/src/Chronos.App/Jobs/DesktopScheduleHost.cs @@ -67,6 +67,8 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? []; diff --git a/src/Chronos.App/Sections/ServerView.xaml b/src/Chronos.App/Sections/ServerView.xaml index 3e039e1c..180f271e 100644 --- a/src/Chronos.App/Sections/ServerView.xaml +++ b/src/Chronos.App/Sections/ServerView.xaml @@ -5,7 +5,8 @@ xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui" xmlns:infra="clr-namespace:Chronos.App.Infrastructure" xmlns:shell="clr-namespace:Chronos.App.Shell" - xmlns:srv="clr-namespace:Chronos.App.Server"> + xmlns:srv="clr-namespace:Chronos.App.Server" + xmlns:sec="clr-namespace:Chronos.App.Sections"> - + + - + + + + + + public bool ImagesAfterScan { get; init; } + /// + /// Whether holds now, read at every scan and trash restore (owner review 5, #67): Chronos + /// Desktop makes thumbnails and proxies after its scans while it shares its library, as a server does. Null: the fixed + /// . + /// + public Func? ImagesAfterScanWhen { get; init; } + + /// as it is now, else . + public bool QueuesImagesAfterScan => ImagesAfterScanWhen?.Invoke() ?? ImagesAfterScan; + /// /// The index may hold settings newer than a sequence's project.json: the server, whose PATCH wrote the /// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two diff --git a/src/Chronos.Server.Host/Chronos.Server.Host.csproj b/src/Chronos.Server.Host/Chronos.Server.Host.csproj new file mode 100644 index 00000000..e7445bf5 --- /dev/null +++ b/src/Chronos.Server.Host/Chronos.Server.Host.csproj @@ -0,0 +1,17 @@ + + + + Exe + net10.0 + Chronos.Server.Host + Chronos.Server.Host + $(ChronosIconDir)chronos-server.ico + true + false + + + + + + diff --git a/src/Chronos.Server.Host/Program.cs b/src/Chronos.Server.Host/Program.cs new file mode 100644 index 00000000..40ff87a8 --- /dev/null +++ b/src/Chronos.Server.Host/Program.cs @@ -0,0 +1,30 @@ +using Chronos.Server.Configuration; +using Chronos.Server.Hosting; +using Chronos.Server.Storage; + +var command = ServerCommandLine.Parse(args); +if (command.Error is not null) +{ + await Console.Error.WriteLineAsync(command.Error); + return 2; +} + +switch (command.Command) +{ + case ServerCommand.Help: + Console.WriteLine(ServerCommandLine.Usage); + return 0; + case ServerCommand.HealthCheck: + return await HealthProbe.RunAsync(); + default: + var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules); + await app.RunAsync(); + return 0; +} + +// The archive engine, then analysis and managed rendering over it. +static void RegisterModules(IServiceCollection services) +{ + ArchiveModule.Register(services); + ProcessingModule.Register(services); +} diff --git a/src/Chronos.Server/Admin/web/pages/settings.js b/src/Chronos.Server/Admin/web/pages/settings.js index 76039383..e6f7fb79 100644 --- a/src/Chronos.Server/Admin/web/pages/settings.js +++ b/src/Chronos.Server/Admin/web/pages/settings.js @@ -49,7 +49,9 @@ export async function render(root, { api, info, setMeta, actions }) { // The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless // CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9). const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name; - const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`; + // Chronos Desktop owns the settings of the library it shares (owner review 5, #67): no variable names them. + const lockTip = (name) => variable(name) === "desktop" ? t("Admin.Settings.LockedByDesktop.Tip") : t("Admin.Settings.Locked.Tip", variable(name)); + const lock = (name) => locked(name) ? `disabled title="${attr(lockTip(name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`; const field = (name, input) => ``; const number = (name, value, attrs = "") => field(name, ``); const text = (name, value, attrs = "dir=\"auto\"") => field(name, ``); diff --git a/src/Chronos.Server/Api/JobEndpoints.cs b/src/Chronos.Server/Api/JobEndpoints.cs index 9f40e190..d1ce3f6a 100644 --- a/src/Chronos.Server/Api/JobEndpoints.cs +++ b/src/Chronos.Server/Api/JobEndpoints.cs @@ -32,8 +32,8 @@ public static class JobEndpoints var jobs = api.MapGroup("/jobs").Requires(Permissions.Read); jobs.MapGet("", ListAsync); jobs.MapPost("", CreateAsync); - jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db) => - await db.Jobs.GetAsync(id, context.RequestAborted) is { } job + jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db, JobEngineHost host) => + await db.Jobs.GetAsync(id, context.RequestAborted) is { } job && host.Exposes(job.Kind) ? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto) : ApiErrors.NotFound(context, "job")); jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, ChronosDatabase db, JobEngineHost host) => @@ -47,7 +47,7 @@ public static class JobEndpoints jobs.MapPost("/{id:guid}/priority", PriorityAsync); } - private static async Task ListAsync(HttpContext context, ChronosDatabase db, string? state, string? kind, string? cursor, int? limit) + private static async Task ListAsync(HttpContext context, ChronosDatabase db, JobEngineHost host, string? state, string? kind, string? cursor, int? limit) { JobState? stateFilter = null; JobKind? kindFilter = null; @@ -62,8 +62,10 @@ public static class JobEndpoints kindFilter = k; } // A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none. + if (kindFilter is { } wanted && !host.Exposes(wanted)) return Results.Json(new Page([], null, null), ProtocolJson.Default.PageJobDto); var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted); - return Results.Json(new Page([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto); + // A shared desktop library lists the kinds a server runs alone (owner review 5, #67); the cursor still pages the whole list. + return Results.Json(new Page([.. page.Items.Where(j => host.Exposes(j.Kind)).Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto); } private static async Task CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host, @@ -90,7 +92,7 @@ public static class JobEndpoints var titles = new List(ids.Count); foreach (var id in ids) { - if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + if (await ServedItems.SequenceAsync(db, archive, id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); titles.Add(sequence.DisplayTitle); } targets = ids; @@ -99,7 +101,11 @@ public static class JobEndpoints List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)]; if (kind == JobKind.Render) { - if (ParseRender(request.ParametersJson) is not { } parsed) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson"); + if (ParseRender(request.ParametersJson) is not { } given) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson"); + // A client's export folder means nothing to the server, and on a shared desktop library it would be anywhere the + // desktop's user may write (owner review 5, #67): a render always goes to the sequence's exports. + var parsed = WithoutExportFolder(given); + if (!ReferenceEquals(parsed, given)) request = request with { ParametersJson = JsonSerializer.Serialize(parsed, ProtocolJson.Default.RenderJobParameters) }; // 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); @@ -221,7 +227,9 @@ public static class JobEndpoints private static async Task ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func action) { var ct = context.RequestAborted; - if (await db.Jobs.GetAsync(id, ct) is not { } job) return ApiErrors.NotFound(context, "job"); + // A shared desktop library's own jobs (workspace, sync, downloads) are not the server's (owner review 5, #67). + if (await db.Jobs.GetAsync(id, ct) is not { } job || !context.RequestServices.GetRequiredService().Exposes(job.Kind)) + return ApiErrors.NotFound(context, "job"); if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context); if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State)); await action(job, ct); @@ -230,6 +238,20 @@ public static class JobEndpoints } /// Render parameters, or null when they are missing or incomplete. + /// + /// without the export folder its preset names (key folder, any case), or the same + /// instance when it names none (owner review 5, #67). + /// + public static RenderJobParameters WithoutExportFolder(RenderJobParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + if (System.Text.Json.Nodes.JsonNode.Parse(parameters.PresetJson) is not System.Text.Json.Nodes.JsonObject preset) return parameters; + var folders = preset.Select(p => p.Key).Where(k => k.Equals("folder", StringComparison.OrdinalIgnoreCase)).ToList(); + if (folders.Count == 0) return parameters; + foreach (var key in folders) preset.Remove(key); + return parameters with { PresetJson = preset.ToJsonString() }; + } + public static RenderJobParameters? ParseRender(string? json) { if (string.IsNullOrWhiteSpace(json)) return null; diff --git a/src/Chronos.Server/Api/LibraryEndpoints.cs b/src/Chronos.Server/Api/LibraryEndpoints.cs index f4af700c..cc187a19 100644 --- a/src/Chronos.Server/Api/LibraryEndpoints.cs +++ b/src/Chronos.Server/Api/LibraryEndpoints.cs @@ -219,7 +219,8 @@ public static class LibraryEndpoints var allowed = new List(); foreach (var id in ids) { - if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found"); + if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService().Owns(sequence)) + items[id] = Skip(context, id, "not_found"); else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden"); else allowed.Add(sequence); } @@ -337,7 +338,8 @@ public static class LibraryEndpoints { for (var attempt = 0; attempt < 3; attempt++) { - if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found"); + if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService().Owns(sequence)) + return Skip(context, id, "not_found"); var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList(); tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase))); if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request"); diff --git a/src/Chronos.Server/Api/ServedItems.cs b/src/Chronos.Server/Api/ServedItems.cs new file mode 100644 index 00000000..98786421 --- /dev/null +++ b/src/Chronos.Server/Api/ServedItems.cs @@ -0,0 +1,90 @@ +using Microsoft.AspNetCore.Routing.Patterns; +using Chronos.Core.Model; +using Chronos.Data; +using Chronos.Server.Storage; + +namespace Chronos.Server.Api; + +/// +/// The served archive's items alone (owner review 5, #67): an index may hold several archives (Chronos Desktop's, which +/// shares one of them, also keeps the archives of other servers' originals), and a sequence, frame, render or video of +/// another one answers 404 as an unknown id would, on every route that names one and in every body that lists them. +/// The rule holds on a server of its own too, whose index holds one archive. +/// +public static class ServedItems +{ + /// What the id in a route names, by the route's prefix and the id's name. + private static readonly (string Prefix, string Value, ItemKind Kind)[] Routes = + [ + ("/api/v1/sequences/{id", "id", ItemKind.Sequence), + ("/api/v1/sequences/{sid", "sid", ItemKind.Sequence), + ("/api/v1/frames/{id", "id", ItemKind.Frame), + ("/api/v1/renders/{id", "id", ItemKind.Render), + ("/api/v1/videos/{id", "id", ItemKind.Render), + ]; + + private enum ItemKind + { + Sequence, + Frame, + Render, + } + + /// The endpoint filter of the API group: an id of another archive's item answers 404 before the endpoint runs. + public static async ValueTask FilterAsync(EndpointFilterInvocationContext invocation, EndpointFilterDelegate next) + { + ArgumentNullException.ThrowIfNull(invocation); + ArgumentNullException.ThrowIfNull(next); + var context = invocation.HttpContext; + if (context.GetEndpoint() is RouteEndpoint { RoutePattern: { } pattern } && Named(pattern, context) is var (kind, id)) + { + var db = context.RequestServices.GetRequiredService(); + var archive = context.RequestServices.GetRequiredService(); + if (await ArchiveOfAsync(db, kind, id, context.RequestAborted).ConfigureAwait(false) is { } owner && owner != archive.Id) + return ApiErrors.NotFound(context, kind == ItemKind.Render ? "render" : kind.ToString().ToLowerInvariant()); + } + return await next(invocation).ConfigureAwait(false); + } + + /// The sequence when it belongs to the served archive; null for another archive's or an unknown one. + public static async Task SequenceAsync(ChronosDatabase db, ServerArchive archive, Guid id, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(archive); + return await db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } sequence && archive.Owns(sequence) ? sequence : null; + } + + /// The render when its sequence belongs to the served archive; null otherwise. + public static async Task RenderAsync(ChronosDatabase db, ServerArchive archive, Guid id, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(archive); + return await db.Renders.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } render + && await SequenceAsync(db, archive, render.SequenceId, cancellationToken).ConfigureAwait(false) is not null + ? render + : null; + } + + private static (ItemKind Kind, Guid Id)? Named(RoutePattern pattern, HttpContext context) + { + if (pattern.RawText is not { } text) return null; + foreach (var (prefix, value, kind) in Routes) + { + if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && context.Request.RouteValues.TryGetValue(value, out var raw) + && Guid.TryParse(raw?.ToString(), out var id)) + return (kind, id); + } + return null; + } + + private static async Task ArchiveOfAsync(ChronosDatabase db, ItemKind kind, Guid id, CancellationToken cancellationToken) + { + var sequenceId = kind switch + { + ItemKind.Sequence => id, + ItemKind.Frame => (await db.Frames.GetAsync(id, cancellationToken).ConfigureAwait(false))?.SequenceId, + _ => (await db.Renders.GetAsync(id, cancellationToken).ConfigureAwait(false))?.SequenceId, + }; + return sequenceId is { } sid ? (await db.Sequences.GetAsync(sid, cancellationToken).ConfigureAwait(false))?.ArchiveId : null; + } +} diff --git a/src/Chronos.Server/Api/VideoEndpoints.cs b/src/Chronos.Server/Api/VideoEndpoints.cs index 0086db40..49d39eca 100644 --- a/src/Chronos.Server/Api/VideoEndpoints.cs +++ b/src/Chronos.Server/Api/VideoEndpoints.cs @@ -100,6 +100,7 @@ public static class VideoEndpoints [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime) { if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids"); + ids = await ServedAsync(context, db, ids); var library = Library(videos, archives, db); if (!library.IsAvailable) return Unavailable(context); try @@ -166,7 +167,8 @@ public static class VideoEndpoints var renders = new List(ids.Count); foreach (var id in ids) { - if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render"); + if (await ServedItems.RenderAsync(db, context.RequestServices.GetRequiredService(), id, ct) is not { } render) + return ApiErrors.NotFound(context, "render"); renders.Add(render); } if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context); @@ -200,6 +202,23 @@ public static class VideoEndpoints private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy)); /// The ids of a request, each once in order; null when there are none, too many, or an empty one. + /// + /// without the renders of another archive of the index (owner review 5, #67): they are left out as + /// ids the server does not know. Unknown ids stay, for the library to report. + /// + private static async Task> ServedAsync(HttpContext context, ChronosDatabase db, List ids) + { + var archive = context.RequestServices.GetRequiredService(); + var served = new List(ids.Count); + foreach (var id in ids) + { + if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render + || archive.Owns(await db.Sequences.GetAsync(render.SequenceId, context.RequestAborted))) + served.Add(id); + } + return served; + } + private static List? Ids(IReadOnlyList? ids) { if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null; diff --git a/src/Chronos.Server/Chronos.Server.csproj b/src/Chronos.Server/Chronos.Server.csproj index 34ca3208..878cbd67 100644 --- a/src/Chronos.Server/Chronos.Server.csproj +++ b/src/Chronos.Server/Chronos.Server.csproj @@ -1,12 +1,12 @@ + + Library net10.0 Chronos.Server Chronos.Server - $(ChronosIconDir)chronos-server.ico - true false - diff --git a/src/Chronos.Server/Configuration/ServerOptions.cs b/src/Chronos.Server/Configuration/ServerOptions.cs index dbb79c97..49be97c6 100644 --- a/src/Chronos.Server/Configuration/ServerOptions.cs +++ b/src/Chronos.Server/Configuration/ServerOptions.cs @@ -369,6 +369,121 @@ public sealed class ServerOptions return options; } + /// What names for a setting Chronos Desktop owns while it shares its library (owner review 5, #67). + public const string DesktopLock = "desktop"; + + /// + /// The server Chronos Desktop hosts in-process to share this PC's library (owner review 5, #67): its index, archive service, + /// engine and scheduler are the desktop's (), its own state is in the desktop's data folder. + /// + [JsonIgnore] + public bool Hosted { get; private set; } + + /// + /// The options of the server Chronos Desktop hosts (owner review 5, #67): 's server.json + /// (what the admin panel saved: token lifetime, uploads, sign-in limits, render nodes, audit retention), then the values + /// the desktop owns, locked there with (its name, ports, discovery, archive, videos folder, jobs, + /// language and logs). No environment variable is read: a CHRONOS_* variable set for a server never reaches the + /// desktop. The index is the desktop's (SQLite), the certificate a self-signed one. + /// + public static ServerOptions ForHosted(string dataPath, HostedSettings desktop) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); + ArgumentNullException.ThrowIfNull(desktop); + var options = new ServerOptions(); + var file = Path.Combine(dataPath, "server.json"); + if (File.Exists(file)) + { + try + { + options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options; + } + catch (JsonException ex) + { + throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex); + } + } + options.Hosted = true; + options.DataPath = dataPath; + options.InContainer = false; + options.AdminUser = null; + options.AdminPassword = null; + options.DbConnectionString = null; + options.Database = DatabaseKind.Sqlite; + options.TlsMode = TlsMode.Auto; + options.TlsCert = null; + options.TlsKey = null; + options.TrustedProxies = DefaultTrustedProxies; + options.SpacePath = null; + options.ApplyDesktop(desktop); + options.Locked = HostedLocks; + options.LockedBy = HostedLocks.ToDictionary(s => s, _ => DesktopLock, StringComparer.Ordinal); + options.ValidateHosted(); + return options; + } + + /// The settings Chronos Desktop owns while it shares its library: the admin panel shows them locked. + public static IReadOnlyList HostedLocks { get; } = + [ + nameof(ServerName), nameof(HttpPort), nameof(HttpsPort), nameof(PublicHttpPort), nameof(PublicHttpsPort), nameof(Discovery), nameof(ArchivePath), + nameof(VideosPath), nameof(Parallelism), nameof(PriorityQueue), nameof(JobPriorities), nameof(Language), nameof(LogLevel), nameof(ConsoleLogLevel), + nameof(LogRetentionDays), nameof(LogMaxFileMb), nameof(LogMaxTotalMb), nameof(LogRotation), nameof(DiagnosticsLogMb), nameof(TlsMode), + nameof(Database), nameof(JobHistoryDays), + ]; + + /// + /// Puts the values of Chronos Desktop's settings into these options (owner review 5, #67): when the share starts and + /// whenever the desktop saves its settings, so the parallelism, the priority queue, the language and the logs follow at + /// once; a change of name, port or discovery restarts the share. + /// + public void ApplyDesktop(HostedSettings desktop) + { + ArgumentNullException.ThrowIfNull(desktop); + ServerName = string.IsNullOrWhiteSpace(desktop.ServerName) ? Environment.MachineName : desktop.ServerName.Trim(); + HttpPort = desktop.HttpPort; + HttpsPort = desktop.HttpsPort; + PublicHttpPort = desktop.PublicHttpPort; + PublicHttpsPort = desktop.PublicHttpsPort; + Discovery = desktop.Discovery; + ArchivePath = desktop.ArchivePath; + VideosPath = string.IsNullOrWhiteSpace(desktop.VideosPath) ? null : desktop.VideosPath.Trim(); + Parallelism = Math.Clamp(desktop.Parallelism, 1, MaxParallelism); + PriorityQueue = desktop.PriorityQueue; + JobPriorities = new Dictionary(desktop.JobPriorities, StringComparer.Ordinal); + Language = string.IsNullOrWhiteSpace(desktop.Language) ? "en" : desktop.Language; + LogLevel = MsLevel(desktop.LogLevel); + // Nobody reads the console of a desktop program. + ConsoleLogLevel = LogLevel.None; + LogRetentionDays = desktop.LogRetentionDays; + LogMaxFileMb = desktop.LogMaxFileMb; + LogMaxTotalMb = desktop.LogMaxTotalMb; + LogRotation = desktop.LogRotation; + DiagnosticsLogMb = desktop.DiagnosticsLogMb; + JobHistoryDays = Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays; + } + + private static LogLevel MsLevel(Chronos.Core.Diagnostics.LogLevel level) => level switch + { + Chronos.Core.Diagnostics.LogLevel.Trace => LogLevel.Trace, + Chronos.Core.Diagnostics.LogLevel.Debug => LogLevel.Debug, + Chronos.Core.Diagnostics.LogLevel.Info => LogLevel.Information, + Chronos.Core.Diagnostics.LogLevel.Warning => LogLevel.Warning, + _ => LogLevel.Error, + }; + + /// for : no platform check, as the index is the desktop's. + private void ValidateHosted() + { + if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535 || PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535) + throw new InvalidOperationException("The ports must be between 1 and 65535."); + if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) + throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB."); + if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1) + throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive."); + if (ServerLogging.Problem(LogRetentionDays, LogMaxFileMb, LogMaxTotalMb, AuditRetentionDays, DiagnosticsLogMb) is { } log) + throw new InvalidOperationException($"{log} is out of range: {ServerLogging.Ranges}."); + } + /// The database to open: , the SQLite file in the data folder, or PostgreSQL from the parts. public DatabaseOptions ToDatabaseOptions() { @@ -457,6 +572,31 @@ public sealed class ServerOptions } } +/// +/// What Chronos Desktop decides for the server it hosts when it shares this PC's library (owner review 5, #67): Settings › +/// Server (name, ports, discovery), the current archive, Settings › Videos, Settings › Rendering (parallelism, priority +/// queue), the language and Settings › Advanced › Logs. locks them in the admin panel. +/// +public sealed record HostedSettings( + string? ServerName, + int HttpPort, + int HttpsPort, + int? PublicHttpPort, + int? PublicHttpsPort, + bool Discovery, + string ArchivePath, + string? VideosPath, + int Parallelism, + bool PriorityQueue, + IReadOnlyDictionary JobPriorities, + string? Language, + Chronos.Core.Diagnostics.LogLevel LogLevel, + int LogRetentionDays, + int LogMaxFileMb, + int LogMaxTotalMb, + LogRotation LogRotation, + int DiagnosticsLogMb); + [JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)] [JsonSerializable(typeof(ServerOptions))] internal sealed partial class ServerOptionsJson : JsonSerializerContext; diff --git a/src/Chronos.Server/Hosting/HealthProbe.cs b/src/Chronos.Server/Hosting/HealthProbe.cs index b2b2b9fe..776ef16c 100644 --- a/src/Chronos.Server/Hosting/HealthProbe.cs +++ b/src/Chronos.Server/Hosting/HealthProbe.cs @@ -3,7 +3,7 @@ using Chronos.Server.Configuration; namespace Chronos.Server.Hosting; /// -/// Chronos.Server --healthcheck: probes the local /health endpoint and exits 0/1, so the container +/// Chronos.Server.Host --healthcheck: probes the local /health endpoint and exits 0/1, so the container /// HEALTHCHECK needs no curl/wget in the image. /// public static class HealthProbe diff --git a/src/Chronos.Server/Hosting/HostedServer.cs b/src/Chronos.Server/Hosting/HostedServer.cs new file mode 100644 index 00000000..815a51b9 --- /dev/null +++ b/src/Chronos.Server/Hosting/HostedServer.cs @@ -0,0 +1,168 @@ +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Chronos.Core.Model; +using Chronos.Data; +using Chronos.Data.Archiving; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Housekeeping; +using Chronos.Data.Jobs; +using Chronos.Data.Processing; +using Chronos.Data.Projects; +using Chronos.Data.Scheduling; +using Chronos.Server.Api; +using Chronos.Server.Configuration; +using Chronos.Server.Events; +using Chronos.Server.Jobs; +using Chronos.Server.Security; +using Chronos.Server.Storage; + +namespace Chronos.Server.Hosting; + +/// +/// What Chronos Desktop lends the server it hosts to share this PC's library (owner review 5, #67): its index, archive and +/// processing services, job engine and running scheduler, and the archive it serves. The server uses them and never +/// creates, starts, stops, replaces or disposes any of them. +/// +public sealed record HostedEngine(ChronosDatabase Database, ArchiveService Archives, ProcessingService Processing, JobEngine Engine, Scheduler Scheduler, + Archive Archive); + +/// +/// The server Chronos Desktop runs in its own process while it shares this PC's library (owner review 5, #67), built by +/// : start, stop, and what the desktop shows of it (fingerprint, id, ports, the clients +/// of the last minutes, the first administrator's temporary password); and the way the desktop's own engines tell its +/// clients of what they change (, ). +/// +public sealed class HostedServer : IAsyncDisposable +{ + private readonly WebApplication _app; + private readonly ServerLogging _logging; + private int _started; + private int _disposed; + + internal HostedServer(WebApplication app, ServerOptions options, ServerState state, ServerLogging logging) + { + _app = app; + _logging = logging; + Options = options; + State = state; + var jobs = app.Services.GetRequiredService(); + jobs.ChangedOutside += job => JobChangedOutside?.Invoke(job); + } + + public ServerOptions Options { get; } + + internal ServerState State { get; } + + public IServiceProvider Services => _app.Services; + + /// SHA-256 fingerprint of the certificate, colon hex, as clients see it the first time they connect. + public string? Fingerprint => State.TlsFingerprint; + + /// The server's stable id (), kept in the desktop's index. + public Guid? ServerId => State.ServerId; + + /// The events connected clients receive. + public EventHub Events => _app.Services.GetRequiredService(); + + /// The programs that used the server in the last minutes. + public ClientActivity Clients => _app.Services.GetRequiredService(); + + /// A render node changed a job's state, outside the desktop's engine. + public event Action? JobChangedOutside; + + /// The port the HTTP listener got (the configured one, or the system's choice for 0); 0 before the start. + public int HttpPort { get; private set; } + + /// The port the HTTPS listener got; 0 before the start or without a certificate. + public int HttpsPort { get; private set; } + + /// The file that holds the first administrator's temporary password until it is changed. + public string AdminPasswordFile => Path.Combine(Options.DataPath, AdminBootstrap.PasswordFileName); + + /// The first administrator's temporary password while its file exists; null once an administrator set their own. + public string? AdminPassword() + { + try + { + return File.Exists(AdminPasswordFile) ? File.ReadAllText(AdminPasswordFile).Trim() : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + /// Listens and starts the server's own services; a port in use throws (). + public async Task StartAsync(CancellationToken cancellationToken = default) + { + if (Interlocked.Exchange(ref _started, 1) == 1) return; + await _app.StartAsync(cancellationToken).ConfigureAwait(false); + foreach (var address in _app.Services.GetRequiredService().Features.Get()?.Addresses ?? []) + { + if (!Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal), + UriKind.Absolute, out var uri)) + continue; + if (uri.Scheme == Uri.UriSchemeHttps) HttpsPort = uri.Port; + else if (uri.Scheme == Uri.UriSchemeHttp) HttpPort = uri.Port; + } + } + + /// Stops listening and the server's own services; the desktop's engines run on. + public async Task StopAsync(CancellationToken cancellationToken = default) + { + if (Volatile.Read(ref _started) == 0) return; + await _app.StopAsync(cancellationToken).ConfigureAwait(false); + } + + /// The desktop saved its settings: the parallelism, the priority queue, the language and the logs apply at once. + public void ApplyDesktop(HostedSettings desktop) + { + Options.ApplyDesktop(desktop); + _logging.Apply(Options); + } + + /// The desktop's archive or processing service changed or made sequence : clients are told. + public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) => + ServerEventBridge.SequenceChangedAsync(Services.GetRequiredService(), Events, Services.GetService(), id, change, + cancellationToken); + + /// The desktop's archive service changed a sequence's projects: clients are told. + public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) => + ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService(), Events, changed, cancellationToken); + + /// The uploads clean-up step of the server: abandoned uploads and old upload records (the upload-cleanup schedule). + public Task SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) => + Services.GetRequiredService().RunAsync(context, parameters); + + /// The render nodes online now, by name. + public async Task> RenderNodesAsync(CancellationToken cancellationToken) + { + var since = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(Options.NodeTimeoutSeconds); + var nodes = await Services.GetRequiredService().RenderNodes.ListOnlineAsync(since, cancellationToken).ConfigureAwait(false); + return [.. nodes.Select(n => n.ClientName)]; + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) return; + try + { + await StopAsync(CancellationToken.None).ConfigureAwait(false); + } + finally + { + await _app.DisposeAsync().ConfigureAwait(false); + } + } +} + +/// +/// The lifetime of the server Chronos Desktop hosts (owner review 5, #67): the desktop starts and stops it, so nothing hooks +/// Ctrl+C, the process's exit or a termination signal, as the console lifetime would. +/// +internal sealed class DesktopHostLifetime : IHostLifetime +{ + public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/Chronos.Server/Hosting/ServerCommandLine.cs b/src/Chronos.Server/Hosting/ServerCommandLine.cs index a91d85bb..ef797770 100644 --- a/src/Chronos.Server/Hosting/ServerCommandLine.cs +++ b/src/Chronos.Server/Hosting/ServerCommandLine.cs @@ -1,17 +1,11 @@ namespace Chronos.Server.Hosting; -/// What Chronos.Server was asked to do. +/// What Chronos.Server.Host was asked to do. public enum ServerCommand { /// Run in the console (Docker, Linux, development). Run, - /// Run under the Windows Service Control Manager (the command line the installed service uses). - Service, - - InstallService, - UninstallService, - /// Probe /health of the local server and exit 0/1 (container health check). HealthCheck, @@ -24,12 +18,9 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList ServerCommand.Service, - "--install-service" => ServerCommand.InstallService, - "--uninstall-service" => ServerCommand.UninstallService, "--healthcheck" => ServerCommand.HealthCheck, "--help" or "-h" or "-?" or "/?" => ServerCommand.Help, _ => null, diff --git a/src/Chronos.Server/Hosting/ServerHost.cs b/src/Chronos.Server/Hosting/ServerHost.cs index 2c83814f..77920f8a 100644 --- a/src/Chronos.Server/Hosting/ServerHost.cs +++ b/src/Chronos.Server/Hosting/ServerHost.cs @@ -16,12 +16,13 @@ using Chronos.Server.Storage; namespace Chronos.Server.Hosting; /// -/// Builds the Chronos Server web application from (used by Program, the Windows service -/// host and tests). The archive module plugs in through the configureServices callback of , +/// Builds the Chronos Server web application from (used by Chronos.Server.Host's Program and +/// tests). The archive module plugs in through the configureServices callback of , /// which runs before the server's own registrations: it must register and /// (the server refuses to start without them), may add /// s, and may resolve , -/// and from DI in its factories. +/// and from DI in its factories. builds the same server over the index, +/// engines and scheduler of Chronos Desktop, which shares its library with it (owner review 5, #67). /// public static class ServerHost { @@ -61,19 +62,7 @@ public static class ServerHost ServerId = ServerIdAsync(database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(), }; - builder.WebHost.ConfigureKestrel(k => - { - k.AddServerHeader = false; - k.Limits.MaxRequestBodySize = JsonBodyLimit; - k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30); - k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2); - k.ListenAnyIP(options.HttpPort); - if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => - { - l.Protocols = HttpProtocols.Http1AndHttp2; - l.UseHttps(certificate); - }); - }); + ConfigureKestrel(builder, options, certificate); ConfigureServices(builder.Services, options, state, database, archive); var app = builder.Build(); @@ -118,6 +107,69 @@ public static class ServerHost } } + /// + /// The server Chronos Desktop runs in its own process to share this PC's library (owner review 5, #67): the same API, admin + /// panel, accounts, TLS, discovery, uploads, sync, events and render nodes as a server of its own, over the desktop's + /// index, archive service, processing service, job engine and scheduler (), which it never + /// creates, starts, stops or disposes. Its own state is in (made private first); + /// the first administrator is made there as on a new server. It sets no process-wide log sink or level and hooks no + /// console signal: the desktop's stay. Runs synchronously: call it off the UI thread. + /// + public static HostedServer BuildHosted(ServerOptions options, HostedEngine engine) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(engine); + if (!options.Hosted) throw new ArgumentException("The options are not those of a hosted server (ServerOptions.ForHosted).", nameof(options)); + DataFolderAccess.Restrict(options.DataPath); + Directory.CreateDirectory(options.LogPath); + Directory.CreateDirectory(options.UploadsPath); + + // The desktop's command line and environment are not the server's. + var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = [], ContentRootPath = AppContext.BaseDirectory }); + var logging = new ServerLogging(options, setsEngineLevel: false); + logging.AddTo(builder.Logging); + builder.Services.AddSingleton(logging); + + var bootLogger = new FileLoggerProvider(logging).CreateLogger("Chronos.Server"); + var certificate = CertificateStore.Load(options, bootLogger); + AdminBootstrap.RunAsync(engine.Database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult(); + var state = new ServerState + { + TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate), + Database = ServerDatabase.DescribeAsync(engine.Database, CancellationToken.None).GetAwaiter().GetResult(), + ServerId = ServerIdAsync(engine.Database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(), + }; + var archive = ServerArchive.ForArchive(engine.Archive); + + ConfigureKestrel(builder, options, certificate); + ConfigureServices(builder.Services, options, state, engine.Database, archive, engine); + + var app = builder.Build(); + ConfigurePipeline(app, options); + app.Logger.LogInformation("Chronos Server {Version} in Chronos Desktop · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}", + SystemEndpoints.Version, archive.Root, options.DataPath, options.TlsMode, + state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint); + if (archive.Structure is { IsComplete: false } structure) + app.Logger.LogWarning("The archive's folders are incomplete: {Problem} {Detail}", structure.Message, structure.Detail ?? string.Empty); + return new HostedServer(app, options, state, logging); + } + + /// Kestrel on every interface: the HTTP port, and the HTTPS port with HTTP/2 when there is a certificate. + private static void ConfigureKestrel(WebApplicationBuilder builder, ServerOptions options, System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) => + builder.WebHost.ConfigureKestrel(k => + { + k.AddServerHeader = false; + k.Limits.MaxRequestBodySize = JsonBodyLimit; + k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30); + k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2); + k.ListenAnyIP(options.HttpPort); + if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => + { + l.Protocols = HttpProtocols.Http1AndHttp2; + l.UseHttps(certificate); + }); + }); + /// The app setting that holds the server's stable id (). public const string ServerIdKey = "server.id"; @@ -153,8 +205,12 @@ public static class ServerHost return id; } - /// The single composition root of the server's services. - public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive) + /// + /// The single composition root of the server's services; with , those of the library Chronos + /// Desktop shares, whose engines, engine and scheduler are the desktop's (owner review 5, #67). + /// + public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive, + HostedEngine? hosted = null) { services.AddSingleton(options); services.AddSingleton(state); @@ -165,7 +221,9 @@ public static class ServerHost services.TryAddSingleton(); services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); services.Configure(o => o.ThrowOnBadRequest = true); - services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30)); + // The desktop's exit waits for everything it runs: the server it hosts stops within a few seconds. + services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(hosted is null ? 30 : 5)); + if (hosted is not null) RegisterHosted(services, hosted); if (options.TlsMode == TlsMode.Proxy) { // Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would @@ -192,18 +250,24 @@ public static class ServerHost services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + if (hosted is null) services.AddSingleton(); + else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService())); services.AddHostedService(sp => sp.GetRequiredService()); // After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10). services.AddSingleton(); - services.AddSingleton(); + if (hosted is null) services.AddSingleton(); + else services.AddSingleton(sp => new SchedulerHost(database, hosted.Scheduler, sp.GetRequiredService(), options, + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>())); services.AddHostedService(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddHostedService(sp => sp.GetRequiredService()); // Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule. services.AddSingleton(); services.AddHostedService(sp => sp.GetRequiredService()); - services.AddSingleton(); + // The desktop's archive service holds a step of its own that runs this one while it shares its library. + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); // Main takes settings written outside the projects soon after they are (owner review 2, R8). services.AddSingleton(); services.AddHostedService(sp => sp.GetRequiredService()); @@ -211,6 +275,22 @@ public static class ServerHost services.AddHostedService(sp => sp.GetRequiredService()); } + /// + /// The desktop's engines as the archive and processing modules would register them, and a lifetime that hooks no console + /// signal of the desktop's process (owner review 5, #67). + /// + private static void RegisterHosted(IServiceCollection services, HostedEngine hosted) + { + services.AddSingleton(hosted); + services.AddSingleton(hosted.Archives); + services.AddSingleton(hosted.Archives.Ingest); + services.AddSingleton(hosted.Archives.Videos); + services.AddSingleton(); + services.AddSingleton(hosted.Processing); + services.AddSingleton(); + services.AddSingleton(); + } + private static void ConfigurePipeline(WebApplication app, ServerOptions options) { if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders(); @@ -221,6 +301,8 @@ public static class ServerHost AdminPanel.Map(app, options); var api = app.MapGroup("/api/v1"); + // A sequence, frame, render or video of another archive of the index answers as an unknown id (owner review 5, #67). + api.AddEndpointFilter(ServedItems.FilterAsync); SystemEndpoints.Map(app, api); AuthEndpoints.Map(api); UserEndpoints.Map(api); diff --git a/src/Chronos.Server/Hosting/ServerLogging.cs b/src/Chronos.Server/Hosting/ServerLogging.cs index e9a196d1..28ef568a 100644 --- a/src/Chronos.Server/Hosting/ServerLogging.cs +++ b/src/Chronos.Server/Hosting/ServerLogging.cs @@ -33,12 +33,21 @@ public sealed class ServerLogging private volatile MsLogLevel _console; /// Opens the log files of and applies its levels (call once the data folder is prepared). - public ServerLogging(ServerOptions options) + /// The server's settings. + /// + /// Whether the levels also set the engine's : false when Chronos Desktop hosts the server + /// (owner review 5, #67), whose own log settings keep it. + /// + public ServerLogging(ServerOptions options, bool setsEngineLevel = true) { + SetsEngineLevel = setsEngineLevel; Sink = new FileLogSink(options.LogPath, "server", FileOptions(options)); Apply(options); } + /// The levels set the process's too (a server of its own, not one Chronos Desktop hosts). + public bool SetsEngineLevel { get; } + public FileLogSink Sink { get; } public MsLogLevel FileLevel => _file; @@ -63,7 +72,7 @@ public sealed class ServerLogging _file = options.LogLevel; _console = options.ConsoleLogLevel; Sink.Configure(FileOptions(options)); - Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel); + if (SetsEngineLevel) Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel); } public static LogFileOptions FileOptions(ServerOptions options) => new() diff --git a/src/Chronos.Server/Hosting/Windows/ServiceEventLog.cs b/src/Chronos.Server/Hosting/Windows/ServiceEventLog.cs deleted file mode 100644 index 81ada5f3..00000000 --- a/src/Chronos.Server/Hosting/Windows/ServiceEventLog.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Runtime.Versioning; -using static Chronos.Server.Hosting.Windows.ServiceNative; - -namespace Chronos.Server.Hosting.Windows; - -/// -/// Errors of the Windows service in the Application event log (source ChronosServer). A service has no console, -/// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very -/// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered -/// with a message file: Event Viewer says it found no description for the event, then shows the text whole. -/// -internal static unsafe class ServiceEventLog -{ - public const uint StartFailed = 1; - public const uint StopFailed = 2; - - /// ReportEvent takes at most 31,839 characters per string. - public const int MaxLength = 31_839; - - /// - /// The event text: and the reason the server gave (the entry to check, for a refused data - /// folder), then the exception for a bug report; cut to . - /// - public static string Describe(string what, Exception exception) - { - var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}"; - if (text.Length <= MaxLength) return text; - var cut = MaxLength - 1; - // Never half a surrogate pair. - if (char.IsHighSurrogate(text[cut - 1])) cut--; - return string.Concat(text.AsSpan(0, cut), "…"); - } - - /// Writes an error event; false when the event log could not be written (the console still gets it). - [SupportedOSPlatform("windows")] - public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text); - - /// as (tests write as their own source). - [SupportedOSPlatform("windows")] - internal static bool Error(string sourceName, uint eventId, string text) - { - var source = RegisterEventSourceW(null, sourceName); - if (source == 0) return false; - try - { - fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength]) - { - var strings = stackalloc char*[1]; - strings[0] = chars; - return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null); - } - } - finally - { - DeregisterEventSource(source); - } - } -} diff --git a/src/Chronos.Server/Hosting/Windows/ServiceInstaller.cs b/src/Chronos.Server/Hosting/Windows/ServiceInstaller.cs deleted file mode 100644 index 84c578ab..00000000 --- a/src/Chronos.Server/Hosting/Windows/ServiceInstaller.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Security.Principal; -using Chronos.Core.Localization; -using static Chronos.Server.Hosting.Windows.ServiceNative; - -namespace Chronos.Server.Hosting.Windows; - -/// -/// --install-service / --uninstall-service: registers the server with the Service Control Manager -/// (automatic start, LocalSystem, command line "…\Chronos.Server.exe" --service) or stops and removes it. -/// Both need an elevated prompt; failures surface as . A LocalSystem service runs whatever -/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM, -/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to -/// any program of that user. Otherwise refuses with . -/// -[SupportedOSPlatform("windows")] -public static unsafe class ServiceInstaller -{ - private const string DisplayName = "Chronos Server"; - - /// TrustedInstaller, the owner of Windows' own files under Program Files. - private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"); - - /// This copy is not in a folder that only administrators can change. - public static void Install() - { - if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem); - var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService); - if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); - try - { - var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart, - ServiceErrorNormal, CommandLine(), null, 0, null, null, null); - if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); - try - { - fixed (char* text = Loc.L("Server.Service.Description")) - { - var description = new ServiceDescription { Description = text }; - ChangeServiceConfig2W(service, ServiceConfigDescription, &description); - } - } - finally - { - CloseServiceHandle(service); - } - } - finally - { - CloseServiceHandle(manager); - } - } - - public static void Uninstall() - { - var manager = OpenSCManagerW(null, null, ScManagerConnect); - if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); - try - { - var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus); - if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); - try - { - ServiceStatus status; - if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive) - throw new Win32Exception(stopError); - if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete) - throw new Win32Exception(deleteError); - } - finally - { - CloseServiceHandle(service); - } - } - finally - { - CloseServiceHandle(manager); - } - } - - /// - /// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when - /// run by dotnet, the host's folder) must be inside Program Files and changeable only by administrators. - /// - internal static string? UnsafeLocation() - { - var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory); - if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program); - if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open); - // Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it. - if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host - && !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase)) - { - if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host); - if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen); - } - return null; - } - - /// True for a path inside %ProgramFiles% or %ProgramFiles(x86)% (not the folder itself). - internal static bool IsUnderProgramFiles(string path) - { - var full = Path.GetFullPath(path); - foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }) - { - var root = Environment.GetFolderPath(folder); - if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) - return true; - } - return false; - } - - /// - /// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than - /// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none. - /// - internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts()); - - private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet trusted) - { - if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName; - foreach (var file in folder.EnumerateFiles()) - { - if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName; - } - if (!recursive) return null; - foreach (var child in folder.EnumerateDirectories()) - { - if (FindChangeable(child, recursive: true, trusted) is { } path) return path; - } - return null; - } - - private static HashSet TrustedAccounts() - { - var trusted = new HashSet - { - new(WellKnownSidType.LocalSystemSid, null), - new(WellKnownSidType.BuiltinAdministratorsSid, null), - TrustedInstaller, - }; - // Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it. - using var identity = WindowsIdentity.GetCurrent(); - if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user); - return trusted; - } - - /// The service's command line: this executable (or dotnet plus this assembly) with --service. - private static string CommandLine() - { - var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown."); - // Assembly.Location is empty in a single-file app; under dotnet the entry assembly sits in the base directory. - var assembly = Path.Combine(AppContext.BaseDirectory, typeof(ServiceInstaller).Assembly.GetName().Name + ".dll"); - return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase) - ? $"\"{process}\" \"{assembly}\" --service" - : $"\"{process}\" --service"; - } -} diff --git a/src/Chronos.Server/Hosting/Windows/ServiceNative.cs b/src/Chronos.Server/Hosting/Windows/ServiceNative.cs deleted file mode 100644 index aa74fd87..00000000 --- a/src/Chronos.Server/Hosting/Windows/ServiceNative.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Runtime.InteropServices; -using System.Runtime.Versioning; - -namespace Chronos.Server.Hosting.Windows; - -/// Service Control Manager and event log functions of advapi32 (no Windows-only package needed). -[SupportedOSPlatform("windows")] -internal static unsafe partial class ServiceNative -{ - public const uint ServiceWin32OwnProcess = 0x10; - public const uint ServiceAutoStart = 2; - public const uint ServiceErrorNormal = 1; - public const uint ScManagerConnect = 0x1; - public const uint ScManagerCreateService = 0x2; - public const uint ServiceAllAccess = 0xF01FF; - public const uint ServiceQueryStatus = 0x4; - public const uint ServiceStop = 0x20; - public const uint Delete = 0x10000; - public const uint ServiceConfigDescription = 1; - - public const uint ControlStop = 1; - public const uint ControlInterrogate = 4; - public const uint ControlShutdown = 5; - - public const int ErrorFailedServiceControllerConnect = 1063; - public const int ErrorServiceNotActive = 1062; - public const int ErrorServiceMarkedForDelete = 1072; - public const uint NoError = 0; - public const uint ErrorCallNotImplemented = 120; - public const uint ErrorExceptionInService = 1064; - - public const ushort EventLogErrorType = 0x1; - - [StructLayout(LayoutKind.Sequential)] - public struct ServiceStatus - { - public uint ServiceType; - public uint CurrentState; - public uint ControlsAccepted; - public uint Win32ExitCode; - public uint ServiceSpecificExitCode; - public uint CheckPoint; - public uint WaitHint; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ServiceTableEntry - { - public char* ServiceName; - public delegate* unmanaged[Stdcall] ServiceProc; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ServiceDescription - { - public char* Description; - } - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool StartServiceCtrlDispatcherW(ServiceTableEntry* table); - - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - public static partial nint RegisterServiceCtrlHandlerExW(string serviceName, delegate* unmanaged[Stdcall] handler, nint context); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool SetServiceStatus(nint statusHandle, ServiceStatus* status); - - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess); - - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - public static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType, - uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password); - - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool ChangeServiceConfig2W(nint service, uint infoLevel, void* info); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool ControlService(nint service, uint control, ServiceStatus* status); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool DeleteService(nint service); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool CloseServiceHandle(nint handle); - - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - public static partial nint RegisterEventSourceW(string? uncServerName, string sourceName); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool ReportEventW(nint eventLog, ushort type, ushort category, uint eventId, nint userSid, ushort stringCount, uint dataSize, - char** strings, void* rawData); - - [LibraryImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool DeregisterEventSource(nint eventLog); -} diff --git a/src/Chronos.Server/Hosting/Windows/ServiceStatusTracker.cs b/src/Chronos.Server/Hosting/Windows/ServiceStatusTracker.cs deleted file mode 100644 index 548aafeb..00000000 --- a/src/Chronos.Server/Hosting/Windows/ServiceStatusTracker.cs +++ /dev/null @@ -1,68 +0,0 @@ -namespace Chronos.Server.Hosting.Windows; - -/// SERVICE_STATUS.dwCurrentState values the server reports. -public enum ServiceState : uint -{ - Stopped = 1, - StartPending = 2, - StopPending = 3, - Running = 4, -} - -/// One status report for SetServiceStatus. -public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode); - -/// -/// The service's state machine and the rules of SERVICE_STATUS: no controls are accepted while pending, the check point -/// grows with every pending report and is zero otherwise, a stopped service carries its exit code. -/// -public sealed class ServiceStatusTracker -{ - public const uint AcceptStop = 0x1; - public const uint AcceptShutdown = 0x4; - - private readonly Lock _gate = new(); - private uint _checkPoint; - - public ServiceStatusReport Current { get; private set; } = new(ServiceState.Stopped, 0, 0, 0, 0); - - public ServiceStatusReport StartPending(uint waitHintMilliseconds) => Pending(ServiceState.StartPending, waitHintMilliseconds, ServiceState.Stopped, ServiceState.StartPending); - - public ServiceStatusReport Running() - { - lock (_gate) - { - Require(ServiceState.StartPending); - _checkPoint = 0; - return Current = new ServiceStatusReport(ServiceState.Running, AcceptStop | AcceptShutdown, 0, 0, 0); - } - } - - /// Stopping from start-up or from running; repeating it reports progress (a higher check point). - public ServiceStatusReport StopPending(uint waitHintMilliseconds) => - Pending(ServiceState.StopPending, waitHintMilliseconds, ServiceState.StartPending, ServiceState.Running, ServiceState.StopPending); - - public ServiceStatusReport Stopped(uint exitCode) - { - lock (_gate) - { - _checkPoint = 0; - return Current = new ServiceStatusReport(ServiceState.Stopped, 0, 0, 0, exitCode); - } - } - - private ServiceStatusReport Pending(ServiceState state, uint waitHintMilliseconds, params ServiceState[] from) - { - lock (_gate) - { - Require(from); - _checkPoint = Current.State == state ? _checkPoint + 1 : 1; - return Current = new ServiceStatusReport(state, 0, _checkPoint, waitHintMilliseconds, 0); - } - } - - private void Require(params ServiceState[] allowed) - { - if (!allowed.Contains(Current.State)) throw new InvalidOperationException($"A service cannot go from {Current.State} to that state."); - } -} diff --git a/src/Chronos.Server/Hosting/Windows/WindowsServiceHost.cs b/src/Chronos.Server/Hosting/Windows/WindowsServiceHost.cs deleted file mode 100644 index 4da49b6e..00000000 --- a/src/Chronos.Server/Hosting/Windows/WindowsServiceHost.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using static Chronos.Server.Hosting.Windows.ServiceNative; - -namespace Chronos.Server.Hosting.Windows; - -/// -/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW, -/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running -/// jobs keep their checkpoints and resume at the next start. A failure to start or stop goes to the Application event -/// log (), since a service has no console. -/// -[SupportedOSPlatform("windows")] -public static class WindowsServiceHost -{ - public const string ServiceName = "ChronosServer"; - private const uint StartWaitHint = 60_000; - private const uint StopWaitHint = 35_000; - - private static readonly ServiceStatusTracker Status = new(); - private static Func? _build; - private static WebApplication? _app; - private static nint _statusHandle; - - /// - /// Hands the process to the Service Control Manager and returns when the service has stopped. False when the - /// process was not started by the SCM (for example from a console). - /// - public static unsafe bool Run(Func build) - { - _build = build; - fixed (char* name = ServiceName) - { - var table = stackalloc ServiceTableEntry[2]; - table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain }; - table[1] = default; - if (StartServiceCtrlDispatcherW(table)) return true; - } - var error = Marshal.GetLastPInvokeError(); - if (error == ErrorFailedServiceControllerConnect) return false; - throw new Win32Exception(error); - } - - [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] - private static unsafe void ServiceMain(uint argc, char** argv) - { - _statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0); - if (_statusHandle == 0) return; - Report(Status.StartPending(StartWaitHint)); - try - { - _app = _build!(); - _app.StartAsync().GetAwaiter().GetResult(); - Report(Status.Running()); - } - catch (Exception ex) - { - // A refused data folder or server.json says which entry to check; the SCM itself records only error 1064. - Console.Error.WriteLine(ex); - ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Chronos Server did not start:", ex)); - Report(Status.Stopped(ErrorExceptionInService)); - } - } - - [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] - private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context) - { - switch (control) - { - case ControlStop or ControlShutdown: - if (Status.Current.State is ServiceState.Running or ServiceState.StartPending) - { - Report(Status.StopPending(StopWaitHint)); - // The handler must return at once; the host stops on the thread pool. - _ = Task.Run(StopAsync); - } - return NoError; - case ControlInterrogate: - Report(Status.Current); - return NoError; - default: - return ErrorCallNotImplemented; - } - } - - private static async Task StopAsync() - { - uint exitCode = 0; - try - { - if (_app is { } app) - { - await app.StopAsync(); - await app.DisposeAsync(); - } - } - catch (Exception ex) - { - Console.Error.WriteLine(ex); - ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Chronos Server did not stop cleanly:", ex)); - exitCode = ErrorExceptionInService; - } - Report(Status.Stopped(exitCode)); - } - - private static unsafe void Report(ServiceStatusReport report) - { - var status = new ServiceStatus - { - ServiceType = ServiceWin32OwnProcess, - CurrentState = (uint)report.State, - ControlsAccepted = report.ControlsAccepted, - Win32ExitCode = report.ExitCode, - CheckPoint = report.CheckPoint, - WaitHint = report.WaitHintMilliseconds, - }; - SetServiceStatus(_statusHandle, &status); - } -} diff --git a/src/Chronos.Server/Jobs/JobEngineHost.cs b/src/Chronos.Server/Jobs/JobEngineHost.cs index e77f3fc1..5cbac8f6 100644 --- a/src/Chronos.Server/Jobs/JobEngineHost.cs +++ b/src/Chronos.Server/Jobs/JobEngineHost.cs @@ -16,21 +16,24 @@ namespace Chronos.Server.Jobs; /// running one, in the order of the priority queue of the settings (owner review 1). Render jobs run here only when the registered render /// handler accepts them (: managed formats, and MP4 jobs no render node can take); /// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. +/// When Chronos Desktop shares its library (owner review 5, #67) the engine is the desktop's own: this host relays it while the +/// server runs, never starts, stops or disposes it, and the jobs API shows only the kinds a server runs (): +/// the desktop's workspace, sync and download jobs stay its own. /// public sealed class JobEngineHost : IHostedService { private static readonly long ProgressInterval = Stopwatch.Frequency / 4; - private readonly ChronosDatabase _db; private readonly EventHub _events; private readonly HashSet _kinds; private readonly Dictionary _lastProgress = []; private readonly Lock _gate = new(); + private readonly bool _ownsEngine = true; + private int _subscribed; public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options, EventHub events) { - _db = db; _events = events; // A render handler must be selective: a plain one would take the jobs that need a render node's encoder. var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList(); @@ -42,8 +45,20 @@ public sealed class JobEngineHost : IHostedService Kinds = _kinds, PriorityQueue = () => ServerSettingsStore.PriorityQueue(options), }); - Engine.JobChanged += OnJobChanged; - Engine.Progress += OnProgress; + Subscribe(); + } + + /// + /// Relays , an engine Chronos Desktop runs (owner review 5, #67), from to + /// ; the engine stays the desktop's. + /// + public JobEngineHost(JobEngine engine, EventHub events) + { + ArgumentNullException.ThrowIfNull(engine); + _events = events; + _ownsEngine = false; + _kinds = []; + Engine = engine; } /// Node id stamped on jobs this server runs. @@ -51,15 +66,60 @@ public sealed class JobEngineHost : IHostedService public JobEngine Engine { get; } + /// The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67). + public bool Hosted => !_ownsEngine; + /// True when a job of has somewhere to run: a local handler, or render nodes for renders. - public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind); + public bool CanRun(JobKind kind) => kind == JobKind.Render || (_ownsEngine ? _kinds.Contains(kind) : Engine.CanRun(kind) && Exposes(kind)); - public Task StartAsync(CancellationToken cancellationToken) => Engine.StartAsync(cancellationToken); + /// + /// Whether the jobs API lists, shows and acts on jobs of : every kind on a server of its own; on a + /// shared desktop library only the kinds a server runs (), so a client never sees or + /// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67). + /// + public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind); - public async Task StopAsync(CancellationToken cancellationToken) => await Engine.DisposeAsync(); + public Task StartAsync(CancellationToken cancellationToken) + { + if (_ownsEngine) return Engine.StartAsync(cancellationToken); + Subscribe(); + return Task.CompletedTask; + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + if (_ownsEngine) + { + await Engine.DisposeAsync(); + return; + } + // The desktop's engine runs on: only this server stops following it. + if (Interlocked.Exchange(ref _subscribed, 0) == 1) + { + Engine.JobChanged -= OnJobChanged; + Engine.Progress -= OnProgress; + } + } + + private void Subscribe() + { + if (Interlocked.Exchange(ref _subscribed, 1) == 1) return; + Engine.JobChanged += OnJobChanged; + Engine.Progress += OnProgress; + } + + /// + /// A job's state changed outside the engine (render nodes, cancellation of node jobs): Chronos Desktop's Jobs section + /// follows these as it follows its engine's own changes while it shares its library (owner review 5, #67). + /// + public event Action? ChangedOutside; /// Publishes a state change made outside the engine (render nodes, cancellation of node jobs). - public void Publish(Job job) => OnJobChanged(job); + public void Publish(Job job) + { + OnJobChanged(job); + ChangedOutside?.Invoke(job); + } private void OnJobChanged(Job job) { diff --git a/src/Chronos.Server/Jobs/SchedulerHost.cs b/src/Chronos.Server/Jobs/SchedulerHost.cs index 8d8ae5e8..f5dd3a2e 100644 --- a/src/Chronos.Server/Jobs/SchedulerHost.cs +++ b/src/Chronos.Server/Jobs/SchedulerHost.cs @@ -19,7 +19,10 @@ namespace Chronos.Server.Jobs; /// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step: /// Settings › Logs shows it () and sets it (); /// is only what the schedule is seeded and reset with, or what an environment -/// variable fixes. Every schedule change and run goes out as a . +/// variable fixes. Every schedule change and run goes out as a . On the library Chronos +/// Desktop shares (owner review 5, #67) the scheduler is the desktop's, already running: this host follows it while the +/// server runs, adds the server's own system schedules to it () and never +/// starts, seeds the desktop's schedules for or disposes it. /// public sealed class SchedulerHost : IHostedService { @@ -29,6 +32,10 @@ public sealed class SchedulerHost : IHostedService private readonly CancellationTokenSource _stopping = new(); private Task _startScan = Task.CompletedTask; private Task _refresh = Task.CompletedTask; + private readonly bool _ownsScheduler = true; + private readonly Action _changed; + private readonly Action _deleted; + private readonly int _auditRetentionDays; private int _stopped; public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger logger) @@ -41,8 +48,31 @@ public sealed class SchedulerHost : IHostedService Host = host; Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time }); // The Scheduled tab of the admin panel follows them, the runs that queue no job included. - Scheduler.ScheduleChanged += schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false)); - Scheduler.ScheduleDeleted += id => events.Publish(new ScheduleChangedEvent(id, Deleted: true)); + _changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false)); + _deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true)); + Scheduler.ScheduleChanged += _changed; + Scheduler.ScheduleDeleted += _deleted; + } + + /// + /// Follows , the running scheduler of Chronos Desktop (owner review 5, #67), from + /// to . + /// + public SchedulerHost(ChronosDatabase db, Scheduler scheduler, ServerScheduleHost host, ServerOptions options, EventHub events, TimeProvider time, + ILogger logger) + { + ArgumentNullException.ThrowIfNull(scheduler); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(events); + _db = db; + _time = time; + _logger = logger; + _ownsScheduler = false; + _auditRetentionDays = options.AuditRetentionDays; + Host = host; + Scheduler = scheduler; + _changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false)); + _deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true)); } public Scheduler Scheduler { get; } @@ -51,10 +81,21 @@ public sealed class SchedulerHost : IHostedService public async Task StartAsync(CancellationToken cancellationToken) { - var started = Scheduler.Options.Time.GetUtcNow(); - await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken); var stopping = _stopping.Token; - _startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None); + if (!_ownsScheduler) + { + Scheduler.ScheduleChanged += _changed; + Scheduler.ScheduleDeleted += _deleted; + // The desktop seeds its own system schedules; the server's state brings two more (never overwritten once there). + if (await _db.Schedules.EnsureSystemAsync(ServerScheduleHost.ShareSchedules(_auditRetentionDays), _time.GetUtcNow(), cancellationToken) > 0) + Scheduler.Wake(); + } + else + { + var started = Scheduler.Options.Time.GetUtcNow(); + await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken); + _startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None); + } // Created here, so its first period counts from the start. var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time); _refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None); @@ -66,7 +107,16 @@ public sealed class SchedulerHost : IHostedService await _stopping.CancelAsync(); await _startScan; await _refresh; - await Scheduler.DisposeAsync(); + if (_ownsScheduler) + { + await Scheduler.DisposeAsync(); + } + else + { + // The desktop's scheduler runs on: only this server stops following it. + Scheduler.ScheduleChanged -= _changed; + Scheduler.ScheduleDeleted -= _deleted; + } _stopping.Dispose(); } diff --git a/src/Chronos.Server/Jobs/ServerScheduleHost.cs b/src/Chronos.Server/Jobs/ServerScheduleHost.cs index 0cffda9a..9a37aa86 100644 --- a/src/Chronos.Server/Jobs/ServerScheduleHost.cs +++ b/src/Chronos.Server/Jobs/ServerScheduleHost.cs @@ -66,13 +66,13 @@ public sealed class ServerScheduleHost : IScheduleHost { get { - var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0), Audit: new TimeOnly(4, 30)); + var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0)); + var share = ShareSchedules(_options.AuditRetentionDays); var list = new List { // A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start. new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false), - new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours), - new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])), + share[0], }; // PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once // when the newest copy is a day old, as the daily loop it replaced made one at start. @@ -83,13 +83,24 @@ public sealed class ServerScheduleHost : IScheduleHost } list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History), new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory]))); - var audit = _options.AuditRetentionDays; - list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit), - new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0)); + list.Add(share[1]); return list; } } + /// + /// The system schedules of a server's own state, which Chronos Desktop adds to its own while it shares its library + /// (owner review 5, #67), the archive scan, the index backup and the housekeeping being the desktop's: the uploads sweep + /// every hours and the audit log clean-up, nightly at 04:30, off at 0 days. + /// + public static IReadOnlyList ShareSchedules(int auditRetentionDays) => + [ + new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours), + new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])), + new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(new TimeOnly(4, 30)), + new ScheduleParametersDto(OlderThanDays: auditRetentionDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: auditRetentionDays > 0), + ]; + /// /// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as /// the former polling did; while it is offline, or the file cannot be read, as the index has it. diff --git a/src/Chronos.Server/Program.cs b/src/Chronos.Server/Program.cs deleted file mode 100644 index 7c19fafd..00000000 --- a/src/Chronos.Server/Program.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.ComponentModel; -using Chronos.Server.Configuration; -using Chronos.Server.Hosting; -using Chronos.Server.Hosting.Windows; -using Chronos.Server.Storage; - -var command = ServerCommandLine.Parse(args); -if (command.Error is not null) -{ - await Console.Error.WriteLineAsync(command.Error); - return 2; -} - -switch (command.Command) -{ - case ServerCommand.Help: - Console.WriteLine(ServerCommandLine.Usage); - return 0; - case ServerCommand.HealthCheck: - return await HealthProbe.RunAsync(); - case ServerCommand.Service or ServerCommand.InstallService or ServerCommand.UninstallService when !OperatingSystem.IsWindows(): - await Console.Error.WriteLineAsync("Windows services are available on Windows only."); - return 2; - case ServerCommand.InstallService when OperatingSystem.IsWindows(): - return ServiceAction(ServiceInstaller.Install, $"Installed the {WindowsServiceHost.ServiceName} service."); - case ServerCommand.UninstallService when OperatingSystem.IsWindows(): - return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service."); - case ServerCommand.Service when OperatingSystem.IsWindows(): - if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0; - await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start ChronosServer'."); - return 1; - default: - var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules); - await app.RunAsync(); - return 0; -} - -// The archive engine, then analysis and managed rendering over it. -static void RegisterModules(IServiceCollection services) -{ - ArchiveModule.Register(services); - ProcessingModule.Register(services); -} - -static int ServiceAction(Action action, string done) -{ - try - { - action(); - Console.WriteLine(done); - return 0; - } - catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) - { - // Win32: the Service Control Manager's reason; InvalidOperation: a folder the service must not run from. - Console.Error.WriteLine(ex.Message); - return 1; - } -} - -/// Entry point type, visible to the in-process test host. -public partial class Program; diff --git a/src/Chronos.Server/Security/AdminBootstrap.cs b/src/Chronos.Server/Security/AdminBootstrap.cs index bdb69966..3ddfe773 100644 --- a/src/Chronos.Server/Security/AdminBootstrap.cs +++ b/src/Chronos.Server/Security/AdminBootstrap.cs @@ -16,7 +16,8 @@ namespace Chronos.Server.Security; public static class AdminBootstrap { public const string DefaultUsername = "admin"; - private const string PasswordFileName = "initial-admin-password.txt"; + /// The file in the data folder that holds a generated temporary password until an administrator sets their own. + public const string PasswordFileName = "initial-admin-password.txt"; public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken) { diff --git a/src/Chronos.Server/Security/AuthenticationMiddleware.cs b/src/Chronos.Server/Security/AuthenticationMiddleware.cs index 322801dc..834c4585 100644 --- a/src/Chronos.Server/Security/AuthenticationMiddleware.cs +++ b/src/Chronos.Server/Security/AuthenticationMiddleware.cs @@ -6,12 +6,15 @@ namespace Chronos.Server.Security; /// /// Resolves the caller of every /api request (bearer token or admin cookie) and enforces the endpoint's /// : 401 without a valid token, 403 for a missing permission, a missing CSRF header on a -/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. +/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. Every request it +/// lets through is noted in (owner review 5, #67). /// public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens) { - public async Task InvokeAsync(HttpContext context) + public async Task InvokeAsync(HttpContext context, ClientActivity activity) { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(activity); var rule = context.GetEndpoint()?.Metadata.GetMetadata(); if (rule is null && !context.Request.Path.StartsWithSegments("/api")) { @@ -48,6 +51,8 @@ public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService return; } context.Features.Set(caller); + var address = context.Connection.RemoteIpAddress; + activity.Record(caller, (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString()); await next(context); } diff --git a/src/Chronos.Server/Security/ClientActivity.cs b/src/Chronos.Server/Security/ClientActivity.cs new file mode 100644 index 00000000..6994b414 --- /dev/null +++ b/src/Chronos.Server/Security/ClientActivity.cs @@ -0,0 +1,42 @@ +using System.Collections.Concurrent; + +namespace Chronos.Server.Security; + +/// A program that used the server lately: its account, its name (the token's client), its address and when. +public sealed record ClientSeen(string User, string Client, string Address, DateTimeOffset LastSeen); + +/// +/// The programs that used the server in the last (owner review 5, #67): Chronos Desktop shows them in +/// its Server section while it shares its library, and asks before it stops sharing while there are any. Kept in memory +/// only; records every signed-in request. +/// +public sealed class ClientActivity(TimeProvider time) +{ + /// How long a program counts as active after its last request. + public static TimeSpan Window { get; } = TimeSpan.FromMinutes(5); + + /// What a request signed in through the admin panel's cookie shows as its program. + public const string AdminPanel = "Admin panel"; + + private readonly ConcurrentDictionary<(Guid User, string Client, string Address), ClientSeen> _seen = new(); + + /// A signed-in request of from . + public void Record(Caller caller, string? address) + { + ArgumentNullException.ThrowIfNull(caller); + var client = caller.Source == CredentialSource.Cookie ? AdminPanel : string.IsNullOrWhiteSpace(caller.ClientName) ? "?" : caller.ClientName.Trim(); + var from = string.IsNullOrEmpty(address) ? "?" : address; + _seen[(caller.Id, client, from)] = new ClientSeen(caller.User.Username, client, from, time.GetUtcNow()); + } + + /// The programs seen in the last , the latest first; older entries are dropped. + public IReadOnlyList Recent() + { + var since = time.GetUtcNow() - Window; + foreach (var (key, seen) in _seen) + { + if (seen.LastSeen < since) _seen.TryRemove(new KeyValuePair<(Guid, string, string), ClientSeen>(key, seen)); + } + return [.. _seen.Values.Where(s => s.LastSeen >= since).OrderByDescending(s => s.LastSeen)]; + } +} diff --git a/src/Chronos.Server/Storage/ArchiveModule.cs b/src/Chronos.Server/Storage/ArchiveModule.cs index 7776227b..6aeddd69 100644 --- a/src/Chronos.Server/Storage/ArchiveModule.cs +++ b/src/Chronos.Server/Storage/ArchiveModule.cs @@ -23,8 +23,6 @@ namespace Chronos.Server.Storage; /// public static class ArchiveModule { - /// The change a conversion's Replace tells about a sequence (sequenceChanged). - private const string ConvertedChange = "converted"; /// Name the server writes into the archive's lease files. public static string Owner { get; } = "server@" + Environment.MachineName; @@ -40,24 +38,10 @@ public static class ArchiveModule // Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1). var service = new ArchiveService(db, new ArchiveServiceOptions { - // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3). - SequenceChanged = async (id, change, ct) => - { - 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()?.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)); - }, + // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3), and + // every change of a sequence's projects reaches them too (owner review 2, R8). + SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService(), id, change, ct), + ProjectsChanged = (changed, ct) => ServerEventBridge.ProjectsChangedAsync(db, events, changed, ct), Decoder = DecoderFactory.CreateServer(), // Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space // (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages diff --git a/src/Chronos.Server/Storage/ProcessingModule.cs b/src/Chronos.Server/Storage/ProcessingModule.cs index 5314e46b..e46f485e 100644 --- a/src/Chronos.Server/Storage/ProcessingModule.cs +++ b/src/Chronos.Server/Storage/ProcessingModule.cs @@ -45,13 +45,8 @@ public static class ProcessingModule Host = EncoderHost.Server, AwaitsRenderNode = sp.GetRequiredService().AwaitsNodeAsync, ProducedBy = options.ServerName, - SequenceChanged = async (id, change, ct) => - { - 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()?.Touch(id); - }, + // Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8). + SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService(), id, change, ct), }); }); services.AddSingleton(sp => sp.GetRequiredService()); diff --git a/src/Chronos.Server/Storage/ServerArchive.cs b/src/Chronos.Server/Storage/ServerArchive.cs index 8b48633a..e0cf658e 100644 --- a/src/Chronos.Server/Storage/ServerArchive.cs +++ b/src/Chronos.Server/Storage/ServerArchive.cs @@ -45,6 +45,12 @@ public sealed class ServerArchive(Archive archive) public Guid Id => _current.Id; + /// + /// Whether is one of this archive's (owner review 5, #67): an index may hold other archives, + /// whose items the API treats as unknown (). + /// + public bool Owns(Sequence? sequence) => sequence is not null && sequence.ArchiveId == Id; + public string Root => _current.RootPath; /// @@ -87,6 +93,18 @@ public sealed class ServerArchive(Archive archive) /// (and relinked if it moved), any other folder becomes a new archive with the default templates. Either way the /// folders of the archive's layout are made (). /// + /// + /// Serves , an archive Chronos Desktop already opened (owner review 5, #67): nothing is adopted, + /// the folders of its layout are made as at a server's start (). + /// + public static ServerArchive ForArchive(Archive archive) + { + ArgumentNullException.ThrowIfNull(archive); + var served = new ServerArchive(archive); + served.CheckStructure(); + return served; + } + public static async Task OpenAsync(ChronosDatabase db, ServerOptions options, CancellationToken cancellationToken) { var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath)); diff --git a/src/Chronos.Server/Storage/ServerEventBridge.cs b/src/Chronos.Server/Storage/ServerEventBridge.cs new file mode 100644 index 00000000..5715812b --- /dev/null +++ b/src/Chronos.Server/Storage/ServerEventBridge.cs @@ -0,0 +1,48 @@ +using Chronos.Data; +using Chronos.Data.Processing; +using Chronos.Data.Projects; +using Chronos.Protocol; +using Chronos.Server.Events; + +namespace Chronos.Server.Storage; + +/// +/// What the archive and processing engines tell about sequences and projects, as events for connected clients (BRIEF +/// §14.3; owner review 2, R8): the same on a server of its own (, ) +/// and on the library Chronos Desktop shares, whose engines are the desktop's (owner review 5, #67). +/// +public static class ServerEventBridge +{ + /// The change a conversion's Replace tells about a sequence (sequenceChanged). + public const string ConvertedChange = "converted"; + + /// + /// A Reorganize, a conversion, a render or an analysis changed or made sequence : clients are told + /// (sequenceChanged), and a conversion's or an analysis's settings become Main's next version soon. + /// + public static async Task SequenceChangedAsync(ChronosDatabase db, EventHub events, ProjectCatchUp? projects, Guid id, string change, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(events); + if (await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) is { } sequence) + events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); + // A conversion may leave settings Main has not taken yet, and an analysis writes Auto values (owner review 2, R8). + if (change is ConvertedChange or ProcessingOptions.SettingsChange) projects?.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). + /// + public static async Task ProjectsChangedAsync(ChronosDatabase db, EventHub events, ProjectChangeSet changed, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(events); + ArgumentNullException.ThrowIfNull(changed); + 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).ConfigureAwait(false) is { } sequence) + events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion)); + } +} diff --git a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs index 1e492f39..e67fb7a0 100644 --- a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs +++ b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs @@ -41,6 +41,27 @@ public sealed class ConnectFlowTests Assert.Contains(Fingerprint, server.Created[^1]); } + /// Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted. + [Test] + public async Task ThisPcsOwnSharedLibraryIsRefused() + { + var server = new FakeServer { SelfSigned = true }; + var trust = new MemoryTrust(); + using var flow = new ConnectFlow(server, trust) { IsOwnLibrary = (fingerprint, _) => fingerprint == Fingerprint }; + Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443")); + Assert.Equal(ConnectError.OwnLibrary, flow.Error); + Assert.Null(flow.PendingFingerprint); + Assert.Empty(trust.Fingerprints); + + trust.Trust("https://localhost:8443", Fingerprint); + Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443")); + Assert.Equal(ConnectError.OwnLibrary, flow.Error); + Assert.Equal(0, server.Logins); + + flow.IsOwnLibrary = (_, _) => false; + Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("localhost:8443")); + } + [Test] public async Task RejectingTheCertificateSendsNothing() { diff --git a/tests/Chronos.App.Tests/Server/LibraryShareTests.cs b/tests/Chronos.App.Tests/Server/LibraryShareTests.cs new file mode 100644 index 00000000..3bb06529 --- /dev/null +++ b/tests/Chronos.App.Tests/Server/LibraryShareTests.cs @@ -0,0 +1,192 @@ +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using Chronos.App.Infrastructure; +using Chronos.App.Jobs; +using Chronos.App.Server; +using Chronos.App.Tests.Uploader; +using Chronos.Core.Localization; +using Chronos.Data; +using Chronos.Data.Archiving; +using Chronos.Server.Jobs; +using Chronos.Testing; + +namespace Chronos.App.Tests.Server; + +/// Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts over its own index and engines. +[WindowsOnly] +[Serial] // the hosted server's logging and Kestrel share the process with the other tests' Log sink +[Timeout(180_000)] +public sealed class LibraryShareTests +{ + private sealed class NoDialogs : IAppDialogs + { + public string? PickFolder(string title, string? initialFolder = null) => null; + public string? PickJsonFile(string title) => null; + public bool Confirm(ConfirmRequest request) => false; + public bool SignIn(string server, string? username, Func> signIn) => false; + } + + [Test] + public void A10SettingsFileSharesNothingOnDockersPortsAndResetTurnsSharingOff() + { + var settings = Assert.NotNull(AppSettings.Parse("""{ "Language": "en" }""")); + Assert.False(settings.Share.Enabled); + Assert.Equal((8443, 8080, true), (settings.Share.HttpsPort, settings.Share.HttpPort, settings.Share.Discovery)); + Assert.Null(settings.Share.PublicHttpsPort); + + settings.Share.Enabled = true; + settings.Share.HttpsPort = 9443; + var copy = Assert.NotNull(AppSettings.Parse(settings.ToJson())); + Assert.True(copy.Share.Enabled); + Assert.Equal(9443, copy.Share.HttpsPort); + Assert.False(settings.ResetKeepingState().Share.Enabled); + Assert.Equal(8443, settings.ResetKeepingState().Share.HttpsPort); + } + + [Test] + public void TheSharedLibrarysCleanUpsAreScheduledOnlyWhileSharing() + { + var settings = new AppSettings(); + var host = new DesktopScheduleHost(settings, () => null, () => null); + Assert.False(host.SystemSchedules.Any(s => s.SystemKey == ServerScheduleHost.UploadCleanup)); + settings.Share.Enabled = true; + var keys = host.SystemSchedules.Select(s => s.SystemKey).ToList(); + Assert.Contains(ServerScheduleHost.UploadCleanup, keys); + Assert.Contains(ServerScheduleHost.AuditCleanup, keys); + Assert.Contains(DesktopScheduleHost.ArchiveScan, keys); + } + + [Test] + public void SharingStartsAfterTheSchedulesOnTheDesktopsEngineAndStopsFirst() + { + var environment = AppEnvironment.ForCapture(); + try + { + SingleThreadedContext.Run(async () => + { + var root = await ArchiveAsync(environment); + var (https, http) = (FreePort(), FreePort()); + var settings = Settings(root, https, http); + var services = new AppServices(environment, settings, () => { }, new NoDialogs()); + try + { + await services.OpenAsync(environment.DatabasePath); + Assert.True(await services.SchedulerReady, "the schedules started"); + await WaitAsync(services.Share, ShareState.On); + + var share = services.Share; + Assert.Equal((https, http), (share.HttpsPort, share.HttpPort)); + Assert.True(share.Addresses.Count > 0, "addresses"); + Assert.True(share.Addresses.All(a => a.StartsWith("https://", StringComparison.Ordinal) && a.EndsWith($":{https}", StringComparison.Ordinal)), + string.Join(", ", share.Addresses)); + var fingerprint = Assert.NotNull(share.Fingerprint); + Assert.True(share.IsOwn(fingerprint, null), "own by fingerprint"); + Assert.True(share.IsOwn(null, share.Server!.ServerId), "own by id"); + Assert.False(share.IsOwn("00:11", Guid.NewGuid()), "another server"); + Assert.NotNull(share.AdminPassword); + Assert.Same(services.Engine, share.Server.Services.GetService(typeof(JobEngineHost)) is JobEngineHost jobs ? jobs.Engine : null); + using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }) + { + using var health = await client.GetAsync($"http://127.0.0.1:{http}/health"); + Assert.Equal(HttpStatusCode.OK, health.StatusCode); + } + Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup)); + Assert.True(Directory.Exists(environment.ShareDirectory), "the share's folder"); + + // Stopped, the engine and the index run on; started again, the same certificate. + await share.StopAsync(); + Assert.Equal(ShareState.Off, share.State); + Assert.Null(share.Server); + Assert.NotNull(await services.Database.Archives.ListAsync()); + await share.RestartAsync(); + Assert.Equal(ShareState.On, share.State); + Assert.Equal(fingerprint, share.Fingerprint); + + // Sharing turned off in Settings stops it. + settings.Share.Enabled = false; + share.Apply(); + await WaitAsync(share, ShareState.Off); + } + finally + { + Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped"); + } + Assert.Null(services.Share.Server); + }); + } + finally + { + environment.DeleteCaptureData(); + } + } + + [Test] + public void APortInUseLeavesSharingNotStartedNamingThePort() + { + var environment = AppEnvironment.ForCapture(); + try + { + SingleThreadedContext.Run(async () => + { + var root = await ArchiveAsync(environment); + // Held as another server would (both address families, exclusively): Windows lets a second program share a port otherwise. + using var taken = new TcpListener(IPAddress.IPv6Any, 0) { ExclusiveAddressUse = true }; + taken.Server.DualMode = true; + taken.Start(); + var https = ((IPEndPoint)taken.LocalEndpoint).Port; + var services = new AppServices(environment, Settings(root, https, FreePort()), () => { }, new NoDialogs()); + try + { + await services.OpenAsync(environment.DatabasePath); + Assert.True(await services.SchedulerReady, "the schedules started"); + await WaitAsync(services.Share, ShareState.Failed); + Assert.Equal(Loc.L("Errors.Share.PortInUse", https), services.Share.Reason); + Assert.Null(services.Share.Server); + Assert.False(services.Share.IsOwn(null, null), "nothing shared"); + } + finally + { + Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped"); + } + }); + } + finally + { + environment.DeleteCaptureData(); + } + } + + private static AppSettings Settings(string root, int https, int http) => new() + { + Language = "en", + LastArchivePath = root, + Share = new ShareSettings { Enabled = true, HttpsPort = https, HttpPort = http, Discovery = false }, + }; + + private static async Task ArchiveAsync(AppEnvironment environment) + { + var root = Path.Combine(environment.DataDirectory, "archive"); + await using var setup = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db"))); + await new ArchiveService(setup).CreateAsync(root, "Shared"); + return root; + } + + private static int FreePort() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return ((IPEndPoint)listener.LocalEndpoint).Port; + } + + private static async Task WaitAsync(LibraryShare share, ShareState state) + { + var until = DateTime.UtcNow + TimeSpan.FromSeconds(60); + while (share.State != state) + { + Assert.True(DateTime.UtcNow < until, $"sharing is {share.State} ({share.Reason}), not {state}"); + await Task.Delay(50); + } + } +} diff --git a/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs new file mode 100644 index 00000000..4db81467 --- /dev/null +++ b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs @@ -0,0 +1,336 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Extensions.DependencyInjection; +using Chronos.Core.Diagnostics; +using Chronos.Core.Imaging.Decoders; +using Chronos.Core.Model; +using Chronos.Core.Video.Managed; +using Chronos.Data; +using Chronos.Data.Archiving; +using Chronos.Data.Jobs; +using Chronos.Data.Processing; +using Chronos.Data.Scheduling; +using Chronos.Protocol; +using Chronos.Server.Api; +using Chronos.Server.Configuration; +using Chronos.Server.Hosting; +using Chronos.Server.Jobs; +using Chronos.Server.Security; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Hosting; + +/// +/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job +/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes. +/// +[Category("server")] +[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own +public sealed class HostedServerTests(TestContext context) +{ + [Test] + public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts() + { + await using var desktop = await DesktopFixture.StartAsync(context); + Guid? firstId; + string? fingerprint; + await using (var shared = await desktop.ShareAsync()) + { + using var http = desktop.Client(shared); + using var health = await http.GetAsync("/health"); + Assert.Equal(HttpStatusCode.OK, health.StatusCode); + var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo)); + var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null); + Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint); + Assert.Equal(shared.ServerId, info.ServerId); + Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port"); + firstId = shared.ServerId; + fingerprint = shared.Fingerprint; + } + // A second start on the same folder and index: the same certificate, id and administrator. + await using var again = await desktop.ShareAsync(); + Assert.Equal(fingerprint, again.Fingerprint); + Assert.Equal(firstId, again.ServerId); + Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin)); + } + + [Test] + public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer() + { + await using var desktop = await DesktopFixture.StartAsync(context); + var sink = Log.Sink; + await using (var shared = await desktop.ShareAsync()) + { + Assert.Same(desktop.Engine, shared.Services.GetRequiredService().Engine); + Assert.True(shared.Services.GetRequiredService().Hosted, "hosted"); + using var admin = await desktop.AdminAsync(shared); + using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest); + Assert.Equal(HttpStatusCode.Accepted, created.StatusCode); + var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto)); + var done = await desktop.WaitAsync(job.Id); + Assert.Equal(JobState.Done, done.State); + Assert.Equal(DesktopFixture.WorkerId, done.NodeId); + Assert.Same(sink, Log.Sink); + } + // Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's. + Assert.Same(sink, Log.Sink); + var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after"); + Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State); + Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation)); + } + + [Test] + public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops() + { + await using var desktop = await DesktopFixture.StartAsync(context); + var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType().ToHashSet(); + await using var shared = await desktop.ShareAsync(); + var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType().ToHashSet(); + Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal)); + Assert.SequenceEqual([DesktopFixture.ScanKey], before); + } + + [Test] + public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs() + { + await using var desktop = await DesktopFixture.StartAsync(context); + var mine = await desktop.SequenceAsync(desktop.Archive); + var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation); + var theirs = await desktop.SequenceAsync(other); + var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace"); + await using var shared = await desktop.ShareAsync(); + using var admin = await desktop.AdminAsync(shared); + + using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode); + foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" }) + { + using var hidden = await admin.GetAsync(path); + Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path); + } + using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest)) + Assert.Equal(HttpStatusCode.NotFound, job.StatusCode); + + var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto)); + Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own"); + using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode); + using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode); + Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State); + } + + [Test] + public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder() + { + await using var desktop = await DesktopFixture.StartAsync(context); + Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable"); + try + { + var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" }); + Assert.Equal("Studio PC", options.ServerName); + Assert.True(options.Hosted, "hosted"); + Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked); + Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]); + Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime"); + Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel); + } + finally + { + Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null); + } + await using var shared = await desktop.ShareAsync(); + Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file"); + Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile); + Assert.NotNull(shared.AdminPassword()); + using var admin = await desktop.AdminAsync(shared); + Assert.Null(shared.AdminPassword()); + var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto)); + Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]); + } + + [Test] + public async Task ClientsAreKeptForFiveMinutes() + { + var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture)); + var activity = new ClientActivity(time); + var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() }; + activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20"); + activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21"); + var seen = activity.Recent(); + Assert.Count(2, seen); + Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client)); + Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client)); + time.Advance(TimeSpan.FromMinutes(6)); + Assert.Count(0, activity.Recent()); + } + + [Test] + public void ARenderNeverKeepsTheExportFolderAClientChose() + { + var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null); + var stripped = JobEndpoints.WithoutExportFolder(parameters); + Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson); + Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson); + var plain = parameters with { PresetJson = """{"preset":"1080p"}""" }; + Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain)); + } + + [Test] + public void TheServiceSwitchesAreGone() + { + var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]); + Assert.Equal(ServerCommand.Run, parsed.Command); + Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments); + Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service"); + } + + /// A clock the test moves. + private sealed class ManualTime(DateTimeOffset start) : TimeProvider + { + private DateTimeOffset _now = start; + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; + } +} + +/// +/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed +/// codecs), a started job engine and a started scheduler with one system schedule of its own. +/// +internal sealed class DesktopFixture : IAsyncDisposable +{ + public const string WorkerId = "STUDIO-PC"; + public const string ScanKey = "archive-scan"; + + private readonly TestContext _context; + + private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine, + Scheduler scheduler, Archive archive) + { + _context = context; + Root = root; + Database = db; + Archives = archives; + Processing = processing; + Engine = engine; + Scheduler = scheduler; + Archive = archive; + } + + public string Root { get; } + public ChronosDatabase Database { get; } + public ArchiveService Archives { get; } + public ProcessingService Processing { get; } + public JobEngine Engine { get; } + public Scheduler Scheduler { get; } + public Archive Archive { get; } + public string ShareData => Path.Combine(Root, "data", "server"); + + public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary(), "en", + LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4); + + public static async Task StartAsync(TestContext context) + { + var root = context.CreateTempDirectory("desktop"); + Directory.CreateDirectory(Path.Combine(root, "data")); + var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation); + var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 }; + var archives = new ArchiveService(db, archiveOptions); + var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] }); + var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation); + var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList(); + var engine = new JobEngine(db, handlers, new JobEngineOptions + { + WorkerId = WorkerId, + Kinds = [.. handlers.Select(h => h.Kind).Distinct()], + PollInterval = TimeSpan.FromMilliseconds(100), + }); + await engine.StartAsync(context.Cancellation); + var scheduler = new Scheduler(db, engine); + await scheduler.StartAsync(new Host(archives, archive), context.Cancellation); + return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive); + } + + public async Task ShareAsync() + { + var options = ServerOptions.ForHosted(ShareData, Settings); + options.LoginAttemptsPerMinute = 1000; + var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive)); + await server.StartAsync(_context.Cancellation); + return server; + } + + public HttpClient Client(HostedServer server, string? token = null) + { + var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) }; + if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + return client; + } + + /// The first administrator, signed in with its temporary password, which it then replaces. + public async Task AdminAsync(HostedServer server) + { + var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password"); + using var anonymous = Client(server); + using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest); + login.EnsureSuccessStatusCode(); + var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!; + var client = Client(server, token); + using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"), + ProtocolJson.Default.ChangePasswordRequest); + changed.EnsureSuccessStatusCode(); + return client; + } + + public async Task SequenceAsync(Archive archive) + { + var sequence = new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archive.Id, + Title = "Roof " + archive.Name, + Folder = string.Empty, + Origin = SequenceOrigin.Server, + UpdatedAt = DateTimeOffset.UtcNow, + }; + await Database.Sequences.UpsertAsync(sequence, _context.Cancellation); + return sequence; + } + + public async Task WaitAsync(Guid id) + { + var until = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job; + Assert.True(DateTime.UtcNow < until, "the job did not finish"); + await Task.Delay(50, _context.Cancellation); + } + } + + public async ValueTask DisposeAsync() + { + await Scheduler.DisposeAsync(); + await Engine.DisposeAsync(); + await Database.DisposeAsync(); + } + + /// A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps. + private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost + { + public TimeZoneInfo TimeZone => TimeZoneInfo.Utc; + + public IReadOnlyList SystemSchedules => + [new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)]; + + public IReadOnlyList CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)]; + + public bool DeepAnalysisAfterScan => false; + + public ValueTask GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult(archive); + + public string? Unavailable(string action) => null; + } +} diff --git a/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs b/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs deleted file mode 100644 index 32771694..00000000 --- a/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System.Diagnostics.Eventing.Reader; -using System.Security.AccessControl; -using System.Security.Principal; -using Chronos.Server.Hosting; -using Chronos.Server.Hosting.Windows; -using Chronos.Testing; - -namespace Chronos.Server.Tests.Hosting; - -public sealed class WindowsServiceTests(TestContext context) -{ - [Test] - public void CommandSwitchesAreParsedAndTheRestPassedOn() - { - Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command); - var service = ServerCommandLine.Parse(["--service", "--urls", "x"]); - Assert.Equal(ServerCommand.Service, service.Command); - Assert.SequenceEqual(["--urls", "x"], service.HostArguments); - Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command); - Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command); - Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command); - Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command); - Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error); - Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error); - } - - [Test] - public void StatusReportsFollowTheServiceControlManagerRules() - { - var tracker = new ServiceStatusTracker(); - var start = tracker.StartPending(60_000); - Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds)); - Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint); - var running = tracker.Running(); - Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint)); - Assert.Throws(() => tracker.Running()); - Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint); - Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint); - var stopped = tracker.Stopped(0); - Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint)); - Assert.Throws(() => tracker.StopPending(1)); - Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode); - } - - [Test] - public void AServiceFailureLeadsWithTheReasonTheServerGave() - { - var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as."); - var text = ServiceEventLog.Describe("Chronos Server did not start:", refused); - Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text); - Assert.Contains("System.InvalidOperationException", text); - - // ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair. - var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength))); - Assert.Equal(ServiceEventLog.MaxLength, cut.Length); - Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]); - var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99))); - Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length); - Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]); - } - - [Test] - [WindowsOnly] - public void AServiceFailureReachesTheApplicationEventLog() - { - if (!OperatingSystem.IsWindows()) return; - // Written as a source of its own, so a test run never looks like a failed service in Event Viewer. - const string source = "Chronos.Server.Tests"; - var marker = source + " " + Guid.NewGuid().ToString("N"); - Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event"); - var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]"; - var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true }; - for (var attempt = 0; attempt < 50; attempt++) - { - using (var reader = new EventLogReader(query)) - { - for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++) - { - using (record) - { - // The event's one string, which Event Viewer shows whole. - if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue; - Assert.Equal((byte?)2, record.Level, "an error"); - return; - } - } - } - Thread.Sleep(100); - } - Assert.Fail($"No {source} event carries '{marker}'."); - } - - [Test] - [WindowsOnly] - public void TheServiceIsRegisteredOnlyFromInsideProgramFiles() - { - if (!OperatingSystem.IsWindows()) return; - var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe"))); - Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles)); - Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos")); - Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos"))); - Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos"))); - // The test build is not under Program Files: registering it is refused, naming the folder. - Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation())); - } - - [Test] - [WindowsOnly] - public void AnyFileOrdinaryUsersCanChangeIsFound() - { - if (!OperatingSystem.IsWindows()) return; - using var identity = WindowsIdentity.GetCurrent(); - if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator"); - var folder = new DirectoryInfo(context.CreateTempDirectory("program")); - File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]); - var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll")); - File.WriteAllBytes(satellite.FullName, [1]); - - // Like Program Files: administrators may change the folder, users only read it. - var locked = new DirectorySecurity(); - locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); - var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; - foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! }) - locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow)); - locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything, - PropagationFlags.None, AccessControlType.Allow)); - folder.SetAccessControl(locked); - Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true)); - - // One satellite assembly users may replace is enough: the service would load it as SYSTEM. - var open = satellite.GetAccessControl(); - open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow)); - satellite.SetAccessControl(open); - Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true)); - Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false)); - } - - [Test] - [WindowsOnly] - public void TheDispatcherDeclinesAConsoleProcess() - { - if (!OperatingSystem.IsWindows()) return; - var built = false; - Assert.False(WindowsServiceHost.Run(() => - { - built = true; - throw new InvalidOperationException("never built outside the SCM"); - })); - Assert.False(built); - } -}