diff --git a/Chronos.slnx b/Chronos.slnx
index 58d06039..a81cf613 100644
--- a/Chronos.slnx
+++ b/Chronos.slnx
@@ -5,6 +5,7 @@
+
diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile
index 898fcb85..98104d1c 100644
--- a/deploy/docker/Dockerfile
+++ b/deploy/docker/Dockerfile
@@ -10,7 +10,8 @@ COPY src/Chronos.Core/ src/Chronos.Core/
COPY src/Chronos.Data/ src/Chronos.Data/
COPY src/Chronos.Protocol/ src/Chronos.Protocol/
COPY src/Chronos.Server/ src/Chronos.Server/
-RUN dotnet publish src/Chronos.Server/Chronos.Server.csproj \
+COPY src/Chronos.Server.Host/ src/Chronos.Server.Host/
+RUN dotnet publish src/Chronos.Server.Host/Chronos.Server.Host.csproj \
-c Release -a "$TARGETARCH" --no-self-contained \
-p:ChronosVersion="$CHRONOS_VERSION" -o /out \
&& rm -f /out/*.pdb
@@ -43,5 +44,5 @@ RUN chmod 0755 /usr/local/bin/chronos-entrypoint && mkdir -p /archive /data /vid
VOLUME ["/archive", "/data"]
EXPOSE 8080 8443
HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \
- CMD ["dotnet", "/app/Chronos.Server.dll", "--healthcheck"]
+ CMD ["dotnet", "/app/Chronos.Server.Host.dll", "--healthcheck"]
ENTRYPOINT ["/usr/local/bin/chronos-entrypoint"]
diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh
index 2bd812cd..5575060b 100755
--- a/deploy/docker/entrypoint.sh
+++ b/deploy/docker/entrypoint.sh
@@ -14,7 +14,7 @@ umask 002
# Help and the health probe touch neither folder.
case "${1:-}" in
- --help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.dll "$@" ;;
+ --help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.Host.dll "$@" ;;
esac
as_user() {
@@ -62,7 +62,7 @@ if [ "$(id -u)" = "0" ]; then
fi
fi
fi
- exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.dll "$@"
+ exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.Host.dll "$@"
fi
-exec dotnet /app/Chronos.Server.dll "$@"
+exec dotnet /app/Chronos.Server.Host.dll "$@"
diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx
index 019960a6..588d9922 100644
--- a/i18n/en/Admin.resx
+++ b/i18n/en/Admin.resx
@@ -869,6 +869,7 @@
WarningLimits and retentionSet by the environment variable {0}; remove the variable to change it here
+ Set in Chronos Desktop; change it in Settings on the PC that shares this libraryFile levelLeast severe level written to the log files; Debug and Trace help find problems but fill the files fastFile size (MB)
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 6b0eb1c2..da8fa47a 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -29,6 +29,10 @@
The sequence to render is no longer in the archive.Enter a server address such as nas.local:8443 or https://chronos.example.com.This file does not contain Chronos settings.
+ Sharing could not start: {0}
+ Open or create an archive before sharing it.
+ The library is not open yet; sharing starts once it is.
+ Port {0} is used by another program. Choose another one in Settings › Server.This PC or the server changed the sequence again; compare and choose again.The disk needs {0} GB more for this download.{0} gigabytes missing{0} render is no longer on this PC; the others were sent.{0} count
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 16dd7563..74fa448d 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -85,6 +85,7 @@
Not found.longThat address is not a Chronos Server.longThe plan converts nothing: every photo is skipped or every sequence is blocked.long
+ This address is this PC's own shared library, already open here.longChange your password first.longThe photo was deleted from the sequence while it was being uploaded, so it was not added.long{0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.long
@@ -134,6 +135,7 @@
ServerStatus{0} ms
+ Sharing off: nothing swept.longUploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}long: job log lineCancelPassword
@@ -197,6 +199,28 @@
Trail lengthTransitionsWB smoothing
+ Addresses
+ Admin panel
+ Admin password
+ {0} client
+ {0} clients
+ {0} · {1} · {2}
+ Clients
+ Copy
+ Fingerprint
+ Hide
+ None
+ Ports
+ HTTPS {0} · HTTP {1}
+ Render node
+ Restart
+ Sharing settings
+ Show
+ Not started
+ Not shared
+ Sharing
+ Starting…
+ This librarySign outConnectedConnecting…
diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx
index 38ce56ae..5a0a26d3 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -178,17 +178,27 @@
testing…Reset sectionSearch settings
+ Announce on LANServer cacheTrusted certificatesDefault server
+ LAN discoveryForget: {0}
+ HTTP port
+ HTTPS portKnown serversNoneOffer this PCOfflineOriginals folder
+ Public HTTP port
+ Public HTTPS portRender nodeServer ID
+ Sharing
+ Server data
+ Share this library
+ Library nameSigned inClearSpilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.long
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index ba8ca96d..a215375f 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -706,6 +706,18 @@
Editors import, edit and render; only admins manage usersUploaders send photos; editing needs an editorViewers browse and download
+ Open the admin panel in your browser to manage accounts; the browser warns once about the self-signed certificate: compare its fingerprint with the one here
+ Temporary password of the account admin; change it at the first sign-in, then this row goes
+ Programs that used this library in the last 5 minutes, and the render nodes online
+ Copy this address for the Uploader or another Chronos
+ Copy the fingerprint
+ Copy the temporary password
+ Clients see this fingerprint the first time they connect; it must match
+ The ports the shared library listens on
+ Try to start sharing again
+ Open Settings › Server to share this library
+ Show or hide the password
+ Whether other PCs and the Uploader can use this PC's library nowSign in; the token is stored encrypted for this Windows user · EnterSign out; the token is removed from this PCConnection to the server
@@ -778,10 +790,13 @@
Server Chronos connects to at start; changing it signs out · Enter applies, Esc revertsZip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left outHow much of the end of each log file the diagnostics bundle includes
+ Announce this library to Chronos programs on the local networkOpen the data this portable copy kept beside it before it ran from OneDrive. Chronos no longer uses it and leaves it as it isSave every setting as JSON, without the session tokenFile name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc revertsArchive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts
+ Port the shared library listens on for HTTP (8080 by default); a change restarts sharing · Enter applies, Esc reverts
+ Port the shared library listens on for HTTPS (8443 by default); a change restarts sharing · Enter applies, Esc revertsLoad settings from a JSON file; the session and the window layout stay as they areOpen the Microsoft Store page of this free or paid extension; Re-detect after installing itWhile Chronos is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses
@@ -804,7 +819,9 @@
Without this extension some formats are read only from their embedded preview, or not at all, on this PCFrames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc revertsOpen the data folder in Explorer
+ Open the shared library's data folder in ExplorerShow the workspace folder in Explorer
+ Port clients reach when a router forwards another port to this PC; empty: the one above · Enter applies, Esc revertsThis server's proxies, render-node files and staged imports, inside the cache folderServers this PC has signed in to, with the folders kept for eachNot signed in: its projects open from the workspace and wait to sync
@@ -822,7 +839,7 @@
Session rules, verification, duplicates, after-import actionsWhile Chronos is minimised or in the background, inserted cards, finished jobs and server messages also appear as Windows notificationsQuality profile, memory budget, parallelism, encoders
- Default server, render node, trusted certificates
+ Sharing, default server, render node, trusted certificatesCache folder, thumbnails in memory, cache limitUpdate check on startWhere projects are edited on this PC: the folder, sync and versions kept
@@ -851,6 +868,9 @@
Find a setting by nameEncode a short synthetic clip with every encoder and report pass or fail and speed · about a minuteSpeed on the synthetic 1280×720 test clip
+ Certificate, server settings, partial uploads and logs of the shared library; its accounts are in the index and its backups
+ Other PCs and the Uploader on your network use this PC's library as a Chronos Server, while Chronos runs and you are signed in
+ The name clients see on sign-in and in LAN discovery; empty: this PC's name · Enter applies, Esc revertsAlways the Microsoft software H.264 encoder; slower, identical everywhereRemember the folder and leave it as it isStars per megapixel from which a night frame counts as a star field · Enter applies, Esc reverts
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index e7032d65..aadfe0e3 100644
--- a/i18n/it/Admin.it.resx
+++ b/i18n/it/Admin.it.resx
@@ -862,6 +862,7 @@
AvvisoLimiti e conservazioneImpostato dalla variabile d'ambiente {0}; rimuovi la variabile per cambiarlo qui
+ Impostato in Chronos Desktop; cambialo nelle Impostazioni del PC che condivide questa libreriaLivello fileLivello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in frettaDimensione file (MB)
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 2000a8d5..d7d36ff4 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -29,6 +29,10 @@
La sequenza da renderizzare non è più nell'archivio.Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://chronos.example.com.Questo file non contiene impostazioni di Chronos.
+ Impossibile avviare la condivisione: {0}
+ Apri o crea un archivio prima di condividerlo.
+ La libreria non è ancora aperta; la condivisione parte appena lo è.
+ La porta {0} è usata da un altro programma. Scegline un'altra in Impostazioni › Server.La sequenza è cambiata di nuovo su questo PC o sul server; confronta e scegli di nuovo.Al disco servono altri {0} GB per questo scaricamento.{0} render non è più su questo PC; gli altri sono stati inviati.
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 7002d187..3d48946c 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -83,6 +83,7 @@
Non trovato.Questo indirizzo non è un Chronos Server.Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata.
+ Questo indirizzo è la libreria condivisa di questo PC, già aperta qui.longCambia prima la password.La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.longImpossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova.
@@ -132,6 +133,7 @@
ServerStato{0} ms
+ Condivisione spenta: nulla da ripulire.longCaricamenti scaduti: {0}, file rimossi: {1}, record rimossi: {2}, token rimossi: {3}long: job log lineAnnullaPassword
@@ -195,6 +197,28 @@
Lunghezza scieTransizioniLivellamento WB
+ Indirizzi
+ Pannello admin
+ Password admin
+ {0} client
+ {0} client
+ {0} · {1} · {2}
+ Client
+ Copia
+ Impronta
+ Nascondi
+ Nessuno
+ Porte
+ HTTPS {0} · HTTP {1}
+ Nodo di rendering
+ Riavvia
+ Impostazioni condivisione
+ Mostra
+ Non avviata
+ Non condivisa
+ In condivisione
+ Avvio…
+ Questa libreriaEsciConnessoConnessione…
diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx
index 0a78d616..ce776c93 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -175,17 +175,27 @@
in prova…Ripristina sezioneCerca impostazioni
+ Annuncia in LANCache del serverCertificati attendibiliServer predefinito
+ Rilevamento LANDimentica: {0}
+ Porta HTTP
+ Porta HTTPSServer notiNessunoOffri questo PCNon in lineaCartella originali
+ Porta HTTP pubblica
+ Porta HTTPS pubblicaNodo di renderingID server
+ Condivisione
+ Dati server
+ Condividi questa libreria
+ Nome libreriaConnessoSvuotaI fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 3ab4112f..11cd5543 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -777,6 +777,18 @@
Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utentiI caricatori inviano foto; per modificare serve un editorI visualizzatori sfogliano e scaricano
+ Apri il pannello admin nel browser per gestire gli account; il browser avvisa una volta del certificato autofirmato: confronta l'impronta con quella qui
+ Password temporanea dell'account admin; cambiala al primo accesso, poi questa riga sparisce
+ Programmi che hanno usato questa libreria negli ultimi 5 minuti, e i nodi di rendering online
+ Copia questo indirizzo per l'Uploader o un altro Chronos
+ Copia l'impronta
+ Copia la password temporanea
+ I client vedono questa impronta la prima volta che si connettono; deve coincidere
+ Le porte su cui ascolta la libreria condivisa
+ Riprova ad avviare la condivisione
+ Apri Impostazioni › Server per condividere questa libreria
+ Mostra o nascondi la password
+ Se altri PC e l'Uploader possono usare ora la libreria di questo PCAccedi; il token viene salvato cifrato per questo utente di Windows · InvioEsci; il token viene rimosso da questo PCConnessione al server
@@ -849,10 +861,13 @@
Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annullaComprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuoriQuanta parte finale di ogni file di log include il pacchetto di diagnostica
+ Annuncia questa libreria ai programmi Chronos della rete localeApri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Chronos non li usa più e li lascia com'eranoSalva tutte le impostazioni in JSON, senza il token di sessioneNome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annullaCartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla
+ Porta su cui la libreria condivisa ascolta in HTTP (8080 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla
+ Porta su cui la libreria condivisa ascolta in HTTPS (8443 di default); cambiarla riavvia la condivisione · Invio applica, Esc annullaCarica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariateApri la pagina del Microsoft Store di questa estensione, gratuita o a pagamento; dopo averla installata premi Rileva di nuovoMentre Chronos è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi
@@ -875,7 +890,9 @@
Senza questa estensione alcuni formati si leggono solo dall'anteprima incorporata, o per niente, su questo PCI fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annullaApri la cartella dati in Esplora file
+ Apri in Esplora risorse la cartella dati della libreria condivisaMostra la cartella dello spazio di lavoro in Esplora file
+ Porta che i client raggiungono quando un router inoltra un'altra porta a questo PC; vuoto: quella sopra · Invio applica, Esc annullaProxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cacheI server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascunoAccesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione
@@ -893,7 +910,7 @@
Lingua, tema, avvio, notificheRegole delle sessioni, verifica, duplicati, azioni dopo l'importazioneProfilo di qualità, memoria, parallelismo, encoder
- Server predefinito, nodo di rendering, certificati attendibili
+ Condivisione, server predefinito, nodo di rendering, certificati attendibiliCartella della cache, miniature in memoria, limite della cacheControllo degli aggiornamenti all'avvioDove si modificano i progetti su questo PC: cartella, sincronizzazione e versioni tenute
@@ -922,6 +939,9 @@
Trova un'impostazione per nomeCodifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minutoVelocità sulla clip di prova sintetica 1280×720
+ Certificato, impostazioni del server, upload parziali e log della libreria condivisa; i suoi account sono nell'indice e nei suoi backup
+ Altri PC e l'Uploader della tua rete usano la libreria di questo PC come Chronos Server, finché Chronos è aperto e hai effettuato l'accesso
+ Il nome che i client vedono all'accesso e nel rilevamento LAN; vuoto: il nome di questo PC · Invio applica, Esc annullaSempre l'encoder software H.264 di Microsoft; più lento, identico ovunqueRicorda la cartella e lasciala com'èStelle per megapixel da cui un fotogramma notturno conta come campo stellare · Invio applica, Esc annulla
diff --git a/src/Chronos.App/Chronos.App.csproj b/src/Chronos.App/Chronos.App.csproj
index be99345b..855311af 100644
--- a/src/Chronos.App/Chronos.App.csproj
+++ b/src/Chronos.App/Chronos.App.csproj
@@ -13,8 +13,13 @@
+
+
+
+
+
diff --git a/src/Chronos.App/DesignTime/SampleData.cs b/src/Chronos.App/DesignTime/SampleData.cs
index 27577fb2..5a42e65f 100644
--- a/src/Chronos.App/DesignTime/SampleData.cs
+++ b/src/Chronos.App/DesignTime/SampleData.cs
@@ -69,6 +69,36 @@ public sealed class SampleData
/// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga).
public Guid ProxiedSequenceId => _sunrise;
+ /// The certificate fingerprint of this PC's shared library in the captures.
+ public const string ShareFingerprint = "4F:0B:E2:91:7C:3A:D5:68:B0:1E:29:C7:83:5D:F4:A6:12:9E:7B:40:D8:6C:35:E1:A9:52:0F:BD:74:C3:86:2E";
+
+ /// Server › This library shared (owner review 5, #67): sample addresses, two clients, the temporary password.
+ public static void ShowShare(AppServices services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+ var pc = AppEnvironment.SamplePcName;
+ services.Share.ShowSample(ShareState.On, null,
+ [$"https://{pc}:8443", $"https://{pc}.studio.lan:8443", "https://192.168.1.20:8443", "https://100.88.14.3:8443"], 8443, 8080, ShareFingerprint,
+ "kT7p-Qm2x-Wf9r", [
+ new ShareClient("anna", "Chronos Uploader (ANNA-LAPTOP)", "192.168.1.31", Now.AddMinutes(-1)),
+ new ShareClient("admin", Chronos.Server.Security.ClientActivity.AdminPanel, "127.0.0.1", Now.AddMinutes(-3)),
+ ]);
+ }
+
+ /// Server › This library that could not start: the port is taken.
+ public static void ShowShareFailed(AppServices services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+ services.Share.ShowSample(ShareState.Failed, Loc.L("Errors.Share.PortInUse", 8443), [], 0, 0, null, null, []);
+ }
+
+ /// Server › This library not shared, as before .
+ public static void HideShare(AppServices services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+ services.Share.ShowSample(ShareState.Off, null, [], 0, 0, null, null, []);
+ }
+
/// Points the services at fakes (server, encoders, update check) for an empty first-run state.
public static SampleData Configure(AppServices services)
{
diff --git a/src/Chronos.App/Infrastructure/AppEnvironment.cs b/src/Chronos.App/Infrastructure/AppEnvironment.cs
index d97520bf..4edd9582 100644
--- a/src/Chronos.App/Infrastructure/AppEnvironment.cs
+++ b/src/Chronos.App/Infrastructure/AppEnvironment.cs
@@ -44,6 +44,16 @@ public sealed class AppEnvironment
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
+
+ /// The private folder of the server this PC runs while it shares its library: certificate, settings, uploads, logs.
+ public string ShareDirectory => Path.Combine(DataDirectory, "server");
+
+ /// The PC's name as the screens show it: a capture shows .
+ public string PcName => IsCapture ? SamplePcName : Environment.MachineName;
+
+ /// The PC name captures show.
+ public const string SamplePcName = "STUDIO-PC";
+
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs
index c88ee52b..98da75b6 100644
--- a/src/Chronos.App/Infrastructure/AppServices.cs
+++ b/src/Chronos.App/Infrastructure/AppServices.cs
@@ -74,6 +74,7 @@ public sealed class AppServices : IAsyncDisposable
// The editor's open and closed groups survive a restart (owner review 1, R3).
Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings);
_renderNode = new RenderNodeHost(StartRenderNode);
+ Share = new LibraryShare(this);
ArchiveSetup = new EngineArchiveSetup(this);
Sync = new SyncHost(this);
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
@@ -114,6 +115,7 @@ public sealed class AppServices : IAsyncDisposable
{
if (_server is not null) _server.PropertyChanged -= OnServerChanged;
_server = value;
+ _server.IsOwnLibrary = Share.IsOwn;
_server.PropertyChanged += OnServerChanged;
UpdateRenderNode();
Sync.Update();
@@ -123,6 +125,9 @@ public sealed class AppServices : IAsyncDisposable
/// Sync with the signed-in server: engine, job connection, background comparison.
public SyncHost Sync { get; }
+ /// Settings › Server › Share this library: this PC's library served to the LAN while Chronos runs (owner review 5, #67).
+ public LibraryShare Share { get; }
+
///
/// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), or replaced its
/// frames' files (a conversion), with the sequence's id (any thread): an open editor reads it again where and as it is now.
@@ -239,6 +244,7 @@ public sealed class AppServices : IAsyncDisposable
SaveSettingsAction();
UpdateRenderNode();
ApplyJobSettings();
+ if (!Environment.IsCapture) Share.Apply();
}
/// Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).
@@ -329,6 +335,8 @@ public sealed class AppServices : IAsyncDisposable
{
await _stopping.CancelAsync().ConfigureAwait(false);
await _schedules.ConfigureAwait(false);
+ // First: the shared library's clients and its subscriptions to the engine and the scheduler go before they do.
+ await Share.DisposeAsync().ConfigureAwait(false);
_schedulerReady.TrySetResult(false);
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
_stopping.Dispose();
@@ -361,6 +369,7 @@ public sealed class AppServices : IAsyncDisposable
await StartSchedulerAsync(ct).ConfigureAwait(false);
if (reopen is null)
{
+ await Share.StartAsync(ct).ConfigureAwait(false);
await ScanNowAsync(started, ct).ConfigureAwait(false);
return;
}
@@ -369,6 +378,7 @@ public sealed class AppServices : IAsyncDisposable
{
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
+ await Share.StartAsync(ct).ConfigureAwait(false);
await ScanNowAsync(null, ct).ConfigureAwait(false);
Scheduler?.Wake();
return;
@@ -559,19 +569,24 @@ public sealed class AppServices : IAsyncDisposable
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
// The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c).
+ // The shared library's upload-cleanup schedule runs on this PC's scheduler (owner review 5, #67).
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)),
- new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)],
+ new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace), new ShareUploadsStep(() => Share)],
BackupDirectory = Environment.BackupDirectory,
- // Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs.
- SequenceChanged = (id, _, _) =>
+ // While the library is shared, its clients see thumbnails and proxies of what a scan finds, as a server's do.
+ ImagesAfterScanWhen = () => Share.IsOn,
+ // Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job
+ // runs; the shared library's clients are told too.
+ SequenceChanged = (id, change, token) =>
{
SequenceReorganized?.Invoke(id);
- return Task.CompletedTask;
+ return Share.SequenceChangedAsync(id, change, token);
},
+ ProjectsChanged = (changed, token) => Share.ProjectsChangedAsync(changed, token),
};
Archives = new ArchiveService(database, archive);
// The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5).
- Archives.Videos.ProtectedFolders = () => [Workspace.Root];
+ Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder];
Archives.Videos.Servers = Sync;
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
@@ -602,6 +617,8 @@ public sealed class AppServices : IAsyncDisposable
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
+ // A render or an advice recorded on this PC reaches the shared library's clients (owner review 5, #67).
+ SequenceChanged = (id, change, token) => Share.SequenceChangedAsync(id, change, token),
Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount,
CacheStore.Folder(Environment, Settings)),
};
diff --git a/src/Chronos.App/Infrastructure/AppSettings.cs b/src/Chronos.App/Infrastructure/AppSettings.cs
index 0e41bd62..b4a56044 100644
--- a/src/Chronos.App/Infrastructure/AppSettings.cs
+++ b/src/Chronos.App/Infrastructure/AppSettings.cs
@@ -88,6 +88,40 @@ public sealed class KnownServer
public DateTimeOffset LastSeen { get; set; }
}
+///
+/// Settings › Server › Sharing (owner review 5, #67): this PC's library served to the LAN by the server Chronos hosts
+/// while it runs. Absent in a 1.0 settings file: off, on Docker's ports.
+///
+public sealed class ShareSettings
+{
+ public const int DefaultHttpsPort = 8443;
+ public const int DefaultHttpPort = 8080;
+
+ public bool Enabled { get; set; }
+
+ /// The name clients see; empty: this PC's name.
+ public string? Name { get; set; }
+
+ public int HttpsPort { get; set; } = DefaultHttpsPort;
+ public int HttpPort { get; set; } = DefaultHttpPort;
+
+ /// The ports clients reach when a router forwards others to this PC; null: the ones above.
+ public int? PublicHttpsPort { get; set; }
+
+ public int? PublicHttpPort { get; set; }
+
+ /// Announce the library to Chronos programs on the local network.
+ public bool Discovery { get; set; } = true;
+
+ /// What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.
+ public bool SameEndpoint(ShareSettings other)
+ {
+ ArgumentNullException.ThrowIfNull(other);
+ return string.Equals(Name?.Trim() ?? string.Empty, other.Name?.Trim() ?? string.Empty, StringComparison.Ordinal) && HttpsPort == other.HttpsPort &&
+ HttpPort == other.HttpPort && PublicHttpsPort == other.PublicHttpsPort && PublicHttpPort == other.PublicHttpPort && Discovery == other.Discovery;
+ }
+}
+
///
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// settings.json next to the database and written atomically, because language and theme apply before the
@@ -292,6 +326,9 @@ public sealed class AppSettings
/// The known server of ; null when this PC has none.
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
+ /// Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).
+ public ShareSettings Share { get; set; } = new();
+
/// Let the server send render jobs to this PC (BRIEF §14.7).
public bool RenderNodeOptIn { get; set; }
diff --git a/src/Chronos.App/Jobs/DesktopScheduleHost.cs b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
index 3a378ce3..25f622f8 100644
--- a/src/Chronos.App/Jobs/DesktopScheduleHost.cs
+++ b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
@@ -67,6 +67,8 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
diff --git a/src/Chronos.App/Sections/ServerView.xaml b/src/Chronos.App/Sections/ServerView.xaml
index 3e039e1c..180f271e 100644
--- a/src/Chronos.App/Sections/ServerView.xaml
+++ b/src/Chronos.App/Sections/ServerView.xaml
@@ -5,7 +5,8 @@
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
xmlns:shell="clr-namespace:Chronos.App.Shell"
- xmlns:srv="clr-namespace:Chronos.App.Server">
+ xmlns:srv="clr-namespace:Chronos.App.Server"
+ xmlns:sec="clr-namespace:Chronos.App.Sections">
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -167,7 +241,7 @@
-
+
diff --git a/src/Chronos.App/Sections/ServerViewModel.cs b/src/Chronos.App/Sections/ServerViewModel.cs
index c2d33220..7525030b 100644
--- a/src/Chronos.App/Sections/ServerViewModel.cs
+++ b/src/Chronos.App/Sections/ServerViewModel.cs
@@ -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);
}
/// Sequences of this PC and of the server, where they stand and what can be done.
public SyncTableViewModel Sync { get; }
+ /// This PC's library shared to the LAN (owner review 5, #67).
+ 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();
}
diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml
index 299d4d7d..665a6299 100644
--- a/src/Chronos.App/Sections/SettingsView.xaml
+++ b/src/Chronos.App/Sections/SettingsView.xaml
@@ -635,6 +635,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 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
/// Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.
public LogSettingsRows Logs { get; }
+ /// Settings › Server › Sharing: this PC's library shared to the LAN (owner review 5, #67).
+ 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();
diff --git a/src/Chronos.App/Sections/SharePanelViewModel.cs b/src/Chronos.App/Sections/SharePanelViewModel.cs
new file mode 100644
index 00000000..387b2300
--- /dev/null
+++ b/src/Chronos.App/Sections/SharePanelViewModel.cs
@@ -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;
+
+/// An address of the shared library with its Copy button.
+public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
+
+///
+/// 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 on the UI thread; the clients are read again every few seconds.
+///
+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; }
+
+ /// Sharing is on in the settings, whether it runs or not: the details show.
+ 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 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;
+
+ /// The temporary password, masked until Show.
+ 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");
+
+ /// "anna · Chronos Uploader · 192.168.1.20", the latest first.
+ public IReadOnlyList 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();
+ }
+}
diff --git a/src/Chronos.App/Server/ConnectFlow.cs b/src/Chronos.App/Server/ConnectFlow.cs
index a20d7d70..1eea1e0d 100644
--- a/src/Chronos.App/Server/ConnectFlow.cs
+++ b/src/Chronos.App/Server/ConnectFlow.cs
@@ -75,6 +75,9 @@ public enum ConnectError
/// The certificate differs from the trusted one; the saved session was dropped.
CertificateChanged,
Failed,
+
+ /// The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.
+ OwnLibrary,
}
///
@@ -112,6 +115,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
/// Raised after every step change.
public event EventHandler? Changed;
+ ///
+ /// 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.
+ ///
+ public Func? IsOwnLibrary { get; set; }
+
/// Identifies the server at : ends in AwaitingTrust, AwaitingCredentials or Failed.
public async Task 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);
}
diff --git a/src/Chronos.App/Server/LibraryShare.cs b/src/Chronos.App/Server/LibraryShare.cs
new file mode 100644
index 00000000..a27a8cf7
--- /dev/null
+++ b/src/Chronos.App/Server/LibraryShare.cs
@@ -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;
+
+/// Where sharing this PC's library stands (Server › This library).
+public enum ShareState
+{
+ /// Settings › Server › Share this library is off.
+ Off,
+
+ Starting,
+
+ /// The library is served: clients connect to .
+ On,
+
+ /// Sharing is on in the settings but could not start: says why.
+ Failed,
+}
+
+/// A program that used the shared library lately, as the Server section lists it.
+public sealed record ShareClient(string User, string Program, string Address, DateTimeOffset? LastSeen);
+
+///
+/// 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 (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).
+///
+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 _addresses = [];
+ private IReadOnlyList _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();
+ }
+ }
+
+ /// True while the library is served.
+ public bool IsOn => _state == ShareState.On;
+
+ /// One sentence on why sharing did not start; null otherwise.
+ public string? Reason
+ {
+ get => _reason;
+ private set => Set(ref _reason, value);
+ }
+
+ /// The addresses clients reach this library at, one per name and network address of this PC.
+ public IReadOnlyList Addresses
+ {
+ get => _addresses;
+ private set => Set(ref _addresses, value);
+ }
+
+ /// The certificate's SHA-256 fingerprint, colon hex, as clients see it on their first connection.
+ public string? Fingerprint
+ {
+ get => _fingerprint;
+ private set => Set(ref _fingerprint, value);
+ }
+
+ /// The port the HTTPS listener got; 0 while not shared.
+ public int HttpsPort
+ {
+ get => _httpsPort;
+ private set => Set(ref _httpsPort, value);
+ }
+
+ /// The port the HTTP listener got; 0 while not shared.
+ public int HttpPort
+ {
+ get => _httpPort;
+ private set => Set(ref _httpPort, value);
+ }
+
+ /// The first administrator's temporary password while its file exists; null once an administrator set their own.
+ public string? AdminPassword
+ {
+ get => _adminPassword;
+ private set => Set(ref _adminPassword, value);
+ }
+
+ /// The programs of the last minutes and the render nodes online ().
+ public IReadOnlyList Clients
+ {
+ get => _clients;
+ private set => Set(ref _clients, value);
+ }
+
+ /// The server while the library is served (tests, the change bridge); null otherwise.
+ public HostedServer? Server => _server;
+
+ /// The private folder of the shared library's own state: certificate, settings, partial uploads, logs.
+ public string Folder => _services.Environment.ShareDirectory;
+
+ /// The state changed (any thread).
+ public event Action? Changed;
+
+ ///
+ /// 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 with its .
+ ///
+ 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();
+ }
+ }
+
+ /// Stops sharing (the desktop's engines run on); the state reads as the settings say.
+ public async Task StopAsync()
+ {
+ await _gate.WaitAsync().ConfigureAwait(false);
+ try
+ {
+ await StopCoreAsync().ConfigureAwait(false);
+ State = ShareState.Off;
+ Reason = null;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ /// Stops sharing if it runs and starts it again (Server › Restart, a new port or archive).
+ 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();
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ 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());
+ }
+
+ /// True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself.
+ 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);
+ }
+
+ /// Reads the programs of the last minutes, the render nodes online and the temporary password again.
+ 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();
+ }
+
+ /// The uploads clean-up step while sharing (): the server's sweep, or nothing.
+ public Task SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
+ _server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff"));
+
+ /// The desktop's archive or processing service changed sequence : the clients are told.
+ public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
+ _server is { } server ? server.SequenceChangedAsync(id, change, cancellationToken) : Task.CompletedTask;
+
+ /// The desktop's archive service changed a sequence's projects: the clients are told.
+ public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
+ _server is { } server ? server.ProjectsChangedAsync(changed, cancellationToken) : Task.CompletedTask;
+
+ /// Capture and design time: a shared library with sample values, no server.
+ internal void ShowSample(ShareState state, string? reason, IReadOnlyList addresses, int httpsPort, int httpPort, string? fingerprint,
+ string? adminPassword, IReadOnlyList 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();
+ }
+ }
+
+ /// The addresses of on this PC: its name, its full name, and each network address that is up.
+ public static IReadOnlyList AddressesOf(int port)
+ {
+ var hosts = new List { 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;
+ }
+
+ /// The desktop's values the shared library takes: Settings › Server, Rendering, Videos and Advanced › Logs.
+ 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(s.JobPriorities, StringComparer.OrdinalIgnoreCase), Loc.Culture.TwoLetterISOLanguageName,
+ s.LogLevel, s.LogRetentionDays, s.LogMaxFileMb, s.LogMaxTotalMb, s.LogRotation, s.DiagnosticsLogMb);
+ }
+
+ /// The sentence for a start that failed; null for an exception that is not an expected failure.
+ 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;
+ }
+
+ /// The configured port another program listens on (the HTTPS one when neither can be told).
+ 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);
+ }
+
+ /// A render node changed a job outside the engine: the Jobs section follows it as it follows the engine's own changes.
+ private void OnJobChangedOutside(Chronos.Core.Model.Job job) => JobChangedOutside?.Invoke(job);
+
+ /// A render node changed a job's state outside this PC's engine (any thread).
+ public event Action? JobChangedOutside;
+
+ /// Runs a fire-and-forget step, logging what it throws.
+ 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);
+ }
+ }
+}
+
+///
+/// The desktop's clean-up step uploads (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.
+///
+public sealed class ShareUploadsStep(Func share) : ICleanupStep
+{
+ public string Name => Chronos.Server.Storage.UploadCleanupStep.StepName;
+
+ public Task RunAsync(CleanupContext context, CleanupParameters parameters) => share().SweepUploadsAsync(context, parameters);
+}
diff --git a/src/Chronos.App/Server/ServerApi.cs b/src/Chronos.App/Server/ServerApi.cs
index a1e719fb..ba85d515 100644
--- a/src/Chronos.App/Server/ServerApi.cs
+++ b/src/Chronos.App/Server/ServerApi.cs
@@ -70,7 +70,8 @@ public sealed class DpapiTokenProtector : ITokenProtector
}
/// A Chronos Server announced on the LAN.
-public sealed record DiscoveredServer(string Name, string Address);
+/// A server announced on the LAN; is its beacon's certificate fingerprint, if any.
+public sealed record DiscoveredServer(string Name, string Address, string? Fingerprint = null);
///
/// Listens for the server's UDP beacon () 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;
diff --git a/src/Chronos.App/Server/ServerSession.cs b/src/Chronos.App/Server/ServerSession.cs
index 34d0786c..cfd9d707 100644
--- a/src/Chronos.App/Server/ServerSession.cs
+++ b/src/Chronos.App/Server/ServerSession.cs
@@ -32,6 +32,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
public ConnectFlow Flow => _flow;
+ /// True for this PC's own shared library (by fingerprint or server id): never connected to, never listed as found.
+ public Func? IsOwnLibrary
+ {
+ get => _flow.IsOwnLibrary;
+ set => _flow.IsOwnLibrary = value;
+ }
+
/// Servers that announced themselves on this network.
public ObservableCollection 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);
};
diff --git a/src/Chronos.App/Settings/ShareSettingsRows.cs b/src/Chronos.App/Settings/ShareSettingsRows.cs
new file mode 100644
index 00000000..fe3c13e0
--- /dev/null
+++ b/src/Chronos.App/Settings/ShareSettingsRows.cs
@@ -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;
+
+///
+/// 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 (), which restarts on a new name, port or
+/// announcement. The rows read each time: Reset and Import replace it.
+///
+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();
+ }
+ }
+
+ /// The name clients see while is empty: this PC's.
+ public string PcName { get; }
+
+ /// The shared library's private folder, as the screens show paths.
+ public string Folder { get; }
+
+ public ICommand OpenFolderCommand { get; }
+
+ /// Settings › Server › Reset: sharing off, on the default ports.
+ public void Reset()
+ {
+ _settings.Share = new ShareSettings();
+ Refresh();
+ }
+
+ /// Shows the values as they are now (after Reset all, Import, or a reset of the page).
+ 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 read, Action 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 read, Action 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));
+}
diff --git a/src/Chronos.App/Shell/ScreenCapture.cs b/src/Chronos.App/Shell/ScreenCapture.cs
index 2062d953..0547c1d2 100644
--- a/src/Chronos.App/Shell/ScreenCapture.cs
+++ b/src/Chronos.App/Shell/ScreenCapture.cs
@@ -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);
diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
index a0249ea1..51ca8a08 100644
--- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs
+++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
@@ -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.
///
- private SequenceStatus Uncovered => _writer.Options.ImagesAfterScan ? CoveringStatus : SequenceStatus.None;
+ private SequenceStatus Uncovered => _writer.Options.QueuesImagesAfterScan ? CoveringStatus : SequenceStatus.None;
///
/// The projects of a sequence brought in line with their sidecars (), under its lease, in the
diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs
index 74dad4f4..78650e1f 100644
--- a/src/Chronos.Data/Archiving/ArchiveService.cs
+++ b/src/Chronos.Data/Archiving/ArchiveService.cs
@@ -104,8 +104,8 @@ public sealed class ArchiveService : IJobHandlerProvider
///
public IReadOnlyList 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 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.
diff --git a/src/Chronos.Data/Archiving/FrameTrash.cs b/src/Chronos.Data/Archiving/FrameTrash.cs
index d1f496b3..900c3cac 100644
--- a/src/Chronos.Data/Archiving/FrameTrash.cs
+++ b/src/Chronos.Data/Archiving/FrameTrash.cs
@@ -627,7 +627,7 @@ public sealed partial class FrameTrash
var label = sequence.DisplayTitle;
List 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));
diff --git a/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs
index d571b3fd..3258470f 100644
--- a/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs
+++ b/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs
@@ -21,11 +21,11 @@ internal static class JobArchive
/// . Checkpoint: after:<folder>, 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 asks. On the
-/// server (, ) the sequences it indexed
+/// server (, , 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 () have nothing to analyse or draw yet and are left out.
///
-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? 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);
diff --git a/src/Chronos.Data/Archiving/SequenceWriter.cs b/src/Chronos.Data/Archiving/SequenceWriter.cs
index 042066fb..b0d8c211 100644
--- a/src/Chronos.Data/Archiving/SequenceWriter.cs
+++ b/src/Chronos.Data/Archiving/SequenceWriter.cs
@@ -26,6 +26,16 @@ public sealed record ArchiveServiceOptions
///
public bool ImagesAfterScan { get; init; }
+ ///
+ /// Whether holds now, read at every scan and trash restore (owner review 5, #67): Chronos
+ /// Desktop makes thumbnails and proxies after its scans while it shares its library, as a server does. Null: the fixed
+ /// .
+ ///
+ public Func? ImagesAfterScanWhen { get; init; }
+
+ /// as it is now, else .
+ public bool QueuesImagesAfterScan => ImagesAfterScanWhen?.Invoke() ?? ImagesAfterScan;
+
///
/// The index may hold settings newer than a sequence's project.json: the server, whose PATCH wrote the
/// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two
diff --git a/src/Chronos.Server.Host/Chronos.Server.Host.csproj b/src/Chronos.Server.Host/Chronos.Server.Host.csproj
new file mode 100644
index 00000000..e7445bf5
--- /dev/null
+++ b/src/Chronos.Server.Host/Chronos.Server.Host.csproj
@@ -0,0 +1,17 @@
+
+
+
+ Exe
+ net10.0
+ Chronos.Server.Host
+ Chronos.Server.Host
+ $(ChronosIconDir)chronos-server.ico
+ true
+ false
+
+
+
+
+
+
diff --git a/src/Chronos.Server.Host/Program.cs b/src/Chronos.Server.Host/Program.cs
new file mode 100644
index 00000000..40ff87a8
--- /dev/null
+++ b/src/Chronos.Server.Host/Program.cs
@@ -0,0 +1,30 @@
+using Chronos.Server.Configuration;
+using Chronos.Server.Hosting;
+using Chronos.Server.Storage;
+
+var command = ServerCommandLine.Parse(args);
+if (command.Error is not null)
+{
+ await Console.Error.WriteLineAsync(command.Error);
+ return 2;
+}
+
+switch (command.Command)
+{
+ case ServerCommand.Help:
+ Console.WriteLine(ServerCommandLine.Usage);
+ return 0;
+ case ServerCommand.HealthCheck:
+ return await HealthProbe.RunAsync();
+ default:
+ var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
+ await app.RunAsync();
+ return 0;
+}
+
+// The archive engine, then analysis and managed rendering over it.
+static void RegisterModules(IServiceCollection services)
+{
+ ArchiveModule.Register(services);
+ ProcessingModule.Register(services);
+}
diff --git a/src/Chronos.Server/Admin/web/pages/settings.js b/src/Chronos.Server/Admin/web/pages/settings.js
index 76039383..e6f7fb79 100644
--- a/src/Chronos.Server/Admin/web/pages/settings.js
+++ b/src/Chronos.Server/Admin/web/pages/settings.js
@@ -49,7 +49,9 @@ export async function render(root, { api, info, setMeta, actions }) {
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
- const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
+ // Chronos Desktop owns the settings of the library it shares (owner review 5, #67): no variable names them.
+ const lockTip = (name) => variable(name) === "desktop" ? t("Admin.Settings.LockedByDesktop.Tip") : t("Admin.Settings.Locked.Tip", variable(name));
+ const lock = (name) => locked(name) ? `disabled title="${attr(lockTip(name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => ``;
const number = (name, value, attrs = "") => field(name, ``);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, ``);
diff --git a/src/Chronos.Server/Api/JobEndpoints.cs b/src/Chronos.Server/Api/JobEndpoints.cs
index 9f40e190..d1ce3f6a 100644
--- a/src/Chronos.Server/Api/JobEndpoints.cs
+++ b/src/Chronos.Server/Api/JobEndpoints.cs
@@ -32,8 +32,8 @@ public static class JobEndpoints
var jobs = api.MapGroup("/jobs").Requires(Permissions.Read);
jobs.MapGet("", ListAsync);
jobs.MapPost("", CreateAsync);
- jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db) =>
- await db.Jobs.GetAsync(id, context.RequestAborted) is { } job
+ jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db, JobEngineHost host) =>
+ await db.Jobs.GetAsync(id, context.RequestAborted) is { } job && host.Exposes(job.Kind)
? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto)
: ApiErrors.NotFound(context, "job"));
jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, ChronosDatabase db, JobEngineHost host) =>
@@ -47,7 +47,7 @@ public static class JobEndpoints
jobs.MapPost("/{id:guid}/priority", PriorityAsync);
}
- private static async Task ListAsync(HttpContext context, ChronosDatabase db, string? state, string? kind, string? cursor, int? limit)
+ private static async Task ListAsync(HttpContext context, ChronosDatabase db, JobEngineHost host, string? state, string? kind, string? cursor, int? limit)
{
JobState? stateFilter = null;
JobKind? kindFilter = null;
@@ -62,8 +62,10 @@ public static class JobEndpoints
kindFilter = k;
}
// A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none.
+ if (kindFilter is { } wanted && !host.Exposes(wanted)) return Results.Json(new Page([], null, null), ProtocolJson.Default.PageJobDto);
var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
- return Results.Json(new Page([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
+ // A shared desktop library lists the kinds a server runs alone (owner review 5, #67); the cursor still pages the whole list.
+ return Results.Json(new Page([.. page.Items.Where(j => host.Exposes(j.Kind)).Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
}
private static async Task CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
@@ -90,7 +92,7 @@ public static class JobEndpoints
var titles = new List(ids.Count);
foreach (var id in ids)
{
- if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
+ if (await ServedItems.SequenceAsync(db, archive, id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
titles.Add(sequence.DisplayTitle);
}
targets = ids;
@@ -99,7 +101,11 @@ public static class JobEndpoints
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
if (kind == JobKind.Render)
{
- if (ParseRender(request.ParametersJson) is not { } parsed) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
+ if (ParseRender(request.ParametersJson) is not { } given) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
+ // A client's export folder means nothing to the server, and on a shared desktop library it would be anywhere the
+ // desktop's user may write (owner review 5, #67): a render always goes to the sequence's exports.
+ var parsed = WithoutExportFolder(given);
+ if (!ReferenceEquals(parsed, given)) request = request with { ParametersJson = JsonSerializer.Serialize(parsed, ProtocolJson.Default.RenderJobParameters) };
// A render of a project version (owner review 2, R8): of the sequence's projects, a project alone pinned to its head.
var (render, missing) = await ProjectRenderAsync(db, archives, targets[0], parsed, ct);
if (missing is not null) return ApiErrors.NotFound(context, missing);
@@ -221,7 +227,9 @@ public static class JobEndpoints
private static async Task ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func action)
{
var ct = context.RequestAborted;
- if (await db.Jobs.GetAsync(id, ct) is not { } job) return ApiErrors.NotFound(context, "job");
+ // A shared desktop library's own jobs (workspace, sync, downloads) are not the server's (owner review 5, #67).
+ if (await db.Jobs.GetAsync(id, ct) is not { } job || !context.RequestServices.GetRequiredService().Exposes(job.Kind))
+ return ApiErrors.NotFound(context, "job");
if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context);
if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State));
await action(job, ct);
@@ -230,6 +238,20 @@ public static class JobEndpoints
}
/// Render parameters, or null when they are missing or incomplete.
+ ///
+ /// without the export folder its preset names (key folder, any case), or the same
+ /// instance when it names none (owner review 5, #67).
+ ///
+ public static RenderJobParameters WithoutExportFolder(RenderJobParameters parameters)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
+ if (System.Text.Json.Nodes.JsonNode.Parse(parameters.PresetJson) is not System.Text.Json.Nodes.JsonObject preset) return parameters;
+ var folders = preset.Select(p => p.Key).Where(k => k.Equals("folder", StringComparison.OrdinalIgnoreCase)).ToList();
+ if (folders.Count == 0) return parameters;
+ foreach (var key in folders) preset.Remove(key);
+ return parameters with { PresetJson = preset.ToJsonString() };
+ }
+
public static RenderJobParameters? ParseRender(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
diff --git a/src/Chronos.Server/Api/LibraryEndpoints.cs b/src/Chronos.Server/Api/LibraryEndpoints.cs
index f4af700c..cc187a19 100644
--- a/src/Chronos.Server/Api/LibraryEndpoints.cs
+++ b/src/Chronos.Server/Api/LibraryEndpoints.cs
@@ -219,7 +219,8 @@ public static class LibraryEndpoints
var allowed = new List();
foreach (var id in ids)
{
- if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found");
+ if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService().Owns(sequence))
+ items[id] = Skip(context, id, "not_found");
else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden");
else allowed.Add(sequence);
}
@@ -337,7 +338,8 @@ public static class LibraryEndpoints
{
for (var attempt = 0; attempt < 3; attempt++)
{
- if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found");
+ if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService().Owns(sequence))
+ return Skip(context, id, "not_found");
var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList();
tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase)));
if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request");
diff --git a/src/Chronos.Server/Api/ServedItems.cs b/src/Chronos.Server/Api/ServedItems.cs
new file mode 100644
index 00000000..98786421
--- /dev/null
+++ b/src/Chronos.Server/Api/ServedItems.cs
@@ -0,0 +1,90 @@
+using Microsoft.AspNetCore.Routing.Patterns;
+using Chronos.Core.Model;
+using Chronos.Data;
+using Chronos.Server.Storage;
+
+namespace Chronos.Server.Api;
+
+///
+/// The served archive's items alone (owner review 5, #67): an index may hold several archives (Chronos Desktop's, which
+/// shares one of them, also keeps the archives of other servers' originals), and a sequence, frame, render or video of
+/// another one answers 404 as an unknown id would, on every route that names one and in every body that lists them.
+/// The rule holds on a server of its own too, whose index holds one archive.
+///
+public static class ServedItems
+{
+ /// What the id in a route names, by the route's prefix and the id's name.
+ private static readonly (string Prefix, string Value, ItemKind Kind)[] Routes =
+ [
+ ("/api/v1/sequences/{id", "id", ItemKind.Sequence),
+ ("/api/v1/sequences/{sid", "sid", ItemKind.Sequence),
+ ("/api/v1/frames/{id", "id", ItemKind.Frame),
+ ("/api/v1/renders/{id", "id", ItemKind.Render),
+ ("/api/v1/videos/{id", "id", ItemKind.Render),
+ ];
+
+ private enum ItemKind
+ {
+ Sequence,
+ Frame,
+ Render,
+ }
+
+ /// The endpoint filter of the API group: an id of another archive's item answers 404 before the endpoint runs.
+ public static async ValueTask
public sealed class JobEngineHost : IHostedService
{
private static readonly long ProgressInterval = Stopwatch.Frequency / 4;
- private readonly ChronosDatabase _db;
private readonly EventHub _events;
private readonly HashSet _kinds;
private readonly Dictionary _lastProgress = [];
private readonly Lock _gate = new();
+ private readonly bool _ownsEngine = true;
+ private int _subscribed;
public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options,
EventHub events)
{
- _db = db;
_events = events;
// A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList();
@@ -42,8 +45,20 @@ public sealed class JobEngineHost : IHostedService
Kinds = _kinds,
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
});
- Engine.JobChanged += OnJobChanged;
- Engine.Progress += OnProgress;
+ Subscribe();
+ }
+
+ ///
+ /// Relays , an engine Chronos Desktop runs (owner review 5, #67), from to
+ /// ; the engine stays the desktop's.
+ ///
+ public JobEngineHost(JobEngine engine, EventHub events)
+ {
+ ArgumentNullException.ThrowIfNull(engine);
+ _events = events;
+ _ownsEngine = false;
+ _kinds = [];
+ Engine = engine;
}
/// Node id stamped on jobs this server runs.
@@ -51,15 +66,60 @@ public sealed class JobEngineHost : IHostedService
public JobEngine Engine { get; }
+ /// The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67).
+ public bool Hosted => !_ownsEngine;
+
/// True when a job of has somewhere to run: a local handler, or render nodes for renders.
- public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind);
+ public bool CanRun(JobKind kind) => kind == JobKind.Render || (_ownsEngine ? _kinds.Contains(kind) : Engine.CanRun(kind) && Exposes(kind));
- public Task StartAsync(CancellationToken cancellationToken) => Engine.StartAsync(cancellationToken);
+ ///
+ /// Whether the jobs API lists, shows and acts on jobs of : every kind on a server of its own; on a
+ /// shared desktop library only the kinds a server runs (), so a client never sees or
+ /// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67).
+ ///
+ public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind);
- public async Task StopAsync(CancellationToken cancellationToken) => await Engine.DisposeAsync();
+ public Task StartAsync(CancellationToken cancellationToken)
+ {
+ if (_ownsEngine) return Engine.StartAsync(cancellationToken);
+ Subscribe();
+ return Task.CompletedTask;
+ }
+
+ public async Task StopAsync(CancellationToken cancellationToken)
+ {
+ if (_ownsEngine)
+ {
+ await Engine.DisposeAsync();
+ return;
+ }
+ // The desktop's engine runs on: only this server stops following it.
+ if (Interlocked.Exchange(ref _subscribed, 0) == 1)
+ {
+ Engine.JobChanged -= OnJobChanged;
+ Engine.Progress -= OnProgress;
+ }
+ }
+
+ private void Subscribe()
+ {
+ if (Interlocked.Exchange(ref _subscribed, 1) == 1) return;
+ Engine.JobChanged += OnJobChanged;
+ Engine.Progress += OnProgress;
+ }
+
+ ///
+ /// A job's state changed outside the engine (render nodes, cancellation of node jobs): Chronos Desktop's Jobs section
+ /// follows these as it follows its engine's own changes while it shares its library (owner review 5, #67).
+ ///
+ public event Action? ChangedOutside;
/// Publishes a state change made outside the engine (render nodes, cancellation of node jobs).
- public void Publish(Job job) => OnJobChanged(job);
+ public void Publish(Job job)
+ {
+ OnJobChanged(job);
+ ChangedOutside?.Invoke(job);
+ }
private void OnJobChanged(Job job)
{
diff --git a/src/Chronos.Server/Jobs/SchedulerHost.cs b/src/Chronos.Server/Jobs/SchedulerHost.cs
index 8d8ae5e8..f5dd3a2e 100644
--- a/src/Chronos.Server/Jobs/SchedulerHost.cs
+++ b/src/Chronos.Server/Jobs/SchedulerHost.cs
@@ -19,7 +19,10 @@ namespace Chronos.Server.Jobs;
/// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step:
/// Settings › Logs shows it () and sets it ();
/// is only what the schedule is seeded and reset with, or what an environment
-/// variable fixes. Every schedule change and run goes out as a .
+/// variable fixes. Every schedule change and run goes out as a . On the library Chronos
+/// Desktop shares (owner review 5, #67) the scheduler is the desktop's, already running: this host follows it while the
+/// server runs, adds the server's own system schedules to it () and never
+/// starts, seeds the desktop's schedules for or disposes it.
///
public sealed class SchedulerHost : IHostedService
{
@@ -29,6 +32,10 @@ public sealed class SchedulerHost : IHostedService
private readonly CancellationTokenSource _stopping = new();
private Task _startScan = Task.CompletedTask;
private Task _refresh = Task.CompletedTask;
+ private readonly bool _ownsScheduler = true;
+ private readonly Action _changed;
+ private readonly Action _deleted;
+ private readonly int _auditRetentionDays;
private int _stopped;
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger logger)
@@ -41,8 +48,31 @@ public sealed class SchedulerHost : IHostedService
Host = host;
Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time });
// The Scheduled tab of the admin panel follows them, the runs that queue no job included.
- Scheduler.ScheduleChanged += schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
- Scheduler.ScheduleDeleted += id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
+ _changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
+ _deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
+ Scheduler.ScheduleChanged += _changed;
+ Scheduler.ScheduleDeleted += _deleted;
+ }
+
+ ///
+ /// Follows , the running scheduler of Chronos Desktop (owner review 5, #67), from
+ /// to .
+ ///
+ public SchedulerHost(ChronosDatabase db, Scheduler scheduler, ServerScheduleHost host, ServerOptions options, EventHub events, TimeProvider time,
+ ILogger logger)
+ {
+ ArgumentNullException.ThrowIfNull(scheduler);
+ ArgumentNullException.ThrowIfNull(options);
+ ArgumentNullException.ThrowIfNull(events);
+ _db = db;
+ _time = time;
+ _logger = logger;
+ _ownsScheduler = false;
+ _auditRetentionDays = options.AuditRetentionDays;
+ Host = host;
+ Scheduler = scheduler;
+ _changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
+ _deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
}
public Scheduler Scheduler { get; }
@@ -51,10 +81,21 @@ public sealed class SchedulerHost : IHostedService
public async Task StartAsync(CancellationToken cancellationToken)
{
- var started = Scheduler.Options.Time.GetUtcNow();
- await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
var stopping = _stopping.Token;
- _startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
+ if (!_ownsScheduler)
+ {
+ Scheduler.ScheduleChanged += _changed;
+ Scheduler.ScheduleDeleted += _deleted;
+ // The desktop seeds its own system schedules; the server's state brings two more (never overwritten once there).
+ if (await _db.Schedules.EnsureSystemAsync(ServerScheduleHost.ShareSchedules(_auditRetentionDays), _time.GetUtcNow(), cancellationToken) > 0)
+ Scheduler.Wake();
+ }
+ else
+ {
+ var started = Scheduler.Options.Time.GetUtcNow();
+ await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
+ _startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
+ }
// Created here, so its first period counts from the start.
var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time);
_refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None);
@@ -66,7 +107,16 @@ public sealed class SchedulerHost : IHostedService
await _stopping.CancelAsync();
await _startScan;
await _refresh;
- await Scheduler.DisposeAsync();
+ if (_ownsScheduler)
+ {
+ await Scheduler.DisposeAsync();
+ }
+ else
+ {
+ // The desktop's scheduler runs on: only this server stops following it.
+ Scheduler.ScheduleChanged -= _changed;
+ Scheduler.ScheduleDeleted -= _deleted;
+ }
_stopping.Dispose();
}
diff --git a/src/Chronos.Server/Jobs/ServerScheduleHost.cs b/src/Chronos.Server/Jobs/ServerScheduleHost.cs
index 0cffda9a..9a37aa86 100644
--- a/src/Chronos.Server/Jobs/ServerScheduleHost.cs
+++ b/src/Chronos.Server/Jobs/ServerScheduleHost.cs
@@ -66,13 +66,13 @@ public sealed class ServerScheduleHost : IScheduleHost
{
get
{
- var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0), Audit: new TimeOnly(4, 30));
+ var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0));
+ var share = ShareSchedules(_options.AuditRetentionDays);
var list = new List
{
// A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start.
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false),
- new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
- new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
+ share[0],
};
// PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once
// when the newest copy is a day old, as the daily loop it replaced made one at start.
@@ -83,13 +83,24 @@ public sealed class ServerScheduleHost : IScheduleHost
}
list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History),
new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory])));
- var audit = _options.AuditRetentionDays;
- list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit),
- new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0));
+ list.Add(share[1]);
return list;
}
}
+ ///
+ /// The system schedules of a server's own state, which Chronos Desktop adds to its own while it shares its library
+ /// (owner review 5, #67), the archive scan, the index backup and the housekeeping being the desktop's: the uploads sweep
+ /// every hours and the audit log clean-up, nightly at 04:30, off at 0 days.
+ ///
+ public static IReadOnlyList ShareSchedules(int auditRetentionDays) =>
+ [
+ new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
+ new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
+ new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(new TimeOnly(4, 30)),
+ new ScheduleParametersDto(OlderThanDays: auditRetentionDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: auditRetentionDays > 0),
+ ];
+
///
/// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as
/// the former polling did; while it is offline, or the file cannot be read, as the index has it.
diff --git a/src/Chronos.Server/Program.cs b/src/Chronos.Server/Program.cs
deleted file mode 100644
index 7c19fafd..00000000
--- a/src/Chronos.Server/Program.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System.ComponentModel;
-using Chronos.Server.Configuration;
-using Chronos.Server.Hosting;
-using Chronos.Server.Hosting.Windows;
-using Chronos.Server.Storage;
-
-var command = ServerCommandLine.Parse(args);
-if (command.Error is not null)
-{
- await Console.Error.WriteLineAsync(command.Error);
- return 2;
-}
-
-switch (command.Command)
-{
- case ServerCommand.Help:
- Console.WriteLine(ServerCommandLine.Usage);
- return 0;
- case ServerCommand.HealthCheck:
- return await HealthProbe.RunAsync();
- case ServerCommand.Service or ServerCommand.InstallService or ServerCommand.UninstallService when !OperatingSystem.IsWindows():
- await Console.Error.WriteLineAsync("Windows services are available on Windows only.");
- return 2;
- case ServerCommand.InstallService when OperatingSystem.IsWindows():
- return ServiceAction(ServiceInstaller.Install, $"Installed the {WindowsServiceHost.ServiceName} service.");
- case ServerCommand.UninstallService when OperatingSystem.IsWindows():
- return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service.");
- case ServerCommand.Service when OperatingSystem.IsWindows():
- if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0;
- await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start ChronosServer'.");
- return 1;
- default:
- var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
- await app.RunAsync();
- return 0;
-}
-
-// The archive engine, then analysis and managed rendering over it.
-static void RegisterModules(IServiceCollection services)
-{
- ArchiveModule.Register(services);
- ProcessingModule.Register(services);
-}
-
-static int ServiceAction(Action action, string done)
-{
- try
- {
- action();
- Console.WriteLine(done);
- return 0;
- }
- catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
- {
- // Win32: the Service Control Manager's reason; InvalidOperation: a folder the service must not run from.
- Console.Error.WriteLine(ex.Message);
- return 1;
- }
-}
-
-/// Entry point type, visible to the in-process test host.
-public partial class Program;
diff --git a/src/Chronos.Server/Security/AdminBootstrap.cs b/src/Chronos.Server/Security/AdminBootstrap.cs
index bdb69966..3ddfe773 100644
--- a/src/Chronos.Server/Security/AdminBootstrap.cs
+++ b/src/Chronos.Server/Security/AdminBootstrap.cs
@@ -16,7 +16,8 @@ namespace Chronos.Server.Security;
public static class AdminBootstrap
{
public const string DefaultUsername = "admin";
- private const string PasswordFileName = "initial-admin-password.txt";
+ /// The file in the data folder that holds a generated temporary password until an administrator sets their own.
+ public const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken)
{
diff --git a/src/Chronos.Server/Security/AuthenticationMiddleware.cs b/src/Chronos.Server/Security/AuthenticationMiddleware.cs
index 322801dc..834c4585 100644
--- a/src/Chronos.Server/Security/AuthenticationMiddleware.cs
+++ b/src/Chronos.Server/Security/AuthenticationMiddleware.cs
@@ -6,12 +6,15 @@ namespace Chronos.Server.Security;
///
/// Resolves the caller of every /api request (bearer token or admin cookie) and enforces the endpoint's
/// : 401 without a valid token, 403 for a missing permission, a missing CSRF header on a
-/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known.
+/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. Every request it
+/// lets through is noted in (owner review 5, #67).
///
public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens)
{
- public async Task InvokeAsync(HttpContext context)
+ public async Task InvokeAsync(HttpContext context, ClientActivity activity)
{
+ ArgumentNullException.ThrowIfNull(context);
+ ArgumentNullException.ThrowIfNull(activity);
var rule = context.GetEndpoint()?.Metadata.GetMetadata();
if (rule is null && !context.Request.Path.StartsWithSegments("/api"))
{
@@ -48,6 +51,8 @@ public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService
return;
}
context.Features.Set(caller);
+ var address = context.Connection.RemoteIpAddress;
+ activity.Record(caller, (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString());
await next(context);
}
diff --git a/src/Chronos.Server/Security/ClientActivity.cs b/src/Chronos.Server/Security/ClientActivity.cs
new file mode 100644
index 00000000..6994b414
--- /dev/null
+++ b/src/Chronos.Server/Security/ClientActivity.cs
@@ -0,0 +1,42 @@
+using System.Collections.Concurrent;
+
+namespace Chronos.Server.Security;
+
+/// A program that used the server lately: its account, its name (the token's client), its address and when.
+public sealed record ClientSeen(string User, string Client, string Address, DateTimeOffset LastSeen);
+
+///
+/// The programs that used the server in the last (owner review 5, #67): Chronos Desktop shows them in
+/// its Server section while it shares its library, and asks before it stops sharing while there are any. Kept in memory
+/// only; records every signed-in request.
+///
+public sealed class ClientActivity(TimeProvider time)
+{
+ /// How long a program counts as active after its last request.
+ public static TimeSpan Window { get; } = TimeSpan.FromMinutes(5);
+
+ /// What a request signed in through the admin panel's cookie shows as its program.
+ public const string AdminPanel = "Admin panel";
+
+ private readonly ConcurrentDictionary<(Guid User, string Client, string Address), ClientSeen> _seen = new();
+
+ /// A signed-in request of from .
+ public void Record(Caller caller, string? address)
+ {
+ ArgumentNullException.ThrowIfNull(caller);
+ var client = caller.Source == CredentialSource.Cookie ? AdminPanel : string.IsNullOrWhiteSpace(caller.ClientName) ? "?" : caller.ClientName.Trim();
+ var from = string.IsNullOrEmpty(address) ? "?" : address;
+ _seen[(caller.Id, client, from)] = new ClientSeen(caller.User.Username, client, from, time.GetUtcNow());
+ }
+
+ /// The programs seen in the last , the latest first; older entries are dropped.
+ public IReadOnlyList Recent()
+ {
+ var since = time.GetUtcNow() - Window;
+ foreach (var (key, seen) in _seen)
+ {
+ if (seen.LastSeen < since) _seen.TryRemove(new KeyValuePair<(Guid, string, string), ClientSeen>(key, seen));
+ }
+ return [.. _seen.Values.Where(s => s.LastSeen >= since).OrderByDescending(s => s.LastSeen)];
+ }
+}
diff --git a/src/Chronos.Server/Storage/ArchiveModule.cs b/src/Chronos.Server/Storage/ArchiveModule.cs
index 7776227b..6aeddd69 100644
--- a/src/Chronos.Server/Storage/ArchiveModule.cs
+++ b/src/Chronos.Server/Storage/ArchiveModule.cs
@@ -23,8 +23,6 @@ namespace Chronos.Server.Storage;
///
public static class ArchiveModule
{
- /// The change a conversion's Replace tells about a sequence (sequenceChanged).
- private const string ConvertedChange = "converted";
/// Name the server writes into the archive's lease files.
public static string Owner { get; } = "server@" + Environment.MachineName;
@@ -40,24 +38,10 @@ public static class ArchiveModule
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
var service = new ArchiveService(db, new ArchiveServiceOptions
{
- // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3).
- SequenceChanged = async (id, change, ct) =>
- {
- if (await db.Sequences.GetAsync(id, ct) is { } sequence)
- events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
- // A conversion may leave settings Main has not taken yet (owner review 2, R8).
- if (change == ConvertedChange) sp.GetService()?.Touch(id);
- },
- // Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that
- // project checked out knows its home moved, the admin panel lists the projects again. Main's head written into the
- // sequence's settings is a settings change for the clients that read those (an older client, a desktop's sync).
- ProjectsChanged = async (changed, ct) =>
- {
- foreach (var change in changed.Changes)
- events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
- if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct) is { } sequence)
- events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
- },
+ // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3), and
+ // every change of a sequence's projects reaches them too (owner review 2, R8).
+ SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService(), id, change, ct),
+ ProjectsChanged = (changed, ct) => ServerEventBridge.ProjectsChangedAsync(db, events, changed, ct),
Decoder = DecoderFactory.CreateServer(),
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
// (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages
diff --git a/src/Chronos.Server/Storage/ProcessingModule.cs b/src/Chronos.Server/Storage/ProcessingModule.cs
index 5314e46b..e46f485e 100644
--- a/src/Chronos.Server/Storage/ProcessingModule.cs
+++ b/src/Chronos.Server/Storage/ProcessingModule.cs
@@ -45,13 +45,8 @@ public static class ProcessingModule
Host = EncoderHost.Server,
AwaitsRenderNode = sp.GetRequiredService().AwaitsNodeAsync,
ProducedBy = options.ServerName,
- SequenceChanged = async (id, change, ct) =>
- {
- if (await db.Sequences.GetAsync(id, ct) is { } sequence)
- events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
- // Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
- if (change == ProcessingOptions.SettingsChange) sp.GetService()?.Touch(id);
- },
+ // Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
+ SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService(), id, change, ct),
});
});
services.AddSingleton(sp => sp.GetRequiredService());
diff --git a/src/Chronos.Server/Storage/ServerArchive.cs b/src/Chronos.Server/Storage/ServerArchive.cs
index 8b48633a..e0cf658e 100644
--- a/src/Chronos.Server/Storage/ServerArchive.cs
+++ b/src/Chronos.Server/Storage/ServerArchive.cs
@@ -45,6 +45,12 @@ public sealed class ServerArchive(Archive archive)
public Guid Id => _current.Id;
+ ///
+ /// Whether is one of this archive's (owner review 5, #67): an index may hold other archives,
+ /// whose items the API treats as unknown ().
+ ///
+ public bool Owns(Sequence? sequence) => sequence is not null && sequence.ArchiveId == Id;
+
public string Root => _current.RootPath;
///
@@ -87,6 +93,18 @@ public sealed class ServerArchive(Archive archive)
/// (and relinked if it moved), any other folder becomes a new archive with the default templates. Either way the
/// folders of the archive's layout are made ().
///
+ ///
+ /// Serves , an archive Chronos Desktop already opened (owner review 5, #67): nothing is adopted,
+ /// the folders of its layout are made as at a server's start ().
+ ///
+ public static ServerArchive ForArchive(Archive archive)
+ {
+ ArgumentNullException.ThrowIfNull(archive);
+ var served = new ServerArchive(archive);
+ served.CheckStructure();
+ return served;
+ }
+
public static async Task OpenAsync(ChronosDatabase db, ServerOptions options, CancellationToken cancellationToken)
{
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath));
diff --git a/src/Chronos.Server/Storage/ServerEventBridge.cs b/src/Chronos.Server/Storage/ServerEventBridge.cs
new file mode 100644
index 00000000..5715812b
--- /dev/null
+++ b/src/Chronos.Server/Storage/ServerEventBridge.cs
@@ -0,0 +1,48 @@
+using Chronos.Data;
+using Chronos.Data.Processing;
+using Chronos.Data.Projects;
+using Chronos.Protocol;
+using Chronos.Server.Events;
+
+namespace Chronos.Server.Storage;
+
+///
+/// What the archive and processing engines tell about sequences and projects, as events for connected clients (BRIEF
+/// §14.3; owner review 2, R8): the same on a server of its own (, )
+/// and on the library Chronos Desktop shares, whose engines are the desktop's (owner review 5, #67).
+///
+public static class ServerEventBridge
+{
+ /// The change a conversion's Replace tells about a sequence (sequenceChanged).
+ public const string ConvertedChange = "converted";
+
+ ///
+ /// A Reorganize, a conversion, a render or an analysis changed or made sequence : clients are told
+ /// (sequenceChanged), and a conversion's or an analysis's settings become Main's next version soon.
+ ///
+ public static async Task SequenceChangedAsync(ChronosDatabase db, EventHub events, ProjectCatchUp? projects, Guid id, string change, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(db);
+ ArgumentNullException.ThrowIfNull(events);
+ if (await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) is { } sequence)
+ events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
+ // A conversion may leave settings Main has not taken yet, and an analysis writes Auto values (owner review 2, R8).
+ if (change is ConvertedChange or ProcessingOptions.SettingsChange) projects?.Touch(id);
+ }
+
+ ///
+ /// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that project
+ /// checked out knows its home moved, the admin panel lists the projects again. Main's head written into the sequence's
+ /// settings is a settings change for the clients that read those (an older client, a desktop's sync).
+ ///
+ public static async Task ProjectsChangedAsync(ChronosDatabase db, EventHub events, ProjectChangeSet changed, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(db);
+ ArgumentNullException.ThrowIfNull(events);
+ ArgumentNullException.ThrowIfNull(changed);
+ foreach (var change in changed.Changes)
+ events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
+ if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct).ConfigureAwait(false) is { } sequence)
+ events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
+ }
+}
diff --git a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs
index 1e492f39..e67fb7a0 100644
--- a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs
+++ b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs
@@ -41,6 +41,27 @@ public sealed class ConnectFlowTests
Assert.Contains(Fingerprint, server.Created[^1]);
}
+ /// Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted.
+ [Test]
+ public async Task ThisPcsOwnSharedLibraryIsRefused()
+ {
+ var server = new FakeServer { SelfSigned = true };
+ var trust = new MemoryTrust();
+ using var flow = new ConnectFlow(server, trust) { IsOwnLibrary = (fingerprint, _) => fingerprint == Fingerprint };
+ Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
+ Assert.Equal(ConnectError.OwnLibrary, flow.Error);
+ Assert.Null(flow.PendingFingerprint);
+ Assert.Empty(trust.Fingerprints);
+
+ trust.Trust("https://localhost:8443", Fingerprint);
+ Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
+ Assert.Equal(ConnectError.OwnLibrary, flow.Error);
+ Assert.Equal(0, server.Logins);
+
+ flow.IsOwnLibrary = (_, _) => false;
+ Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("localhost:8443"));
+ }
+
[Test]
public async Task RejectingTheCertificateSendsNothing()
{
diff --git a/tests/Chronos.App.Tests/Server/LibraryShareTests.cs b/tests/Chronos.App.Tests/Server/LibraryShareTests.cs
new file mode 100644
index 00000000..3bb06529
--- /dev/null
+++ b/tests/Chronos.App.Tests/Server/LibraryShareTests.cs
@@ -0,0 +1,192 @@
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Net.Sockets;
+using Chronos.App.Infrastructure;
+using Chronos.App.Jobs;
+using Chronos.App.Server;
+using Chronos.App.Tests.Uploader;
+using Chronos.Core.Localization;
+using Chronos.Data;
+using Chronos.Data.Archiving;
+using Chronos.Server.Jobs;
+using Chronos.Testing;
+
+namespace Chronos.App.Tests.Server;
+
+/// Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts over its own index and engines.
+[WindowsOnly]
+[Serial] // the hosted server's logging and Kestrel share the process with the other tests' Log sink
+[Timeout(180_000)]
+public sealed class LibraryShareTests
+{
+ private sealed class NoDialogs : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => false;
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+
+ [Test]
+ public void A10SettingsFileSharesNothingOnDockersPortsAndResetTurnsSharingOff()
+ {
+ var settings = Assert.NotNull(AppSettings.Parse("""{ "Language": "en" }"""));
+ Assert.False(settings.Share.Enabled);
+ Assert.Equal((8443, 8080, true), (settings.Share.HttpsPort, settings.Share.HttpPort, settings.Share.Discovery));
+ Assert.Null(settings.Share.PublicHttpsPort);
+
+ settings.Share.Enabled = true;
+ settings.Share.HttpsPort = 9443;
+ var copy = Assert.NotNull(AppSettings.Parse(settings.ToJson()));
+ Assert.True(copy.Share.Enabled);
+ Assert.Equal(9443, copy.Share.HttpsPort);
+ Assert.False(settings.ResetKeepingState().Share.Enabled);
+ Assert.Equal(8443, settings.ResetKeepingState().Share.HttpsPort);
+ }
+
+ [Test]
+ public void TheSharedLibrarysCleanUpsAreScheduledOnlyWhileSharing()
+ {
+ var settings = new AppSettings();
+ var host = new DesktopScheduleHost(settings, () => null, () => null);
+ Assert.False(host.SystemSchedules.Any(s => s.SystemKey == ServerScheduleHost.UploadCleanup));
+ settings.Share.Enabled = true;
+ var keys = host.SystemSchedules.Select(s => s.SystemKey).ToList();
+ Assert.Contains(ServerScheduleHost.UploadCleanup, keys);
+ Assert.Contains(ServerScheduleHost.AuditCleanup, keys);
+ Assert.Contains(DesktopScheduleHost.ArchiveScan, keys);
+ }
+
+ [Test]
+ public void SharingStartsAfterTheSchedulesOnTheDesktopsEngineAndStopsFirst()
+ {
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ var root = await ArchiveAsync(environment);
+ var (https, http) = (FreePort(), FreePort());
+ var settings = Settings(root, https, http);
+ var services = new AppServices(environment, settings, () => { }, new NoDialogs());
+ try
+ {
+ await services.OpenAsync(environment.DatabasePath);
+ Assert.True(await services.SchedulerReady, "the schedules started");
+ await WaitAsync(services.Share, ShareState.On);
+
+ var share = services.Share;
+ Assert.Equal((https, http), (share.HttpsPort, share.HttpPort));
+ Assert.True(share.Addresses.Count > 0, "addresses");
+ Assert.True(share.Addresses.All(a => a.StartsWith("https://", StringComparison.Ordinal) && a.EndsWith($":{https}", StringComparison.Ordinal)),
+ string.Join(", ", share.Addresses));
+ var fingerprint = Assert.NotNull(share.Fingerprint);
+ Assert.True(share.IsOwn(fingerprint, null), "own by fingerprint");
+ Assert.True(share.IsOwn(null, share.Server!.ServerId), "own by id");
+ Assert.False(share.IsOwn("00:11", Guid.NewGuid()), "another server");
+ Assert.NotNull(share.AdminPassword);
+ Assert.Same(services.Engine, share.Server.Services.GetService(typeof(JobEngineHost)) is JobEngineHost jobs ? jobs.Engine : null);
+ using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
+ {
+ using var health = await client.GetAsync($"http://127.0.0.1:{http}/health");
+ Assert.Equal(HttpStatusCode.OK, health.StatusCode);
+ }
+ Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup));
+ Assert.True(Directory.Exists(environment.ShareDirectory), "the share's folder");
+
+ // Stopped, the engine and the index run on; started again, the same certificate.
+ await share.StopAsync();
+ Assert.Equal(ShareState.Off, share.State);
+ Assert.Null(share.Server);
+ Assert.NotNull(await services.Database.Archives.ListAsync());
+ await share.RestartAsync();
+ Assert.Equal(ShareState.On, share.State);
+ Assert.Equal(fingerprint, share.Fingerprint);
+
+ // Sharing turned off in Settings stops it.
+ settings.Share.Enabled = false;
+ share.Apply();
+ await WaitAsync(share, ShareState.Off);
+ }
+ finally
+ {
+ Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
+ }
+ Assert.Null(services.Share.Server);
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
+
+ [Test]
+ public void APortInUseLeavesSharingNotStartedNamingThePort()
+ {
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ var root = await ArchiveAsync(environment);
+ // Held as another server would (both address families, exclusively): Windows lets a second program share a port otherwise.
+ using var taken = new TcpListener(IPAddress.IPv6Any, 0) { ExclusiveAddressUse = true };
+ taken.Server.DualMode = true;
+ taken.Start();
+ var https = ((IPEndPoint)taken.LocalEndpoint).Port;
+ var services = new AppServices(environment, Settings(root, https, FreePort()), () => { }, new NoDialogs());
+ try
+ {
+ await services.OpenAsync(environment.DatabasePath);
+ Assert.True(await services.SchedulerReady, "the schedules started");
+ await WaitAsync(services.Share, ShareState.Failed);
+ Assert.Equal(Loc.L("Errors.Share.PortInUse", https), services.Share.Reason);
+ Assert.Null(services.Share.Server);
+ Assert.False(services.Share.IsOwn(null, null), "nothing shared");
+ }
+ finally
+ {
+ Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
+ }
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
+
+ private static AppSettings Settings(string root, int https, int http) => new()
+ {
+ Language = "en",
+ LastArchivePath = root,
+ Share = new ShareSettings { Enabled = true, HttpsPort = https, HttpPort = http, Discovery = false },
+ };
+
+ private static async Task ArchiveAsync(AppEnvironment environment)
+ {
+ var root = Path.Combine(environment.DataDirectory, "archive");
+ await using var setup = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db")));
+ await new ArchiveService(setup).CreateAsync(root, "Shared");
+ return root;
+ }
+
+ private static int FreePort()
+ {
+ using var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.Start();
+ return ((IPEndPoint)listener.LocalEndpoint).Port;
+ }
+
+ private static async Task WaitAsync(LibraryShare share, ShareState state)
+ {
+ var until = DateTime.UtcNow + TimeSpan.FromSeconds(60);
+ while (share.State != state)
+ {
+ Assert.True(DateTime.UtcNow < until, $"sharing is {share.State} ({share.Reason}), not {state}");
+ await Task.Delay(50);
+ }
+ }
+}
diff --git a/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs
new file mode 100644
index 00000000..4db81467
--- /dev/null
+++ b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs
@@ -0,0 +1,336 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Security.Cryptography.X509Certificates;
+using Microsoft.Extensions.DependencyInjection;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Imaging.Decoders;
+using Chronos.Core.Model;
+using Chronos.Core.Video.Managed;
+using Chronos.Data;
+using Chronos.Data.Archiving;
+using Chronos.Data.Jobs;
+using Chronos.Data.Processing;
+using Chronos.Data.Scheduling;
+using Chronos.Protocol;
+using Chronos.Server.Api;
+using Chronos.Server.Configuration;
+using Chronos.Server.Hosting;
+using Chronos.Server.Jobs;
+using Chronos.Server.Security;
+using Chronos.Testing;
+
+namespace Chronos.Server.Tests.Hosting;
+
+///
+/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job
+/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes.
+///
+[Category("server")]
+[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own
+public sealed class HostedServerTests(TestContext context)
+{
+ [Test]
+ public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts()
+ {
+ await using var desktop = await DesktopFixture.StartAsync(context);
+ Guid? firstId;
+ string? fingerprint;
+ await using (var shared = await desktop.ShareAsync())
+ {
+ using var http = desktop.Client(shared);
+ using var health = await http.GetAsync("/health");
+ Assert.Equal(HttpStatusCode.OK, health.StatusCode);
+ var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo));
+ var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null);
+ Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint);
+ Assert.Equal(shared.ServerId, info.ServerId);
+ Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port");
+ firstId = shared.ServerId;
+ fingerprint = shared.Fingerprint;
+ }
+ // A second start on the same folder and index: the same certificate, id and administrator.
+ await using var again = await desktop.ShareAsync();
+ Assert.Equal(fingerprint, again.Fingerprint);
+ Assert.Equal(firstId, again.ServerId);
+ Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin));
+ }
+
+ [Test]
+ public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer()
+ {
+ await using var desktop = await DesktopFixture.StartAsync(context);
+ var sink = Log.Sink;
+ await using (var shared = await desktop.ShareAsync())
+ {
+ Assert.Same(desktop.Engine, shared.Services.GetRequiredService().Engine);
+ Assert.True(shared.Services.GetRequiredService().Hosted, "hosted");
+ using var admin = await desktop.AdminAsync(shared);
+ using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest);
+ Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
+ var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
+ var done = await desktop.WaitAsync(job.Id);
+ Assert.Equal(JobState.Done, done.State);
+ Assert.Equal(DesktopFixture.WorkerId, done.NodeId);
+ Assert.Same(sink, Log.Sink);
+ }
+ // Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's.
+ Assert.Same(sink, Log.Sink);
+ var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after");
+ Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State);
+ Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation));
+ }
+
+ [Test]
+ public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops()
+ {
+ await using var desktop = await DesktopFixture.StartAsync(context);
+ var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType().ToHashSet();
+ await using var shared = await desktop.ShareAsync();
+ var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType().ToHashSet();
+ Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal));
+ Assert.SequenceEqual([DesktopFixture.ScanKey], before);
+ }
+
+ [Test]
+ public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs()
+ {
+ await using var desktop = await DesktopFixture.StartAsync(context);
+ var mine = await desktop.SequenceAsync(desktop.Archive);
+ var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation);
+ var theirs = await desktop.SequenceAsync(other);
+ var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace");
+ await using var shared = await desktop.ShareAsync();
+ using var admin = await desktop.AdminAsync(shared);
+
+ using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
+ foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" })
+ {
+ using var hidden = await admin.GetAsync(path);
+ Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path);
+ }
+ using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest))
+ Assert.Equal(HttpStatusCode.NotFound, job.StatusCode);
+
+ var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
+ Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own");
+ using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
+ using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode);
+ Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State);
+ }
+
+ [Test]
+ public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder()
+ {
+ await using var desktop = await DesktopFixture.StartAsync(context);
+ Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable");
+ try
+ {
+ var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" });
+ Assert.Equal("Studio PC", options.ServerName);
+ Assert.True(options.Hosted, "hosted");
+ Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked);
+ Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]);
+ Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime");
+ Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel);
+ }
+ finally
+ {
+ Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null);
+ }
+ await using var shared = await desktop.ShareAsync();
+ Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file");
+ Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile);
+ Assert.NotNull(shared.AdminPassword());
+ using var admin = await desktop.AdminAsync(shared);
+ Assert.Null(shared.AdminPassword());
+ var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto));
+ Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]);
+ }
+
+ [Test]
+ public async Task ClientsAreKeptForFiveMinutes()
+ {
+ var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
+ var activity = new ClientActivity(time);
+ var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() };
+ activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20");
+ activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21");
+ var seen = activity.Recent();
+ Assert.Count(2, seen);
+ Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client));
+ Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client));
+ time.Advance(TimeSpan.FromMinutes(6));
+ Assert.Count(0, activity.Recent());
+ }
+
+ [Test]
+ public void ARenderNeverKeepsTheExportFolderAClientChose()
+ {
+ var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null);
+ var stripped = JobEndpoints.WithoutExportFolder(parameters);
+ Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson);
+ Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson);
+ var plain = parameters with { PresetJson = """{"preset":"1080p"}""" };
+ Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain));
+ }
+
+ [Test]
+ public void TheServiceSwitchesAreGone()
+ {
+ var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]);
+ Assert.Equal(ServerCommand.Run, parsed.Command);
+ Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments);
+ Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service");
+ }
+
+ /// A clock the test moves.
+ private sealed class ManualTime(DateTimeOffset start) : TimeProvider
+ {
+ private DateTimeOffset _now = start;
+
+ public override DateTimeOffset GetUtcNow() => _now;
+
+ public void Advance(TimeSpan by) => _now += by;
+ }
+}
+
+///
+/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed
+/// codecs), a started job engine and a started scheduler with one system schedule of its own.
+///
+internal sealed class DesktopFixture : IAsyncDisposable
+{
+ public const string WorkerId = "STUDIO-PC";
+ public const string ScanKey = "archive-scan";
+
+ private readonly TestContext _context;
+
+ private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine,
+ Scheduler scheduler, Archive archive)
+ {
+ _context = context;
+ Root = root;
+ Database = db;
+ Archives = archives;
+ Processing = processing;
+ Engine = engine;
+ Scheduler = scheduler;
+ Archive = archive;
+ }
+
+ public string Root { get; }
+ public ChronosDatabase Database { get; }
+ public ArchiveService Archives { get; }
+ public ProcessingService Processing { get; }
+ public JobEngine Engine { get; }
+ public Scheduler Scheduler { get; }
+ public Archive Archive { get; }
+ public string ShareData => Path.Combine(Root, "data", "server");
+
+ public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary(), "en",
+ LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
+
+ public static async Task StartAsync(TestContext context)
+ {
+ var root = context.CreateTempDirectory("desktop");
+ Directory.CreateDirectory(Path.Combine(root, "data"));
+ var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation);
+ var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 };
+ var archives = new ArchiveService(db, archiveOptions);
+ var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] });
+ var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation);
+ var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList();
+ var engine = new JobEngine(db, handlers, new JobEngineOptions
+ {
+ WorkerId = WorkerId,
+ Kinds = [.. handlers.Select(h => h.Kind).Distinct()],
+ PollInterval = TimeSpan.FromMilliseconds(100),
+ });
+ await engine.StartAsync(context.Cancellation);
+ var scheduler = new Scheduler(db, engine);
+ await scheduler.StartAsync(new Host(archives, archive), context.Cancellation);
+ return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive);
+ }
+
+ public async Task ShareAsync()
+ {
+ var options = ServerOptions.ForHosted(ShareData, Settings);
+ options.LoginAttemptsPerMinute = 1000;
+ var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive));
+ await server.StartAsync(_context.Cancellation);
+ return server;
+ }
+
+ public HttpClient Client(HostedServer server, string? token = null)
+ {
+ var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) };
+ if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ return client;
+ }
+
+ /// The first administrator, signed in with its temporary password, which it then replaces.
+ public async Task AdminAsync(HostedServer server)
+ {
+ var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password");
+ using var anonymous = Client(server);
+ using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest);
+ login.EnsureSuccessStatusCode();
+ var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!;
+ var client = Client(server, token);
+ using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"),
+ ProtocolJson.Default.ChangePasswordRequest);
+ changed.EnsureSuccessStatusCode();
+ return client;
+ }
+
+ public async Task SequenceAsync(Archive archive)
+ {
+ var sequence = new Sequence
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = archive.Id,
+ Title = "Roof " + archive.Name,
+ Folder = string.Empty,
+ Origin = SequenceOrigin.Server,
+ UpdatedAt = DateTimeOffset.UtcNow,
+ };
+ await Database.Sequences.UpsertAsync(sequence, _context.Cancellation);
+ return sequence;
+ }
+
+ public async Task WaitAsync(Guid id)
+ {
+ var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
+ while (true)
+ {
+ if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job;
+ Assert.True(DateTime.UtcNow < until, "the job did not finish");
+ await Task.Delay(50, _context.Cancellation);
+ }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await Scheduler.DisposeAsync();
+ await Engine.DisposeAsync();
+ await Database.DisposeAsync();
+ }
+
+ /// A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.
+ private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
+ {
+ public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
+
+ public IReadOnlyList SystemSchedules =>
+ [new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
+
+ public IReadOnlyList CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
+
+ public bool DeepAnalysisAfterScan => false;
+
+ public ValueTask GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult(archive);
+
+ public string? Unavailable(string action) => null;
+ }
+}
diff --git a/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs b/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs
deleted file mode 100644
index 32771694..00000000
--- a/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.cs
+++ /dev/null
@@ -1,152 +0,0 @@
-using System.Diagnostics.Eventing.Reader;
-using System.Security.AccessControl;
-using System.Security.Principal;
-using Chronos.Server.Hosting;
-using Chronos.Server.Hosting.Windows;
-using Chronos.Testing;
-
-namespace Chronos.Server.Tests.Hosting;
-
-public sealed class WindowsServiceTests(TestContext context)
-{
- [Test]
- public void CommandSwitchesAreParsedAndTheRestPassedOn()
- {
- Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
- var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
- Assert.Equal(ServerCommand.Service, service.Command);
- Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
- Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
- Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
- Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
- Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
- Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
- Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
- }
-
- [Test]
- public void StatusReportsFollowTheServiceControlManagerRules()
- {
- var tracker = new ServiceStatusTracker();
- var start = tracker.StartPending(60_000);
- Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
- Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
- var running = tracker.Running();
- Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
- Assert.Throws(() => tracker.Running());
- Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
- Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
- var stopped = tracker.Stopped(0);
- Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
- Assert.Throws(() => tracker.StopPending(1));
- Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
- }
-
- [Test]
- public void AServiceFailureLeadsWithTheReasonTheServerGave()
- {
- var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
- var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
- Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
- Assert.Contains("System.InvalidOperationException", text);
-
- // ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
- var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
- Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
- Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
- var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
- Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
- Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
- }
-
- [Test]
- [WindowsOnly]
- public void AServiceFailureReachesTheApplicationEventLog()
- {
- if (!OperatingSystem.IsWindows()) return;
- // Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
- const string source = "Chronos.Server.Tests";
- var marker = source + " " + Guid.NewGuid().ToString("N");
- Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
- var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
- var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
- for (var attempt = 0; attempt < 50; attempt++)
- {
- using (var reader = new EventLogReader(query))
- {
- for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
- {
- using (record)
- {
- // The event's one string, which Event Viewer shows whole.
- if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
- Assert.Equal((byte?)2, record.Level, "an error");
- return;
- }
- }
- }
- Thread.Sleep(100);
- }
- Assert.Fail($"No {source} event carries '{marker}'.");
- }
-
- [Test]
- [WindowsOnly]
- public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
- {
- if (!OperatingSystem.IsWindows()) return;
- var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
- Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
- Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
- Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
- Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
- Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
- // The test build is not under Program Files: registering it is refused, naming the folder.
- Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
- }
-
- [Test]
- [WindowsOnly]
- public void AnyFileOrdinaryUsersCanChangeIsFound()
- {
- if (!OperatingSystem.IsWindows()) return;
- using var identity = WindowsIdentity.GetCurrent();
- if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
- var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
- File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
- var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
- File.WriteAllBytes(satellite.FullName, [1]);
-
- // Like Program Files: administrators may change the folder, users only read it.
- var locked = new DirectorySecurity();
- locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
- var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
- foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
- locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
- locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
- PropagationFlags.None, AccessControlType.Allow));
- folder.SetAccessControl(locked);
- Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
-
- // One satellite assembly users may replace is enough: the service would load it as SYSTEM.
- var open = satellite.GetAccessControl();
- open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
- satellite.SetAccessControl(open);
- Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
- Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
- }
-
- [Test]
- [WindowsOnly]
- public void TheDispatcherDeclinesAConsoleProcess()
- {
- if (!OperatingSystem.IsWindows()) return;
- var built = false;
- Assert.False(WindowsServiceHost.Run(() =>
- {
- built = true;
- throw new InvalidOperationException("never built outside the SCM");
- }));
- Assert.False(built);
- }
-}