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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 14:55:50 +01:00
1 parent 9ad8c6f7a9
commit 8d41992d84
69 files changed
+2633 -859

No files matched your search

+1
View File
@@ -5,6 +5,7 @@
<Project Path="src/Chronos.Data/Chronos.Data.csproj" />
<Project Path="src/Chronos.Protocol/Chronos.Protocol.csproj" />
<Project Path="src/Chronos.Server/Chronos.Server.csproj" />
<Project Path="src/Chronos.Server.Host/Chronos.Server.Host.csproj" />
<Project Path="src/Chronos.Ui/Chronos.Ui.csproj" />
<Project Path="src/Chronos.App/Chronos.App.csproj" />
<Project Path="src/Chronos.Uploader/Chronos.Uploader.csproj" />
+3 -2
View File
@@ -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"]
+3 -3
View File
@@ -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 "$@"
+1
View File
@@ -869,6 +869,7 @@
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Warning</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limits and retention</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Set by the environment variable {0}; remove the variable to change it here</value></data>
<data name="Admin.Settings.LockedByDesktop.Tip" xml:space="preserve"><value>Set in Chronos Desktop; change it in Settings on the PC that shares this library</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>File level</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Least severe level written to the log files; Debug and Trace help find problems but fill the files fast</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>File size (MB)</value></data>
+4
View File
@@ -29,6 +29,10 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>The sequence to render is no longer in the archive.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Enter a server address such as nas.local:8443 or https://chronos.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>This file does not contain Chronos settings.</value></data>
<data name="Errors.Share.Failed" xml:space="preserve"><value>Sharing could not start: {0}</value></data>
<data name="Errors.Share.NoArchive" xml:space="preserve"><value>Open or create an archive before sharing it.</value></data>
<data name="Errors.Share.NotReady" xml:space="preserve"><value>The library is not open yet; sharing starts once it is.</value></data>
<data name="Errors.Share.PortInUse" xml:space="preserve"><value>Port {0} is used by another program. Choose another one in Settings › Server.</value></data>
<data name="Errors.Sync.ChangedAgain" xml:space="preserve"><value>This PC or the server changed the sequence again; compare and choose again.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>The disk needs {0} GB more for this download.</value><comment>{0} gigabytes missing</comment></data>
<data name="Errors.Sync.ExportsGone.one" xml:space="preserve"><value>{0} render is no longer on this PC; the others were sent.</value><comment>{0} count</comment></data>
+24
View File
@@ -85,6 +85,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
<data name="Server.Error.NotChronos" xml:space="preserve"><value>That address is not a Chronos Server.</value><comment>long</comment></data>
<data name="Server.Error.NothingToConvert" xml:space="preserve"><value>The plan converts nothing: every photo is skipped or every sequence is blocked.</value><comment>long</comment></data>
<data name="Server.Error.OwnLibrary" xml:space="preserve"><value>This address is this PC's own shared library, already open here.</value><comment>long</comment></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>The photo was deleted from the sequence while it was being uploaded, so it was not added.</value><comment>long</comment></data>
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>{0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.</value><comment>long</comment></data>
@@ -134,6 +135,7 @@
<data name="Server.Label.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Label.Status" xml:space="preserve"><value>Status</value></data>
<data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data>
<data name="Server.Log.SharingOff" xml:space="preserve"><value>Sharing off: nothing swept.</value><comment>long</comment></data>
<data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Uploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}</value><comment>long: job log line</comment></data>
<data name="Server.Login.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -197,6 +199,28 @@
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Trail length</value></data>
<data name="Server.Setting.Transitions" xml:space="preserve"><value>Transitions</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>WB smoothing</value></data>
<data name="Server.Share.Addresses" xml:space="preserve"><value>Addresses</value></data>
<data name="Server.Share.AdminPanel" xml:space="preserve"><value>Admin panel</value></data>
<data name="Server.Share.AdminPassword" xml:space="preserve"><value>Admin password</value></data>
<data name="Server.Share.ClientCount.one" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientCount.other" xml:space="preserve"><value>{0} clients</value></data>
<data name="Server.Share.ClientRow" xml:space="preserve"><value>{0} · {1} · {2}</value></data>
<data name="Server.Share.Clients" xml:space="preserve"><value>Clients</value></data>
<data name="Server.Share.Copy" xml:space="preserve"><value>Copy</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Fingerprint</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Hide</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>None</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Ports</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
<data name="Server.Share.RenderNode" xml:space="preserve"><value>Render node</value></data>
<data name="Server.Share.Restart" xml:space="preserve"><value>Restart</value></data>
<data name="Server.Share.Settings" xml:space="preserve"><value>Sharing settings</value></data>
<data name="Server.Share.Show" xml:space="preserve"><value>Show</value></data>
<data name="Server.Share.State.Failed" xml:space="preserve"><value>Not started</value></data>
<data name="Server.Share.State.Off" xml:space="preserve"><value>Not shared</value></data>
<data name="Server.Share.State.On" xml:space="preserve"><value>Sharing</value></data>
<data name="Server.Share.State.Starting" xml:space="preserve"><value>Starting…</value></data>
<data name="Server.Share.Title" xml:space="preserve"><value>This library</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Sign out</value></data>
<data name="Server.Status.Connected" xml:space="preserve"><value>Connected</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connecting…</value></data>
+10
View File
@@ -178,17 +178,27 @@
<data name="Settings.Rendering.Testing" xml:space="preserve"><value>testing…</value></data>
<data name="Settings.ResetSection" xml:space="preserve"><value>Reset section</value></data>
<data name="Settings.Search" xml:space="preserve"><value>Search settings</value></data>
<data name="Settings.Server.Announce" xml:space="preserve"><value>Announce on LAN</value></data>
<data name="Settings.Server.Cache" xml:space="preserve"><value>Server cache</value></data>
<data name="Settings.Server.Certificates" xml:space="preserve"><value>Trusted certificates</value></data>
<data name="Settings.Server.Default" xml:space="preserve"><value>Default server</value></data>
<data name="Settings.Server.Discovery" xml:space="preserve"><value>LAN discovery</value></data>
<data name="Settings.Server.ForgetName" xml:space="preserve"><value>Forget: {0}</value></data>
<data name="Settings.Server.HttpPort" xml:space="preserve"><value>HTTP port</value></data>
<data name="Settings.Server.HttpsPort" xml:space="preserve"><value>HTTPS port</value></data>
<data name="Settings.Server.Known" xml:space="preserve"><value>Known servers</value></data>
<data name="Settings.Server.NoCertificates" xml:space="preserve"><value>None</value></data>
<data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offer this PC</value></data>
<data name="Settings.Server.Offline" xml:space="preserve"><value>Offline</value></data>
<data name="Settings.Server.Originals" xml:space="preserve"><value>Originals folder</value></data>
<data name="Settings.Server.PublicHttpPort" xml:space="preserve"><value>Public HTTP port</value></data>
<data name="Settings.Server.PublicHttpsPort" xml:space="preserve"><value>Public HTTPS port</value></data>
<data name="Settings.Server.RenderNode" xml:space="preserve"><value>Render node</value></data>
<data name="Settings.Server.ServerId" xml:space="preserve"><value>Server ID</value></data>
<data name="Settings.Server.Share" xml:space="preserve"><value>Sharing</value></data>
<data name="Settings.Server.ShareFolder" xml:space="preserve"><value>Server data</value></data>
<data name="Settings.Server.ShareLibrary" xml:space="preserve"><value>Share this library</value></data>
<data name="Settings.Server.ShareName" xml:space="preserve"><value>Library name</value></data>
<data name="Settings.Server.SignedIn" xml:space="preserve"><value>Signed in</value></data>
<data name="Settings.Storage.Clear" xml:space="preserve"><value>Clear</value></data>
<data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.</value><comment>long</comment></data>
+21 -1
View File
@@ -706,6 +706,18 @@
<data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Editors import, edit and render; only admins manage users</value></data>
<data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>Uploaders send photos; editing needs an editor</value></data>
<data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>Viewers browse and download</value></data>
<data name="Tooltips.Server.Share.AdminPanel" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Server.Share.AdminPassword" xml:space="preserve"><value>Temporary password of the account admin; change it at the first sign-in, then this row goes</value></data>
<data name="Tooltips.Server.Share.Clients" xml:space="preserve"><value>Programs that used this library in the last 5 minutes, and the render nodes online</value></data>
<data name="Tooltips.Server.Share.Copy" xml:space="preserve"><value>Copy this address for the Uploader or another Chronos</value></data>
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copy the fingerprint</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copy the temporary password</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>Clients see this fingerprint the first time they connect; it must match</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>The ports the shared library listens on</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Try to start sharing again</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Open Settings › Server to share this library</value></data>
<data name="Tooltips.Server.Share.Show" xml:space="preserve"><value>Show or hide the password</value></data>
<data name="Tooltips.Server.Share.State" xml:space="preserve"><value>Whether other PCs and the Uploader can use this PC's library now</value></data>
<data name="Tooltips.Server.SignIn" xml:space="preserve"><value>Sign in; the token is stored encrypted for this Windows user · Enter</value></data>
<data name="Tooltips.Server.SignOut" xml:space="preserve"><value>Sign out; the token is removed from this PC</value></data>
<data name="Tooltips.Server.Status" xml:space="preserve"><value>Connection to the server</value></data>
@@ -778,10 +790,13 @@
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server Chronos connects to at start; changing it signs out · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>How much of the end of each log file the diagnostics bundle includes</value></data>
<data name="Tooltips.Settings.Discovery" xml:space="preserve"><value>Announce this library to Chronos programs on the local network</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Save every setting as JSON, without the session token</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.HttpPort" xml:space="preserve"><value>Port the shared library listens on for HTTP (8080 by default); a change restarts sharing · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.HttpsPort" xml:space="preserve"><value>Port the shared library listens on for HTTPS (8443 by default); a change restarts sharing · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Import" xml:space="preserve"><value>Load settings from a JSON file; the session and the window layout stay as they are</value></data>
<data name="Tooltips.Settings.Install" xml:space="preserve"><value>Open the Microsoft Store page of this free or paid extension; Re-detect after installing it</value></data>
<data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>While Chronos is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses</value></data>
@@ -804,7 +819,9 @@
<data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Without this extension some formats are read only from their embedded preview, or not at all, on this PC</value></data>
<data name="Tooltips.Settings.Night" xml:space="preserve"><value>Frames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Open the data folder in Explorer</value></data>
<data name="Tooltips.Settings.OpenShareFolder" xml:space="preserve"><value>Open the shared library's data folder in Explorer</value></data>
<data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Show the workspace folder in Explorer</value></data>
<data name="Tooltips.Settings.PublicPorts" xml:space="preserve"><value>Port clients reach when a router forwards another port to this PC; empty: the one above · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Server.Cache" xml:space="preserve"><value>This server's proxies, render-node files and staged imports, inside the cache folder</value></data>
<data name="Tooltips.Settings.Server.Known" xml:space="preserve"><value>Servers this PC has signed in to, with the folders kept for each</value></data>
<data name="Tooltips.Settings.Server.Offline" xml:space="preserve"><value>Not signed in: its projects open from the workspace and wait to sync</value></data>
@@ -822,7 +839,7 @@
<data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Session rules, verification, duplicates, after-import actions</value></data>
<data name="Tooltips.Settings.OsNotifications" xml:space="preserve"><value>While Chronos is minimised or in the background, inserted cards, finished jobs and server messages also appear as Windows notifications</value></data>
<data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Quality profile, memory budget, parallelism, encoders</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Default server, render node, trusted certificates</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Sharing, default server, render node, trusted certificates</value></data>
<data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cache folder, thumbnails in memory, cache limit</value></data>
<data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Update check on start</value></data>
<data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Where projects are edited on this PC: the folder, sync and versions kept</value></data>
@@ -851,6 +868,9 @@
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Find a setting by name</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Speed on the synthetic 1280×720 test clip</value></data>
<data name="Tooltips.Settings.ShareFolder" xml:space="preserve"><value>Certificate, server settings, partial uploads and logs of the shared library; its accounts are in the index and its backups</value></data>
<data name="Tooltips.Settings.ShareLibrary" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.ShareName" xml:space="preserve"><value>The name clients see on sign-in and in LAN discovery; empty: this PC's name · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Always the Microsoft software H.264 encoder; slower, identical everywhere</value></data>
<data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Remember the folder and leave it as it is</value></data>
<data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stars per megapixel from which a night frame counts as a star field · Enter applies, Esc reverts</value></data>
+1
View File
@@ -862,6 +862,7 @@
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Avviso</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limiti e conservazione</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Impostato dalla variabile d'ambiente {0}; rimuovi la variabile per cambiarlo qui</value></data>
<data name="Admin.Settings.LockedByDesktop.Tip" xml:space="preserve"><value>Impostato in Chronos Desktop; cambialo nelle Impostazioni del PC che condivide questa libreria</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>Livello file</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>Dimensione file (MB)</value></data>
+4
View File
@@ -29,6 +29,10 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>La sequenza da renderizzare non è più nell'archivio.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://chronos.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>Questo file non contiene impostazioni di Chronos.</value></data>
<data name="Errors.Share.Failed" xml:space="preserve"><value>Impossibile avviare la condivisione: {0}</value></data>
<data name="Errors.Share.NoArchive" xml:space="preserve"><value>Apri o crea un archivio prima di condividerlo.</value></data>
<data name="Errors.Share.NotReady" xml:space="preserve"><value>La libreria non è ancora aperta; la condivisione parte appena lo è.</value></data>
<data name="Errors.Share.PortInUse" xml:space="preserve"><value>La porta {0} è usata da un altro programma. Scegline un'altra in Impostazioni › Server.</value></data>
<data name="Errors.Sync.ChangedAgain" xml:space="preserve"><value>La sequenza è cambiata di nuovo su questo PC o sul server; confronta e scegli di nuovo.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>Al disco servono altri {0} GB per questo scaricamento.</value></data>
<data name="Errors.Sync.ExportsGone.one" xml:space="preserve"><value>{0} render non è più su questo PC; gli altri sono stati inviati.</value></data>
+24
View File
@@ -83,6 +83,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
<data name="Server.Error.NotChronos" xml:space="preserve"><value>Questo indirizzo non è un Chronos Server.</value></data>
<data name="Server.Error.NothingToConvert" xml:space="preserve"><value>Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata.</value></data>
<data name="Server.Error.OwnLibrary" xml:space="preserve"><value>Questo indirizzo è la libreria condivisa di questo PC, già aperta qui.</value><comment>long</comment></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.</value><comment>long</comment></data>
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova.</value></data>
@@ -132,6 +133,7 @@
<data name="Server.Label.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Label.Status" xml:space="preserve"><value>Stato</value></data>
<data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data>
<data name="Server.Log.SharingOff" xml:space="preserve"><value>Condivisione spenta: nulla da ripulire.</value><comment>long</comment></data>
<data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Caricamenti scaduti: {0}, file rimossi: {1}, record rimossi: {2}, token rimossi: {3}</value><comment>long: job log line</comment></data>
<data name="Server.Login.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -195,6 +197,28 @@
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Lunghezza scie</value></data>
<data name="Server.Setting.Transitions" xml:space="preserve"><value>Transizioni</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>Livellamento WB</value></data>
<data name="Server.Share.Addresses" xml:space="preserve"><value>Indirizzi</value></data>
<data name="Server.Share.AdminPanel" xml:space="preserve"><value>Pannello admin</value></data>
<data name="Server.Share.AdminPassword" xml:space="preserve"><value>Password admin</value></data>
<data name="Server.Share.ClientCount.one" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientCount.other" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientRow" xml:space="preserve"><value>{0} · {1} · {2}</value></data>
<data name="Server.Share.Clients" xml:space="preserve"><value>Client</value></data>
<data name="Server.Share.Copy" xml:space="preserve"><value>Copia</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Impronta</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Nascondi</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>Nessuno</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Porte</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
<data name="Server.Share.RenderNode" xml:space="preserve"><value>Nodo di rendering</value></data>
<data name="Server.Share.Restart" xml:space="preserve"><value>Riavvia</value></data>
<data name="Server.Share.Settings" xml:space="preserve"><value>Impostazioni condivisione</value></data>
<data name="Server.Share.Show" xml:space="preserve"><value>Mostra</value></data>
<data name="Server.Share.State.Failed" xml:space="preserve"><value>Non avviata</value></data>
<data name="Server.Share.State.Off" xml:space="preserve"><value>Non condivisa</value></data>
<data name="Server.Share.State.On" xml:space="preserve"><value>In condivisione</value></data>
<data name="Server.Share.State.Starting" xml:space="preserve"><value>Avvio…</value></data>
<data name="Server.Share.Title" xml:space="preserve"><value>Questa libreria</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Esci</value></data>
<data name="Server.Status.Connected" xml:space="preserve"><value>Connesso</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connessione…</value></data>
+10
View File
@@ -175,17 +175,27 @@
<data name="Settings.Rendering.Testing" xml:space="preserve"><value>in prova…</value></data>
<data name="Settings.ResetSection" xml:space="preserve"><value>Ripristina sezione</value></data>
<data name="Settings.Search" xml:space="preserve"><value>Cerca impostazioni</value></data>
<data name="Settings.Server.Announce" xml:space="preserve"><value>Annuncia in LAN</value></data>
<data name="Settings.Server.Cache" xml:space="preserve"><value>Cache del server</value></data>
<data name="Settings.Server.Certificates" xml:space="preserve"><value>Certificati attendibili</value></data>
<data name="Settings.Server.Default" xml:space="preserve"><value>Server predefinito</value></data>
<data name="Settings.Server.Discovery" xml:space="preserve"><value>Rilevamento LAN</value></data>
<data name="Settings.Server.ForgetName" xml:space="preserve"><value>Dimentica: {0}</value></data>
<data name="Settings.Server.HttpPort" xml:space="preserve"><value>Porta HTTP</value></data>
<data name="Settings.Server.HttpsPort" xml:space="preserve"><value>Porta HTTPS</value></data>
<data name="Settings.Server.Known" xml:space="preserve"><value>Server noti</value></data>
<data name="Settings.Server.NoCertificates" xml:space="preserve"><value>Nessuno</value></data>
<data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offri questo PC</value></data>
<data name="Settings.Server.Offline" xml:space="preserve"><value>Non in linea</value></data>
<data name="Settings.Server.Originals" xml:space="preserve"><value>Cartella originali</value></data>
<data name="Settings.Server.PublicHttpPort" xml:space="preserve"><value>Porta HTTP pubblica</value></data>
<data name="Settings.Server.PublicHttpsPort" xml:space="preserve"><value>Porta HTTPS pubblica</value></data>
<data name="Settings.Server.RenderNode" xml:space="preserve"><value>Nodo di rendering</value></data>
<data name="Settings.Server.ServerId" xml:space="preserve"><value>ID server</value></data>
<data name="Settings.Server.Share" xml:space="preserve"><value>Condivisione</value></data>
<data name="Settings.Server.ShareFolder" xml:space="preserve"><value>Dati server</value></data>
<data name="Settings.Server.ShareLibrary" xml:space="preserve"><value>Condividi questa libreria</value></data>
<data name="Settings.Server.ShareName" xml:space="preserve"><value>Nome libreria</value></data>
<data name="Settings.Server.SignedIn" xml:space="preserve"><value>Connesso</value></data>
<data name="Settings.Storage.Clear" xml:space="preserve"><value>Svuota</value></data>
<data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.</value></data>
+21 -1
View File
@@ -777,6 +777,18 @@
<data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti</value></data>
<data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>I caricatori inviano foto; per modificare serve un editor</value></data>
<data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>I visualizzatori sfogliano e scaricano</value></data>
<data name="Tooltips.Server.Share.AdminPanel" xml:space="preserve"><value>Apri il pannello admin nel browser per gestire gli account; il browser avvisa una volta del certificato autofirmato: confronta l'impronta con quella qui</value></data>
<data name="Tooltips.Server.Share.AdminPassword" xml:space="preserve"><value>Password temporanea dell'account admin; cambiala al primo accesso, poi questa riga sparisce</value></data>
<data name="Tooltips.Server.Share.Clients" xml:space="preserve"><value>Programmi che hanno usato questa libreria negli ultimi 5 minuti, e i nodi di rendering online</value></data>
<data name="Tooltips.Server.Share.Copy" xml:space="preserve"><value>Copia questo indirizzo per l'Uploader o un altro Chronos</value></data>
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copia l'impronta</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copia la password temporanea</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>I client vedono questa impronta la prima volta che si connettono; deve coincidere</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>Le porte su cui ascolta la libreria condivisa</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Riprova ad avviare la condivisione</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Apri Impostazioni › Server per condividere questa libreria</value></data>
<data name="Tooltips.Server.Share.Show" xml:space="preserve"><value>Mostra o nascondi la password</value></data>
<data name="Tooltips.Server.Share.State" xml:space="preserve"><value>Se altri PC e l'Uploader possono usare ora la libreria di questo PC</value></data>
<data name="Tooltips.Server.SignIn" xml:space="preserve"><value>Accedi; il token viene salvato cifrato per questo utente di Windows · Invio</value></data>
<data name="Tooltips.Server.SignOut" xml:space="preserve"><value>Esci; il token viene rimosso da questo PC</value></data>
<data name="Tooltips.Server.Status" xml:space="preserve"><value>Connessione al server</value></data>
@@ -849,10 +861,13 @@
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>Quanta parte finale di ogni file di log include il pacchetto di diagnostica</value></data>
<data name="Tooltips.Settings.Discovery" xml:space="preserve"><value>Annuncia questa libreria ai programmi Chronos della rete locale</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Salva tutte le impostazioni in JSON, senza il token di sessione</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.HttpPort" xml:space="preserve"><value>Porta su cui la libreria condivisa ascolta in HTTP (8080 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.HttpsPort" xml:space="preserve"><value>Porta su cui la libreria condivisa ascolta in HTTPS (8443 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Import" xml:space="preserve"><value>Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate</value></data>
<data name="Tooltips.Settings.Install" xml:space="preserve"><value>Apri la pagina del Microsoft Store di questa estensione, gratuita o a pagamento; dopo averla installata premi Rileva di nuovo</value></data>
<data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>Mentre Chronos è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi</value></data>
@@ -875,7 +890,9 @@
<data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Senza questa estensione alcuni formati si leggono solo dall'anteprima incorporata, o per niente, su questo PC</value></data>
<data name="Tooltips.Settings.Night" xml:space="preserve"><value>I fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Apri la cartella dati in Esplora file</value></data>
<data name="Tooltips.Settings.OpenShareFolder" xml:space="preserve"><value>Apri in Esplora risorse la cartella dati della libreria condivisa</value></data>
<data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Mostra la cartella dello spazio di lavoro in Esplora file</value></data>
<data name="Tooltips.Settings.PublicPorts" xml:space="preserve"><value>Porta che i client raggiungono quando un router inoltra un'altra porta a questo PC; vuoto: quella sopra · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Server.Cache" xml:space="preserve"><value>Proxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cache</value></data>
<data name="Tooltips.Settings.Server.Known" xml:space="preserve"><value>I server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascuno</value></data>
<data name="Tooltips.Settings.Server.Offline" xml:space="preserve"><value>Accesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione</value></data>
@@ -893,7 +910,7 @@
<data name="Tooltips.Settings.Page.General" xml:space="preserve"><value>Lingua, tema, avvio, notifiche</value></data>
<data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Regole delle sessioni, verifica, duplicati, azioni dopo l'importazione</value></data>
<data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Profilo di qualità, memoria, parallelismo, encoder</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Server predefinito, nodo di rendering, certificati attendibili</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Condivisione, server predefinito, nodo di rendering, certificati attendibili</value></data>
<data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cartella della cache, miniature in memoria, limite della cache</value></data>
<data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Controllo degli aggiornamenti all'avvio</value></data>
<data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Dove si modificano i progetti su questo PC: cartella, sincronizzazione e versioni tenute</value></data>
@@ -922,6 +939,9 @@
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Trova un'impostazione per nome</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Velocità sulla clip di prova sintetica 1280×720</value></data>
<data name="Tooltips.Settings.ShareFolder" xml:space="preserve"><value>Certificato, impostazioni del server, upload parziali e log della libreria condivisa; i suoi account sono nell'indice e nei suoi backup</value></data>
<data name="Tooltips.Settings.ShareLibrary" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Settings.ShareName" xml:space="preserve"><value>Il nome che i client vedono all'accesso e nel rilevamento LAN; vuoto: il nome di questo PC · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque</value></data>
<data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Ricorda la cartella e lasciala com'è</value></data>
<data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stelle per megapixel da cui un fotogramma notturno conta come campo stellare · Invio applica, Esc annulla</value></data>
+5
View File
@@ -13,8 +13,13 @@
<ProjectReference Include="..\Chronos.Core.Windows\Chronos.Core.Windows.csproj" />
<ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" />
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
<ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Share this library hosts the server in-process (owner review 5, #67): ASP.NET Core is a shared framework, no package. -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Chronos.App.Tests" />
</ItemGroup>
+30
View File
@@ -69,6 +69,36 @@ public sealed class SampleData
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
public Guid ProxiedSequenceId => _sunrise;
/// <summary>The certificate fingerprint of this PC's shared library in the captures.</summary>
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";
/// <summary>Server › This library shared (owner review 5, #67): sample addresses, two clients, the temporary password.</summary>
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)),
]);
}
/// <summary>Server › This library that could not start: the port is taken.</summary>
public static void ShowShareFailed(AppServices services)
{
ArgumentNullException.ThrowIfNull(services);
services.Share.ShowSample(ShareState.Failed, Loc.L("Errors.Share.PortInUse", 8443), [], 0, 0, null, null, []);
}
/// <summary>Server › This library not shared, as before <see cref="ShowShare"/>.</summary>
public static void HideShare(AppServices services)
{
ArgumentNullException.ThrowIfNull(services);
services.Share.ShowSample(ShareState.Off, null, [], 0, 0, null, null, []);
}
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
public static SampleData Configure(AppServices services)
{
@@ -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");
/// <summary>The private folder of the server this PC runs while it shares its library: certificate, settings, uploads, logs.</summary>
public string ShareDirectory => Path.Combine(DataDirectory, "server");
/// <summary>The PC's name as the screens show it: a capture shows <see cref="SamplePcName"/>.</summary>
public string PcName => IsCapture ? SamplePcName : Environment.MachineName;
/// <summary>The PC name captures show.</summary>
public const string SamplePcName = "STUDIO-PC";
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
+22 -5
View File
@@ -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
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; }
/// <summary>Settings › Server › Share this library: this PC's library served to the LAN while Chronos runs (owner review 5, #67).</summary>
public LibraryShare Share { get; }
/// <summary>
/// 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();
}
/// <summary>Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).</summary>
@@ -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)),
};
@@ -88,6 +88,40 @@ public sealed class KnownServer
public DateTimeOffset LastSeen { get; set; }
}
/// <summary>
/// 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.
/// </summary>
public sealed class ShareSettings
{
public const int DefaultHttpsPort = 8443;
public const int DefaultHttpPort = 8080;
public bool Enabled { get; set; }
/// <summary>The name clients see; empty: this PC's name.</summary>
public string? Name { get; set; }
public int HttpsPort { get; set; } = DefaultHttpsPort;
public int HttpPort { get; set; } = DefaultHttpPort;
/// <summary>The ports clients reach when a router forwards others to this PC; null: the ones above.</summary>
public int? PublicHttpsPort { get; set; }
public int? PublicHttpPort { get; set; }
/// <summary>Announce the library to Chronos programs on the local network.</summary>
public bool Discovery { get; set; } = true;
/// <summary>What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.</summary>
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;
}
}
/// <summary>
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the
@@ -292,6 +326,9 @@ public sealed class AppSettings
/// <summary>The known server of <paramref name="id"/>; null when this PC has none.</summary>
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).</summary>
public ShareSettings Share { get; set; } = new();
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
public bool RenderNodeOptIn { get; set; }
@@ -67,6 +67,8 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
// The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own.
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)),
// While this PC shares its library (owner review 5, #67): the shared library's own clean-ups, which its Reset restores.
.. settings.Share.Enabled ? Chronos.Server.Jobs.ServerScheduleHost.ShareSchedules(0) : [],
];
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
+78 -4
View File
@@ -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">
<UserControl.Resources>
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="MinWidth" Value="60" />
@@ -42,14 +43,87 @@
</Style>
</UserControl.Resources>
<!-- Server.html: the connection panel, then the sync table. The render-node status panel is not built (see the decisions). -->
<!-- Server.html: this PC's shared library, the connection panel, then the sync table. The render-node status panel is not
built (see the decisions). -->
<Grid Margin="20,16,20,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="16,14">
<!-- This library (owner review 5, #67): sharing state, addresses with Copy, ports, fingerprint, temporary admin password,
clients and the admin panel; off, one row and Sharing settings. -->
<Border Style="{StaticResource Border.Panel}" Padding="16,12" DataContext="{Binding SharePanel}">
<StackPanel>
<DockPanel>
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Title}" FontWeight="SemiBold" VerticalAlignment="Center" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.AdminPanel}" Command="{Binding AdminPanelCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.AdminPanel}" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Settings}" Command="{Binding SettingsCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.Settings}" Visibility="{Binding IsNotShared, Converter={StaticResource BoolToVisibility}}" />
<WrapPanel VerticalAlignment="Center">
<ui:StatusGlyph Kind="{Binding StatusKind}" Text="{Binding StateText}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Share.State}"
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateText}" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Restart}" Command="{Binding RestartCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Restart}"
Margin="12,0,0,0" Visibility="{Binding HasFailed, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</DockPanel>
<ui:StatusGlyph Kind="Error" Text="{Binding Reason}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
Visibility="{Binding Reason, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<Grid Margin="0,10,0,0" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Addresses}" Margin="0,4,10,0" VerticalAlignment="Top" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Addresses}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type sec:ShareAddressRow}">
<StackPanel Orientation="Horizontal" Margin="0,0,18,4">
<TextBlock Text="{Binding Address}" FlowDirection="LeftToRight" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyCommand}" CommandParameter="{Binding Address}"
ToolTip="{l:Loc Tooltips.Server.Share.Copy}" AutomationProperties.Name="{Binding Address}" Margin="8,0,0,0" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Grid.Row="1" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Ports}" Margin="0,6,10,0" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PortsText}" Margin="0,6,0,0" Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Share.Ports}" />
<TextBlock Grid.Row="2" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Fingerprint}" Margin="0,10,10,0" VerticalAlignment="Center" />
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0">
<TextBlock Text="{Binding Fingerprint}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
ToolTip="{l:Loc Tooltips.Server.Share.Fingerprint}" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyFingerprintCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.CopyFingerprint}" Margin="8,0,0,0" />
</StackPanel>
<TextBlock Grid.Row="3" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.AdminPassword}" Margin="0,10,10,0" VerticalAlignment="Center"
Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}" />
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0" Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding PasswordText}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Server.Share.AdminPassword}" />
<Button Style="{StaticResource Button.Compact}" Content="{Binding ShowPasswordText}" Command="{Binding ShowPasswordCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Show}"
Margin="8,0,0,0" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyPasswordCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.CopyPassword}" Margin="8,0,0,0" />
</StackPanel>
<TextBlock Grid.Row="4" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Clients}" Margin="0,10,10,0" VerticalAlignment="Top" />
<StackPanel Grid.Row="4" Grid.Column="1" Margin="0,10,0,0" ToolTip="{l:Loc Tooltips.Server.Share.Clients}">
<TextBlock Text="{Binding ClientsText}" Foreground="{DynamicResource Brush.TextMuted}" />
<ItemsControl ItemsSource="{Binding Clients}" Focusable="False" Visibility="{Binding HasClients, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Grid>
</StackPanel>
</Border>
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Padding="16,14" Margin="0,14,0,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
@@ -167,7 +241,7 @@
</Border>
<!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. -->
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
<Border Grid.Row="2" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -41,11 +41,15 @@ public sealed class ServerViewModel : SectionViewModel
Sync = new SyncTableViewModel(shell);
_conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts);
_conflicts.PropertyChanged += OnConflictsChanged;
SharePanel = new SharePanelViewModel(shell);
}
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
public SyncTableViewModel Sync { get; }
/// <summary>This PC's library shared to the LAN (owner review 5, #67).</summary>
public SharePanelViewModel SharePanel { get; }
public ShellViewModel Shell { get; }
private ServerSession Session => _session ?? Shell.Services.Server;
@@ -222,6 +226,7 @@ public sealed class ServerViewModel : SectionViewModel
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
Sync.Dispose();
SharePanel.Dispose();
base.Dispose();
}
@@ -635,6 +635,47 @@
<!-- ================= Server ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
<!-- Sharing (owner review 5, #67): this PC's library served to the LAN while Chronos runs. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Share}">
<CheckBox Content="{l:Loc Settings.Server.ShareLibrary}" IsChecked="{Binding ShareRows.Enabled}" ToolTip="{l:Loc Tooltips.Settings.ShareLibrary}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareName}">
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding ShareRows.Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.Name}" ToolTip="{Binding ShareRows.Name.ToolTip}" ui:Field.Placeholder="{Binding ShareRows.PcName}"
AutomationProperties.Name="{l:Loc Settings.Server.ShareName}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpsPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.HttpsPort}" ToolTip="{Binding ShareRows.HttpsPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpsPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.HttpPort}" ToolTip="{Binding ShareRows.HttpPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpsPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpsPort}" ToolTip="{Binding ShareRows.PublicHttpsPort.ToolTip}"
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpsPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpPort}" ToolTip="{Binding ShareRows.PublicHttpPort.ToolTip}"
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Discovery}">
<CheckBox Content="{l:Loc Settings.Server.Announce}" IsChecked="{Binding ShareRows.Discovery}" ToolTip="{l:Loc Tooltips.Settings.Discovery}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareFolder}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding ShareRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.ShareFolder}"
AutomationProperties.Name="{l:Loc Settings.Server.ShareFolder}" />
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding ShareRows.OpenFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenShareFolder}" Margin="10,0,0,0" />
</Grid>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
+10 -1
View File
@@ -91,7 +91,8 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
new(SettingsPage.Server, ["Settings.Server.Share", "Settings.Server.ShareName", "Settings.Server.HttpsPort", "Settings.Server.HttpPort",
"Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
@@ -177,6 +178,9 @@ public sealed class SettingsViewModel : SectionViewModel
// Saving applies them to the log files (App.SaveSettings).
Logs = new LogSettingsRows(_s, Save);
// ---- Server › Sharing (owner review 5, #67); saving applies it to the share (AppServices.SaveSettings). ----
ShareRows = new ShareSettingsRows(_s, Save, Shell.Services.Environment.ShareDirectory, Shell.Services.Environment.PcName);
// ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
@@ -831,6 +835,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
public LogSettingsRows Logs { get; }
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN (owner review 5, #67).</summary>
public ShareSettingsRows ShareRows { get; }
public ICommand OpenDataFolderCommand { get; }
public ICommand OpenLogsCommand { get; }
public ICommand ExportDiagnosticsCommand { get; }
@@ -1667,6 +1674,7 @@ public sealed class SettingsViewModel : SectionViewModel
break;
case SettingsPage.Server:
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
ShareRows.Reset();
break;
case SettingsPage.Updates:
_s.CheckForUpdates = defaults.CheckForUpdates;
@@ -1774,6 +1782,7 @@ public sealed class SettingsViewModel : SectionViewModel
foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh();
WorkspaceRows.Refresh();
ShareRows.Refresh();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
@@ -0,0 +1,171 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
/// <summary>An address of the shared library with its Copy button.</summary>
public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
/// <summary>
/// Server › This library (owner review 5, #67): whether this PC shares its library, why not when it could not start
/// (with Restart), the addresses with Copy, the ports, the certificate's fingerprint with Copy, the first administrator's
/// temporary password while it exists (Show, Copy), the clients of the last minutes and the admin panel. Off, one row and
/// Sharing settings. Follows <see cref="LibraryShare"/> on the UI thread; the clients are read again every few seconds.
/// </summary>
public sealed class SharePanelViewModel : LocalizedViewModel
{
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(10);
private readonly ShellViewModel _shell;
private readonly LibraryShare _share;
private readonly DispatcherTimer? _timer;
private bool _showPassword;
public SharePanelViewModel(ShellViewModel shell)
{
_shell = shell;
_share = shell.Services.Share;
_share.PropertyChanged += OnShareChanged;
CopyCommand = new RelayCommand(p => Copy(p as string));
CopyFingerprintCommand = new RelayCommand(() => Copy(_share.Fingerprint), () => _share.Fingerprint is not null);
ShowPasswordCommand = new RelayCommand(() =>
{
_showPassword = !_showPassword;
OnPropertyChanged(nameof(PasswordText));
OnPropertyChanged(nameof(ShowPasswordText));
}, () => _share.AdminPassword is not null);
CopyPasswordCommand = new RelayCommand(() => Copy(_share.AdminPassword), () => _share.AdminPassword is not null);
AdminPanelCommand = new RelayCommand(() => ShellActions.OpenUrl($"https://localhost:{_share.HttpsPort}/admin"), () => _share.IsOn && _share.HttpsPort > 0);
RestartCommand = new RelayCommand(() => _ = RestartAsync(), () => _share.State is ShareState.Failed);
SettingsCommand = new RelayCommand(() =>
{
_shell.Settings.Page = SettingsPage.Server;
_shell.Navigate(SectionKey.Settings);
});
if (Application.Current is not null && !shell.Services.Environment.IsCapture)
{
_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = RefreshInterval };
_timer.Tick += (_, _) =>
{
if (_share.IsOn) _ = RefreshAsync();
};
_timer.Start();
}
}
public ICommand CopyCommand { get; }
public ICommand CopyFingerprintCommand { get; }
public ICommand ShowPasswordCommand { get; }
public ICommand CopyPasswordCommand { get; }
public ICommand AdminPanelCommand { get; }
public ICommand RestartCommand { get; }
public ICommand SettingsCommand { get; }
/// <summary>Sharing is on in the settings, whether it runs or not: the details show.</summary>
public bool IsShared => _share.State is not ShareState.Off;
public bool IsNotShared => !IsShared;
public bool IsOn => _share.IsOn;
public bool HasFailed => _share.State is ShareState.Failed;
public StatusKind StatusKind => _share.State switch
{
ShareState.On => StatusKind.Online,
ShareState.Starting => StatusKind.Running,
ShareState.Failed => StatusKind.Error,
_ => StatusKind.Offline,
};
public string StateText => Loc.L("Server.Share.State." + _share.State);
public string? Reason => _share.Reason;
public IReadOnlyList<ShareAddressRow> Addresses => [.. _share.Addresses.Select(a => new ShareAddressRow(a, CopyCommand))];
public string? PortsText => _share.IsOn ? Loc.L("Server.Share.PortsValue", _share.HttpsPort, _share.HttpPort) : null;
public string? Fingerprint => _share.Fingerprint is { } fingerprint ? Formatting.LeftToRight(fingerprint) : null;
public bool HasAdminPassword => _share.AdminPassword is not null;
/// <summary>The temporary password, masked until Show.</summary>
public string? PasswordText => _share.AdminPassword is not { } password ? null : _showPassword ? password : new string('•', 12);
public string ShowPasswordText => Loc.L(_showPassword ? "Server.Share.Hide" : "Server.Share.Show");
/// <summary>"anna · Chronos Uploader · 192.168.1.20", the latest first.</summary>
public IReadOnlyList<string> Clients => [.. _share.Clients.Select(c => Loc.L("Server.Share.ClientRow", c.User, c.Program, c.Address).TrimEnd(' ', '·'))];
public bool HasClients => _share.Clients.Count > 0;
public string ClientsText => HasClients ? Loc.Plural("Server.Share.ClientCount", _share.Clients.Count) : Loc.L("Server.Share.NoClients");
public override void Dispose()
{
_timer?.Stop();
_share.PropertyChanged -= OnShareChanged;
base.Dispose();
}
private async Task RestartAsync()
{
await _share.RestartAsync();
CommandManager.InvalidateRequerySuggested();
}
private async Task RefreshAsync()
{
try
{
await _share.RefreshAsync();
}
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException)
{
Log.Warning("share", "The clients of the shared library could not be read", ex);
}
}
private static void Copy(string? text)
{
if (string.IsNullOrEmpty(text)) return;
try
{
Clipboard.SetText(text);
}
catch (ExternalException ex)
{
// Another program holds the clipboard: nothing was copied, as the next try may.
Log.Warning("share", "The clipboard is busy", ex);
}
}
private void OnShareChanged(object? sender, PropertyChangedEventArgs e)
{
if (Application.Current?.Dispatcher is { } dispatcher && !dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(Changed);
return;
}
Changed();
}
private void Changed()
{
if (!_share.IsOn) _showPassword = false;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}
+11
View File
@@ -75,6 +75,9 @@ public enum ConnectError
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
CertificateChanged,
Failed,
/// <summary>The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.</summary>
OwnLibrary,
}
/// <summary>
@@ -112,6 +115,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
/// <summary>Raised after every step change.</summary>
public event EventHandler? Changed;
/// <summary>
/// True for this PC's own shared library, by its certificate fingerprint or its server id (owner review 5, #67): the
/// flow refuses it before any trust question or password.
/// </summary>
public Func<string?, Guid?, bool>? IsOwnLibrary { get; set; }
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
{
@@ -221,10 +230,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
var clock = Stopwatch.StartNew();
Info = await _api.GetInfoAsync(ct);
Latency = clock.Elapsed;
if (IsOwnLibrary?.Invoke(Info.TlsFingerprint, Info.ServerId) == true) return Fail(ConnectError.OwnLibrary);
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
}
catch (UntrustedCertificateException untrusted)
{
if (IsOwnLibrary?.Invoke(untrusted.Fingerprint, null) == true) return Fail(ConnectError.OwnLibrary);
PendingFingerprint = untrusted.Fingerprint;
return Set(ConnectStep.AwaitingTrust, ConnectError.None);
}
+495
View File
@@ -0,0 +1,495 @@
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Projects;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>Where sharing this PC's library stands (Server › This library).</summary>
public enum ShareState
{
/// <summary>Settings › Server › Share this library is off.</summary>
Off,
Starting,
/// <summary>The library is served: clients connect to <see cref="LibraryShare.Addresses"/>.</summary>
On,
/// <summary>Sharing is on in the settings but could not start: <see cref="LibraryShare.Reason"/> says why.</summary>
Failed,
}
/// <summary>A program that used the shared library lately, as the Server section lists it.</summary>
public sealed record ShareClient(string User, string Program, string Address, DateTimeOffset? LastSeen);
/// <summary>
/// Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts in its own process to serve this
/// PC's current archive to the LAN, over the index, engines, job engine and scheduler of <see cref="AppServices"/> (one
/// engine, one index). Started after the schedules, stopped before them; started, stopped and restarted off the UI thread,
/// one at a time. A settings save applies the live values at once and restarts on a new name, port, discovery choice or
/// archive. Its state, addresses, fingerprint, clients and the first administrator's temporary password are what the Server
/// section shows. Property changes are raised on any thread (scalar values and whole lists only).
/// </summary>
public sealed class LibraryShare : ObservableObject, IAsyncDisposable
{
private readonly AppServices _services;
private readonly SemaphoreSlim _gate = new(1, 1);
private HostedServer? _server;
private ShareSettings? _running;
private string? _archiveRoot;
private ShareState _state = ShareState.Off;
private string? _reason;
private IReadOnlyList<string> _addresses = [];
private IReadOnlyList<ShareClient> _clients = [];
private string? _fingerprint;
private string? _adminPassword;
private int _httpsPort;
private int _httpPort;
private bool _sample;
private bool _disposed;
public LibraryShare(AppServices services)
{
_services = services;
}
public ShareState State
{
get => _state;
private set
{
if (!Set(ref _state, value)) return;
OnPropertyChanged(nameof(IsOn));
Changed?.Invoke();
}
}
/// <summary>True while the library is served.</summary>
public bool IsOn => _state == ShareState.On;
/// <summary>One sentence on why sharing did not start; null otherwise.</summary>
public string? Reason
{
get => _reason;
private set => Set(ref _reason, value);
}
/// <summary>The addresses clients reach this library at, one per name and network address of this PC.</summary>
public IReadOnlyList<string> Addresses
{
get => _addresses;
private set => Set(ref _addresses, value);
}
/// <summary>The certificate's SHA-256 fingerprint, colon hex, as clients see it on their first connection.</summary>
public string? Fingerprint
{
get => _fingerprint;
private set => Set(ref _fingerprint, value);
}
/// <summary>The port the HTTPS listener got; 0 while not shared.</summary>
public int HttpsPort
{
get => _httpsPort;
private set => Set(ref _httpsPort, value);
}
/// <summary>The port the HTTP listener got; 0 while not shared.</summary>
public int HttpPort
{
get => _httpPort;
private set => Set(ref _httpPort, value);
}
/// <summary>The first administrator's temporary password while its file exists; null once an administrator set their own.</summary>
public string? AdminPassword
{
get => _adminPassword;
private set => Set(ref _adminPassword, value);
}
/// <summary>The programs of the last minutes and the render nodes online (<see cref="RefreshAsync"/>).</summary>
public IReadOnlyList<ShareClient> Clients
{
get => _clients;
private set => Set(ref _clients, value);
}
/// <summary>The server while the library is served (tests, the change bridge); null otherwise.</summary>
public HostedServer? Server => _server;
/// <summary>The private folder of the shared library's own state: certificate, settings, partial uploads, logs.</summary>
public string Folder => _services.Environment.ShareDirectory;
/// <summary>The state changed (any thread).</summary>
public event Action? Changed;
/// <summary>
/// Starts sharing when Settings › Server says so and it is not running: the current archive of Settings › Archive is
/// served. Never throws: a failure is the state <see cref="ShareState.Failed"/> with its <see cref="Reason"/>.
/// </summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed || _sample || _server is not null || !_services.Settings.Share.Enabled) return;
await StartCoreAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>Stops sharing (the desktop's engines run on); the state reads as the settings say.</summary>
public async Task StopAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
await StopCoreAsync().ConfigureAwait(false);
State = ShareState.Off;
Reason = null;
}
finally
{
_gate.Release();
}
}
/// <summary>Stops sharing if it runs and starts it again (Server › Restart, a new port or archive).</summary>
public async Task RestartAsync(CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed || _sample) return;
await StopCoreAsync().ConfigureAwait(false);
if (_services.Settings.Share.Enabled) await StartCoreAsync(cancellationToken).ConfigureAwait(false);
else State = ShareState.Off;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// The settings were saved: sharing turned off stops, turned on starts, a new name, port, discovery choice or archive
/// restarts; the parallelism, the priority queue, the language and the logs apply to the running server at once.
/// </summary>
public void Apply()
{
if (_disposed || _sample) return;
var share = _services.Settings.Share;
if (!share.Enabled)
{
if (_server is not null || _state != ShareState.Off) _ = Run(StopAsync());
return;
}
if (_server is not { } server)
{
// Not running yet: the start after the schedules starts it, or it waits for the index; a failed one tries again.
if (_services.Scheduler is not null && _state != ShareState.Starting) _ = Run(StartAsync());
return;
}
if (_running is { } running && running.SameEndpoint(share) && string.Equals(_archiveRoot, _services.Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase))
{
try
{
server.ApplyDesktop(DesktopValues(_archiveRoot!));
}
catch (InvalidOperationException ex)
{
Log.Warning("share", "The settings could not be applied to the shared library", ex);
}
return;
}
_ = Run(RestartAsync());
}
/// <summary>True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself.</summary>
public bool IsOwn(string? fingerprint, Guid? serverId)
{
if (_server is not { } server) return false;
if (serverId is { } id && server.ServerId == id) return true;
return fingerprint is { Length: > 0 } && string.Equals(fingerprint, server.Fingerprint, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Reads the programs of the last minutes, the render nodes online and the temporary password again.</summary>
public async Task RefreshAsync(CancellationToken cancellationToken = default)
{
if (_sample || _server is not { } server) return;
var clients = server.Clients.Recent().Select(c => new ShareClient(c.User, c.Client, c.Address, c.LastSeen)).ToList();
try
{
foreach (var node in await server.RenderNodesAsync(cancellationToken).ConfigureAwait(false))
clients.Add(new ShareClient(node, Loc.L("Server.Share.RenderNode"), string.Empty, null));
}
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or ObjectDisposedException)
{
Log.Warning("share", "The render nodes online could not be read", ex);
}
Clients = clients;
AdminPassword = server.AdminPassword();
}
/// <summary>The <c>uploads</c> clean-up step while sharing (<see cref="ShareUploadsStep"/>): the server's sweep, or nothing.</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
_server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff"));
/// <summary>The desktop's archive or processing service changed sequence <paramref name="id"/>: the clients are told.</summary>
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
_server is { } server ? server.SequenceChangedAsync(id, change, cancellationToken) : Task.CompletedTask;
/// <summary>The desktop's archive service changed a sequence's projects: the clients are told.</summary>
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
_server is { } server ? server.ProjectsChangedAsync(changed, cancellationToken) : Task.CompletedTask;
/// <summary>Capture and design time: a shared library with sample values, no server.</summary>
internal void ShowSample(ShareState state, string? reason, IReadOnlyList<string> addresses, int httpsPort, int httpPort, string? fingerprint,
string? adminPassword, IReadOnlyList<ShareClient> clients)
{
_sample = true;
Reason = reason;
Addresses = addresses;
HttpsPort = httpsPort;
HttpPort = httpPort;
Fingerprint = fingerprint;
AdminPassword = adminPassword;
Clients = clients;
State = state;
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed) return;
_disposed = true;
await StopCoreAsync().ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>The addresses of <paramref name="port"/> on this PC: its name, its full name, and each network address that is up.</summary>
public static IReadOnlyList<string> AddressesOf(int port)
{
var hosts = new List<string> { System.Environment.MachineName };
try
{
if (IPGlobalProperties.GetIPGlobalProperties().DomainName is { Length: > 0 } domain) hosts.Add(System.Environment.MachineName + "." + domain);
foreach (var network in NetworkInterface.GetAllNetworkInterfaces())
{
if (network.OperationalStatus != OperationalStatus.Up || network.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var unicast in network.GetIPProperties().UnicastAddresses)
{
var ip = unicast.Address;
if (IPAddress.IsLoopback(ip)) continue;
if (ip.AddressFamily == AddressFamily.InterNetwork && !ip.ToString().StartsWith("169.254.", StringComparison.Ordinal)) hosts.Add(ip.ToString());
else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !ip.IsIPv6LinkLocal && !ip.IsIPv6SiteLocal && !ip.IsIPv6Multicast)
hosts.Add("[" + new IPAddress(ip.GetAddressBytes()) + "]");
}
}
}
catch (NetworkInformationException ex)
{
Log.Warning("share", "The network addresses of this PC could not be read", ex);
}
return [.. hosts.Distinct(StringComparer.OrdinalIgnoreCase).Select(h => $"https://{h}:{port}")];
}
private async Task StartCoreAsync(CancellationToken cancellationToken)
{
var s = _services;
if (s.Database is not { } db || s.Archives is not { } archives || s.Processing is not { } processing || s.Engine is not { } engine
|| s.Scheduler is not { } scheduler)
{
Fail(Loc.L("Errors.Share.NotReady"));
return;
}
Reason = null;
State = ShareState.Starting;
var archive = await s.ScheduleHost.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
if (archive is null)
{
Fail(Loc.L("Errors.Share.NoArchive"));
return;
}
var share = Snapshot(s.Settings.Share);
HostedServer? server = null;
try
{
server = await Task.Run(() =>
{
var options = ServerOptions.ForHosted(Folder, DesktopValues(archive.RootPath));
return ServerHost.BuildHosted(options, new HostedEngine(db, archives, processing, engine, scheduler, archive));
}, cancellationToken).ConfigureAwait(false);
// Off the caller's thread: the server's own services never continue on the UI thread.
await Task.Run(() => server.StartAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException && Failure(ex, share) is { } reason)
{
if (server is not null) await DisposeQuietlyAsync(server).ConfigureAwait(false);
Log.Error("share", "This library could not be shared", ex);
Fail(reason);
return;
}
_server = server;
_running = share;
_archiveRoot = archive.RootPath;
server.JobChangedOutside += OnJobChangedOutside;
HttpsPort = server.HttpsPort;
HttpPort = server.HttpPort;
Fingerprint = server.Fingerprint;
Addresses = AddressesOf(server.HttpsPort);
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
await RefreshAsync(cancellationToken).ConfigureAwait(false);
Log.Info("share", $"Sharing {archive.RootPath} on HTTPS {server.HttpsPort} and HTTP {server.HttpPort}");
State = ShareState.On;
}
private async Task StopCoreAsync()
{
if (_server is not { } server) return;
_server = null;
_running = null;
_archiveRoot = null;
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
server.JobChangedOutside -= OnJobChangedOutside;
await DisposeQuietlyAsync(server).ConfigureAwait(false);
Addresses = [];
Clients = [];
Fingerprint = null;
AdminPassword = null;
HttpsPort = 0;
HttpPort = 0;
Log.Info("share", "Sharing stopped");
}
private void Fail(string reason)
{
Reason = reason;
State = ShareState.Failed;
}
/// <summary>The desktop's values the shared library takes: Settings › Server, Rendering, Videos and Advanced › Logs.</summary>
private HostedSettings DesktopValues(string archiveRoot)
{
var s = _services.Settings;
var share = s.Share;
return new HostedSettings(string.IsNullOrWhiteSpace(share.Name) ? null : share.Name.Trim(), share.HttpPort, share.HttpsPort, share.PublicHttpPort,
share.PublicHttpsPort, share.Discovery, archiveRoot, string.IsNullOrWhiteSpace(s.VideosFolder) ? null : s.VideosFolder, _services.Parallelism,
s.PriorityQueue, new Dictionary<string, string>(s.JobPriorities, StringComparer.OrdinalIgnoreCase), Loc.Culture.TwoLetterISOLanguageName,
s.LogLevel, s.LogRetentionDays, s.LogMaxFileMb, s.LogMaxTotalMb, s.LogRotation, s.DiagnosticsLogMb);
}
/// <summary>The sentence for a start that failed; null for an exception that is not an expected failure.</summary>
private static string? Failure(Exception ex, ShareSettings share)
{
if (IsAddressInUse(ex)) return Loc.L("Errors.Share.PortInUse", PortInUse(share));
return ex is InvalidOperationException or IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException
or DatabaseException or ArgumentException
? Loc.L("Errors.Share.Failed", ex.Message)
: null;
}
private static bool IsAddressInUse(Exception ex)
{
for (var e = ex; e is not null; e = e.InnerException)
{
if (e is Microsoft.AspNetCore.Connections.AddressInUseException or SocketException { SocketErrorCode: SocketError.AddressAlreadyInUse }) return true;
}
return false;
}
/// <summary>The configured port another program listens on (the HTTPS one when neither can be told).</summary>
private static int PortInUse(ShareSettings share)
{
try
{
var listening = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Select(e => e.Port).ToHashSet();
if (!listening.Contains(share.HttpsPort) && listening.Contains(share.HttpPort)) return share.HttpPort;
}
catch (NetworkInformationException)
{
}
return share.HttpsPort;
}
private static ShareSettings Snapshot(ShareSettings share) => new()
{
Enabled = share.Enabled,
Name = share.Name,
HttpsPort = share.HttpsPort,
HttpPort = share.HttpPort,
PublicHttpsPort = share.PublicHttpsPort,
PublicHttpPort = share.PublicHttpPort,
Discovery = share.Discovery,
};
private static async Task DisposeQuietlyAsync(HostedServer server)
{
try
{
// The app's exit waits for this on the UI thread: nothing the server's services await may continue on it.
await Task.Run(() => server.DisposeAsync().AsTask()).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException or ObjectDisposedException or OperationCanceledException or AggregateException)
{
Log.Warning("share", "The shared library did not stop cleanly", ex);
}
}
private void OnNetworkChanged(object? sender, EventArgs e)
{
if (_server is { } server) Addresses = AddressesOf(server.HttpsPort);
}
/// <summary>A render node changed a job outside the engine: the Jobs section follows it as it follows the engine's own changes.</summary>
private void OnJobChangedOutside(Chronos.Core.Model.Job job) => JobChangedOutside?.Invoke(job);
/// <summary>A render node changed a job's state outside this PC's engine (any thread).</summary>
public event Action<Chronos.Core.Model.Job>? JobChangedOutside;
/// <summary>Runs a fire-and-forget step, logging what it throws.</summary>
private static async Task Run(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Error("share", "Sharing could not be updated", ex);
}
}
}
/// <summary>
/// The desktop's clean-up step <c>uploads</c> (owner review 5, #67): the upload-cleanup schedule the shared library adds runs
/// on this PC's scheduler, so the step is the desktop's, and it sweeps the shared library's abandoned uploads while it runs.
/// </summary>
public sealed class ShareUploadsStep(Func<LibraryShare> share) : ICleanupStep
{
public string Name => Chronos.Server.Storage.UploadCleanupStep.StepName;
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters) => share().SweepUploadsAsync(context, parameters);
}
+3 -2
View File
@@ -70,7 +70,8 @@ public sealed class DpapiTokenProtector : ITokenProtector
}
/// <summary>A Chronos Server announced on the LAN.</summary>
public sealed record DiscoveredServer(string Name, string Address);
/// <summary>A server announced on the LAN; <paramref name="Fingerprint"/> is its beacon's certificate fingerprint, if any.</summary>
public sealed record DiscoveredServer(string Name, string Address, string? Fingerprint = null);
/// <summary>
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once.
@@ -120,7 +121,7 @@ public sealed class DiscoveryListener : IDisposable
{
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address), beacon.TlsFingerprint);
lock (_seen)
{
if (!_seen.Add(server.Address)) continue;
+9
View File
@@ -32,6 +32,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
public ConnectFlow Flow => _flow;
/// <summary>True for this PC's own shared library (by fingerprint or server id): never connected to, never listed as found.</summary>
public Func<string?, Guid?, bool>? IsOwnLibrary
{
get => _flow.IsOwnLibrary;
set => _flow.IsOwnLibrary = value;
}
/// <summary>Servers that announced themselves on this network.</summary>
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
@@ -185,6 +192,8 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
_discovery = new DiscoveryListener();
_discovery.Found += server =>
{
// This PC's own shared library announces itself too: it is open here already (owner review 5, #67).
if (_flow.IsOwnLibrary?.Invoke(server.Fingerprint, null) == true) return;
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
Discovered.Add(server);
};
@@ -0,0 +1,117 @@
using System.Globalization;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Settings;
/// <summary>
/// The sharing rows of Settings › Server (owner review 5, #67): Share this library, its name, its ports (the public ones
/// may stay empty), the LAN announcement and the shared library's own data folder. Each value is stored and saved at once;
/// saving applies it to the share (<see cref="AppServices.SaveSettings"/>), which restarts on a new name, port or
/// announcement. The rows read <see cref="AppSettings.Share"/> each time: Reset and Import replace it.
/// </summary>
public sealed class ShareSettingsRows : ObservableObject
{
private readonly AppSettings _settings;
private readonly Action _save;
public ShareSettingsRows(AppSettings settings, Action save, string folder, string pcName)
{
_settings = settings;
_save = save;
PcName = pcName;
Folder = AppEnvironment.Shown(folder);
Name = new EditableField(Share.Name ?? string.Empty, _ => null, v =>
{
Share.Name = v.Trim().Length == 0 ? null : v.Trim();
_save();
}, () => Loc.L("Tooltips.Settings.ShareName"));
HttpsPort = Port(() => Share.HttpsPort, v => Share.HttpsPort = v, "Tooltips.Settings.HttpsPort");
HttpPort = Port(() => Share.HttpPort, v => Share.HttpPort = v, "Tooltips.Settings.HttpPort");
PublicHttpsPort = PublicPort(() => Share.PublicHttpsPort, v => Share.PublicHttpsPort = v);
PublicHttpPort = PublicPort(() => Share.PublicHttpPort, v => Share.PublicHttpPort = v);
OpenFolderCommand = new RelayCommand(() => ShellActions.Reveal(folder));
}
private ShareSettings Share => _settings.Share;
public bool Enabled
{
get => Share.Enabled;
set
{
if (Share.Enabled == value) return;
Share.Enabled = value;
_save();
OnPropertyChanged();
}
}
public EditableField Name { get; }
public EditableField HttpsPort { get; }
public EditableField HttpPort { get; }
public EditableField PublicHttpsPort { get; }
public EditableField PublicHttpPort { get; }
public bool Discovery
{
get => Share.Discovery;
set
{
if (Share.Discovery == value) return;
Share.Discovery = value;
_save();
OnPropertyChanged();
}
}
/// <summary>The name clients see while <see cref="Name"/> is empty: this PC's.</summary>
public string PcName { get; }
/// <summary>The shared library's private folder, as the screens show paths.</summary>
public string Folder { get; }
public ICommand OpenFolderCommand { get; }
/// <summary>Settings › Server › Reset: sharing off, on the default ports.</summary>
public void Reset()
{
_settings.Share = new ShareSettings();
Refresh();
}
/// <summary>Shows the values as they are now (after Reset all, Import, or a reset of the page).</summary>
public void Refresh()
{
Name.Load(Share.Name ?? string.Empty);
HttpsPort.Load(Text(Share.HttpsPort));
HttpPort.Load(Text(Share.HttpPort));
PublicHttpsPort.Load(Share.PublicHttpsPort is { } https ? Text(https) : string.Empty);
PublicHttpPort.Load(Share.PublicHttpPort is { } http ? Text(http) : string.Empty);
OnPropertyChanged(nameof(Enabled));
OnPropertyChanged(nameof(Discovery));
}
private EditableField Port(Func<int> read, Action<int> write, string toolTip) =>
new(Text(read()), v => ValidatePort(v), v =>
{
write(int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
_save();
}, () => Loc.L(toolTip));
private EditableField PublicPort(Func<int?> read, Action<int?> write) =>
new(read() is { } port ? Text(port) : string.Empty, v => v.Trim().Length == 0 ? null : ValidatePort(v), v =>
{
write(v.Trim().Length == 0 ? null : int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
_save();
}, () => Loc.L("Tooltips.Settings.PublicPorts"));
private static string Text(int port) => port.ToString(CultureInfo.InvariantCulture);
private static string? ValidatePort(string text) =>
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n is >= 1 and <= 65535
? null
: Loc.L("Errors.Number.Range", 1.ToString("N0", Loc.Culture), 65535.ToString("N0", Loc.Culture));
}
+6
View File
@@ -113,6 +113,12 @@ public static class ScreenCapture
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server", theme);
// This PC's library shared (owner review 5, #67), then one that could not start.
SampleData.ShowShare(shell.Services);
written += await SaveAsync(window, directory, "server-share", theme);
SampleData.ShowShareFailed(shell.Services);
written += await SaveAsync(window, directory, "server-share-failed", theme);
SampleData.HideShare(shell.Services);
// Every page, About last (owner review 2, R5).
shell.Navigate(SectionKey.Settings);
+1 -1
View File
@@ -342,7 +342,7 @@ public sealed class ArchiveIndexer
/// the flags in the sidecar are the writer's that added the frames (which analyses them, and on a server draws them
/// after every upload), and clearing them there would have the server make everything again.
/// </summary>
private SequenceStatus Uncovered => _writer.Options.ImagesAfterScan ? CoveringStatus : SequenceStatus.None;
private SequenceStatus Uncovered => _writer.Options.QueuesImagesAfterScan ? CoveringStatus : SequenceStatus.None;
/// <summary>
/// The projects of a sequence brought in line with their sidecars (<see cref="ProjectIndexer"/>), under its lease, in the
+3 -3
View File
@@ -104,8 +104,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild, _writer.Options.ImagesAfterScan),
new ScanJobHandler(_db, Indexer, JobKind.Scan, () => _writer.Options.QueuesImagesAfterScan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild, () => _writer.Options.QueuesImagesAfterScan),
new VerifyJobHandler(_db, Verifier),
new ImportJobHandler(_db, Imports),
new ImageJobHandler(_db, Images, JobKind.Thumbs),
@@ -450,7 +450,7 @@ public sealed class ArchiveService : IJobHandlerProvider
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequenceId], sequence.DisplayTitle)];
// BRIEF §10.2: background, low priority.
if (deepAnalysis) requests.Add(ProcessingJobs.DeepAnalysis([sequenceId], sequence.DisplayTitle) with { Priority = JobPriority.Background });
if (_writer.Options.ImagesAfterScan)
if (_writer.Options.QueuesImagesAfterScan)
{
requests.Add(ArchiveJobs.Thumbnails([sequenceId], sequence.DisplayTitle));
// An archive whose policy makes no proxies would get a pass that does nothing.
+1 -1
View File
@@ -627,7 +627,7 @@ public sealed partial class FrameTrash
var label = sequence.DisplayTitle;
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)];
if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background });
var images = _writer.Options.ImagesAfterScan;
var images = _writer.Options.QueuesImagesAfterScan;
if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label));
if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled)
requests.Add(ArchiveJobs.Proxies([sequence.Id], label));
@@ -21,11 +21,11 @@ internal static class JobArchive
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.ImagesAfterScan"/>) the sequences it indexed
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.QueuesImagesAfterScan"/>, read at each run) the sequences it indexed
/// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for
/// their first frame (<see cref="ArchiveIndexer.AwaitingFolderAsync"/>) have nothing to analyse or draw yet and are left out.
/// </summary>
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, Func<bool>? imagesAfterScan = null) : IJobHandler
{
private const string Prefix = "after:";
@@ -53,7 +53,7 @@ internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer,
.Where(id => !awaiting.Contains(id)).ToList();
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
if (imagesAfterScan)
if (imagesAfterScan?.Invoke() == true)
{
var resumed = resume is not null;
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
@@ -26,6 +26,16 @@ public sealed record ArchiveServiceOptions
/// </summary>
public bool ImagesAfterScan { get; init; }
/// <summary>
/// Whether <see cref="ImagesAfterScan"/> 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
/// <see cref="ImagesAfterScan"/>.
/// </summary>
public Func<bool>? ImagesAfterScanWhen { get; init; }
/// <summary><see cref="ImagesAfterScanWhen"/> as it is now, else <see cref="ImagesAfterScan"/>.</summary>
public bool QueuesImagesAfterScan => ImagesAfterScanWhen?.Invoke() ?? ImagesAfterScan;
/// <summary>
/// The index may hold settings newer than a sequence's <c>project.json</c>: the server, whose <c>PATCH</c> wrote the
/// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<!-- The console program of Chronos Server (the Docker image, development runs); the server itself is the
Chronos.Server library, which Chronos Desktop also hosts in-process to share its library (owner review 5, #67). -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Chronos.Server.Host</RootNamespace>
<AssemblyName>Chronos.Server.Host</AssemblyName>
<ApplicationIcon Condition="Exists('$(ChronosIconDir)chronos-server.ico')">$(ChronosIconDir)chronos-server.ico</ApplicationIcon>
<ServerGarbageCollection>true</ServerGarbageCollection>
<InvariantGlobalization>false</InvariantGlobalization>
<UserSecretsId />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
</ItemGroup>
</Project>
+30
View File
@@ -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);
}
@@ -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) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
+29 -7
View File
@@ -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<IResult> ListAsync(HttpContext context, ChronosDatabase db, string? state, string? kind, string? cursor, int? limit)
private static async Task<IResult> 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<JobDto>([], 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<JobDto>([.. 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<JobDto>([.. page.Items.Where(j => host.Exposes(j.Kind)).Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
}
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
@@ -90,7 +92,7 @@ public static class JobEndpoints
var titles = new List<string>(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<IResult> ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func<Job, CancellationToken, Task> 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<JobEngineHost>().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
}
/// <summary>Render parameters, or null when they are missing or incomplete.</summary>
/// <summary>
/// <paramref name="parameters"/> without the export folder its preset names (key <c>folder</c>, any case), or the same
/// instance when it names none (owner review 5, #67).
/// </summary>
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;
+4 -2
View File
@@ -219,7 +219,8 @@ public static class LibraryEndpoints
var allowed = new List<Sequence>();
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<ServerArchive>().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<ServerArchive>().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");
+90
View File
@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.Routing.Patterns;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// 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.
/// </summary>
public static class ServedItems
{
/// <summary>What the id in a route names, by the route's prefix and the id's name.</summary>
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,
}
/// <summary>The endpoint filter of the API group: an id of another archive's item answers 404 before the endpoint runs.</summary>
public static async ValueTask<object?> 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<ChronosDatabase>();
var archive = context.RequestServices.GetRequiredService<ServerArchive>();
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);
}
/// <summary>The sequence <paramref name="id"/> when it belongs to the served archive; null for another archive's or an unknown one.</summary>
public static async Task<Sequence?> 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;
}
/// <summary>The render <paramref name="id"/> when its sequence belongs to the served archive; null otherwise.</summary>
public static async Task<Render?> 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<Guid?> 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;
}
}
+20 -1
View File
@@ -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<Render>(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<ServerArchive>(), 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));
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
/// <summary>
/// <paramref name="ids"/> 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.
/// </summary>
private static async Task<List<Guid>> ServedAsync(HttpContext context, ChronosDatabase db, List<Guid> ids)
{
var archive = context.RequestServices.GetRequiredService<ServerArchive>();
var served = new List<Guid>(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<Guid>? Ids(IReadOnlyList<Guid>? ids)
{
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
+3 -3
View File
@@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<!-- A library (owner review 5, #67): Chronos.Server.Host is the console program, and Chronos Desktop hosts the same
server in-process when it shares its library. -->
<OutputType>Library</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Chronos.Server</RootNamespace>
<AssemblyName>Chronos.Server</AssemblyName>
<ApplicationIcon Condition="Exists('$(ChronosIconDir)chronos-server.ico')">$(ChronosIconDir)chronos-server.ico</ApplicationIcon>
<ServerGarbageCollection>true</ServerGarbageCollection>
<InvariantGlobalization>false</InvariantGlobalization>
<UserSecretsId />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Chronos.Core\Chronos.Core.csproj" />
@@ -369,6 +369,121 @@ public sealed class ServerOptions
return options;
}
/// <summary>What <see cref="LockedBy"/> names for a setting Chronos Desktop owns while it shares its library (owner review 5, #67).</summary>
public const string DesktopLock = "desktop";
/// <summary>
/// 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 (<see cref="HostedEngine"/>), its own state is in the desktop's data folder.
/// </summary>
[JsonIgnore]
public bool Hosted { get; private set; }
/// <summary>
/// The options of the server Chronos Desktop hosts (owner review 5, #67): <paramref name="dataPath"/>'s <c>server.json</c>
/// (what the admin panel saved: token lifetime, uploads, sign-in limits, render nodes, audit retention), then the values
/// the desktop owns, locked there with <see cref="DesktopLock"/> (its name, ports, discovery, archive, videos folder, jobs,
/// language and logs). No environment variable is read: a <c>CHRONOS_*</c> variable set for a server never reaches the
/// desktop. The index is the desktop's (SQLite), the certificate a self-signed one.
/// </summary>
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;
}
/// <summary>The settings Chronos Desktop owns while it shares its library: the admin panel shows them locked.</summary>
public static IReadOnlyList<string> 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),
];
/// <summary>
/// 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.
/// </summary>
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<string, string>(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,
};
/// <summary><see cref="Validate"/> for <see cref="ForHosted"/>: no platform check, as the index is the desktop's.</summary>
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}.");
}
/// <summary>The database to open: <see cref="DbConnectionString"/>, the SQLite file in the data folder, or PostgreSQL from the parts.</summary>
public DatabaseOptions ToDatabaseOptions()
{
@@ -457,6 +572,31 @@ public sealed class ServerOptions
}
}
/// <summary>
/// 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. <see cref="ServerOptions.ForHosted"/> locks them in the admin panel.
/// </summary>
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<string, string> 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;
+1 -1
View File
@@ -3,7 +3,7 @@ using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting;
/// <summary>
/// <c>Chronos.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
/// <c>Chronos.Server.Host --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
/// HEALTHCHECK needs no curl/wget in the image.
/// </summary>
public static class HealthProbe
+168
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed record HostedEngine(ChronosDatabase Database, ArchiveService Archives, ProcessingService Processing, JobEngine Engine, Scheduler Scheduler,
Archive Archive);
/// <summary>
/// The server Chronos Desktop runs in its own process while it shares this PC's library (owner review 5, #67), built by
/// <see cref="ServerHost.BuildHosted"/>: 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 (<see cref="SequenceChangedAsync"/>, <see cref="ProjectsChangedAsync"/>).
/// </summary>
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<JobEngineHost>();
jobs.ChangedOutside += job => JobChangedOutside?.Invoke(job);
}
public ServerOptions Options { get; }
internal ServerState State { get; }
public IServiceProvider Services => _app.Services;
/// <summary>SHA-256 fingerprint of the certificate, colon hex, as clients see it the first time they connect.</summary>
public string? Fingerprint => State.TlsFingerprint;
/// <summary>The server's stable id (<see cref="Protocol.ServerInfo.ServerId"/>), kept in the desktop's index.</summary>
public Guid? ServerId => State.ServerId;
/// <summary>The events connected clients receive.</summary>
public EventHub Events => _app.Services.GetRequiredService<EventHub>();
/// <summary>The programs that used the server in the last minutes.</summary>
public ClientActivity Clients => _app.Services.GetRequiredService<ClientActivity>();
/// <summary>A render node changed a job's state, outside the desktop's engine.</summary>
public event Action<Job>? JobChangedOutside;
/// <summary>The port the HTTP listener got (the configured one, or the system's choice for 0); 0 before the start.</summary>
public int HttpPort { get; private set; }
/// <summary>The port the HTTPS listener got; 0 before the start or without a certificate.</summary>
public int HttpsPort { get; private set; }
/// <summary>The file that holds the first administrator's temporary password until it is changed.</summary>
public string AdminPasswordFile => Path.Combine(Options.DataPath, AdminBootstrap.PasswordFileName);
/// <summary>The first administrator's temporary password while its file exists; null once an administrator set their own.</summary>
public string? AdminPassword()
{
try
{
return File.Exists(AdminPasswordFile) ? File.ReadAllText(AdminPasswordFile).Trim() : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>Listens and starts the server's own services; a port in use throws (<see cref="IOException"/>).</summary>
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<IServer>().Features.Get<IServerAddressesFeature>()?.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;
}
}
/// <summary>Stops listening and the server's own services; the desktop's engines run on.</summary>
public async Task StopAsync(CancellationToken cancellationToken = default)
{
if (Volatile.Read(ref _started) == 0) return;
await _app.StopAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The desktop saved its settings: the parallelism, the priority queue, the language and the logs apply at once.</summary>
public void ApplyDesktop(HostedSettings desktop)
{
Options.ApplyDesktop(desktop);
_logging.Apply(Options);
}
/// <summary>The desktop's archive or processing service changed or made sequence <paramref name="id"/>: clients are told.</summary>
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
ServerEventBridge.SequenceChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, Services.GetService<ProjectCatchUp>(), id, change,
cancellationToken);
/// <summary>The desktop's archive service changed a sequence's projects: clients are told.</summary>
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, changed, cancellationToken);
/// <summary>The <c>uploads</c> clean-up step of the server: abandoned uploads and old upload records (the upload-cleanup schedule).</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
Services.GetRequiredService<UploadCleanupStep>().RunAsync(context, parameters);
/// <summary>The render nodes online now, by name.</summary>
public async Task<IReadOnlyList<string>> RenderNodesAsync(CancellationToken cancellationToken)
{
var since = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(Options.NodeTimeoutSeconds);
var nodes = await Services.GetRequiredService<ChronosDatabase>().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);
}
}
}
/// <summary>
/// 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.
/// </summary>
internal sealed class DesktopHostLifetime : IHostLifetime
{
public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -1,17 +1,11 @@
namespace Chronos.Server.Hosting;
/// <summary>What <c>Chronos.Server</c> was asked to do.</summary>
/// <summary>What <c>Chronos.Server.Host</c> was asked to do.</summary>
public enum ServerCommand
{
/// <summary>Run in the console (Docker, Linux, development).</summary>
Run,
/// <summary>Run under the Windows Service Control Manager (the command line the installed service uses).</summary>
Service,
InstallService,
UninstallService,
/// <summary>Probe <c>/health</c> of the local server and exit 0/1 (container health check).</summary>
HealthCheck,
@@ -24,12 +18,9 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
public const string Usage = """
Chronos Server — time-lapse archive, uploads, jobs and rendering.
Usage: Chronos.Server [--service | --install-service | --uninstall-service | --healthcheck | --help]
Usage: Chronos.Server.Host [--healthcheck | --help]
(no switch) run in the console until Ctrl+C
--service run under the Windows Service Control Manager
--install-service register the "ChronosServer" Windows service (automatic start, LocalSystem)
--uninstall-service stop and remove the Windows service
--healthcheck exit 0 when the local server answers /health, 1 otherwise
Configuration: /data/server.json (CHRONOS_DATA_PATH) overridden by environment variables:
@@ -72,9 +63,6 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
{
ServerCommand? parsed = arg switch
{
"--service" => ServerCommand.Service,
"--install-service" => ServerCommand.InstallService,
"--uninstall-service" => ServerCommand.UninstallService,
"--healthcheck" => ServerCommand.HealthCheck,
"--help" or "-h" or "-?" or "/?" => ServerCommand.Help,
_ => null,
+104 -22
View File
@@ -16,12 +16,13 @@ using Chronos.Server.Storage;
namespace Chronos.Server.Hosting;
/// <summary>
/// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Program, the Windows service
/// host and tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>,
/// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Chronos.Server.Host's Program and
/// tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>,
/// which runs before the server's own registrations: it must register <see cref="IArchiveIngest"/> and
/// <see cref="IFrameAssetLocator"/> (the server refuses to start without them), may add
/// <see cref="Chronos.Data.Jobs.IJobHandler"/>s, and may resolve <see cref="ChronosDatabase"/>, <see cref="ServerArchive"/>
/// and <see cref="ServerOptions"/> from DI in its factories.
/// and <see cref="ServerOptions"/> from DI in its factories. <see cref="BuildHosted"/> builds the same server over the index,
/// engines and scheduler of Chronos Desktop, which shares its library with it (owner review 5, #67).
/// </summary>
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
}
}
/// <summary>
/// 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 (<paramref name="engine"/>), which it never
/// creates, starts, stops or disposes. Its own state is in <see cref="ServerOptions.DataPath"/> (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.
/// </summary>
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);
}
/// <summary>Kestrel on every interface: the HTTP port, and the HTTPS port with HTTP/2 when there is a certificate.</summary>
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);
});
});
/// <summary>The app setting that holds the server's stable id (<see cref="ServerInfo.ServerId"/>).</summary>
public const string ServerIdKey = "server.id";
@@ -153,8 +205,12 @@ public static class ServerHost
return id;
}
/// <summary>The single composition root of the server's services.</summary>
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive)
/// <summary>
/// The single composition root of the server's services; with <paramref name="hosted"/>, those of the library Chronos
/// Desktop shares, whose engines, engine and scheduler are the desktop's (owner review 5, #67).
/// </summary>
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<VolumeSpace>();
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
services.Configure<HostOptions>(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<HostOptions>(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<SequenceJobs>();
services.AddSingleton<PlanCache>();
services.AddSingleton<RenderNodeService>();
services.AddSingleton<JobEngineHost>();
services.AddSingleton<ClientActivity>();
if (hosted is null) services.AddSingleton<JobEngineHost>();
else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService<EventHub>()));
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
services.AddSingleton<ServerScheduleHost>();
services.AddSingleton<SchedulerHost>();
if (hosted is null) services.AddSingleton<SchedulerHost>();
else services.AddSingleton(sp => new SchedulerHost(database, hosted.Scheduler, sp.GetRequiredService<ServerScheduleHost>(), options,
sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<SchedulerHost>>()));
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
services.AddSingleton<RenderNodeMonitor>();
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
services.AddSingleton<UploadMaintenance>();
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
// The desktop's archive service holds a step of its own that runs this one while it shares its library.
services.AddSingleton<UploadCleanupStep>();
services.AddSingleton<ICleanupStep>(sp => sp.GetRequiredService<UploadCleanupStep>());
// Main takes settings written outside the projects soon after they are (owner review 2, R8).
services.AddSingleton<ProjectCatchUp>();
services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>());
@@ -211,6 +275,22 @@ public static class ServerHost
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
}
/// <summary>
/// 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).
/// </summary>
private static void RegisterHosted(IServiceCollection services, HostedEngine hosted)
{
services.AddSingleton(hosted);
services.AddSingleton(hosted.Archives);
services.AddSingleton<IArchiveIngest>(hosted.Archives.Ingest);
services.AddSingleton<Chronos.Data.Videos.IVideoLibrary>(hosted.Archives.Videos);
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
services.AddSingleton(hosted.Processing);
services.AddSingleton<RenderNodeAvailability>();
services.AddSingleton<IHostLifetime, DesktopHostLifetime>();
}
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);
+11 -2
View File
@@ -33,12 +33,21 @@ public sealed class ServerLogging
private volatile MsLogLevel _console;
/// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary>
public ServerLogging(ServerOptions options)
/// <param name="options">The server's settings.</param>
/// <param name="setsEngineLevel">
/// Whether the levels also set the engine's <see cref="Log.MinimumLevel"/>: false when Chronos Desktop hosts the server
/// (owner review 5, #67), whose own log settings keep it.
/// </param>
public ServerLogging(ServerOptions options, bool setsEngineLevel = true)
{
SetsEngineLevel = setsEngineLevel;
Sink = new FileLogSink(options.LogPath, "server", FileOptions(options));
Apply(options);
}
/// <summary>The levels set the process's <see cref="Log.MinimumLevel"/> too (a server of its own, not one Chronos Desktop hosts).</summary>
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()
@@ -1,58 +0,0 @@
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Errors of the Windows service in the Application event log (source <c>ChronosServer</c>). 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.
/// </summary>
internal static unsafe class ServiceEventLog
{
public const uint StartFailed = 1;
public const uint StopFailed = 2;
/// <summary>ReportEvent takes at most 31,839 characters per string.</summary>
public const int MaxLength = 31_839;
/// <summary>
/// The event text: <paramref name="what"/> and the reason the server gave (the entry to check, for a refused data
/// folder), then the exception for a bug report; cut to <see cref="MaxLength"/>.
/// </summary>
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), "…");
}
/// <summary>Writes an error event; false when the event log could not be written (the console still gets it).</summary>
[SupportedOSPlatform("windows")]
public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text);
/// <summary><see cref="Error(uint, string)"/> as <paramref name="sourceName"/> (tests write as their own source).</summary>
[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);
}
}
}
@@ -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;
/// <summary>
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
/// (automatic start, LocalSystem, command line <c>"…\Chronos.Server.exe" --service</c>) or stops and removes it.
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. 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 <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
/// </summary>
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
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);
}
}
/// <summary>
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
/// </summary>
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;
}
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> 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<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
{
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;
}
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
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";
}
}
@@ -1,107 +0,0 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace Chronos.Server.Hosting.Windows;
/// <summary>Service Control Manager and event log functions of advapi32 (no Windows-only package needed).</summary>
[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]<uint, char**, void> 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]<uint, uint, nint, nint, uint> 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);
}
@@ -1,68 +0,0 @@
namespace Chronos.Server.Hosting.Windows;
/// <summary>SERVICE_STATUS.dwCurrentState values the server reports.</summary>
public enum ServiceState : uint
{
Stopped = 1,
StartPending = 2,
StopPending = 3,
Running = 4,
}
/// <summary>One status report for <c>SetServiceStatus</c>.</summary>
public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode);
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>Stopping from start-up or from running; repeating it reports progress (a higher check point).</summary>
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.");
}
}
@@ -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;
/// <summary>
/// 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 (<see cref="ServiceEventLog"/>), since a service has no console.
/// </summary>
[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<WebApplication>? _build;
private static WebApplication? _app;
private static nint _statusHandle;
/// <summary>
/// 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).
/// </summary>
public static unsafe bool Run(Func<WebApplication> 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);
}
}
+68 -8
View File
@@ -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 (<see cref="ISelectiveJobHandler"/>: 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 (<see cref="Exposes"/>):
/// the desktop's workspace, sync and download jobs stay its own.
/// </summary>
public sealed class JobEngineHost : IHostedService
{
private static readonly long ProgressInterval = Stopwatch.Frequency / 4;
private readonly ChronosDatabase _db;
private readonly EventHub _events;
private readonly HashSet<JobKind> _kinds;
private readonly Dictionary<Guid, long> _lastProgress = [];
private readonly Lock _gate = new();
private readonly bool _ownsEngine = true;
private int _subscribed;
public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> 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();
}
/// <summary>
/// Relays <paramref name="engine"/>, an engine Chronos Desktop runs (owner review 5, #67), from <see cref="StartAsync"/> to
/// <see cref="StopAsync"/>; the engine stays the desktop's.
/// </summary>
public JobEngineHost(JobEngine engine, EventHub events)
{
ArgumentNullException.ThrowIfNull(engine);
_events = events;
_ownsEngine = false;
_kinds = [];
Engine = engine;
}
/// <summary>Node id stamped on jobs this server runs.</summary>
@@ -51,15 +66,60 @@ public sealed class JobEngineHost : IHostedService
public JobEngine Engine { get; }
/// <summary>The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67).</summary>
public bool Hosted => !_ownsEngine;
/// <summary>True when a job of <paramref name="kind"/> has somewhere to run: a local handler, or render nodes for renders.</summary>
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);
/// <summary>
/// Whether the jobs API lists, shows and acts on jobs of <paramref name="kind"/>: every kind on a server of its own; on a
/// shared desktop library only the kinds a server runs (<see cref="ServerSettingsStore.Kinds"/>), so a client never sees or
/// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67).
/// </summary>
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;
}
/// <summary>
/// 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).
/// </summary>
public event Action<Job>? ChangedOutside;
/// <summary>Publishes a state change made outside the engine (render nodes, cancellation of node jobs).</summary>
public void Publish(Job job) => OnJobChanged(job);
public void Publish(Job job)
{
OnJobChanged(job);
ChangedOutside?.Invoke(job);
}
private void OnJobChanged(Job job)
{
+57 -7
View File
@@ -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 (<see cref="AuditRetentionAsync"/>) and sets it (<see cref="ApplyAuditRetentionAsync"/>);
/// <see cref="ServerOptions.AuditRetentionDays"/> 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 <see cref="ScheduleChangedEvent"/>.
/// variable fixes. Every schedule change and run goes out as a <see cref="ScheduleChangedEvent"/>. 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 (<see cref="ServerScheduleHost.ShareSchedules"/>) and never
/// starts, seeds the desktop's schedules for or disposes it.
/// </summary>
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<ScheduleDto> _changed;
private readonly Action<Guid> _deleted;
private readonly int _auditRetentionDays;
private int _stopped;
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger<SchedulerHost> 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;
}
/// <summary>
/// Follows <paramref name="scheduler"/>, the running scheduler of Chronos Desktop (owner review 5, #67), from
/// <see cref="StartAsync"/> to <see cref="StopAsync"/>.
/// </summary>
public SchedulerHost(ChronosDatabase db, Scheduler scheduler, ServerScheduleHost host, ServerOptions options, EventHub events, TimeProvider time,
ILogger<SchedulerHost> 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();
}
+17 -6
View File
@@ -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<SystemSchedule>
{
// 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;
}
}
/// <summary>
/// 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 <see cref="UploadSweepHours"/> hours and the audit log clean-up, nightly at 04:30, off at 0 days.
/// </summary>
public static IReadOnlyList<SystemSchedule> 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),
];
/// <summary>
/// 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.
-62
View File
@@ -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;
}
}
/// <summary>Entry point type, visible to the in-process test host.</summary>
public partial class Program;
@@ -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";
/// <summary>The file in the data folder that holds a generated temporary password until an administrator sets their own.</summary>
public const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken)
{
@@ -6,12 +6,15 @@ namespace Chronos.Server.Security;
/// <summary>
/// Resolves the caller of every <c>/api</c> request (bearer token or admin cookie) and enforces the endpoint's
/// <see cref="AccessRule"/>: 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 <see cref="ClientActivity"/> (owner review 5, #67).
/// </summary>
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<AccessRule>();
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);
}
@@ -0,0 +1,42 @@
using System.Collections.Concurrent;
namespace Chronos.Server.Security;
/// <summary>A program that used the server lately: its account, its name (the token's client), its address and when.</summary>
public sealed record ClientSeen(string User, string Client, string Address, DateTimeOffset LastSeen);
/// <summary>
/// The programs that used the server in the last <see cref="Window"/> (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; <see cref="AuthenticationMiddleware"/> records every signed-in request.
/// </summary>
public sealed class ClientActivity(TimeProvider time)
{
/// <summary>How long a program counts as active after its last request.</summary>
public static TimeSpan Window { get; } = TimeSpan.FromMinutes(5);
/// <summary>What a request signed in through the admin panel's cookie shows as its program.</summary>
public const string AdminPanel = "Admin panel";
private readonly ConcurrentDictionary<(Guid User, string Client, string Address), ClientSeen> _seen = new();
/// <summary>A signed-in request of <paramref name="caller"/> from <paramref name="address"/>.</summary>
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());
}
/// <summary>The programs seen in the last <see cref="Window"/>, the latest first; older entries are dropped.</summary>
public IReadOnlyList<ClientSeen> 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)];
}
}
+4 -20
View File
@@ -23,8 +23,6 @@ namespace Chronos.Server.Storage;
/// </summary>
public static class ArchiveModule
{
/// <summary>The change a conversion's Replace tells about a sequence (<c>sequenceChanged</c>).</summary>
private const string ConvertedChange = "converted";
/// <summary>Name the server writes into the archive's lease files.</summary>
public static string Owner { get; } = "server@" + Environment.MachineName;
@@ -40,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<ProjectCatchUp>()?.Touch(id);
},
// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that
// project checked out knows its home moved, the admin panel lists the projects again. Main's head written into the
// sequence's settings is a settings change for the clients that read those (an older client, a desktop's sync).
ProjectsChanged = async (changed, ct) =>
{
foreach (var change in changed.Changes)
events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
},
// 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<ProjectCatchUp>(), 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
@@ -45,13 +45,8 @@ public static class ProcessingModule
Host = EncoderHost.Server,
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().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<ProjectCatchUp>()?.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<ProjectCatchUp>(), id, change, ct),
});
});
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>());
@@ -45,6 +45,12 @@ public sealed class ServerArchive(Archive archive)
public Guid Id => _current.Id;
/// <summary>
/// Whether <paramref name="sequence"/> is one of this archive's (owner review 5, #67): an index may hold other archives,
/// whose items the API treats as unknown (<see cref="Api.ServedItems"/>).
/// </summary>
public bool Owns(Sequence? sequence) => sequence is not null && sequence.ArchiveId == Id;
public string Root => _current.RootPath;
/// <summary>
@@ -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 (<see cref="CheckStructure"/>).
/// </summary>
/// <summary>
/// Serves <paramref name="archive"/>, 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 (<see cref="CheckStructure"/>).
/// </summary>
public static ServerArchive ForArchive(Archive archive)
{
ArgumentNullException.ThrowIfNull(archive);
var served = new ServerArchive(archive);
served.CheckStructure();
return served;
}
public static async Task<ServerArchive> OpenAsync(ChronosDatabase db, ServerOptions options, CancellationToken cancellationToken)
{
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath));
@@ -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;
/// <summary>
/// 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 (<see cref="ArchiveModule"/>, <see cref="ProcessingModule"/>)
/// and on the library Chronos Desktop shares, whose engines are the desktop's (owner review 5, #67).
/// </summary>
public static class ServerEventBridge
{
/// <summary>The change a conversion's Replace tells about a sequence (<c>sequenceChanged</c>).</summary>
public const string ConvertedChange = "converted";
/// <summary>
/// A Reorganize, a conversion, a render or an analysis changed or made sequence <paramref name="id"/>: clients are told
/// (<c>sequenceChanged</c>), and a conversion's or an analysis's settings become Main's next version soon.
/// </summary>
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);
}
/// <summary>
/// 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).
/// </summary>
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));
}
}
@@ -41,6 +41,27 @@ public sealed class ConnectFlowTests
Assert.Contains(Fingerprint, server.Created[^1]);
}
/// <summary>Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted.</summary>
[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()
{
@@ -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;
/// <summary>Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts over its own index and engines.</summary>
[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<string, string, Task<string?>> 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<string> 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);
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<JobEngineHost>().Engine);
Assert.True(shared.Services.GetRequiredService<JobEngineHost>().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<string>().ToHashSet();
await using var shared = await desktop.ShareAsync();
var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().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");
}
/// <summary>A clock the test moves.</summary>
private sealed class ManualTime(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}
}
/// <summary>
/// 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.
/// </summary>
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<string, string>(), "en",
LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
public static async Task<DesktopFixture> 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<HostedServer> 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;
}
/// <summary>The first administrator, signed in with its temporary password, which it then replaces.</summary>
public async Task<HttpClient> 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<Sequence> 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<Job> 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();
}
/// <summary>A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.</summary>
private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
{
public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
public IReadOnlyList<string> CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
public bool DeepAnalysisAfterScan => false;
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult<Archive?>(archive);
public string? Unavailable(string action) => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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);
}
}