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 08b9c1ad..345d97bc 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/Archive.resx b/i18n/en/Archive.resx
index 3cb381b3..77fb1442 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -291,6 +291,7 @@
Restore database…Run maintenanceTrash…
+ {0} (server)the name of the archive of a server's downloaded originals; {0} the server's name{0:N0} issue{0:N0} issuesThe orphan search stoppedlong
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 5c16556f..da8fa47a 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -9,6 +9,8 @@
The archive could not be opened.longThe current index could not be backed up or replaced; the restore runs again at the next start.longThis backup cannot be restored; choose another one.long
+ {0} presents the ID of {1} with another certificate; check that it is not a copy of that server.{0} the server's name now, {1} the name it had
+ The folders could not be sorted: {0}. Nothing was deleted; Chronos tries again at the next start.{0} the reasonEnter a number from {0} to {1}.Enter a whole number from {0} to {1}.Enter a folder.
@@ -27,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
@@ -34,6 +40,7 @@
{0} did not arrive intact; download it again.{0} file nameThe sequence is no longer in this PC's archive index.Open or create an archive on this PC to receive the originals.
+ No folder could be made for the originals of {0}; check that the drive of this PC's archive can be written.{0} the server's nameNot connected to this server; connect and retry the job.This sequence is not on the server yet; upload it first.No original reached the server: they are missing here or already in another server sequence.
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 986c389d..61600f7d 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
@@ -136,6 +137,7 @@
ServerStatus{0} ms
+ Sharing off: nothing swept.longUploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}long: job log lineCancelPassword
@@ -199,6 +201,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 8619d1c8..5a0a26d3 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -178,12 +178,28 @@
testing…Reset sectionSearch settings
+ Announce on LAN
+ Server cacheTrusted certificatesDefault server
+ LAN discoveryForget: {0}
+ HTTP port
+ HTTPS port
+ Known serversNoneOffer this PC
+ Offline
+ Originals folder
+ Public HTTP port
+ Public HTTPS portRender node
+ Server ID
+ Sharing
+ Server data
+ Share this library
+ Library name
+ Signed inClearSpilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.longClear the cache?
@@ -206,11 +222,13 @@
Workspace folder changedChoose the workspace folderlong; folder picker titleFolder
+ Home foldersKept versionsFolder not changedProjects found: {0}{0} count of the projects the folder chosen holdsProjects left: {0}{0} count of the projects the folder in use keepsSync
+ This PCUse folder{0} version{0} versions
diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx
index d9200b8f..e8b4e776 100644
--- a/i18n/en/Shell.resx
+++ b/i18n/en/Shell.resx
@@ -5,6 +5,13 @@
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Chronosinvariant
+ Server ID clash
+ {0} project moved{0} count
+ {0} projects moved{0} count
+ Originals folder made
+ Folders pending
+ Projects in use, or a workspace being moved, follow at the next start.long; toast message under Folders pending
+ Folders sortedJob finished{0} job finished{0} jobs finished
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index a1992e6a..b81501f7 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -708,6 +708,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
@@ -780,10 +792,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
@@ -806,7 +821,17 @@
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 reverts
+ This server's proxies, render-node files and staged imports, inside the cache folder
+ Servers this PC has signed in to, with the folders kept for each
+ Not signed in: its projects open from the workspace and wait to sync
+ Show this server's share of the cache in Explorer
+ Show the archive of this server's downloaded originals in Explorer
+ Where Download originals puts this server's photos, apart from this PC's archive
+ Identifies the server even when its address or name changes: {0}{0} the whole id
+ This PC is signed in to this server nowVersion, build, system, licence, third-party codePortable mode, logs, diagnostics, database backup and restore, resetAnalysis width, night and star thresholds, deep analysis
@@ -816,7 +841,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
@@ -845,6 +870,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
@@ -902,6 +930,7 @@
Update the installed programs in place and apply the changes listed · your data is keptCollapse navigation to icons · Ctrl+BShow navigation names · Ctrl+B
+ Show the logs folder in Explorer: the log says which folder could not be sortedPause the job shown; it continues from its checkpoint when resumedStop the current job · it can be resumed laterAdd a folder to watch
@@ -996,6 +1025,10 @@
Keep the workspace's trash as it isWhat the workspace folder takes on its drive, its trash includedThe workspace's folder (a fast disk is best); Change uses another one, Move takes the projects along
+ Each home keeps its projects in its own folder inside the workspace
+ Open this home's folder in Explorer
+ Projects of sequences on {0}: {1}{0} the server's name, {1} the folder
+ Projects of sequences in this PC's archive: {0}{0} the folderMove the workspace folder with its projects to another folder, after a plan; each file is checked before its source goesPast this size, the media of the projects used longest ago are removed once they are in step with their home; their versions stayThe workspace grows as needed; only Clean after removes media
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index 96ebc21d..bae94aee 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/Archive.it.resx b/i18n/it/Archive.it.resx
index 3fecf541..cea69074 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -285,6 +285,7 @@
Ripristina database…Esegui manutenzioneCestino…
+ {0} (server){0:N0} problema{0:N0} problemiRicerca degli orfani interrotta
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 601bb54b..d7d36ff4 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -9,6 +9,8 @@
Impossibile aprire l'archivio.Non è stato possibile copiare o sostituire l'indice attuale; il ripristino riparte al prossimo avvio.Questa copia non si può ripristinare; scegline un'altra.
+ {0} presenta l'ID di {1} con un altro certificato; verifica che non sia una copia di quel server.
+ Non è stato possibile riordinare le cartelle: {0}. Non è stato eliminato nulla; Chronos riprova al prossimo avvio.Inserisci un numero da {0} a {1}.Inserisci un numero intero da {0} a {1}.Inserisci una cartella.
@@ -27,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.
@@ -34,6 +40,7 @@
{0} non è arrivato integro; scaricalo di nuovo.La sequenza non è più nell'indice dell'archivio di questo PC.Apri o crea un archivio su questo PC per ricevere gli originali.
+ Non è stato possibile creare una cartella per gli originali di {0}; verifica che il disco dell'archivio di questo PC sia scrivibile.Non connesso a questo server; collegati e riprova l'attività.Questa sequenza non è ancora sul server; caricala prima.Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server.
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 264fc26b..34e65705 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.
@@ -134,6 +135,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
@@ -197,6 +199,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 c0bc4322..ce776c93 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -175,12 +175,28 @@
in prova…Ripristina sezioneCerca impostazioni
+ Annuncia in LAN
+ Cache del serverCertificati attendibiliServer predefinito
+ Rilevamento LANDimentica: {0}
+ Porta HTTP
+ Porta HTTPS
+ Server notiNessunoOffri questo PC
+ Non in linea
+ Cartella originali
+ Porta HTTP pubblica
+ Porta HTTPS pubblicaNodo di rendering
+ ID server
+ Condivisione
+ Dati server
+ Condividi questa libreria
+ Nome libreria
+ ConnessoSvuotaI fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.Svuotare la cache?
@@ -203,11 +219,13 @@
Cartella cambiataScegli la cartella dello spazio di lavoroCartella
+ Cartelle per origineVersioni tenuteCartella non cambiataProgetti trovati: {0}Progetti lasciati: {0}Sincronizzazione
+ Questo PCUsa cartella{0} versione{0} versioni
diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx
index 0b51d68b..13b193e9 100644
--- a/i18n/it/Shell.it.resx
+++ b/i18n/it/Shell.it.resx
@@ -4,6 +4,13 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ ID server in conflitto
+ {0} progetto spostato
+ {0} progetti spostati
+ Cartella originali creata
+ Cartelle in attesa
+ I progetti in uso, o uno spazio di lavoro in spostamento, seguono al prossimo avvio.
+ Cartelle riordinateAttività completata{0} attività completata{0} attività completate
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index e12845a4..30cadddb 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -779,6 +779,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
@@ -851,10 +863,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
@@ -877,7 +892,17 @@
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 annulla
+ Proxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cache
+ I server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascuno
+ Accesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione
+ Mostra la parte della cache di questo server in Esplora file
+ Mostra l'archivio degli originali scaricati da questo server in Esplora file
+ Dove Scarica originali mette le foto di questo server, separate dall'archivio di questo PC
+ Identifica il server anche quando cambiano indirizzo o nome: {0}
+ Questo PC ha effettuato l'accesso a questo server oraQuando Chronos è ridotto a icona o in secondo piano, schede inserite, attività finite e messaggi del server compaiono anche come notifiche di WindowsVersione, build, sistema, licenza, codice di terze partiModalità portatile, log, diagnostica, backup e ripristino del database, valori predefiniti
@@ -887,7 +912,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
@@ -916,6 +941,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
@@ -937,6 +965,10 @@
Svuota per sempre il cestino dello spazio di lavoro, dopo un elenco di ciò che contiene e una conferma scrittaIl cestino dello spazio di lavoro è vuotoLa cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, Sposta porta con sé i progetti
+ Ogni origine tiene i suoi progetti in una cartella propria dentro lo spazio di lavoro
+ Apri la cartella di questa origine in Esplora file
+ Progetti delle sequenze su {0}: {1}
+ Progetti delle sequenze nell'archivio di questo PC: {0}Il progetto che hai aperto per ultimo per la sequenzaIl progetto Principale della sequenza, che ne tiene le impostazioniSposta la cartella dello spazio di lavoro con i suoi progetti in un'altra cartella, dopo un piano; ogni file è verificato prima di rimuovere l'origine
@@ -999,6 +1031,7 @@
Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restanoRiduci la navigazione alle icone · Ctrl+BMostra i nomi della navigazione · Ctrl+B
+ Mostra la cartella dei log in Esplora file: il log dice quale cartella non è stata riordinataMette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresaFerma l'attività in corso · potrai riprenderlaAggiungi una cartella da controllare
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 ace1ca49..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)
{
@@ -84,7 +114,7 @@ public sealed class SampleData
services.CheckForUpdateAsync = _ => Task.FromResult(null);
services.Devices.Dispose();
services.Devices = new SampleDeviceMonitor();
- services.Sync.RemoteFactory = (_, _, _) => sample._remote;
+ services.Sync.RemoteFactory = (_, _, _, _) => sample._remote;
services.Sync.EditorFactory = (_, _, _) => sample._remote;
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
services.SchedulerTime = new FixedTime(Now);
@@ -134,6 +164,16 @@ public sealed class SampleData
settings.ProtectedToken = "sample-token";
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
settings.RecentServers = ["https://nas.local:8443"];
+ // Settings › Server › Known servers (owner review 5): the sample's server, known by its id.
+ settings.KnownServers =
+ [
+ new KnownServer
+ {
+ Id = Guid.Parse("5a3c1f0e-7d2b-4c8e-9f10-2b6d4e8a1c37"), Name = "Studio NAS", LastAddress = "https://nas.local:8443", Fingerprint = ServerFingerprint,
+ Aliases = [Chronos.Data.Sync.SyncService.ServerKey(new Uri("https://nas.local:8443"))], LastSeen = Now,
+ },
+ ];
+ _services.Sync.KnownServersChanged();
settings.RenderNodeOptIn = true;
// The jobs sample shows a deep analysis that yielded to the render (owner review 1).
settings.PriorityQueue = true;
diff --git a/src/Chronos.App/Editor/ProjectFiles.cs b/src/Chronos.App/Editor/ProjectFiles.cs
index e1436daa..49eb6313 100644
--- a/src/Chronos.App/Editor/ProjectFiles.cs
+++ b/src/Chronos.App/Editor/ProjectFiles.cs
@@ -74,7 +74,7 @@ public sealed class ProjectFiles(ShellViewModel shell)
if (bundle.Workspace is { } workspace)
{
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
- var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project
+ var own = shell.Services.Workspace.Find(workspace.ProjectId) is { } project
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
return;
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 d87a7c8d..98da75b6 100644
--- a/src/Chronos.App/Infrastructure/AppServices.cs
+++ b/src/Chronos.App/Infrastructure/AppServices.cs
@@ -12,6 +12,7 @@ using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
+using Chronos.Core.IO;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
@@ -21,6 +22,7 @@ using Chronos.Core.Windows.MediaFoundation;
using Chronos.Core.Windows.Wic;
using Chronos.Data;
using Chronos.Data.Archiving;
+using Chronos.Data.Homes;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Scheduling;
@@ -72,12 +74,15 @@ 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);
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
// A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b).
Workspace.ServerHomes = Sync.ProjectHome;
+ // A server home's folder is named by its server's id, whichever address reached it (owner review 5, #66).
+ Workspace.Identity = () => Sync.Identity;
Sync.ProjectChanged += Workspace.OnServerProjectChanged;
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
@@ -110,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();
@@ -119,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.
@@ -151,6 +160,12 @@ public sealed class AppServices : IAsyncDisposable
/// How the restore staged in Settings › Advanced went when the index opened; null when none was staged.
public StagedRestoreResult? StagedRestore { get; private set; }
+ /// What the sorting of the folders into homes did when the index opened (owner review 5, #66); null when it had nothing to do.
+ public HomeLayoutResult? HomeLayout { get; private set; }
+
+ /// Why the folders could not be sorted into homes when the index opened; null when they were, or had nothing to sort.
+ public Exception? HomeLayoutError { get; private set; }
+
/// Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
@@ -201,7 +216,8 @@ public sealed class AppServices : IAsyncDisposable
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync,
- () => services.Workspace.Root);
+ () => services.Workspace.Root,
+ services.Workspace.SameServer);
///
/// Queues a scan of unless one is already waiting or running; the sequences it indexes get
@@ -228,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).
@@ -284,6 +301,8 @@ public sealed class AppServices : IAsyncDisposable
_schedulerReady.TrySetResult(false);
return;
}
+ // Before any job runs: the folders of the workspace and the cache go to their homes (owner review 5, #66).
+ await SortHomesAsync(Database, ct);
try
{
await StartJobsAsync(Database, startEngine: true, ct);
@@ -316,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();
@@ -348,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;
}
@@ -356,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;
@@ -474,6 +497,66 @@ public sealed class AppServices : IAsyncDisposable
}
}
+ ///
+ /// Sorts the workspace's projects and the cache's server folders into their homes (owner review 5, #66:
+ /// ; renames only, a clash to the trash, never deleted), or takes up a sorting a previous
+ /// start left half done. Projects in use or a workspace being moved wait for a later start; a failure is logged and kept
+ /// for Settings to tell (), and the start goes on: the folders not sorted read as before.
+ ///
+ private async Task SortHomesAsync(ChronosDatabase database, CancellationToken ct)
+ {
+ try
+ {
+ var migration = new HomeLayoutMigration(new HomeLayoutOptions
+ {
+ DataDirectory = Environment.DataDirectory,
+ WorkspaceRoot = Workspace.IsEnabled ? Workspace.Root : null,
+ CacheRoot = CacheStore.Folder(Environment, Settings),
+ Identity = Sync.Identity,
+ CurrentServer = Sync.LastServer,
+ Database = database,
+ });
+ var result = await Task.Run(() => migration.ApplyAsync(ct), ct);
+ if (result != HomeLayoutResult.Nothing)
+ {
+ HomeLayout = result;
+ Log.Info("app", $"Folders sorted into homes: {result.ProjectsMoved} project(s), {result.EntriesMoved} entr(ies), {result.InUse} in use, "
+ + $"{result.Clashes} clash(es){(result.Deferred is { } deferred ? $", the workspace waits ({deferred})" : string.Empty)}");
+ }
+ }
+ catch (Exception ex) when (ex is HomeLayoutException or IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ HomeLayoutError = ex;
+ Log.Error("app", "The folders could not be sorted into homes; the next start tries again", ex);
+ }
+ finally
+ {
+ Workspace.Reopen();
+ }
+ }
+
+ ///
+ /// The scan schedule scanned this PC's archive (any thread): the archives of the servers' downloaded originals are scanned
+ /// after it (owner review 5, Q1: they are archives of their own, which the schedule, made for one archive, does not name).
+ ///
+ private void OnScheduledScanDone(Job job)
+ {
+ if (job is not { Kind: JobKind.Scan, State: JobState.Done, ScheduleId: not null, TargetIds: [var scanned] }) return;
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ var archives = await Sync.OriginalsArchivesAsync(_stopping.Token).ConfigureAwait(false);
+ if (archives.Any(a => a.Id == scanned)) return;
+ foreach (var originals in archives) await QueueScanAsync(originals, full: false, _stopping.Token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or OperationCanceledException)
+ {
+ Log.Warning("app", "The archives of the servers' originals could not be queued to be scanned", ex);
+ }
+ });
+ }
+
private async Task StartJobsAsync(ChronosDatabase database, bool startEngine, CancellationToken ct)
{
_wic = new WicDecoderProvider();
@@ -486,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);
@@ -508,6 +596,7 @@ public sealed class AppServices : IAsyncDisposable
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
// The workspace's size limit runs after each copy of media into it (phase 5c).
Engine.JobChanged += Workspace.OnJobChanged;
+ Engine.JobChanged += OnScheduledScanDone;
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
@@ -528,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)),
};
@@ -554,7 +645,8 @@ public sealed class AppServices : IAsyncDisposable
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
- CacheDirectory = Path.Combine(cache, "render-node"),
+ // Each server keeps its own downloads (owner review 5, #66: the render-node folder of its home in the cache).
+ CacheDirectory = Path.Combine(CacheStore.ServerFolder(cache, Sync.KeyOf(session.Address), Sync.Identity), HomeFolders.RenderNode),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
diff --git a/src/Chronos.App/Infrastructure/AppSettings.cs b/src/Chronos.App/Infrastructure/AppSettings.cs
index f8abdfe0..b4a56044 100644
--- a/src/Chronos.App/Infrastructure/AppSettings.cs
+++ b/src/Chronos.App/Infrastructure/AppSettings.cs
@@ -10,6 +10,7 @@ using Chronos.Core.Naming;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
+using Chronos.Data.Sync;
using Chronos.Ui.Theming;
namespace Chronos.App.Infrastructure;
@@ -66,6 +67,61 @@ public sealed class TrustedCertificate
public DateTimeOffset TrustedAt { get; set; }
}
+///
+/// A server this PC signed in to that announced its stable id (owner review 5, #66): its name and last address, the TLS
+/// fingerprint it presented, the address keys it was reached under before (or besides) its id
+/// (: projects, links and jobs made then still name them), the archive its
+/// downloaded originals go to, and when it was last seen. Its folders (servers\<id> in the workspace and the
+/// cache) are named by the id, never by the name.
+///
+public sealed class KnownServer
+{
+ public Guid Id { get; set; }
+ public string? Name { get; set; }
+ public string? LastAddress { get; set; }
+ public string? Fingerprint { get; set; }
+ public List Aliases { get; set; } = [];
+
+ /// The archive of this PC that holds the server's downloaded originals (owner review 5, Q1); null until the first download.
+ public Guid? OriginalsArchiveId { get; set; }
+
+ 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
@@ -257,6 +313,22 @@ public sealed class AppSettings
public List TrustedCertificates { get; set; } = [];
public List RecentServers { get; set; } = [];
+ ///
+ /// The servers known by their stable id and the address keys each was reached under (owner review 5, #66): a server's
+ /// projects, links and jobs stay its own whatever address it is reached by. This PC's state: Reset and Import keep it,
+ /// Export leaves it out.
+ ///
+ public List KnownServers { get; set; } = [];
+
+ /// The alias table of , as the sync and the workspace compare server keys through it.
+ public ServerIdentity KnownIdentity() => new([.. KnownServers.Where(k => k.Id != Guid.Empty).Select(k => new KnownServerKey(k.Id, [.. k.Aliases]))]);
+
+ /// 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; }
@@ -377,6 +449,7 @@ public sealed class AppSettings
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
+ KnownServers = KnownServers,
Window = Window,
RailCollapsed = RailCollapsed,
EditorGroups = EditorGroups,
@@ -400,6 +473,7 @@ public sealed class AppSettings
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
+ copy.KnownServers = [];
return copy;
}
@@ -423,6 +497,7 @@ public sealed class AppSettings
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
+ imported.KnownServers = KnownServers;
return imported;
}
}
diff --git a/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs b/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
index 35c54b61..ad08192c 100644
--- a/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
+++ b/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
@@ -5,10 +5,12 @@ using System.Text;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
+using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs;
using Chronos.Data;
using Chronos.Data.Sqlite;
+using Chronos.Data.Sync;
namespace Chronos.App.Infrastructure;
@@ -34,8 +36,11 @@ public static class DiagnosticsBundle
var settings = services.Settings.ToJson();
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
+ var workspace = services.Workspace;
+ var cache = CacheStore.Folder(services.Environment, services.Settings);
return Task.Run(async () =>
{
+ report += HomesLines(workspace, cache);
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
@@ -76,6 +81,33 @@ public static class DiagnosticsBundle
return sb.ToString();
}
+ /// The homes' folders (owner review 5, #66): the workspace's, each with its projects, and the servers' in the cache.
+ private static string HomesLines(Chronos.App.Workspace.WorkspaceHost workspace, string cache)
+ {
+ var sb = new StringBuilder();
+ try
+ {
+ if (workspace.IsEnabled && Directory.Exists(workspace.Root))
+ {
+ var homes = workspace.Homes;
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Workspace {homes.Root} ({(homes.IsSplit ? "homes" : "1.0 layout")})");
+ foreach (var home in homes.Homes())
+ sb.AppendLine(CultureInfo.InvariantCulture, $" {(home.IsLegacy ? "(parent)" : home.Folder)}: {home.Store.List().Count} project(s){(home.Server?.Name is { } name ? " · " + name : string.Empty)}");
+ }
+ var servers = CacheStore.ServersFolder(cache);
+ if (Directory.Exists(servers))
+ {
+ foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Cache home {Path.GetFileName(folder)}");
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ sb.AppendLine("The homes could not be listed: " + ex.Message);
+ }
+ return sb.ToString();
+ }
+
private static string DatabaseLine(ChronosDatabase? database)
{
if (database is null) return "Index not open\n";
@@ -135,6 +167,19 @@ public static class CacheStore
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
+ /// The servers' homes in the cache (<cache>\servers, owner review 5, #66).
+ public static string ServersFolder(string cache) => Path.Combine(cache, HomeFolders.Servers);
+
+ ///
+ /// The home of server in the cache (<cache>\servers\<folder>, named by its
+ /// canonical key through ): its proxies, render-node downloads and staged imports.
+ ///
+ public static string ServerFolder(string cache, string serverKey, ServerIdentity identity)
+ {
+ ArgumentNullException.ThrowIfNull(identity);
+ return Path.Combine(ServersFolder(cache), identity.FolderName(serverKey));
+ }
+
/// Creates the folder (if needed) and marks it as Chronos's.
public static void Prepare(string folder)
{
diff --git a/src/Chronos.App/Jobs/DesktopScheduleHost.cs b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
index cf29b2f5..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() ?? [];
@@ -84,7 +86,11 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func GetArchiveAsync(CancellationToken cancellationToken)
{
if (database() is not { } db || archives() is not { } service) return null;
- var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
+ var listed = await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false);
+ // Never a server's originals archive in place of this PC's (owner review 5): the app scans those after this one.
+ var originals = settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ var archive = (settings.LastArchivePath is { Length: > 0 } last ? CurrentArchive.At(listed, last) : null)
+ ?? CurrentArchive.Pick([.. listed.Where(a => !originals.Contains(a.Id))], null) ?? CurrentArchive.Pick(listed, null);
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
try
{
@@ -110,14 +116,15 @@ public sealed class DesktopScheduleHost(AppSettings settings, Funccache-trim (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (). The proxies of server sequences
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
-/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
+/// import to the server stages are never trimmed, in the former shared folders and in each server's own (servers,
+/// owner review 5); Settings › Storage › Clear still empties everything.
///
public sealed class CacheTrimStep(Func folder, Func limitBytes) : ICleanupStep
{
public const string StepName = "cache-trim";
/// Folders of the cache the trim leaves whole.
- public static IReadOnlyList Kept { get; } = ["proxies", "render-node", "server-import"];
+ public static IReadOnlyList Kept { get; } = ["proxies", "render-node", "server-import", Chronos.Core.IO.HomeFolders.Servers];
public string Name => StepName;
diff --git a/src/Chronos.App/Library/LibraryActions.cs b/src/Chronos.App/Library/LibraryActions.cs
index 6f99ff4d..a13f8711 100644
--- a/src/Chronos.App/Library/LibraryActions.cs
+++ b/src/Chronos.App/Library/LibraryActions.cs
@@ -117,11 +117,7 @@ public sealed class LibraryActions(ShellViewModel shell)
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.DownloadOriginals when entry is not null:
- if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
- {
- shell.Notify(Loc.L("Errors.Sync.NoArchive"));
- return false;
- }
+ if (await Services.Sync.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => shell.Notify(title, message, isError: isError)) is not { } archive) return false;
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
return true;
case SyncAction.GetExports when entry is not null:
diff --git a/src/Chronos.App/Sections/ImportViewModel.cs b/src/Chronos.App/Sections/ImportViewModel.cs
index acd4a894..fc17cc81 100644
--- a/src/Chronos.App/Sections/ImportViewModel.cs
+++ b/src/Chronos.App/Sections/ImportViewModel.cs
@@ -989,7 +989,20 @@ public sealed class ImportViewModel : SectionViewModel
/// What the signed-in user may still store on the server; null without a quota.
private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null;
- private string ServerStagingRoot => Path.Combine(CacheStore.Folder(Services.Environment, Services.Settings), "server-import");
+ ///
+ /// Where an import to the server is staged before it is uploaded: the signed-in server's own folder of the cache
+ /// (servers\<id>\import, owner review 5); signed out, the cache's former shared folder.
+ ///
+ private string ServerStagingRoot
+ {
+ get
+ {
+ var cache = CacheStore.Folder(Services.Environment, Services.Settings);
+ return Services.Sync.Server is { } server
+ ? Path.Combine(CacheStore.ServerFolder(cache, server, Services.Sync.Identity), Chronos.Core.IO.HomeFolders.Import)
+ : Path.Combine(cache, Chronos.Data.Homes.HomeLayoutMigration.LegacyServerImport);
+ }
+ }
private async Task PlanAsync()
{
diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs
index 8cb7db73..21fef618 100644
--- a/src/Chronos.App/Sections/SequencePickerViewModel.cs
+++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs
@@ -189,7 +189,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
var generation = _generation;
foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id
- : i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList())
+ : i.Entry.IsServerHome && Shell.Services.Workspace.SameServer(i.Entry.Home.Server, change.Server)).ToList())
{
if (generation != _generation) return;
try
diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs
index c6e7a8fb..e9987ec0 100644
--- a/src/Chronos.App/Sections/SequenceViewModel.cs
+++ b/src/Chronos.App/Sections/SequenceViewModel.cs
@@ -643,7 +643,7 @@ public sealed class SequenceViewModel : SectionViewModel
{
workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
- return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
+ return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
@@ -748,9 +748,9 @@ public sealed class SequenceViewModel : SectionViewModel
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server;
- var editorHome = new WorkspaceServerHome(() => string.Equals(sync.Server, server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null,
+ var editorHome = new WorkspaceServerHome(() => sync.Identity.Same(sync.Server, server) ? sync.ConnectEditor() : null,
() => sync.Session);
- return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
+ return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
}
// An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server.
if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null;
diff --git a/src/Chronos.App/Sections/ServerView.xaml b/src/Chronos.App/Sections/ServerView.xaml
index 2f8b9af0..dc43e909 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">
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -168,10 +242,10 @@
-
+
-
+
diff --git a/src/Chronos.App/Sections/ServerViewModel.cs b/src/Chronos.App/Sections/ServerViewModel.cs
index 3ca37e84..9eb15672 100644
--- a/src/Chronos.App/Sections/ServerViewModel.cs
+++ b/src/Chronos.App/Sections/ServerViewModel.cs
@@ -44,6 +44,7 @@ public sealed class ServerViewModel : SectionViewModel
_conflicts.PropertyChanged += OnConflictsChanged;
Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current,
(title, message) => Shell.Notify(title, message, isError: true));
+ SharePanel = new SharePanelViewModel(shell);
}
/// Sequences of this PC and of the server, where they stand and what can be done.
@@ -55,6 +56,9 @@ public sealed class ServerViewModel : SectionViewModel
/// Opens the job list's connection for a session; the screenshots put the sample server's jobs here.
internal Func JobsConnection { get; set; } = ServerJobsViewModel.ConnectionOf;
+ /// 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;
@@ -233,6 +237,7 @@ public sealed class ServerViewModel : SectionViewModel
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
Sync.Dispose();
Jobs.Dispose();
+ SharePanel.Dispose();
base.Dispose();
}
diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml
index d1deb8e3..665a6299 100644
--- a/src/Chronos.App/Sections/SettingsView.xaml
+++ b/src/Chronos.App/Sections/SettingsView.xaml
@@ -563,6 +563,28 @@
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -613,6 +635,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs
index baf1c69b..cac049b9 100644
--- a/src/Chronos.App/Sections/SettingsViewModel.cs
+++ b/src/Chronos.App/Sections/SettingsViewModel.cs
@@ -90,8 +90,9 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
- "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]),
- new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
+ "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
+ new(SettingsPage.Server, ["Settings.Server.Share", "Settings.Server.ShareName", "Settings.Server.HttpsPort", "Settings.Server.HttpPort",
+ "Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
@@ -177,6 +178,9 @@ public sealed class SettingsViewModel : SectionViewModel
// Saving applies them to the log files (App.SaveSettings).
Logs = new LogSettingsRows(_s, Save);
+ // ---- Server › Sharing (owner review 5, #67); saving applies it to the share (AppServices.SaveSettings). ----
+ ShareRows = new ShareSettingsRows(_s, Save, Shell.Services.Environment.ShareDirectory, Shell.Services.Environment.PcName);
+
// ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
@@ -272,7 +276,12 @@ public sealed class SettingsViewModel : SectionViewModel
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
- if (value == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
+ if (value == SettingsPage.Workspace)
+ {
+ _ = WorkspaceRows.MeasureAsync();
+ _ = LoadHomeFoldersAsync();
+ }
+ if (value == SettingsPage.Server) _ = LoadKnownServersAsync();
if (value == SettingsPage.Advanced) LoadBackups();
}
}
@@ -741,7 +750,7 @@ public sealed class SettingsViewModel : SectionViewModel
{
try
{
- ShellActions.Reveal(Shell.Services.Workspace.Store.Root);
+ ShellActions.Reveal(Shell.Services.Workspace.Homes.Root);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
@@ -793,6 +802,16 @@ public sealed class SettingsViewModel : SectionViewModel
public bool HasCertificates => Certificates.Count > 0;
+ /// Settings › Server › Known servers (owner review 5, #66): the servers this PC signed in to, with their folders.
+ public ObservableCollection KnownServers { get; } = [];
+
+ public bool HasKnownServers => KnownServers.Count > 0;
+
+ /// Settings › Workspace › Home folders (owner review 5, #66): where each home keeps its projects.
+ public ObservableCollection HomeFolderRows { get; } = [];
+
+ public bool HasHomeFolderRows => HomeFolderRows.Count > 0;
+
// ---------------- Updates ----------------
public bool CheckForUpdates
@@ -816,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; }
@@ -897,6 +919,8 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
+ NotifyHomeLayout();
+ Shell.Services.Sync.IdentityClash += (name, was) => Shell.Notify(Loc.L("Shell.Homes.Clash"), Loc.L("Errors.Homes.Clash", name, was), isError: true);
// BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and
// leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe.
var environment = Shell.Services.Environment;
@@ -1559,6 +1583,27 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
+ ///
+ /// How the sorting of the folders into homes went at start (owner review 5, #66): sorted, with Open on the workspace;
+ /// pending, when projects in use or a workspace being moved wait for the next start; or failed, with Open on the logs.
+ ///
+ private void NotifyHomeLayout()
+ {
+ var services = Shell.Services;
+ if (services.HomeLayoutError is { } error)
+ {
+ Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Errors.Homes.Failed", error.Message), Loc.L("Settings.Advanced.Logs"),
+ Loc.L("Tooltips.Shell.Homes.Logs"), () => ShellActions.Reveal(services.Environment.LogDirectory), isError: true);
+ return;
+ }
+ if (services.HomeLayout is not { } result) return;
+ if (result.Deferred is not null || result.InUse > 0)
+ Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Shell.Homes.PendingText"));
+ else if (result.ProjectsMoved > 0)
+ Shell.Notify(Loc.L("Shell.Homes.Sorted"), Loc.Plural("Shell.Homes.Moved", result.ProjectsMoved), Loc.L("Common.Open"),
+ Loc.L("Tooltips.Settings.OpenWorkspace"), OpenWorkspaceFolder);
+ }
+
private void CancelRestore()
{
try
@@ -1629,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;
@@ -1736,6 +1782,7 @@ public sealed class SettingsViewModel : SectionViewModel
foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh();
WorkspaceRows.Refresh();
+ ShareRows.Refresh();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
@@ -1781,6 +1828,57 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Import.Done"));
}
+ /// The home folders of the workspace as they are now (read off the UI thread; none while the workspace cannot be read).
+ private async Task LoadHomeFoldersAsync()
+ {
+ var workspace = Shell.Services.Workspace;
+ if (!workspace.IsEnabled) return;
+ var known = _s.KnownServers.ToList();
+ IReadOnlyList rows;
+ try
+ {
+ rows = await Task.Run(() => HomeFolderRow.Of(workspace.Homes, known, RevealFolder));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ Log.Info("settings", $"The home folders of the workspace could not be read: {ex.Message}");
+ rows = [];
+ }
+ HomeFolderRows.Clear();
+ foreach (var row in rows) HomeFolderRows.Add(row);
+ OnPropertyChanged(nameof(HasHomeFolderRows));
+ }
+
+ /// The known servers, most recently seen first, with the archive of their originals and their share of the cache.
+ private async Task LoadKnownServersAsync()
+ {
+ var services = Shell.Services;
+ IReadOnlyList archives = services.Database is { } db ? await db.Archives.ListAsync() : [];
+ var cache = CacheStore.Folder(services.Environment, services.Settings);
+ var signedIn = services.Sync.Server;
+ KnownServers.Clear();
+ foreach (var server in _s.KnownServers.Where(k => k.Id != Guid.Empty).OrderByDescending(k => k.LastSeen))
+ {
+ var key = HomeFolders.IdKey(server.Id);
+ var originals = server.OriginalsArchiveId is { } id ? archives.FirstOrDefault(a => a.Id == id)?.RootPath : null;
+ KnownServers.Add(new KnownServerRow(server, services.Sync.Identity.Same(signedIn, key), originals,
+ CacheStore.ServerFolder(cache, key, services.Sync.Identity), RevealFolder));
+ }
+ OnPropertyChanged(nameof(HasKnownServers));
+ }
+
+ private void RevealFolder(string folder)
+ {
+ try
+ {
+ ShellActions.Reveal(folder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
private void LoadCertificates()
{
Certificates.Clear();
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/Sections/VideosViewModel.cs b/src/Chronos.App/Sections/VideosViewModel.cs
index 26529849..1b746f04 100644
--- a/src/Chronos.App/Sections/VideosViewModel.cs
+++ b/src/Chronos.App/Sections/VideosViewModel.cs
@@ -551,7 +551,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var workspace = services.Workspace;
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
var projects = await workspace.ListAsync(cancellationToken);
- return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken);
+ return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Homes, projects), cancellationToken);
}
/// The signed-in session's server, its capability and the account's rights.
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/Server/SyncHost.cs b/src/Chronos.App/Server/SyncHost.cs
index a14e3f26..6e3cdadd 100644
--- a/src/Chronos.App/Server/SyncHost.cs
+++ b/src/Chronos.App/Server/SyncHost.cs
@@ -1,10 +1,14 @@
using System.IO;
+using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
+using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
+using Chronos.Data.Homes;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
@@ -13,8 +17,14 @@ using Chronos.Protocol.Client;
namespace Chronos.App.Server;
-/// Makes the sync connection of a signed-in session.
-public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints);
+/// Makes the sync connection of a signed-in session; is the key it names the server by ().
+public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints, string server);
+
+///
+/// Where Download originals puts a server sequence's photos (): the archive's id,
+/// and its root when it was made just now (the first download from that server); a null id when there is none to use.
+///
+public sealed record OriginalsTarget(Guid? ArchiveId, string? Created = null);
///
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the of the index, the
@@ -24,25 +34,37 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// (), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: , ) and the Export "Sync" of finished renders
/// (). Options come from ,
-/// and .
+/// and . A server that announces
+/// its stable id (owner review 5, #66) is keyed by it () and recorded in
+/// with the address keys it was reached under, which match it all the same
+/// (); at a sign-in that tells its id, what this PC keeps under those addresses moves to its id
+/// () before the agent starts.
///
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// How long a job resumed at start waits for the saved session to be restored.
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
+ /// Jobs that write into the workspace or the servers' homes in the cache: a re-key waits for them.
+ private static readonly JobKind[] RekeyHeldBy =
+ [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove, JobKind.Download, JobKind.UploadCommit, JobKind.VideoCopy];
+
private readonly Lock _gate = new();
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private Running? _running;
private JobEngine? _renders;
+ /// The alias table of , made again whenever a sign-in records a server.
+ private ServerIdentity _identity = services.Settings.KnownIdentity();
+
/// The client project homes of the session share, made at first use for the credentials it holds.
private SharedClient? _projects;
/// Connections over ; screenshots substitute a fake server.
- public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
- new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
+ public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted, server) =>
+ new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true,
+ server);
/// Connections of editors of server sequences over ; screenshots substitute a fake server.
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
@@ -61,8 +83,28 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// The agent's connection, for the table's own calls (conflict resolution); null while signed out.
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
- /// Key of the signed-in server (); null while signed out.
- public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
+ ///
+ /// Key of the signed-in server: its id key when it announced its id (), else
+ /// its address key (); null while signed out.
+ ///
+ public string? Server => Volatile.Read(ref _credentials) is { } c ? c.Key : null;
+
+ /// The servers known by id and the address keys each was reached under (any thread).
+ public ServerIdentity Identity => Volatile.Read(ref _identity);
+
+ ///
+ /// A known server id came back with another TLS certificate and another name (owner review 5: a copied server database,
+ /// two servers sharing one id): the server's name now, and the name it had (UI thread).
+ ///
+ public event Action? IdentityClash;
+
+ /// The key a server reached at goes by: the signed-in one's when it is that server, else its address key mapped through the aliases.
+ public string KeyOf(Uri address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ if (Volatile.Read(ref _credentials) is { } c && c.Address == address) return c.Key;
+ return Identity.Canonical(SyncService.ServerKey(address));
+ }
/// The options, and whether the account may change server sequences (without it this PC's edits are not sent).
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
@@ -97,15 +139,15 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
///
/// The project home of a workspace project whose home is a server ( over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
- /// shows the project offline and its work waits.
+ /// shows the project offline and its work waits. A home named by an address the signed-in server was reached under before
+ /// it told its id is that server's all the same (owner review 5).
///
public IProjectHome? ProjectHome(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
- if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
- || !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
+ if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials || !Identity.Same(home.Server, credentials.Key))
return null;
- return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat);
+ return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat, credentials.Key);
}
///
@@ -121,14 +163,23 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// The agent started, stopped or compared, or the table of the signed-in server changed (any thread).
public event Action? Changed;
- /// Creates the engine over the open index; the proxy cache lives in the client's cache folder.
+ ///
+ /// Creates the engine over the open index; the proxy cache lives in the client's cache folder, one home per server
+ /// (<cache>\servers\<folder>\proxies, owner review 5), read where 1.0 put it until it is moved.
+ ///
public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options)
{
var cache = CacheStore.Folder(services.Environment, services.Settings);
- Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
+ Service = new SyncService(database, archives, new SyncOptions
+ {
+ Archive = options,
+ ProxyCacheDirectory = Path.Combine(cache, HomeLayoutMigration.LegacyProxies),
+ ServersDirectory = CacheStore.ServersFolder(cache),
+ Identity = () => Identity,
+ });
Service.Changed += server =>
{
- if (server == Server) Changed?.Invoke();
+ if (Server is { } signedIn && Identity.Same(server, signedIn)) Changed?.Invoke();
};
return Service;
}
@@ -138,8 +189,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
{
var session = services.Server;
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
- ? new Credentials(address, token, session.Fingerprints)
+ ? new Credentials(address, token, session.Fingerprints, session.Flow.Info?.ServerId is { } id && id != Guid.Empty ? id : null)
: null;
+ if (wanted is { ServerId: { } serverId } && session.Flow.Info is { } info) Remember(serverId, wanted.Address, info);
Volatile.Write(ref _credentials, wanted);
_switch = SwitchAsync(_switch, wanted);
if (services.Engine is not { } engine) return;
@@ -150,6 +202,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
engine.JobChanged += OnJobChanged;
}
+ /// The servers known by id were changed elsewhere (Settings › Server › Forget, an import): the alias table follows (UI thread).
+ public void KnownServersChanged() => Volatile.Write(ref _identity, services.Settings.KnownIdentity());
+
/// The sign-in uses now (another object once signed in anew); null while signed out.
public object? Session => Volatile.Read(ref _credentials);
@@ -167,18 +222,73 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// Compares again soon (an option changed, an edit on this PC).
public void RequestRefresh() => Agent?.RequestRefresh();
- /// The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.
+ /// This PC's archive: the one at Settings › Archive's folder, else the only one that is not a server's originals archive.
public async Task CurrentArchiveAsync(CancellationToken ct = default)
{
if (services.Database is not { } db) return null;
var archives = await db.Archives.ListAsync(ct);
- if (services.Settings.LastArchivePath is { Length: > 0 } root)
+ if (services.Settings.LastArchivePath is { Length: > 0 } root && CurrentArchive.At(archives, root) is { } current) return current;
+ var originals = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ var own = archives.Where(a => !originals.Contains(a.Id)).ToList();
+ return own.Count == 1 ? own[0] : null;
+ }
+
+ ///
+ /// Where Download originals puts the photos of a server sequence (owner review 5, Q1; UI thread): the archive of its local
+ /// copy when it has one (a copy keeps receiving where it is), else the signed-in server's own originals archive
+ /// (), made at the first download beside this PC's archive
+ /// (: D:\ChronosArchive - Studio NAS, named "Studio NAS (server)").
+ /// A server that announces no id (an older one) has no home of its own: its originals go to this PC's archive, as in 1.0.
+ ///
+ /// The originals archive's folder cannot be made.
+ public async Task OriginalsArchiveAsync(Sequence? local, CancellationToken ct = default)
+ {
+ if (local?.ArchiveId is { } held) return new OriginalsTarget(held);
+ if (services.Database is not { } db || services.Archives is not { } archives) return new OriginalsTarget(null);
+ if (Volatile.Read(ref _credentials) is not { ServerId: { } id } || services.Settings.FindKnownServer(id) is not { } known)
+ return new OriginalsTarget((await CurrentArchiveAsync(ct))?.Id);
+ var listed = await db.Archives.ListAsync(ct);
+ if (known.OriginalsArchiveId is { } chosen && listed.Any(a => a.Id == chosen)) return new OriginalsTarget(chosen);
+ var name = known.Name is { Length: > 0 } n ? n : services.Server.ServerName ?? known.LastAddress ?? id.ToString("N");
+ var mine = await CurrentArchiveAsync(ct);
+ var root = HomeFolders.OriginalsArchiveRoot(mine?.RootPath ?? services.Settings.LastArchivePath, name, ArchiveLocations.SuggestRoot(),
+ path => Directory.Exists(path) || File.Exists(path) || CurrentArchive.At(listed, path) is not null);
+ var made = await archives.CreateAsync(root, Loc.L("Archive.Name.ServerOriginals", name), cancellationToken: ct);
+ known.OriginalsArchiveId = made.Id;
+ services.SavePreferences();
+ Log.Info("sync", $"The originals of {name} ({id}) go to their own archive {made.RootPath}");
+ return new OriginalsTarget(made.Id, made.RootPath);
+ }
+
+ ///
+ /// The archive Download originals puts a sequence's photos in (; UI thread), with what
+ /// the user is told: where a new originals archive went, or why there is none (: title, message, is error).
+ ///
+ public async Task OriginalsForDownloadAsync(Sequence? local, Action notify)
+ {
+ ArgumentNullException.ThrowIfNull(notify);
+ try
{
- var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
- if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
- is { } current) return current;
+ var target = await OriginalsArchiveAsync(local);
+ if (target.ArchiveId is null) notify(Loc.L("Errors.Sync.NoArchive"), null, true);
+ else if (target.Created is { } made) notify(Loc.L("Shell.Homes.Originals"), AppEnvironment.Shown(made), false);
+ return target.ArchiveId;
}
- return archives.Count == 1 ? archives[0] : null;
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or DatabaseException)
+ {
+ Log.Warning("sync", "The originals archive of the signed-in server could not be made", ex);
+ notify(Loc.L("Errors.Sync.NoOriginalsFolder", services.Server.ServerName ?? Server ?? string.Empty), null, true);
+ return null;
+ }
+ }
+
+ /// The archives of the known servers' downloaded originals that the index holds (the scan schedule scans them too).
+ public async Task> OriginalsArchivesAsync(CancellationToken ct = default)
+ {
+ if (services.Database is not { } db) return [];
+ var ids = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ if (ids.Count == 0) return [];
+ return [.. (await db.Archives.ListAsync(ct).ConfigureAwait(false)).Where(a => ids.Contains(a.Id))];
}
public async ValueTask ConnectAsync(string server, CancellationToken cancellationToken)
@@ -187,9 +297,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var until = DateTime.UtcNow + RestoreWait;
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
await Task.Delay(500, cancellationToken);
- if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
+ // A job queued under an address the server was reached under before it told its id reaches it all the same.
+ if (Volatile.Read(ref _credentials) is not { } c || !Identity.Same(c.Key, server)) return null;
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
- return RemoteFactory(c.Address, c.Token, c.Fingerprints);
+ return RemoteFactory(c.Address, c.Token, c.Fingerprints, c.Key);
}
///
@@ -240,9 +351,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
}
- /// Key of the server of the saved session (Disconnect keeps it); null without one.
+ /// The key of the server this PC is signed in to, else of the saved session's; null without either.
+ public string? LastServer => Server ?? SavedServer();
+
+ /// Key of the server of the saved session (Disconnect keeps it), its id key when it is known by id; null without one.
private string? SavedServer() =>
- services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null;
+ services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? Identity.Canonical(SyncService.ServerKey(address)) : null;
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
{
@@ -265,6 +379,89 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
}
}
+ ///
+ /// Records the signed-in server in (UI thread): its id, name, address, certificate,
+ /// and the address key it was reached by as an alias; the settings are written only when something changed. A known id
+ /// presented with another certificate and another name is told ().
+ ///
+ private void Remember(Guid id, Uri address, ServerInfo info)
+ {
+ var settings = services.Settings;
+ var alias = SyncService.ServerKey(address);
+ var shown = ServerAddress.Display(address);
+ var known = settings.FindKnownServer(id);
+ var changed = false;
+ if (known is null)
+ {
+ known = new KnownServer { Id = id, Name = info.Name, LastAddress = shown, Fingerprint = info.TlsFingerprint };
+ settings.KnownServers.Add(known);
+ changed = true;
+ Log.Info("sync", $"Server {info.Name} is known by its id {id} from now on (reached at {shown})");
+ }
+ else if (known.Fingerprint is { Length: > 0 } before && info.TlsFingerprint is { Length: > 0 } now
+ && !string.Equals(before, now, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(known.Name, info.Name, StringComparison.Ordinal))
+ {
+ Log.Warning("sync", $"Server id {id} was {known.Name} with another certificate; it is {info.Name} now: two servers may share one copied database");
+ IdentityClash?.Invoke(info.Name, known.Name ?? shown);
+ }
+ if (!known.Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase))
+ {
+ known.Aliases.Add(alias);
+ changed = true;
+ }
+ if (!string.Equals(known.Name, info.Name, StringComparison.Ordinal) || !string.Equals(known.LastAddress, shown, StringComparison.OrdinalIgnoreCase)
+ || (info.TlsFingerprint is { Length: > 0 } fingerprint
+ && !string.Equals(known.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)))
+ {
+ (known.Name, known.LastAddress, known.Fingerprint) = (info.Name, shown, info.TlsFingerprint ?? known.Fingerprint);
+ changed = true;
+ }
+ if (DateTimeOffset.UtcNow - known.LastSeen > TimeSpan.FromHours(1))
+ {
+ known.LastSeen = DateTimeOffset.UtcNow;
+ changed = true;
+ }
+ if (!changed) return;
+ Volatile.Write(ref _identity, settings.KnownIdentity());
+ services.SavePreferences();
+ }
+
+ ///
+ /// Whatever this PC keeps under the address keys the server of was reached by moves to its
+ /// id (owner review 5, #66: ), before the agent starts. Skipped while a job
+ /// writes into the workspace or the cache, or the workspace is being moved: a later sign-in does it, and the aliases match
+ /// meanwhile. A failure is logged: nothing is lost, and the next sign-in goes on.
+ ///
+ private async Task RekeyAsync(Credentials credentials)
+ {
+ if (credentials.ServerId is not { } id || services.Database is not { } db) return;
+ var aliases = Identity.AliasesOf(id);
+ if (aliases.Count == 0) return;
+ try
+ {
+ if (await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false))
+ {
+ Log.Info("sync", $"Server {id}: what this PC keeps under its addresses moves to its id at a later sign-in (jobs are under way)");
+ return;
+ }
+ var workspace = services.Workspace;
+ var migration = new HomeLayoutMigration(new HomeLayoutOptions
+ {
+ DataDirectory = services.Environment.DataDirectory,
+ WorkspaceRoot = workspace.IsEnabled && !workspace.IsMoving ? workspace.Root : null,
+ CacheRoot = CacheStore.Folder(services.Environment, services.Settings),
+ Identity = Identity,
+ Database = db,
+ });
+ await migration.RekeyAsync(id, aliases).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ Log.Warning("sync", $"What this PC keeps under the addresses of server {id} could not all move to its id; the next sign-in goes on", ex);
+ }
+ }
+
///
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
/// the old agent when the app exits must not need the UI thread its exit blocks.
@@ -272,7 +469,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
await previous.ConfigureAwait(false);
- if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
+ if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token
+ && running.Credentials.ServerId == same.ServerId)
return;
var stopped = Volatile.Read(ref _running)?.Remote.Server;
await StopAsync().ConfigureAwait(false);
@@ -283,7 +481,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke();
return;
}
- var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
+ await RekeyAsync(start).ConfigureAwait(false);
+ var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints, start.Key);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
@@ -302,7 +501,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke();
}
- private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection Fingerprints);
+ /// The id the server announced (owner review 5); null for an older server.
+ private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection Fingerprints, Guid? ServerId)
+ {
+ /// The key the server goes by ().
+ public string Key => ServerIdentity.Key(ServerId, Address);
+ }
/// The client project homes share, and the session it was made for.
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
diff --git a/src/Chronos.App/Server/SyncTableViewModel.cs b/src/Chronos.App/Server/SyncTableViewModel.cs
index 080b0772..81c635ac 100644
--- a/src/Chronos.App/Server/SyncTableViewModel.cs
+++ b/src/Chronos.App/Server/SyncTableViewModel.cs
@@ -316,11 +316,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
break;
case SyncAction.DownloadOriginals:
- if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
- {
- _shell.Notify(Loc.L("Errors.Sync.NoArchive"), isError: true);
- return;
- }
+ if (await Host.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => _shell.Notify(title, message, isError: isError)) is not { } archive) return;
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
break;
case SyncAction.GetExports:
diff --git a/src/Chronos.App/Settings/HomeRows.cs b/src/Chronos.App/Settings/HomeRows.cs
new file mode 100644
index 00000000..c0785e15
--- /dev/null
+++ b/src/Chronos.App/Settings/HomeRows.cs
@@ -0,0 +1,97 @@
+using System.IO;
+using System.Windows.Input;
+using Chronos.App.Infrastructure;
+using Chronos.Core.Localization;
+using Chronos.Data.Workspaces;
+using Chronos.Ui.Mvvm;
+
+namespace Chronos.App.Settings;
+
+///
+/// One home's folder in Settings › Workspace › Home folders (owner review 5, #66): "This PC" for the projects of this PC's
+/// archive (local), one row per server for its projects (servers\<id>), with Open.
+///
+public sealed class HomeFolderRow(string name, string path, string toolTip, Action open)
+{
+ public string Name { get; } = name;
+
+ /// The folder as shown (a capture's own folders stand for the real ones).
+ public string Path { get; } = AppEnvironment.Shown(path);
+
+ public string ToolTip { get; } = toolTip;
+
+ public ICommand OpenCommand { get; } = new RelayCommand(() => open(path));
+
+ /// The rows of the workspace's homes: this PC first, then each server by name; none while the workspace is not made.
+ public static IReadOnlyList Of(WorkspaceHomes homes, IReadOnlyList known, Action open)
+ {
+ ArgumentNullException.ThrowIfNull(homes);
+ ArgumentNullException.ThrowIfNull(known);
+ ArgumentNullException.ThrowIfNull(open);
+ if (!homes.IsSplit) return [new HomeFolderRow(Loc.L("Settings.Workspace.ThisPc"), homes.Root, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.Root)), open)];
+ var rows = new List
+ {
+ new(Loc.L("Settings.Workspace.ThisPc"), homes.LocalRoot, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.LocalRoot)), open),
+ };
+ foreach (var home in homes.Homes().Where(h => h is { IsLocal: false, IsLegacy: false }).OrderBy(h => NameOf(h, known), StringComparer.CurrentCultureIgnoreCase))
+ {
+ var name = NameOf(home, known);
+ rows.Add(new HomeFolderRow(name, home.Store.Root,
+ Loc.L("Tooltips.Settings.Workspace.ServerHome", name, AppEnvironment.Shown(home.Store.Root)), open));
+ }
+ return rows;
+ }
+
+ /// The server's name as this PC knows it, else as its folder records it, else the folder's name.
+ private static string NameOf(WorkspaceHome home, IReadOnlyList known) =>
+ (home.Server?.Id is { } id ? known.FirstOrDefault(k => k.Id == id)?.Name : null)
+ ?? home.Server?.Name ?? home.Server?.Address ?? System.IO.Path.GetFileName(home.Store.Root);
+}
+
+///
+/// A server this PC signed in to, in Settings › Server › Known servers (owner review 5, #66): its name, last address, id
+/// (short, the whole one in the tooltip), whether this PC is signed in to it now, and its folders: the archive of its
+/// downloaded originals and its share of the cache, each with Open.
+///
+public sealed class KnownServerRow
+{
+ private readonly string? _originals;
+ private readonly string _cache;
+
+ public KnownServerRow(KnownServer server, bool signedIn, string? originalsRoot, string cacheFolder, Action open)
+ {
+ ArgumentNullException.ThrowIfNull(server);
+ ArgumentNullException.ThrowIfNull(open);
+ Server = server;
+ IsSignedIn = signedIn;
+ _originals = originalsRoot;
+ _cache = cacheFolder;
+ OpenOriginalsCommand = new RelayCommand(() => open(_originals!), () => _originals is not null && Directory.Exists(_originals));
+ OpenCacheCommand = new RelayCommand(() => open(_cache), () => Directory.Exists(_cache));
+ }
+
+ public KnownServer Server { get; }
+
+ public string Name => Server.Name is { Length: > 0 } name ? name : Server.LastAddress ?? Server.Id.ToString("N");
+
+ public string Address => Server.LastAddress ?? "—";
+
+ /// The first 8 hex digits of the id; the tooltip has it whole.
+ public string ShortId => Server.Id.ToString("N")[..8];
+
+ public string IdToolTip => Loc.L("Tooltips.Settings.Server.ServerId", Server.Id.ToString("D"));
+
+ public bool IsSignedIn { get; }
+
+ public string StateText => Loc.L(IsSignedIn ? "Settings.Server.SignedIn" : "Settings.Server.Offline");
+
+ public string StateToolTip => Loc.L(IsSignedIn ? "Tooltips.Settings.Server.SignedIn" : "Tooltips.Settings.Server.Offline");
+
+ public string OriginalsPath => _originals is null ? "—" : AppEnvironment.Shown(_originals);
+
+ public string CachePath => AppEnvironment.Shown(_cache);
+
+ public ICommand OpenOriginalsCommand { get; }
+
+ public ICommand OpenCacheCommand { get; }
+}
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 0c4d546d..422c5b71 100644
--- a/src/Chronos.App/Shell/ScreenCapture.cs
+++ b/src/Chronos.App/Shell/ScreenCapture.cs
@@ -117,6 +117,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.App/Videos/VideoSources.cs b/src/Chronos.App/Videos/VideoSources.cs
index 537de7d6..ff608783 100644
--- a/src/Chronos.App/Videos/VideoSources.cs
+++ b/src/Chronos.App/Videos/VideoSources.cs
@@ -429,25 +429,37 @@ public static class VideoSources
public static IReadOnlyList ReadWorkspace(WorkspaceStore store, IEnumerable projects)
{
ArgumentNullException.ThrowIfNull(store);
+ return ReadWorkspace(store.Project, projects);
+ }
+
+ /// The workspace renders of every project, each read in its own home's folder (local\, servers\<id>\).
+ public static IReadOnlyList ReadWorkspace(WorkspaceHomes homes, IEnumerable projects)
+ {
+ ArgumentNullException.ThrowIfNull(homes);
+ return ReadWorkspace(id => homes.Find(id) ?? homes.Local.Project(id), projects);
+ }
+
+ private static List ReadWorkspace(Func project, IEnumerable projects)
+ {
ArgumentNullException.ThrowIfNull(projects);
var entries = new List();
- foreach (var project in projects.Where(p => p.IsReadable))
+ foreach (var entry in projects.Where(p => p.IsReadable))
{
try
{
- var folder = store.Project(project.ProjectId);
+ var folder = project(entry.ProjectId);
foreach (var render in folder.ReadRenders().Entries)
{
var path = folder.ExportFile(render.File);
var exists = File.Exists(path) || Directory.Exists(path);
// A sent render whose file left exports/ is safe at its home, whose entry stands for it: never "missing".
if (render.IsSent && !exists) continue;
- entries.Add(FromWorkspace(render, project, path, exists));
+ entries.Add(FromWorkspace(render, entry, path, exists));
}
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
- Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex);
+ Log.Warning("videos", $"The render ledger of workspace project {entry.ProjectId} cannot be read", ex);
}
}
return entries;
diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
index 5f99dba6..da5e0fcf 100644
--- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
+++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
@@ -986,7 +986,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
///
private void OnHomeChanged(WorkspaceHomeChange change)
{
- if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
+ if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !_host.SameServer(change.Server, Home.Server)))
return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change);
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
index 3bd71f68..cca04bc8 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
@@ -36,6 +36,12 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyListNothing to erase: Empty… is disabled.
public bool IsEmpty => Items.Count == 0;
+
+ ///
+ /// The trash of each home the plan lists (owner review 5, separate homes: local\ and each servers\<id>\
+ /// keep their own), each with its own fingerprint; emptying erases each one only while all of them still match.
+ ///
+ public IReadOnlyList Listings { get; init; } = [];
}
/// What emptying the workspace's trash erased.
@@ -63,21 +69,28 @@ public sealed partial class WorkspaceHost
var root = Root;
if (!Directory.Exists(root)) return WorkspaceUsage.None;
var media = 0L;
- foreach (var folder in Directory.EnumerateDirectories(root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
+ foreach (var store in Homes.All())
{
- cancellationToken.ThrowIfCancellationRequested();
- media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
+ if (!Directory.Exists(store.Root)) continue;
+ foreach (var folder in Directory.EnumerateDirectories(store.Root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
+ }
}
- var trash = WorkspaceTrash.List(root, cancellationToken);
- return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count);
+ var trash = Homes.Trash(cancellationToken);
+ return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Sum(t => t.Bytes), trash.Sum(t => t.Entries.Count));
}, cancellationToken);
- /// The plan of emptying the workspace's trash (); nothing is erased.
+ /// The plan of emptying the trash of every home of the workspace (); nothing is erased.
public Task PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
- var listing = WorkspaceTrash.List(Root, cancellationToken);
- return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes,
- listing.Fingerprint);
+ var listings = Homes.Trash(cancellationToken);
+ var folder = listings.Count == 1 ? listings[0].Folder : WorkspaceTrash.FolderOf(Root);
+ var fingerprint = string.Join('|', listings.Select(l => l.Folder + "=" + l.Fingerprint));
+ return new WorkspaceTrashPlan(folder, [.. listings.SelectMany(l => l.Entries).Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))
+ .OrderBy(i => i.Trashed)], listings.Sum(l => l.Bytes), fingerprint)
+ { Listings = listings };
}, cancellationToken);
///
@@ -92,11 +105,25 @@ public sealed partial class WorkspaceHost
return Task.Run(() =>
{
EnsureNotMoving();
- var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
- plan.Fingerprint);
+ IReadOnlyList listings = plan.Listings.Count > 0 ? plan.Listings
+ : [new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
+ plan.Fingerprint)];
try
{
- var (items, bytes) = WorkspaceTrash.Empty(Root, listing, cancellationToken);
+ // Every trash is checked before any is emptied: a plan is erased whole or not at all.
+ foreach (var listing in listings)
+ {
+ var now = WorkspaceTrash.List(Path.GetDirectoryName(listing.Folder)!, cancellationToken);
+ if (!string.Equals(now.Fingerprint, listing.Fingerprint, StringComparison.Ordinal))
+ throw new WorkspaceTrashChangedException($"The trash {now.Folder} changed after it was listed.");
+ }
+ var (items, bytes) = (0, 0L);
+ foreach (var listing in listings.Where(l => !l.IsEmpty))
+ {
+ var (erased, freed) = WorkspaceTrash.Empty(Path.GetDirectoryName(listing.Folder)!, listing, cancellationToken);
+ items += erased;
+ bytes += freed;
+ }
return new WorkspaceTrashResult(items, bytes);
}
catch (WorkspaceTrashChangedException ex)
@@ -130,7 +157,7 @@ public sealed partial class WorkspaceHost
await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
- var cleaner = new WorkspaceCleaner(Sync, db, HomeOf) { LockWait = LockWait };
+ var cleaner = new WorkspaceCleaner(AllSyncs(), db, HomeOf) { LockWait = LockWait };
return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false);
}
finally
@@ -147,10 +174,7 @@ public sealed partial class WorkspaceHost
{
ArgumentNullException.ThrowIfNull(job);
if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
- if (WorkspaceJobs.CopyParameters(job) is not { } copied
- || !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
- StringComparison.OrdinalIgnoreCase))
- return;
+ if (WorkspaceJobs.CopyParameters(job) is not { } copied || !IsUnderRoot(copied.WorkspaceRoot)) return;
_ = Task.Run(async () =>
{
try
@@ -165,6 +189,16 @@ public sealed partial class WorkspaceHost
});
}
+ /// The folder is the workspace's own or one of its homes (local\, servers\<id>\).
+ private bool IsUnderRoot(string folder)
+ {
+ if (string.IsNullOrWhiteSpace(folder)) return false;
+ var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
+ var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
+ return string.Equals(full, root, StringComparison.OrdinalIgnoreCase)
+ || full.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
+ }
+
/// When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).
private IReadOnlyDictionary OpenedSnapshot()
{
@@ -331,7 +365,7 @@ public sealed partial class WorkspaceHost
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
}
var title = project.ReadBundle().Sequence.Title ?? string.Empty;
- var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, Store.Root, project.ProjectId, [], workspace.Home.Server),
+ var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, project.Store.Root, project.ProjectId, [], workspace.Home.Server),
cancellationToken: cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})");
}
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.Move.cs b/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
index a1477008..093690f5 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
@@ -268,13 +268,13 @@ public sealed partial class WorkspaceHost
/// A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).
private async Task MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
{
- var project = Store.Project(folder.ProjectId);
+ var project = Find(folder.ProjectId) ?? Homes.Local.Project(folder.ProjectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
try
{
- var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(folder.ProjectId).StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly);
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 442a1150..97705210 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -12,6 +12,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
+using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
@@ -203,27 +204,77 @@ public sealed partial class WorkspaceHost
public AppSettings Settings => _settings;
- /// The sync over the workspace folder in use (made, with the folder and its manifest, at first use).
+ ///
+ /// The servers known by id and their aliases (owner review 5, #66; the desktop's SyncHost.Identity): a server home's
+ /// folder is named by its server's canonical key. Unset, every key is its own.
+ ///
+ public Func? Identity { get; set; }
+
+ /// The two server keys name the same server (its id key and the addresses it was reached by, ).
+ public bool SameServer(string? left, string? right) => (Identity?.Invoke() ?? ServerIdentity.None).Same(left, right);
+
+ ///
+ /// The workspace folder in use split into its homes (owner review 5, #66: local for this PC's archive,
+ /// servers\<id> for each server; a folder still in the 1.0 layout is one store until its folders are sorted),
+ /// made, with the folder and its manifest, at first use.
+ ///
/// The folder cannot be made or read.
/// The folder holds another program's or a newer workspace manifest.
- public WorkspaceSync Sync
+ public WorkspaceHomes Homes
{
get
{
var root = Root;
+ var identity = Identity?.Invoke() ?? ServerIdentity.None;
lock (_gate)
{
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
- {
- var store = new WorkspaceStore(root);
- _open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
- }
- return open.Sync;
+ _open = open = new OpenWorkspace(root, new WorkspaceHomes(root, identity));
+ open.Homes.Identity = identity;
+ return open.Homes;
}
}
}
- public WorkspaceStore Store => Sync.Store;
+ /// Opens the folder in use again at next use (after its folders were sorted into homes: its layout changed).
+ public void Reopen()
+ {
+ lock (_gate) _open = null;
+ }
+
+ /// The project's folder in whichever home holds it; null when the workspace has none.
+ public WorkspaceProject? Find(Guid projectId) => Homes.Find(projectId);
+
+ /// The sync over the store of the home that holds .
+ /// The workspace has no such project (Errors.Workspace.NotCheckedOut).
+ public WorkspaceSync SyncOf(Guid projectId) => SyncOf(Existing(projectId).Store);
+
+ /// The sync over the store a project of is checked out into (made, with its manifest, when it is not there).
+ public WorkspaceSync SyncFor(BundleHome home) => SyncOf(Homes.StoreFor(home));
+
+ /// The sync over (one per store of the folder in use).
+ public WorkspaceSync SyncOf(WorkspaceStore store)
+ {
+ ArgumentNullException.ThrowIfNull(store);
+ _ = Homes;
+ lock (_gate)
+ {
+ var open = _open!;
+ if (!open.Syncs.TryGetValue(store.Root, out var sync))
+ {
+ sync = new WorkspaceSync(store, ClientName) { LockWait = LockWait };
+ open.Syncs[store.Root] = sync;
+ }
+ return sync;
+ }
+ }
+
+ /// The syncs of every home's store (the clean-up counts them together).
+ private IReadOnlyList AllSyncs()
+ {
+ var stores = Homes.All();
+ return stores.Count == 0 ? [SyncOf(Homes.Local)] : [.. stores.Select(SyncOf)];
+ }
///
/// The project home of a server home (phase 5b; the desktop's SyncHost.ProjectHome): null while this PC is not
@@ -273,8 +324,8 @@ public sealed partial class WorkspaceHost
BundleHome home;
try
{
- if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
- || !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
+ if (!IsAvailable || Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
+ || !SameServer(held.Server, server))
return;
home = held;
}
@@ -298,7 +349,7 @@ public sealed partial class WorkspaceHost
{
// Nothing is written into a folder being moved: the next status read takes the name.
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
- else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
+ else if (HomeOf(home) is { } reached) await SyncOf(change.ProjectId).FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -316,7 +367,7 @@ public sealed partial class WorkspaceHost
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
var entries = new List();
- foreach (var project in Store.List())
+ foreach (var project in Homes.List())
{
try
{
@@ -345,7 +396,7 @@ public sealed partial class WorkspaceHost
{
EnsureNotMoving();
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
- return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
+ return Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
}, cancellationToken);
/// Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.
@@ -381,7 +432,7 @@ public sealed partial class WorkspaceHost
if (plan.IsSame) return;
if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true };
// Opened before it is named: a folder that is no workspace is refused while the one in use still is.
- await Task.Run(() => new WorkspaceStore(plan.Folder), cancellationToken).ConfigureAwait(false);
+ await Task.Run(() => new WorkspaceHomes(plan.Folder), cancellationToken).ConfigureAwait(false);
// Back on the caller's thread (the UI's): the settings are written there.
_settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder;
_savePreferences();
@@ -470,10 +521,10 @@ public sealed partial class WorkspaceHost
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
}
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
- if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
+ if (Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
- var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
- Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
+ var folder = await SyncFor(home).CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
+ Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {folder.Store.Root}");
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
@@ -507,14 +558,14 @@ public sealed partial class WorkspaceHost
var home = askHome ? HomeOf(named) : null;
try
{
- if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ if (askHome && home is null && !named.IsArchive) return Offline(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}");
- var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with
{
Offline = true,
@@ -545,8 +596,8 @@ public sealed partial class WorkspaceHost
var version = await Task.Run(async () =>
{
EnsureNotMoving();
- EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
+ EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
@@ -568,8 +619,8 @@ public sealed partial class WorkspaceHost
public Task CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
- EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
+ EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
///
@@ -583,10 +634,10 @@ public sealed partial class WorkspaceHost
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
- var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
if (pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone) return pulled;
- var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
@@ -609,16 +660,16 @@ public sealed partial class WorkspaceHost
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
}
else
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
if (resolved.Status.State == WorkspaceState.Conflict)
{
@@ -628,7 +679,7 @@ public sealed partial class WorkspaceHost
// Deleted in the library: nothing more to send (a Save both's copy holds the versions already).
if (resolved.Status.State == WorkspaceState.Gone) return resolved;
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
- var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
{
Kept = resolved.Kept,
@@ -652,11 +703,11 @@ public sealed partial class WorkspaceHost
public Task RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
- var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
- var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
+ var restored = await SyncOf(projectId).RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored;
}, cancellationToken);
@@ -665,7 +716,7 @@ public sealed partial class WorkspaceHost
public Task HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
- var unsent = Sync.Unpushed(projectId);
+ var unsent = SyncOf(projectId).Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList stored;
var offline = false;
@@ -740,9 +791,9 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId);
- var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
- if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
+ if (!local.ReadOnly) await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
@@ -773,7 +824,7 @@ public sealed partial class WorkspaceHost
/// A conflict waits (open the project and Sync to settle it), or something is still not at the home.
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{
- var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
+ var local = await Task.Run(() => SyncOf(projectId).StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
@@ -837,7 +888,7 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
- var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Unsent(workspace.Home));
@@ -894,8 +945,8 @@ public sealed partial class WorkspaceHost
/// The local versions sent (after the home's new ones were taken), as one sync without the pruning.
private async Task SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
- var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
- return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
/// The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.
@@ -948,7 +999,7 @@ public sealed partial class WorkspaceHost
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
// Filled under a staging name Empty… never lists, and named once whole.
- using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow);
+ using var trash = WorkspaceTrash.Begin(project.Store.Root, project.ProjectId, DateTime.UtcNow);
var aside = trash.Path;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
@@ -1087,11 +1138,12 @@ public sealed partial class WorkspaceHost
{
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
- request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
+ request = WorkspaceJobs.Copy(sequence, Existing(projectId).Store.Root, projectId, media);
}
else
{
- request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
+ request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."),
+ Existing(projectId).Store.Root,
projectId, media);
}
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -1108,7 +1160,7 @@ public sealed partial class WorkspaceHost
: "This PC is not signed in to the server of the project, or it keeps no projects.");
}
- private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
+ private WorkspaceProject Existing(Guid projectId) => Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{
@@ -1206,14 +1258,20 @@ public sealed partial class WorkspaceHost
}
}
- /// The projects a workspace folder holds (folders named by a project id with a working state), without making or opening it.
+ ///
+ /// The projects a workspace folder holds (folders named by a project id with a working state), in it and in its homes'
+ /// folders (local, servers\<folder>, owner review 5), without making or opening it.
+ ///
private static int CountProjects(string folder)
{
if (!Directory.Exists(folder)) return 0;
try
{
- return Directory.EnumerateDirectories(folder).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
- && File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
+ var stores = new List { folder, HomeFolders.LocalPath(folder) };
+ var servers = Path.Combine(folder, HomeFolders.Servers);
+ if (Directory.Exists(servers)) stores.AddRange(Directory.EnumerateDirectories(servers).Where(d => HomeFolders.IsServerFolder(Path.GetFileName(d))));
+ return stores.Where(Directory.Exists).Sum(store => Directory.EnumerateDirectories(store).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
+ && File.Exists(Path.Combine(d, WorkspaceProject.BundleFile))));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -1236,5 +1294,9 @@ public sealed partial class WorkspaceHost
return (files, bytes);
}
- private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
+ /// The workspace folder in use, its homes and the sync of each of its stores (by root).
+ private sealed record OpenWorkspace(string Root, WorkspaceHomes Homes)
+ {
+ public Dictionary Syncs { get; } = new(StringComparer.OrdinalIgnoreCase);
+ }
}
diff --git a/src/Chronos.Core.Windows/Shell/AppPaths.cs b/src/Chronos.Core.Windows/Shell/AppPaths.cs
index 19647f6f..9f750891 100644
--- a/src/Chronos.Core.Windows/Shell/AppPaths.cs
+++ b/src/Chronos.Core.Windows/Shell/AppPaths.cs
@@ -7,7 +7,7 @@ namespace Chronos.Core.Windows.Shell;
/// .\data next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable
/// copy in a OneDrive folder keeps its data in %LOCALAPPDATA%\Chronos instead (
/// names that folder to tell the user, the data it kept there before), and a data
-/// root still under OneDrive is reported by and refused by .
+/// root still under OneDrive is reported by .
///
public sealed class AppPaths
{
@@ -35,8 +35,6 @@ public sealed class AppPaths
public string CacheDirectory => Path.Combine(DataRoot, "cache");
- public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails");
-
/// The OneDrive sync root containing , or null when the location is safe.
public string? SyncedFolder { get; }
@@ -69,16 +67,4 @@ public sealed class AppPaths
: null;
return new AppPaths(location, earlier);
}
-
- /// Creates the data, logs, cache and thumbnails folders.
- /// The data root lies inside a OneDrive-synced folder.
- public void CreateDirectories()
- {
- if (SyncedFolder is not null)
- throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation.");
- Directory.CreateDirectory(DataRoot);
- Directory.CreateDirectory(LogsDirectory);
- Directory.CreateDirectory(CacheDirectory);
- Directory.CreateDirectory(ThumbnailsDirectory);
- }
}
diff --git a/src/Chronos.Core/IO/HomeFolders.cs b/src/Chronos.Core/IO/HomeFolders.cs
new file mode 100644
index 00000000..3d5b83fe
--- /dev/null
+++ b/src/Chronos.Core/IO/HomeFolders.cs
@@ -0,0 +1,178 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Chronos.Core.IO;
+
+///
+/// The folders each home of the desktop keeps apart (owner review 5, #66): this PC's archive is the home ,
+/// and every Chronos Server is a home of its own under , named by the server's stable id
+/// (servers\<id:N>), or, for a server that announces none (an older server), by a hash of its address key
+/// (servers\addr-<16 hex>: the hash the 1.0 proxy cache named its folders by, so moving them is a rename).
+/// The same names are used in the workspace (<workspace>\local, <workspace>\servers\<folder>)
+/// and in the cache (<cache>\servers\<folder>\{proxies,render-node,import}). A folder name is never renamed
+/// after the server: its name lives in beside it.
+///
+public static class HomeFolders
+{
+ /// The folder of this PC's archive's home.
+ public const string Local = "local";
+
+ /// The folder that holds one folder per server home.
+ public const string Servers = "servers";
+
+ /// What a server home's folder says about its server (id, name, last address), for someone browsing it.
+ public const string ServerFile = "server.json";
+
+ /// A server home's proxies of its sequences, in the cache.
+ public const string Proxies = "proxies";
+
+ /// A server home's render-node downloads, in the cache.
+ public const string RenderNode = "render-node";
+
+ /// A server home's staged card imports, in the cache.
+ public const string Import = "import";
+
+ /// The start of a server key made from the server's announced id (id:<32 hex>).
+ public const string IdKeyPrefix = "id:";
+
+ /// The start of the folder of a server known by its address only.
+ public const string AddressPrefix = "addr-";
+
+ /// Hex digits of the address hash in a folder name (as the 1.0 proxy cache used).
+ public const int HashLength = 16;
+
+ ///
+ /// The folder of a server home: the 32 hex digits of the id of an id key (id:<N>), else addr- and the
+ /// first 16 hex digits of the SHA-256 of the key (an address key, as SyncService.ServerKey makes it).
+ ///
+ public static string ServerFolder(string serverKey)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
+ return IdOfKey(serverKey) is { } id ? id.ToString("N") : AddressPrefix + AddressHash(serverKey);
+ }
+
+ /// The 16 hex digits the 1.0 proxy cache named a server's folder by: the start of the SHA-256 of its key.
+ public static string AddressHash(string serverKey)
+ {
+ ArgumentNullException.ThrowIfNull(serverKey);
+ return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(serverKey)))[..HashLength];
+ }
+
+ /// The id an id key names (id:<N>); null for an address key.
+ public static Guid? IdOfKey(string? serverKey) =>
+ serverKey is { Length: > 0 } key && key.StartsWith(IdKeyPrefix, StringComparison.OrdinalIgnoreCase)
+ && Guid.TryParseExact(key.AsSpan(IdKeyPrefix.Length), "N", out var id) && id != Guid.Empty
+ ? id
+ : null;
+
+ /// The key of a server known by its announced id.
+ public static string IdKey(Guid serverId)
+ {
+ if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
+ return IdKeyPrefix + serverId.ToString("N");
+ }
+
+ ///
+ /// A name a server home's folder can have: 32 lower-case hex digits (an id) or addr- with 16 lower-case hex
+ /// digits. Anything else under is not a home (left alone).
+ ///
+ public static bool IsServerFolder(string? name) => name is { Length: > 0 } && (IdOfFolder(name) is not null || IsAddressFolder(name));
+
+ /// The server id a folder named by one stands for; null for an address folder or another name.
+ public static Guid? IdOfFolder(string? name) =>
+ name is { Length: 32 } && IsLowerHex(name) && Guid.TryParseExact(name, "N", out var id) && id != Guid.Empty ? id : null;
+
+ /// A folder of a server known by its address only (addr- and 16 lower-case hex digits).
+ public static bool IsAddressFolder(string? name) =>
+ name is { Length: > 0 } && name.Length == AddressPrefix.Length + HashLength && name.StartsWith(AddressPrefix, StringComparison.Ordinal)
+ && IsLowerHex(name.AsSpan(AddressPrefix.Length));
+
+ /// The folder of this PC's home under (a workspace or a cache folder).
+ public static string LocalPath(string root)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(root);
+ return Path.Combine(root, Local);
+ }
+
+ /// The folder of the home of under (a workspace or a cache folder).
+ public static string ServerPath(string root, string serverKey)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(root);
+ return Path.Combine(root, Servers, ServerFolder(serverKey));
+ }
+
+ ///
+ /// Where the originals a server's sequences download go by default (owner review 5, Q1): an archive of their own beside
+ /// this PC's, <parent of the archive>\<archive folder name> - <server name>, for example
+ /// D:\ChronosArchive - Studio NAS. The server's name is made safe as a folder name (); a
+ /// folder says is taken gets " (2)", " (3)"… With no archive of this PC's,
+ /// (where a first archive would go) stands for it.
+ ///
+ /// The root of this PC's archive; null when there is none.
+ /// The server's name as its server/info gives it.
+ /// Where this PC's first archive would go (the desktop's default archive folder).
+ /// Whether a folder is taken (it exists, or another archive uses it); null takes an existing folder or file.
+ public static string OriginalsArchiveRoot(string? localArchiveRoot, string serverName, string fallbackArchiveRoot, Func? taken = null)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(fallbackArchiveRoot);
+ var archive = Path.TrimEndingDirectorySeparator(Path.GetFullPath(string.IsNullOrWhiteSpace(localArchiveRoot) ? fallbackArchiveRoot : localArchiveRoot));
+ var parent = Path.GetDirectoryName(archive) ?? archive;
+ var name = Path.GetFileName(archive);
+ if (string.IsNullOrEmpty(name)) name = SafeName(Path.GetFileName(Path.TrimEndingDirectorySeparator(fallbackArchiveRoot)));
+ var stem = name + " - " + SafeName(serverName);
+ taken ??= path => Directory.Exists(path) || File.Exists(path);
+ for (var n = 1; ; n++)
+ {
+ var candidate = Path.Combine(parent, n == 1 ? stem : stem + " (" + n.ToString(CultureInfo.InvariantCulture) + ")");
+ if (!taken(candidate)) return candidate;
+ }
+ }
+
+ /// Characters no folder name may hold on Windows (and so on any PC a folder may be copied to).
+ private static readonly char[] Unsafe = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
+
+ private static readonly string[] Reserved =
+ [
+ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
+ "LPT6", "LPT7", "LPT8", "LPT9",
+ ];
+
+ /// The longest folder name gives.
+ public const int MaxNameLength = 60;
+
+ ///
+ /// as a folder name every Windows file system takes: characters it refuses and control characters
+ /// become spaces, runs of spaces one, leading and trailing spaces and dots go, a device name (CON, NUL, COM1…) gets an
+ /// underscore, and it is cut to . "Server" when nothing is left.
+ ///
+ public static string SafeName(string? name)
+ {
+ var text = new StringBuilder(name?.Length ?? 0);
+ foreach (var c in name ?? string.Empty)
+ {
+ var bad = char.IsControl(c) || Array.IndexOf(Unsafe, c) >= 0;
+ var space = bad || char.IsWhiteSpace(c);
+ if (space)
+ {
+ if (text.Length > 0 && text[^1] != ' ') text.Append(' ');
+ continue;
+ }
+ text.Append(c);
+ }
+ var safe = text.ToString().Trim(' ', '.');
+ if (safe.Length > MaxNameLength) safe = safe[..MaxNameLength].TrimEnd(' ', '.');
+ if (safe.Length == 0) return "Server";
+ var stem = safe.Split('.')[0];
+ return Reserved.Contains(stem, StringComparer.OrdinalIgnoreCase) ? safe + "_" : safe;
+ }
+
+ private static bool IsLowerHex(ReadOnlySpan text)
+ {
+ foreach (var c in text)
+ {
+ if (c is not ((>= '0' and <= '9') or (>= 'a' and <= 'f'))) return false;
+ }
+ return true;
+ }
+}
diff --git a/src/Chronos.Core/Project/ProjectBundle.cs b/src/Chronos.Core/Project/ProjectBundle.cs
index 86921be2..bb462dec 100644
--- a/src/Chronos.Core/Project/ProjectBundle.cs
+++ b/src/Chronos.Core/Project/ProjectBundle.cs
@@ -23,7 +23,10 @@ public sealed record BundleSequence(Guid Id, string Folder, string? Title, int F
///
/// Where a workspace project's versions live (owner review 2, R8): this PC's archive (, with the
-/// archive's id) or a server (, with its address), and the sequence there.
+/// archive's id) or a server (, with its key), and the sequence there. A server's key is its id key
+/// (id:<N>, ) once the server announced its stable id (owner review 5, #66),
+/// else the address it was reached at (https://nas.local:8443, the 1.0 key, which an id-keyed server keeps as an
+/// alias); the format does not change.
///
public sealed record BundleHome(string Kind, Guid SequenceId, Guid? ArchiveId = null, string? Server = null)
{
diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
index 4e475c1a..a389c9fc 100644
--- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs
+++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
@@ -372,7 +372,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 d6de7b28..5e5ea86b 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.Data/Homes/HomeLayoutJournal.cs b/src/Chronos.Data/Homes/HomeLayoutJournal.cs
new file mode 100644
index 00000000..e68a3d89
--- /dev/null
+++ b/src/Chronos.Data/Homes/HomeLayoutJournal.cs
@@ -0,0 +1,102 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
+
+namespace Chronos.Data.Homes;
+
+/// What one entry of the sorting of the folders into homes moves ().
+public enum HomeEntryKind
+{
+ /// A workspace project's folder (<workspace>\<project id>) into its home's store.
+ Project,
+
+ /// An entry of the workspace's trash (<workspace>\.trash\<name>) into its home's trash.
+ Trash,
+
+ /// A server's proxy cache (<cache>\proxies\<hash>, or one sequence of it) into its home in the cache.
+ Proxies,
+
+ /// The render node's downloads (<cache>\render-node) into the home of the server they came from.
+ RenderNode,
+
+ /// A card import staged for a server (<cache>\server-import) into that server's home in the cache.
+ Import,
+}
+
+/// Why the workspace part of the sorting waits for a later start (the cache part runs all the same).
+public enum HomeLayoutDeferral
+{
+ /// The workspace folder cannot be reached (an unplugged drive).
+ Offline,
+
+ /// A move of the workspace folder is under way or stopped (its journal, or a move job not finished): it is taken up or undone first.
+ Moving,
+}
+
+///
+/// One rename of the sorting (): what it is, the folder it is in (: the
+/// workspace or the cache), the path it leaves and the path it takes (both full, in , so on one
+/// volume), and the inventory read at planning: files and bytes, and the SHA-256 of their relative names and sizes, which the
+/// target must show after the rename. Leases are left out of the inventory.
+///
+/// The server key of the home it goes to (canonical); null for this PC's home and for a server known only by hash.
+/// The server's name as the project's file gives it, for the home's server.json.
+public sealed record HomeLayoutEntry(HomeEntryKind Kind, string Root, string Source, string Target, int Files, long Bytes, string Inventory,
+ string? ServerKey = null, string? ServerName = null);
+
+/// How far the sorting went.
+public enum HomeLayoutStage
+{
+ /// Entries are being renamed; the workspace's parent manifest is not split yet.
+ Moving,
+
+ /// Every entry was renamed or skipped and the parent manifest names the split layout; only the journal is left to go.
+ Committed,
+}
+
+///
+/// The journal of the sorting of the folders into homes (<data>\homes-migration.json,
+/// ): the plan's fingerprint, its entries in order, the ones done (renamed, found
+/// renamed, or skipped because in use), whether it splits the workspace's parent, and the stage. Written whole and
+/// atomically before the first rename and after each one, so a sorting stopped at any moment is taken up from it.
+///
+public sealed record HomeLayoutJournal(string Format, int FormatVersion, string Fingerprint, IReadOnlyList Entries, IReadOnlyList Done,
+ string? WorkspaceRoot, bool SplitsWorkspace, HomeLayoutStage Stage, DateTimeOffset Started)
+{
+ public const string FormatName = "chronos-homes-migration";
+ public const int CurrentFormatVersion = 1;
+
+ /// The journal at ; null when there is none, or it cannot be read (logged).
+ public static HomeLayoutJournal? Read(string path)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ if (!File.Exists(path)) return null;
+ try
+ {
+ if (JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), HomeLayoutJson.Default.HomeLayoutJournal) is
+ { Format: FormatName, Entries: not null, Done: not null } journal && journal.FormatVersion <= CurrentFormatVersion)
+ return journal;
+ Log.Warning("homes", $"{path} is not a journal of the sorting of the folders this Chronos reads");
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("homes", $"{path} cannot be read", ex);
+ }
+ return null;
+ }
+
+ /// Writes the journal whole to a temporary file and moves it into place.
+ public static void Write(string path, HomeLayoutJournal journal)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ ArgumentNullException.ThrowIfNull(journal);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ AtomicFile.WriteAllText(path, JsonSerializer.Serialize(journal, HomeLayoutJson.Default.HomeLayoutJournal));
+ }
+}
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ UseStringEnumConverter = true, WriteIndented = true)]
+[JsonSerializable(typeof(HomeLayoutJournal))]
+internal sealed partial class HomeLayoutJson : JsonSerializerContext;
diff --git a/src/Chronos.Data/Homes/HomeLayoutMigration.cs b/src/Chronos.Data/Homes/HomeLayoutMigration.cs
new file mode 100644
index 00000000..2d354a36
--- /dev/null
+++ b/src/Chronos.Data/Homes/HomeLayoutMigration.cs
@@ -0,0 +1,788 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using Chronos.Core.Archiving;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Projects;
+using Chronos.Data.Sync;
+using Chronos.Data.Workspaces;
+
+namespace Chronos.Data.Homes;
+
+/// What the sorting of the folders into homes works on ().
+public sealed record HomeLayoutOptions
+{
+ /// The program's data folder, which holds the journal ().
+ public required string DataDirectory { get; init; }
+
+ /// The workspace folder (Settings › Workspace › Folder: the parent of the homes); null leaves the workspace alone.
+ public string? WorkspaceRoot { get; init; }
+
+ /// The cache folder (Settings › Storage › Cache folder); null leaves the cache alone.
+ public string? CacheRoot { get; init; }
+
+ /// The servers known by id and their aliases: a home is named by its server's canonical key.
+ public ServerIdentity Identity { get; init; } = ServerIdentity.None;
+
+ ///
+ /// The server this PC is signed in to, or was last (its key): the 1.0 render-node downloads and staged server import,
+ /// shared by every server then, go to its home. Null leaves them where they are (the cache trims them).
+ ///
+ public string? CurrentServer { get; init; }
+
+ /// The index: a workspace move job not finished defers the workspace part, and a re-key moves the server's links. Null skips both.
+ public ChronosDatabase? Database { get; init; }
+
+ public TimeProvider Time { get; init; } = TimeProvider.System;
+}
+
+///
+/// What the sorting would move, read without writing anything (): its entries, the
+/// workspace projects in use now that wait for a later start, why the workspace part waits (null when it does not), whether it
+/// splits the workspace's parent (its manifest goes to format ), and a
+/// fingerprint of what was read.
+///
+public sealed record HomeLayoutPlan(IReadOnlyList Entries, IReadOnlyList InUse, HomeLayoutDeferral? Deferred, bool SplitsWorkspace,
+ string Fingerprint)
+{
+ /// Nothing to rename and no manifest to write.
+ public bool IsEmpty => Entries.Count == 0 && !SplitsWorkspace;
+
+ /// The workspace projects the sorting moves.
+ public int Projects => Entries.Count(e => e.Kind == HomeEntryKind.Project);
+
+ /// The bytes of everything it moves (renamed, never copied).
+ public long Bytes => Entries.Sum(e => e.Bytes);
+}
+
+/// What a sorting did: projects and entries moved, projects left where they are (in use), why the workspace waits, whether it was taken up from a journal.
+/// Entries whose target was taken: what lost went to its home's trash (workspace) or stayed where it is (cache); never deleted.
+public sealed record HomeLayoutResult(int ProjectsMoved, int EntriesMoved, int InUse, HomeLayoutDeferral? Deferred, bool Resumed, int Clashes, bool Split)
+{
+ public static HomeLayoutResult Nothing { get; } = new(0, 0, 0, null, false, 0, false);
+}
+
+/// What a re-key did ().
+/// Home folders renamed whole to the id's (workspace and cache).
+/// Projects moved one by one into the id's home (the same server reached at two addresses).
+/// Copies of one project in both homes whose older one went to the trash of the id's home.
+/// Working states whose home now names the id key.
+/// Working states held by a writer: left naming an alias, which matches all the same.
+public sealed record HomeRekeyResult(int HomesMoved, int ProjectsMoved, int ProjectsTrashed, int BundlesRewritten, int BundlesInUse, int LinksMoved, int LinksDropped);
+
+/// A rename of the sorting did not leave the folder as planned: it stopped there, its journal kept, and nothing was deleted.
+public sealed class HomeLayoutException(string message, Exception? inner = null) : IOException(message, inner);
+
+///
+/// The one-time sorting of the desktop's folders into homes (owner review 5, #66), run at the start of 1.1 before the job
+/// engine runs, and the re-key of a server's home when it first announces its id.
+///
+/// Plan (, a dry run): each workspace project folder of the 1.0 layout goes to the store of its
+/// home (: local, or servers\<folder> of its server), one whose working
+/// state cannot be read to local (it still lists and opens as damaged); each trash entry goes to its project's home's
+/// trash; the 1.0 proxy cache <cache>\proxies\<hash> goes to <cache>\servers\<folder>\proxies
+/// (the folder of a known server's id when the hash is one of its aliases', else addr-<hash>, the same hash), and
+/// the shared render-node and server-import to the current server's home. A project in use (a live lease) is
+/// left for a later start. A workspace folder out of reach, or one being moved, defers the workspace part; the cache part runs.
+///
+///
+/// Apply (): the journal is written first and after every rename; every move is a rename inside
+/// the folder it is in (so on one volume, no byte copied, nothing half-copied), checked by inventory (the same relative names
+/// and sizes at the target, the source gone), which is enough where no byte is rewritten (the rule
+/// uses on one volume). A rename that does not check stops the sorting with its journal; the next start takes it up. A
+/// target already taken is a clash: in the workspace the older working state goes to the home's trash, in the cache the
+/// entry stays where it is; nothing is deleted. Writing the split parent manifest is the last step: it commits the layout.
+/// Running again on sorted folders does nothing.
+///
+///
+public sealed class HomeLayoutMigration
+{
+ /// The journal of a sorting under way, in the data folder (only while one is unfinished).
+ public const string JournalFile = "homes-migration.json";
+
+ /// The 1.0 folder of the proxy cache in the cache folder.
+ public const string LegacyProxies = "proxies";
+
+ /// The 1.0 folder of the render node's downloads in the cache folder.
+ public const string LegacyRenderNode = "render-node";
+
+ /// The 1.0 folder of card imports staged for a server in the cache folder.
+ public const string LegacyServerImport = "server-import";
+
+ private const string TrashFolder = WorkspaceTrash.FolderName;
+
+ private readonly HomeLayoutOptions _options;
+
+ public HomeLayoutMigration(HomeLayoutOptions options)
+ {
+ ArgumentNullException.ThrowIfNull(options);
+ ArgumentException.ThrowIfNullOrWhiteSpace(options.DataDirectory);
+ _options = options;
+ }
+
+ /// The journal's path.
+ public string JournalPath => Path.Combine(_options.DataDirectory, JournalFile);
+
+ ///
+ /// Called at named steps with the path concerned (tests: a crash): journal (the journal first written), rename
+ /// (an entry about to be renamed), renamed (an entry renamed, its journal not written yet), commit (the parent
+ /// manifest about to be written).
+ ///
+ internal Action? Cut { get; init; }
+
+ private DateTimeOffset Now => _options.Time.GetUtcNow();
+
+ // ---------------- Plan ----------------
+
+ /// What the sorting would move now (); nothing is written.
+ /// A folder cannot be read.
+ public async Task PlanAsync(CancellationToken cancellationToken = default)
+ {
+ var entries = new List();
+ var inUse = new List();
+ HomeLayoutDeferral? deferred = null;
+ var splits = false;
+ if (_options.WorkspaceRoot is { Length: > 0 } configured)
+ {
+ var root = WorkspaceStore.FullRoot(configured);
+ if (!Directory.Exists(root))
+ {
+ // Never made yet (the workspace opens split), or on a drive that is not there.
+ if (!Reachable(root)) deferred = HomeLayoutDeferral.Offline;
+ }
+ else if (WorkspaceMover.HasJournal(root) || await MovePendingAsync(cancellationToken).ConfigureAwait(false))
+ {
+ deferred = HomeLayoutDeferral.Moving;
+ }
+ else
+ {
+ splits = !WorkspaceHomes.IsSplitRoot(root);
+ PlanWorkspace(root, entries, inUse, cancellationToken);
+ }
+ }
+ if (_options.CacheRoot is { Length: > 0 } cache && Directory.Exists(cache)) PlanCache(Path.GetFullPath(cache), entries, cancellationToken);
+ var fingerprint = new StringBuilder();
+ foreach (var entry in entries)
+ fingerprint.Append(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Source}|{entry.Target}|{entry.Files}|{entry.Bytes}|{entry.Inventory}\n");
+ if (splits) fingerprint.Append("split\n");
+ var plan = new HomeLayoutPlan(entries, inUse, deferred, splits, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint.ToString()))));
+ if (!plan.IsEmpty || inUse.Count > 0 || deferred is not null)
+ {
+ Log.Info("homes", $"Sorting the folders into homes: {plan.Projects} project(s), {entries.Count} entr(ies), {plan.Bytes} bytes"
+ + (splits ? ", the workspace split" : string.Empty) + (inUse.Count > 0 ? $", {inUse.Count} project(s) in use" : string.Empty)
+ + (deferred is { } why ? $", the workspace deferred ({why})" : string.Empty));
+ foreach (var entry in entries) Log.Info("homes", $" {entry.Kind}: {entry.Source} -> {entry.Target} ({entry.Files} files, {entry.Bytes} bytes)");
+ }
+ return plan;
+ }
+
+ private void PlanWorkspace(string root, List entries, List inUse, CancellationToken cancellationToken)
+ {
+ var homes = new Dictionary();
+ foreach (var directory in Directory.EnumerateDirectories(root).Order(StringComparer.Ordinal))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out var id) || !File.Exists(Path.Combine(directory, WorkspaceProject.BundleFile))) continue;
+ if (Leased(directory))
+ {
+ inUse.Add(id);
+ continue;
+ }
+ var (partition, key, name) = PartitionOf(root, Path.Combine(directory, WorkspaceProject.BundleFile), id);
+ homes[id] = (partition, key, name);
+ var (files, bytes, inventory) = Inventory(directory);
+ entries.Add(new HomeLayoutEntry(HomeEntryKind.Project, root, directory, Path.Combine(partition, id.ToString("N")), files, bytes, inventory, key, name));
+ }
+ var trash = Path.Combine(root, TrashFolder);
+ if (!Directory.Exists(trash)) return;
+ foreach (var entry in new DirectoryInfo(trash).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var partition = HomeFolders.LocalPath(root);
+ string? key = null;
+ string? name = null;
+ var named = TrashProject(entry.Name);
+ if (named is { } projectId && homes.TryGetValue(projectId, out var home)) (partition, key, name) = home;
+ else if (entry is DirectoryInfo && File.Exists(Path.Combine(entry.FullName, WorkspaceProject.BundleFile)))
+ (partition, key, name) = PartitionOf(root, Path.Combine(entry.FullName, WorkspaceProject.BundleFile), named);
+ var (files, bytes, inventory) = entry is DirectoryInfo ? Inventory(entry.FullName) : FileInventory(entry.FullName);
+ entries.Add(new HomeLayoutEntry(HomeEntryKind.Trash, root, entry.FullName, Path.Combine(partition, TrashFolder, entry.Name), files, bytes, inventory, key, name));
+ }
+ }
+
+ /// The store a working state's home belongs in, its server's canonical key and name; local when it cannot be read.
+ private (string Partition, string? Key, string? Name) PartitionOf(string root, string bundlePath, Guid? projectId)
+ {
+ try
+ {
+ var bundle = ProjectBundle.Load(bundlePath);
+ if (bundle.Workspace is { } workspace && (projectId is null || workspace.ProjectId == projectId)
+ && workspace.Home is { Kind: BundleHome.ServerKind, Server: { Length: > 0 } server })
+ {
+ var key = _options.Identity.Canonical(server);
+ return (Path.Combine(root, HomeFolders.Servers, HomeFolders.ServerFolder(key)), key, bundle.Archive.Name);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or System.Text.Json.JsonException)
+ {
+ Log.Info("homes", $"{bundlePath} cannot be read: it goes to this PC's home ({ex.Message})");
+ }
+ return (HomeFolders.LocalPath(root), null, null);
+ }
+
+ /// The project a trash entry was set aside from (<id>-<ticks>, also while staged as .incoming-…).
+ private static Guid? TrashProject(string name)
+ {
+ var text = name.StartsWith(".incoming-", StringComparison.Ordinal) ? name[".incoming-".Length..] : name;
+ return text.Length >= 32 && Guid.TryParseExact(text.AsSpan(0, 32), "N", out var id) ? id : null;
+ }
+
+ private void PlanCache(string cache, List entries, CancellationToken cancellationToken)
+ {
+ var servers = Path.Combine(cache, HomeFolders.Servers);
+ var proxies = Path.Combine(cache, LegacyProxies);
+ if (Directory.Exists(proxies))
+ {
+ foreach (var directory in Directory.EnumerateDirectories(proxies).Order(StringComparer.Ordinal))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var hash = Path.GetFileName(directory);
+ if (hash.Length != HomeFolders.HashLength || !hash.All(Uri.IsHexDigit)) continue;
+ var key = _options.Identity.Servers.SelectMany(s => s.Aliases).FirstOrDefault(a => HomeFolders.AddressHash(a) == hash.ToLowerInvariant());
+ var folder = key is not null ? _options.Identity.FolderName(key) : HomeFolders.AddressPrefix + hash.ToLowerInvariant();
+ var target = Path.Combine(servers, folder, HomeFolders.Proxies);
+ AddCache(HomeEntryKind.Proxies, cache, directory, target, entries, key is null ? null : _options.Identity.Canonical(key));
+ }
+ }
+ if (_options.CurrentServer is not { Length: > 0 } current) return;
+ var home = Path.Combine(servers, _options.Identity.FolderName(current));
+ var key2 = _options.Identity.Canonical(current);
+ var renderNode = Path.Combine(cache, LegacyRenderNode);
+ if (Directory.Exists(renderNode)) AddCache(HomeEntryKind.RenderNode, cache, renderNode, Path.Combine(home, HomeFolders.RenderNode), entries, key2);
+ var import = Path.Combine(cache, LegacyServerImport);
+ if (Directory.Exists(import)) AddCache(HomeEntryKind.Import, cache, import, Path.Combine(home, HomeFolders.Import), entries, key2);
+ }
+
+ ///
+ /// A cache folder renamed whole into its home, or, where the home already has one, each of its entries the home lacks (an
+ /// entry the home has stays where it is: the cache can be made again).
+ ///
+ private static void AddCache(HomeEntryKind kind, string cache, string source, string target, List entries, string? key)
+ {
+ if (!Directory.Exists(target))
+ {
+ var (files, bytes, inventory) = Inventory(source);
+ entries.Add(new HomeLayoutEntry(kind, cache, source, target, files, bytes, inventory, key));
+ return;
+ }
+ foreach (var child in new DirectoryInfo(source).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
+ {
+ var into = Path.Combine(target, child.Name);
+ if (Directory.Exists(into) || File.Exists(into))
+ {
+ Log.Info("homes", $"{child.FullName} stays where it is: {into} is there already");
+ continue;
+ }
+ var (files, bytes, inventory) = child is DirectoryInfo ? Inventory(child.FullName) : FileInventory(child.FullName);
+ entries.Add(new HomeLayoutEntry(kind, cache, child.FullName, into, files, bytes, inventory, key));
+ }
+ }
+
+ // ---------------- Apply ----------------
+
+ ///
+ /// Sorts the folders, or takes up the sorting its journal records (see the class). Projects in use and a workspace that
+ /// waits are left for a later start; a rename that does not check stops the run with its journal kept.
+ ///
+ /// A rename did not leave the folder as planned; the journal stays for the next start.
+ /// A folder could not be read or renamed; the journal stays for the next start.
+ public async Task ApplyAsync(CancellationToken cancellationToken = default)
+ {
+ var journal = HomeLayoutJournal.Read(JournalPath);
+ var resumed = journal is not null;
+ var inUse = 0;
+ HomeLayoutDeferral? deferred = null;
+ if (journal is null)
+ {
+ if (File.Exists(JournalPath)) throw new HomeLayoutException($"{JournalPath} cannot be read; the folders are left as they are.");
+ var plan = await PlanAsync(cancellationToken).ConfigureAwait(false);
+ inUse = plan.InUse.Count;
+ deferred = plan.Deferred;
+ if (plan.IsEmpty) return HomeLayoutResult.Nothing with { InUse = inUse, Deferred = deferred };
+ journal = new HomeLayoutJournal(HomeLayoutJournal.FormatName, HomeLayoutJournal.CurrentFormatVersion, plan.Fingerprint, plan.Entries, [],
+ _options.WorkspaceRoot is { Length: > 0 } root ? WorkspaceStore.FullRoot(root) : null, plan.SplitsWorkspace, HomeLayoutStage.Moving, Now);
+ HomeLayoutJournal.Write(JournalPath, journal);
+ Cut?.Invoke("journal", JournalPath);
+ }
+ else
+ {
+ Log.Info("homes", $"The sorting of the folders into homes is taken up from {JournalPath} ({journal.Done.Count} of {journal.Entries.Count} done, {journal.Stage})");
+ }
+
+ var (projects, moved, clashes) = (0, 0, 0);
+ var waiting = false;
+ if (journal.Stage == HomeLayoutStage.Moving)
+ {
+ var done = journal.Done.ToHashSet();
+ for (var i = 0; i < journal.Entries.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (done.Contains(i)) continue;
+ var entry = journal.Entries[i];
+ if (!Directory.Exists(entry.Root))
+ {
+ // The workspace's drive went since the plan: this entry waits, with the journal, for a start that reaches it.
+ waiting = true;
+ if (entry.Root == journal.WorkspaceRoot) deferred = HomeLayoutDeferral.Offline;
+ continue;
+ }
+ switch (Move(entry))
+ {
+ case Outcome.Moved:
+ moved++;
+ if (entry.Kind == HomeEntryKind.Project) projects++;
+ break;
+ case Outcome.Clash:
+ moved++;
+ clashes++;
+ if (entry.Kind == HomeEntryKind.Project) projects++;
+ break;
+ case Outcome.InUse:
+ inUse++;
+ break;
+ }
+ done.Add(i);
+ journal = journal with { Done = [.. done.Order()] };
+ HomeLayoutJournal.Write(JournalPath, journal);
+ }
+ if (waiting)
+ {
+ Log.Info("homes", $"The sorting of the folders waits for a folder out of reach; {JournalPath} stays for the next start");
+ return new HomeLayoutResult(projects, moved, inUse, deferred ?? HomeLayoutDeferral.Offline, resumed, clashes, false);
+ }
+ if (journal.WorkspaceRoot is { } workspace)
+ {
+ if (journal.SplitsWorkspace)
+ {
+ Cut?.Invoke("commit", workspace);
+ Commit(workspace, journal);
+ }
+ TryDeleteEmpty(Path.Combine(workspace, TrashFolder));
+ }
+ journal = journal with { Stage = HomeLayoutStage.Committed };
+ HomeLayoutJournal.Write(JournalPath, journal);
+ }
+ File.Delete(JournalPath);
+ Log.Info("homes", $"The folders are sorted into homes: {projects} project(s) and {moved} entr(ies) moved"
+ + (clashes > 0 ? $", {clashes} clash(es) kept in the trash or left in place" : string.Empty)
+ + (inUse > 0 ? $", {inUse} project(s) in use left for a later start" : string.Empty));
+ return new HomeLayoutResult(projects, moved, inUse, deferred, resumed, clashes, journal.SplitsWorkspace);
+ }
+
+ private enum Outcome
+ {
+ Moved,
+ AlreadyMoved,
+ Clash,
+ InUse,
+ }
+
+ /// One entry renamed and checked (see the class).
+ private Outcome Move(HomeLayoutEntry entry)
+ {
+ if (!Exists(entry.Source))
+ {
+ // A run that stopped after the rename: the target holds it.
+ if (Exists(entry.Target))
+ {
+ if (EntryInventory(entry.Target).Inventory != entry.Inventory)
+ Log.Warning("homes", $"{entry.Target} is not as {entry.Source} was planned; it is taken as moved");
+ return Outcome.AlreadyMoved;
+ }
+ Log.Warning("homes", $"{entry.Source} is neither there nor at {entry.Target}");
+ return Outcome.AlreadyMoved;
+ }
+ if (entry.Kind == HomeEntryKind.Project && Leased(entry.Source))
+ {
+ Log.Info("homes", $"{entry.Source} is in use: it stays where it is and moves at a later start");
+ return Outcome.InUse;
+ }
+ var outcome = Outcome.Moved;
+ if (Exists(entry.Target))
+ {
+ if (!IsWorkspaceEntry(entry))
+ {
+ Log.Info("homes", $"{entry.Source} stays where it is: {entry.Target} is there already");
+ return Outcome.Clash;
+ }
+ outcome = Outcome.Clash;
+ if (!ResolveClash(entry)) return Outcome.Clash;
+ }
+ Prepare(entry);
+ Cut?.Invoke("rename", entry.Source);
+ try
+ {
+ if (Directory.Exists(entry.Source)) Directory.Move(entry.Source, entry.Target);
+ else File.Move(entry.Source, entry.Target);
+ }
+ catch (Exception ex) when (entry.Kind == HomeEntryKind.Project && ex is IOException or UnauthorizedAccessException)
+ {
+ // A file of the project held open (another Chronos on the same workspace): it moves at a later start.
+ Log.Info("homes", $"{entry.Source} could not be renamed now ({ex.Message}); it moves at a later start");
+ return Outcome.InUse;
+ }
+ Cut?.Invoke("renamed", entry.Target);
+ if (Exists(entry.Source) || EntryInventory(entry.Target).Inventory != entry.Inventory)
+ throw new HomeLayoutException($"{entry.Source} was renamed to {entry.Target}, which does not hold the files planned; the sorting stops there.");
+ return outcome;
+ }
+
+ private static bool IsWorkspaceEntry(HomeLayoutEntry entry) => entry.Kind is HomeEntryKind.Project or HomeEntryKind.Trash;
+
+ ///
+ /// A workspace entry whose target is taken: for a project, the copy whose working state was saved last stays at the target,
+ /// the other goes to its home's trash (never deleted); for a trash entry, another free name is taken. False when the source
+ /// itself went to the trash (nothing more to rename).
+ ///
+ private bool ResolveClash(HomeLayoutEntry entry)
+ {
+ var partition = entry.Kind == HomeEntryKind.Project ? Path.GetDirectoryName(entry.Target)! : Path.GetDirectoryName(Path.GetDirectoryName(entry.Target))!;
+ if (entry.Kind == HomeEntryKind.Trash)
+ {
+ for (var n = 2; ; n++)
+ {
+ var free = entry.Target + "-" + n.ToString(CultureInfo.InvariantCulture);
+ if (Exists(free)) continue;
+ Prepare(entry);
+ if (Directory.Exists(entry.Source)) Directory.Move(entry.Source, free);
+ else File.Move(entry.Source, free);
+ Log.Info("homes", $"{entry.Source} went to {free}: {entry.Target} is there already");
+ return false;
+ }
+ }
+ var id = Guid.ParseExact(Path.GetFileName(entry.Target), "N");
+ var sourceNewer = Saved(entry.Source) > Saved(entry.Target);
+ var loser = sourceNewer ? entry.Target : entry.Source;
+ _ = new WorkspaceStore(partition);
+ var trash = WorkspaceTrash.NewEntry(partition, id, Now.UtcDateTime);
+ Directory.CreateDirectory(Path.GetDirectoryName(trash)!);
+ Directory.Move(loser, trash);
+ Log.Warning("homes", $"Project {id} is in {entry.Source} and in {entry.Target}: the copy saved last stays, the other went to {trash}");
+ return sourceNewer;
+ }
+
+ /// When a project folder's working state was saved (its file's time when it names none); the oldest time when it cannot be read.
+ private static DateTimeOffset Saved(string folder)
+ {
+ var path = Path.Combine(folder, WorkspaceProject.BundleFile);
+ try
+ {
+ return ProjectBundle.Load(path).Saved;
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or System.Text.Json.JsonException)
+ {
+ return File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path), TimeSpan.Zero) : DateTimeOffset.MinValue;
+ }
+ }
+
+ /// The folder an entry goes into is made: a workspace home's store with its manifest (and a server's record), a cache home's folder.
+ private void Prepare(HomeLayoutEntry entry)
+ {
+ if (IsWorkspaceEntry(entry))
+ {
+ var partition = entry.Kind == HomeEntryKind.Project ? Path.GetDirectoryName(entry.Target)! : Path.GetDirectoryName(Path.GetDirectoryName(entry.Target))!;
+ _ = new WorkspaceStore(partition);
+ if (entry.ServerKey is { } key && ServerHomeRecord.Read(partition) is null)
+ ServerHomeRecord.Write(partition, ServerHomeRecord.Of(key, entry.ServerName, ServerIdentity.IsIdKey(key) ? null : key, null, Now));
+ }
+ Directory.CreateDirectory(Path.GetDirectoryName(entry.Target)!);
+ }
+
+ /// The last step: the workspace's parent manifest names the split layout (its id kept), and this PC's home exists.
+ private static void Commit(string workspace, HomeLayoutJournal journal)
+ {
+ var path = Path.Combine(workspace, WorkspaceStore.ManifestFile);
+ var known = WorkspaceStore.TryRead(path);
+ if (known is { Layout: WorkspaceHomes.HomesLayout }) return;
+ _ = new WorkspaceStore(HomeFolders.LocalPath(workspace));
+ var manifest = new WorkspaceManifest(WorkspaceStore.FormatName, WorkspaceHomes.ParentFormatVersion, known?.Id ?? Guid.CreateVersion7(),
+ known?.Created ?? journal.Started, WorkspaceHomes.HomesLayout);
+ WorkspaceStore.Write(path, manifest);
+ Log.Info("homes", $"The workspace {workspace} is split into homes (manifest format {WorkspaceHomes.ParentFormatVersion})");
+ }
+
+ // ---------------- Re-key ----------------
+
+ ///
+ /// The server announced its id: whatever this PC keeps under its address keys
+ /// moves to its id (owner review 5, #66). The home folder servers\addr-<hash> of each
+ /// alias is renamed to servers\<id> in the workspace and in the cache (and the 1.0 proxy folder of the alias
+ /// with it); where the id's home already has one (the server reached at two addresses), projects move one by one and a
+ /// project in both keeps the copy saved last, the other going to the id home's trash. Working states whose home names an
+ /// alias name the id key afterwards, each rewritten under its lease (one in use keeps the alias, which matches all the
+ /// same); and the server's links move to the id key ('s rule). Run before the sync
+ /// agent starts for the server. Nothing is deleted but a home folder left holding only its manifest and record.
+ ///
+ /// A folder could not be read or renamed; what was done stays done, and a later re-key goes on.
+ public async Task RekeyAsync(Guid serverId, IReadOnlyCollection aliases, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(aliases);
+ if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
+ var idKey = HomeFolders.IdKey(serverId);
+ var keys = aliases.Where(a => !string.IsNullOrWhiteSpace(a) && !ServerIdentity.IsIdKey(a)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
+ var (homes, projects, trashed, rewritten, held, links, dropped) = (0, 0, 0, 0, 0, 0, 0);
+ string? workspaceHome = null;
+ if (_options.WorkspaceRoot is { Length: > 0 } configured && WorkspaceHomes.IsSplitRoot(configured))
+ {
+ var root = WorkspaceStore.FullRoot(configured);
+ workspaceHome = Path.Combine(root, HomeFolders.Servers, serverId.ToString("N"));
+ foreach (var alias in keys)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var from = Path.Combine(root, HomeFolders.Servers, HomeFolders.ServerFolder(alias));
+ if (!Directory.Exists(from)) continue;
+ if (!Directory.Exists(workspaceHome) && !Directory.EnumerateDirectories(from).Any(Leased))
+ {
+ RenameChecked(from, workspaceHome);
+ homes++;
+ continue;
+ }
+ var (merged, lost) = MergeWorkspaceHome(from, workspaceHome, serverId);
+ (projects, trashed) = (projects + merged, trashed + lost);
+ }
+ if (Directory.Exists(workspaceHome))
+ {
+ var (done, busy) = await RewriteBundlesAsync(workspaceHome, keys, idKey, cancellationToken).ConfigureAwait(false);
+ (rewritten, held) = (done, busy);
+ var known = ServerHomeRecord.Read(workspaceHome);
+ ServerHomeRecord.Write(workspaceHome, (known ?? ServerHomeRecord.Of(idKey, null, keys.FirstOrDefault(), null, Now)) with
+ {
+ Key = idKey,
+ Id = serverId,
+ Address = known?.Address is { } address && !ServerIdentity.IsIdKey(address) ? address : keys.FirstOrDefault(),
+ LastSeen = Now,
+ });
+ }
+ }
+ if (_options.CacheRoot is { Length: > 0 } cacheRoot && Directory.Exists(cacheRoot))
+ {
+ var cache = Path.GetFullPath(cacheRoot);
+ var target = Path.Combine(cache, HomeFolders.Servers, serverId.ToString("N"));
+ foreach (var alias in keys)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var from = Path.Combine(cache, HomeFolders.Servers, HomeFolders.ServerFolder(alias));
+ if (Directory.Exists(from))
+ {
+ if (!Directory.Exists(target))
+ {
+ RenameChecked(from, target);
+ homes++;
+ }
+ else
+ {
+ foreach (var area in new DirectoryInfo(from).EnumerateDirectories()) MergeCache(area.FullName, Path.Combine(target, area.Name));
+ }
+ }
+ var legacy = Path.Combine(cache, LegacyProxies, HomeFolders.AddressHash(alias));
+ if (Directory.Exists(legacy)) MergeCache(legacy, Path.Combine(target, HomeFolders.Proxies));
+ }
+ }
+ if (_options.Database is { } db)
+ {
+ var store = new SyncLinkStore(db);
+ foreach (var alias in keys)
+ {
+ var (m, d) = await store.RekeyAsync(alias, idKey, cancellationToken).ConfigureAwait(false);
+ (links, dropped) = (links + m, dropped + d);
+ }
+ }
+ var result = new HomeRekeyResult(homes, projects, trashed, rewritten, held, links, dropped);
+ Log.Info("homes", $"Server {serverId} re-keyed from {string.Join(", ", keys)}: {result}");
+ return result;
+ }
+
+ /// The projects and trash of the alias home moved into the id home (see ).
+ private (int Moved, int Trashed) MergeWorkspaceHome(string from, string into, Guid serverId)
+ {
+ var (moved, trashed) = (0, 0);
+ _ = new WorkspaceStore(into);
+ foreach (var directory in Directory.EnumerateDirectories(from).Order(StringComparer.Ordinal))
+ {
+ if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out var id)) continue;
+ if (Leased(directory))
+ {
+ Log.Info("homes", $"{directory} is in use: it stays in the home of an address of server {serverId} and moves at a later re-key");
+ continue;
+ }
+ var target = Path.Combine(into, id.ToString("N"));
+ if (Directory.Exists(target))
+ {
+ var sourceNewer = Saved(directory) > Saved(target);
+ var loser = sourceNewer ? target : directory;
+ var trash = WorkspaceTrash.NewEntry(into, id, Now.UtcDateTime);
+ Directory.CreateDirectory(Path.GetDirectoryName(trash)!);
+ RenameChecked(loser, trash);
+ trashed++;
+ Log.Warning("homes", $"Project {id} is in {directory} and in {target}: the copy saved last stays, the other went to {trash}");
+ if (!sourceNewer) continue;
+ }
+ RenameChecked(directory, target);
+ moved++;
+ }
+ var trashFrom = Path.Combine(from, TrashFolder);
+ if (Directory.Exists(trashFrom))
+ {
+ var trashInto = Path.Combine(into, TrashFolder);
+ Directory.CreateDirectory(trashInto);
+ foreach (var entry in new DirectoryInfo(trashFrom).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
+ {
+ var target = Path.Combine(trashInto, entry.Name);
+ for (var n = 2; Exists(target); n++) target = Path.Combine(trashInto, entry.Name + "-" + n.ToString(CultureInfo.InvariantCulture));
+ RenameChecked(entry.FullName, target);
+ }
+ TryDeleteEmpty(trashFrom);
+ }
+ // Left with its manifest and record only: Chronos's own description of a folder that holds nothing now.
+ var left = Directory.EnumerateFileSystemEntries(from).Select(Path.GetFileName).ToList();
+ if (left.All(n => n is WorkspaceStore.ManifestFile or HomeFolders.ServerFile))
+ {
+ foreach (var name in left) File.Delete(Path.Combine(from, name!));
+ TryDeleteEmpty(from);
+ }
+ return (moved, trashed);
+ }
+
+ /// Each working state in whose home names an alias rewritten to name , under its lease.
+ private static async Task<(int Rewritten, int InUse)> RewriteBundlesAsync(string home, IReadOnlyList aliases, string idKey, CancellationToken cancellationToken)
+ {
+ var (rewritten, inUse) = (0, 0);
+ var store = new WorkspaceStore(home);
+ foreach (var project in store.List())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ ProjectBundle bundle;
+ try
+ {
+ bundle = project.ReadBundle();
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Info("homes", $"The project in {project.Folder} cannot be read: its home stays as it is ({ex.Message})");
+ continue;
+ }
+ if (bundle.Workspace is not { Home: { Kind: BundleHome.ServerKind, Server: { } server } } || !aliases.Contains(server, StringComparer.OrdinalIgnoreCase))
+ continue;
+ IDisposable lease;
+ try
+ {
+ lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
+ }
+ catch (LeaseUnavailableException)
+ {
+ inUse++;
+ continue;
+ }
+ using (lease)
+ {
+ bundle = project.ReadBundle();
+ if (bundle.Workspace is not { Home: { Server: { } now } } current || !aliases.Contains(now, StringComparer.OrdinalIgnoreCase)) continue;
+ var archive = bundle.Archive.Id == ServerProjectHome.ArchiveIdOf(now) ? bundle.Archive with { Id = ServerProjectHome.ArchiveIdOf(idKey) } : bundle.Archive;
+ project.WriteBundle(bundle with { Archive = archive, Workspace = current with { Home = current.Home with { Server = idKey } } });
+ rewritten++;
+ }
+ }
+ return (rewritten, inUse);
+ }
+
+ /// A cache folder's entries moved into where it lacks them; the source renamed whole when is not there. What is left stays (the cache trims it).
+ private static void MergeCache(string from, string into)
+ {
+ if (!Directory.Exists(into))
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(into)!);
+ RenameChecked(from, into);
+ return;
+ }
+ foreach (var entry in new DirectoryInfo(from).EnumerateFileSystemInfos())
+ {
+ var target = Path.Combine(into, entry.Name);
+ if (Exists(target)) continue;
+ RenameChecked(entry.FullName, target);
+ }
+ TryDeleteEmpty(from);
+ }
+
+ /// A folder or file renamed, checked by inventory: the same relative names and sizes at the target, the source gone.
+ private static void RenameChecked(string source, string target)
+ {
+ var directory = Directory.Exists(source);
+ var before = directory ? Inventory(source).Inventory : FileInventory(source).Inventory;
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ if (directory) Directory.Move(source, target);
+ else File.Move(source, target);
+ var after = directory ? Inventory(target).Inventory : FileInventory(target).Inventory;
+ if (Exists(source) || after != before) throw new HomeLayoutException($"{source} was renamed to {target}, which does not hold the same files.");
+ }
+
+ // ---------------- Helpers ----------------
+
+ /// A workspace move job is waiting, running or stopped (null database: none known).
+ private async Task MovePendingAsync(CancellationToken cancellationToken) =>
+ _options.Database is { } db && await db.Jobs.HasPendingAsync([JobKind.WorkspaceMove], null, cancellationToken).ConfigureAwait(false);
+
+ /// The folder's volume is there (so a folder missing on it was never made, rather than out of reach).
+ private static bool Reachable(string folder)
+ {
+ for (var current = Path.GetDirectoryName(folder); !string.IsNullOrEmpty(current); current = Path.GetDirectoryName(current))
+ {
+ if (Directory.Exists(current)) return true;
+ }
+ return false;
+ }
+
+ /// The project folder's lease is held now (another Chronos, with another data folder, works on the same workspace).
+ private bool Leased(string folder) =>
+ LeaseFile.Read(Path.Combine(folder, WorkspaceProject.LeaseFileName)) is { } held && held.Expires > Now;
+
+ private static bool Exists(string path) => Directory.Exists(path) || File.Exists(path);
+
+ /// The inventory of an entry at : a folder's, or a single file's (a trash entry that is one).
+ private static (int Files, long Bytes, string Inventory) EntryInventory(string path) => File.Exists(path) ? FileInventory(path) : Inventory(path);
+
+ /// A folder's files (leases left out): their count and bytes, and the SHA-256 of their relative names and sizes in ordinal order.
+ internal static (int Files, long Bytes, string Inventory) Inventory(string folder)
+ {
+ var lines = new List();
+ var bytes = 0L;
+ foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
+ {
+ if (WorkspaceProject.IsLeaseFile(file.Name)) continue;
+ bytes += file.Length;
+ lines.Add(Path.GetRelativePath(folder, file.FullName).Replace('\\', '/') + "|" + file.Length.ToString(CultureInfo.InvariantCulture));
+ }
+ lines.Sort(StringComparer.Ordinal);
+ return (lines.Count, bytes, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines)))));
+ }
+
+ private static (int Files, long Bytes, string Inventory) FileInventory(string file)
+ {
+ var length = new FileInfo(file).Length;
+ return (1, length, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("|" + length.ToString(CultureInfo.InvariantCulture)))));
+ }
+
+ private static void TryDeleteEmpty(string folder)
+ {
+ try
+ {
+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Debug("homes", $"{folder} stays: {ex.Message}");
+ }
+ }
+}
diff --git a/src/Chronos.Data/Projects/ServerProjectHome.cs b/src/Chronos.Data/Projects/ServerProjectHome.cs
index 7f97ddb3..a146d3aa 100644
--- a/src/Chronos.Data/Projects/ServerProjectHome.cs
+++ b/src/Chronos.Data/Projects/ServerProjectHome.cs
@@ -28,12 +28,16 @@ public sealed class ServerProjectHome : IProjectHome
/// The server's name as its server/info gives it, for the project file; the address's host when null.
/// The settings format its server/info announces (); null, an older server's 1.
- public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null, int? settingsFormat = null)
+ ///
+ /// The key workspace projects name the server by (: its id key once it
+ /// announced one, owner review 5); null takes the client's address key ().
+ ///
+ public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null, int? settingsFormat = null, string? server = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
- Server = SyncService.ServerKey(client.BaseAddress);
+ Server = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
SettingsFormat = settingsFormat is > 0 and var format ? format : ProjectSettings.BaseVersion;
}
@@ -80,6 +84,17 @@ public sealed class ServerProjectHome : IProjectHome
return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}
+ ///
+ /// is the archive id a project file of a sequence of the server name
+ /// carries ( of any of them: its id key, or an address key it was reached under before it
+ /// announced its id, owner review 5).
+ ///
+ public static bool IsArchiveIdOf(Guid archiveId, IEnumerable keys)
+ {
+ ArgumentNullException.ThrowIfNull(keys);
+ return keys.Any(key => !string.IsNullOrWhiteSpace(key) && ArchiveIdOf(key) == archiveId);
+ }
+
public Task> ListAsync(CancellationToken cancellationToken) =>
Reach>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
diff --git a/src/Chronos.Data/Sync/ProxyCache.cs b/src/Chronos.Data/Sync/ProxyCache.cs
index 6af4f9c4..2834ee11 100644
--- a/src/Chronos.Data/Sync/ProxyCache.cs
+++ b/src/Chronos.Data/Sync/ProxyCache.cs
@@ -69,11 +69,15 @@ internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJso
internal sealed partial class ProxyCacheJson : JsonSerializerContext;
///
-/// Proxies of server sequences on this PC: <root>/<server hash>/<sequence id>/ with one JPEG per
-/// frame (named by frame id, so renumbering never mixes them up) and remote.json. Everything here can be
-/// downloaded again, so the folder lives in the client's cache.
+/// Proxies of server sequences on this PC, one folder per sequence with one JPEG per frame (named by frame id, so
+/// renumbering never mixes them up) and remote.json. With a servers root (owner review 5, #66) a sequence's folder is
+/// <servers>/<home folder>/proxies/<sequence id>/ ( of the
+/// server's canonical key); a folder still where an earlier layout put it (<root>/<address hash>/<sequence
+/// id>/, 1.0; or the home folder of one of the server's aliases) is used where it is until it is moved, so a sequence
+/// always has one folder. Without a servers root the 1.0 layout stays. Everything here can be downloaded again, so the
+/// folder lives in the client's cache.
///
-internal sealed class ProxyCache(string root)
+internal sealed class ProxyCache(string root, string? servers = null, Func? identity = null)
{
/// The asset kind of a cached proxy (the server's name for it).
public const string Proxy = "proxy";
@@ -83,8 +87,27 @@ internal sealed class ProxyCache(string root)
private const string IndexFile = "remote.json";
- public string Folder(string server, Guid remoteId) =>
- Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..16], remoteId.ToString("N"));
+ /// The 1.0 folder of a server sequence's proxies: <root>/<address hash>/<sequence id>.
+ internal static string LegacyFolder(string root, string server, Guid remoteId) =>
+ Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..HomeFolders.HashLength], remoteId.ToString("N"));
+
+ /// The folder of a server sequence's proxies: where it is now, or where a new one goes (see the class).
+ public string Folder(string server, Guid remoteId)
+ {
+ if (servers is null) return LegacyFolder(root, server, remoteId);
+ var known = identity?.Invoke() ?? ServerIdentity.None;
+ var name = remoteId.ToString("N");
+ var target = Path.Combine(servers, known.FolderName(server), HomeFolders.Proxies, name);
+ if (Directory.Exists(target)) return target;
+ foreach (var key in known.KeysOf(server))
+ {
+ var home = Path.Combine(servers, HomeFolders.ServerFolder(key), HomeFolders.Proxies, name);
+ if (Directory.Exists(home)) return home;
+ var legacy = LegacyFolder(root, key, remoteId);
+ if (Directory.Exists(legacy)) return legacy;
+ }
+ return target;
+ }
public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg";
diff --git a/src/Chronos.Data/Sync/ServerIdentity.cs b/src/Chronos.Data/Sync/ServerIdentity.cs
new file mode 100644
index 00000000..3be8b836
--- /dev/null
+++ b/src/Chronos.Data/Sync/ServerIdentity.cs
@@ -0,0 +1,121 @@
+using Chronos.Core.IO;
+using Chronos.Protocol;
+
+namespace Chronos.Data.Sync;
+
+/// A server known by its stable id, with the address keys it was reached under ().
+/// The server's id ().
+/// The legacy address keys this id was reached under, in any case.
+public sealed record KnownServerKey(Guid Id, IReadOnlyCollection Aliases);
+
+///
+/// How the desktop names a server (owner review 5, #66). A server that announces its stable id
+/// () is keyed id:<N> (), the same whatever
+/// address it is reached by; an older one keeps its address key (, the 1.0 key, here the
+/// ). An instance holds the alias table: the address keys each known id was reached under, which
+/// projects, links and jobs made before the id was known still carry. turns an alias into its id
+/// key, compares two keys through it, and is the home's folder
+/// () of the canonical key. Keys compare ignoring case, as address keys always did.
+///
+public sealed class ServerIdentity
+{
+ private readonly Dictionary _canonical = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary> _aliases = new(StringComparer.OrdinalIgnoreCase);
+
+ /// No server known by id: every key is its own.
+ public static ServerIdentity None { get; } = new([]);
+
+ public ServerIdentity(IEnumerable servers)
+ {
+ ArgumentNullException.ThrowIfNull(servers);
+ var known = new List();
+ foreach (var server in servers)
+ {
+ if (server.Id == Guid.Empty) continue;
+ var idKey = HomeFolders.IdKey(server.Id);
+ if (!_aliases.TryGetValue(idKey, out var list))
+ {
+ list = [];
+ _aliases[idKey] = list;
+ }
+ foreach (var alias in server.Aliases ?? [])
+ {
+ if (string.IsNullOrWhiteSpace(alias) || string.Equals(alias, idKey, StringComparison.OrdinalIgnoreCase)) continue;
+ // An address that two ids claim (a server replaced at the same address) stays with the first one listed.
+ if (!_canonical.TryAdd(alias, idKey)) continue;
+ list.Add(alias);
+ }
+ known.Add(server);
+ }
+ Servers = known;
+ }
+
+ /// The servers this table knows, as it was given them.
+ public IReadOnlyList Servers { get; }
+
+ /// The key of a server reached at : its id key when announces an id, else its address key.
+ public static string Key(ServerInfo? info, Uri address) => Key(info?.ServerId, address);
+
+ /// The key of a server reached at : id:<N> for an id, else its address key.
+ public static string Key(Guid? serverId, Uri address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ return serverId is { } id && id != Guid.Empty ? HomeFolders.IdKey(id) : LegacyKey(address);
+ }
+
+ /// The key of a server known by its id.
+ public static string IdKey(Guid serverId) => HomeFolders.IdKey(serverId);
+
+ /// The address key (): how 1.0 named every server, and how an older server is still named.
+ public static string LegacyKey(Uri address) => SyncService.ServerKey(address);
+
+ /// The id of an id key; null for an address key.
+ public static Guid? IdOf(string? key) => HomeFolders.IdOfKey(key);
+
+ /// The key names the server by its id.
+ public static bool IsIdKey(string? key) => IdOf(key) is not null;
+
+ /// The id key an alias stands for; any other key as it is.
+ public string Canonical(string key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+ if (IdOf(key) is { } id) return HomeFolders.IdKey(id);
+ return _canonical.TryGetValue(key, out var idKey) ? idKey : key;
+ }
+
+ /// Both keys name one server: equal ignoring case, or one an alias of the other's id (null equals only null).
+ public bool Same(string? a, string? b)
+ {
+ if (a is null || b is null) return a is null && b is null;
+ return string.Equals(Canonical(a), Canonical(b), StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// Every key that names the server of : its canonical key first, then its aliases.
+ public IReadOnlyList KeysOf(string key)
+ {
+ var canonical = Canonical(key);
+ var keys = new List { canonical };
+ if (_aliases.TryGetValue(canonical, out var aliases)) keys.AddRange(aliases);
+ if (!keys.Contains(key, StringComparer.OrdinalIgnoreCase)) keys.Add(key);
+ return keys;
+ }
+
+ /// The aliases of a server id (its legacy address keys); empty when none is known.
+ public IReadOnlyList AliasesOf(Guid serverId) =>
+ _aliases.TryGetValue(HomeFolders.IdKey(serverId), out var aliases) ? aliases : [];
+
+ /// The folder of the home of ( of its canonical key).
+ public string FolderName(string key) => HomeFolders.ServerFolder(Canonical(key));
+
+ /// This table with added to the aliases of (an address it was reached under).
+ public ServerIdentity With(Guid serverId, string alias)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(alias);
+ var servers = Servers.ToList();
+ var index = servers.FindIndex(s => s.Id == serverId);
+ if (index < 0) servers.Add(new KnownServerKey(serverId, [alias]));
+ else if (!servers[index].Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase)) servers[index] = servers[index] with { Aliases = [.. servers[index].Aliases, alias] };
+ else return this;
+ return new ServerIdentity(servers);
+ }
+}
diff --git a/src/Chronos.Data/Sync/SyncLinkStore.cs b/src/Chronos.Data/Sync/SyncLinkStore.cs
index ca38a076..238ad221 100644
--- a/src/Chronos.Data/Sync/SyncLinkStore.cs
+++ b/src/Chronos.Data/Sync/SyncLinkStore.cs
@@ -43,6 +43,53 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
_db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
+ ///
+ /// Moves every link of to in one transaction (owner review 5, #66: an address
+ /// key becomes the server's id key). Where already links the same server sequence, or the same local
+ /// copy, the row compared last (, never compared counting oldest) is kept and the other
+ /// deleted: link rows are recomputed by the next comparison, so nothing is lost.
+ ///
+ public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(from);
+ ArgumentException.ThrowIfNullOrWhiteSpace(to);
+ if (string.Equals(from, to, StringComparison.Ordinal)) return (0, 0);
+ return await _db.InTransactionAsync(async session =>
+ {
+ var inner = new DbAccess(session);
+ var old = await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [from], Map, cancellationToken)
+ .ConfigureAwait(false);
+ if (old.Count == 0) return (0, 0);
+ var current = (await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [to], Map, cancellationToken)
+ .ConfigureAwait(false)).ToList();
+ var (moved, dropped) = (0, 0);
+ foreach (var link in old)
+ {
+ var clashes = current.Where(c => c.RemoteId == link.RemoteId || (link.LocalId is { } local && c.LocalId == local)).ToList();
+ if (clashes.Any(c => Newer(c, link)))
+ {
+ await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [from, link.RemoteId], cancellationToken).ConfigureAwait(false);
+ dropped++;
+ continue;
+ }
+ foreach (var clash in clashes)
+ {
+ await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [to, clash.RemoteId], cancellationToken).ConfigureAwait(false);
+ current.Remove(clash);
+ dropped++;
+ }
+ await inner.ExecuteAsync("UPDATE sync_links SET server = $3 WHERE server = $1 AND remote_id = $2", [from, link.RemoteId, to], cancellationToken)
+ .ConfigureAwait(false);
+ current.Add(link with { Server = to });
+ moved++;
+ }
+ return (moved, dropped);
+ }, cancellationToken).ConfigureAwait(false);
+
+ // The row already under the new key stays on a tie: it is the one the signed-in session works with.
+ static bool Newer(SyncLink kept, SyncLink other) => (kept.SyncedAt ?? DateTimeOffset.MinValue) >= (other.SyncedAt ?? DateTimeOffset.MinValue);
+ }
+
/// Records where a local sequence stands for the Library; touches neither its versions nor its update time.
public Task SetLocalStateAsync(Guid localId, SyncState state, CancellationToken cancellationToken) =>
_db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken);
diff --git a/src/Chronos.Data/Sync/SyncRemote.cs b/src/Chronos.Data/Sync/SyncRemote.cs
index 0261abfa..e9a43b85 100644
--- a/src/Chronos.Data/Sync/SyncRemote.cs
+++ b/src/Chronos.Data/Sync/SyncRemote.cs
@@ -115,7 +115,11 @@ public interface ISyncConnector
}
/// over a signed-in , which it disposes when it owns it.
-public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : ISyncRemote
+///
+/// The key links and homes name the server by (: its id key once it announced
+/// one, owner review 5); null takes the client's address key ().
+///
+public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient, string? server = null) : ISyncRemote
{
private const int SequencePage = 500;
private const int FramePage = 1000;
@@ -137,7 +141,7 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
/// The settings format the server announced, and when it was read (a timestamp).
private sealed record KnownFormat(int Format, long Read);
- public string Server { get; } = SyncService.ServerKey(client.BaseAddress);
+ public string Server { get; } = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
public async Task> ListSequencesAsync(CancellationToken cancellationToken)
{
diff --git a/src/Chronos.Data/Sync/SyncService.cs b/src/Chronos.Data/Sync/SyncService.cs
index 7927bb61..6aebaaed 100644
--- a/src/Chronos.Data/Sync/SyncService.cs
+++ b/src/Chronos.Data/Sync/SyncService.cs
@@ -26,9 +26,23 @@ public sealed record SyncOptions
/// Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).
public ArchiveServiceOptions Archive { get; init; } = new();
- /// Folder of the proxy cache of server sequences (inside the client's cache).
+ ///
+ /// Folder of the proxy cache of server sequences as 1.0 laid it out (<cache>\proxies\<address hash>):
+ /// where proxies go without , and where a sequence's proxies are still read from, with it,
+ /// until they are moved into their server's home.
+ ///
public required string ProxyCacheDirectory { get; init; }
+ ///
+ /// The servers' homes in the client's cache (<cache>\servers, owner review 5, #66): with it, a server's
+ /// proxies go to <servers>\<home folder>\proxies\<sequence id>
+ /// (). Null keeps the 1.0 layout under .
+ ///
+ public string? ServersDirectory { get; init; }
+
+ /// The alias table the cache finds a server's home by (); null: every key is its own.
+ public Func? Identity { get; init; }
+
/// Concurrent frame downloads of one job.
public int Downloads { get; init; } = 4;
@@ -74,7 +88,7 @@ public sealed class SyncService
Options = options;
_links = new SyncLinkStore(db);
_writer = new SequenceWriter(options.Archive);
- Proxies = new ProxyCache(options.ProxyCacheDirectory);
+ Proxies = new ProxyCache(options.ProxyCacheDirectory, options.ServersDirectory, options.Identity);
}
public SyncOptions Options { get; }
@@ -90,9 +104,27 @@ public sealed class SyncService
internal ArchiveService Archives { get; }
- /// "https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).
+ ///
+ /// "https://nas.local:8443": the address key (scheme, lower-case host, port, path), the key every server had in 1.0 and an
+ /// older server, which announces no id, still has. A server that announces one is keyed by it
+ /// (), its address keys kept as aliases.
+ ///
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
+ ///
+ /// Moves the links of (an address key the server was reached under) to (its
+ /// id key, owner review 5, #66) in one transaction. A link both keys hold for one server sequence, or for one local copy,
+ /// keeps the row compared last (); the other row goes, which loses nothing: the next
+ /// comparison makes links again. Nothing happens when the keys are the same.
+ ///
+ /// The links moved, and those dropped for a newer one.
+ public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
+ {
+ var result = await _links.RekeyAsync(from, to, cancellationToken).ConfigureAwait(false);
+ if (result.Moved + result.Dropped > 0) Changed?.Invoke(to);
+ return result;
+ }
+
/// What an upload or download job moves; null for any other job.
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
diff --git a/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs b/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs
index dc36204e..d363c476 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs
@@ -92,21 +92,39 @@ public sealed class WorkspaceCleaner
{
private static readonly JobKind[] ProjectJobs = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend];
- private readonly WorkspaceSync _sync;
+ private readonly IReadOnlyList _syncs;
private readonly ChronosDatabase _db;
private readonly Func _homes;
/// The home of a workspace project; null for one this PC cannot reach now.
public WorkspaceCleaner(WorkspaceSync sync, ChronosDatabase db, Func homes)
+ : this([sync ?? throw new ArgumentNullException(nameof(sync))], db, homes)
{
- ArgumentNullException.ThrowIfNull(sync);
+ }
+
+ ///
+ /// The clean-up of a workspace split into homes (owner review 5, ): one sync per home's store,
+ /// and one run over all of them, so the size limit counts every home's projects together.
+ ///
+ /// The sync of each home's store.
+ /// The home of a workspace project; null for one this PC cannot reach now.
+ public WorkspaceCleaner(IReadOnlyList syncs, ChronosDatabase db, Func homes)
+ {
+ ArgumentNullException.ThrowIfNull(syncs);
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(homes);
- _sync = sync;
+ if (syncs.Count == 0 || syncs.Any(s => s is null)) throw new ArgumentException("At least one sync, and none null.", nameof(syncs));
+ _syncs = syncs;
_db = db;
_homes = homes;
}
+ /// The sync of the store is in.
+ private WorkspaceSync SyncOf(WorkspaceProject project) =>
+ _syncs.FirstOrDefault(s => ReferenceEquals(s.Store, project.Store))
+ ?? _syncs.FirstOrDefault(s => string.Equals(s.Store.Root, project.Store.Root, StringComparison.OrdinalIgnoreCase))
+ ?? _syncs[0];
+
/// How long a project another writer holds is waited for; past it the project is kept ().
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
@@ -120,7 +138,7 @@ public sealed class WorkspaceCleaner
ArgumentNullException.ThrowIfNull(options);
var candidates = new List();
var used = 0L;
- foreach (var project in _sync.Store.List())
+ foreach (var project in _syncs.SelectMany(s => s.Store.List()))
{
cancellationToken.ThrowIfCancellationRequested();
var candidate = Candidate.Of(project, options);
@@ -251,7 +269,7 @@ public sealed class WorkspaceCleaner
WorkspaceStatus status;
try
{
- status = await _sync.StatusAsync(id, home, cancellationToken).ConfigureAwait(false);
+ status = await SyncOf(project).StatusAsync(id, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is ProjectException or DatabaseException or IOException or InvalidDataException or LeaseUnavailableException)
{
@@ -288,7 +306,7 @@ public sealed class WorkspaceCleaner
{
// Asked again under the lease: the editor may have opened it, a save or a render may have come meanwhile.
if (options.IsOpen(id)) return (WorkspaceKeep.Open, 0, 0);
- var local = await _sync.StatusAsync(id, null, cancellationToken).ConfigureAwait(false);
+ var local = await SyncOf(project).StatusAsync(id, null, cancellationToken).ConfigureAwait(false);
if (local.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0);
if (ReadLedger(project) is not { } renders) return (WorkspaceKeep.Unreadable, 0, 0);
if (renders.Unsent.Count > 0) return (WorkspaceKeep.UnsentRenders, 0, 0);
diff --git a/src/Chronos.Data/Workspaces/WorkspaceHomes.cs b/src/Chronos.Data/Workspaces/WorkspaceHomes.cs
new file mode 100644
index 00000000..d5a8b16f
--- /dev/null
+++ b/src/Chronos.Data/Workspaces/WorkspaceHomes.cs
@@ -0,0 +1,293 @@
+using System.Text.Json;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
+using Chronos.Core.Project;
+using Chronos.Data.Sync;
+
+namespace Chronos.Data.Workspaces;
+
+///
+/// What a server home's folder says about its server (, owner review 5, #66): the key it
+/// is named by, the id, the name and last address it was reached at, its TLS fingerprint and when it was first and last seen.
+/// Someone browsing the folders, or a workspace moved to another PC, knows from it what the folder is.
+///
+public sealed record ServerHomeRecord(string Format, int FormatVersion, string Key, Guid? Id, string? Name, string? Address, string? TlsFingerprint,
+ DateTimeOffset FirstSeen, DateTimeOffset LastSeen)
+{
+ public const string FormatName = "chronos-server-home";
+ public const int CurrentFormatVersion = 1;
+
+ /// A record of first and last seen .
+ public static ServerHomeRecord Of(string key, string? name, string? address, string? tlsFingerprint, DateTimeOffset now) =>
+ new(FormatName, CurrentFormatVersion, key, ServerIdentity.IdOf(key), name, address, tlsFingerprint, now, now);
+
+ ///
+ /// Reads the record in ; null when there is none or it cannot be read (it only describes the
+ /// folder: nothing depends on it).
+ ///
+ public static ServerHomeRecord? Read(string folder)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(folder);
+ var path = Path.Combine(folder, HomeFolders.ServerFile);
+ if (!File.Exists(path)) return null;
+ try
+ {
+ return JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.ServerHomeRecord) is { Format: FormatName, Key.Length: > 0 } record
+ ? record
+ : null;
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ Log.Debug("workspace", $"{path} cannot be read: {ex.Message}");
+ return null;
+ }
+ }
+
+ /// Writes into (made when it is not there), whole and atomically.
+ public static void Write(string folder, ServerHomeRecord record)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(folder);
+ ArgumentNullException.ThrowIfNull(record);
+ Directory.CreateDirectory(folder);
+ AtomicFile.WriteAllText(Path.Combine(folder, HomeFolders.ServerFile), JsonSerializer.Serialize(record, WorkspaceJson.Default.ServerHomeRecord));
+ }
+}
+
+/// One home of a workspace (): its folder and store, and for a server home its key and record.
+/// The folder's name: , a server folder (), or empty for the projects still in the parent.
+/// The key the server home's folder is named by (from its record, else made from the folder's name); null for this PC's home.
+public sealed record WorkspaceHome(string Folder, WorkspaceStore Store, string? ServerKey, ServerHomeRecord? Server)
+{
+ /// This PC's archive's home.
+ public bool IsLocal => Folder == HomeFolders.Local;
+
+ /// Projects 1.0 kept in the parent itself, not moved into their home yet (in use when the folders were sorted).
+ public bool IsLegacy => Folder.Length == 0;
+}
+
+///
+/// The desktop's workspace split into one store per home (owner review 5, #66): Settings › Workspace › Folder is the
+/// parent, whose workspace.json is of format with layout
+/// (a 1.0 Chronos refuses it as newer, so it never shows the workspace empty), and each home keeps its projects in its own
+/// : <parent>\local for this PC's archive and <parent>\servers\<folder>
+/// for each server (, with a beside its manifest). Each
+/// is an ordinary store with its own manifest and .trash, so sync, copies, renders, sends, leases and the trash work
+/// on it unchanged. A parent still in the 1.0 layout (projects side by side in it, a manifest of format 1) is used as it is,
+/// one store for every home, until sorts it; projects that sorting could not move
+/// (in use then) are still listed where they are. A new, empty parent is made split.
+///
+public sealed class WorkspaceHomes
+{
+ /// The format of a split parent's manifest (a store's is ).
+ public const int ParentFormatVersion = 2;
+
+ /// The layout a split parent's manifest names.
+ public const string HomesLayout = "homes";
+
+ private readonly Lock _gate = new();
+ private readonly Dictionary _stores = new(StringComparer.OrdinalIgnoreCase);
+ private readonly WorkspaceStore? _legacy;
+ private ServerIdentity _identity;
+
+ /// Opens the workspace at , making the folder, and a split manifest when it holds none and no project.
+ /// The servers known by id and their aliases ().
+ /// The folder's workspace.json is not a workspace manifest, or a newer one.
+ /// The folder cannot be made or read.
+ public WorkspaceHomes(string root, ServerIdentity? identity = null)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(root);
+ _identity = identity ?? ServerIdentity.None;
+ Root = WorkspaceStore.FullRoot(root);
+ Directory.CreateDirectory(Root);
+ var path = Path.Combine(Root, WorkspaceStore.ManifestFile);
+ var manifest = File.Exists(path) ? WorkspaceStore.TryRead(path) : null;
+ if (manifest is { Layout: HomesLayout })
+ {
+ if (manifest.FormatVersion > ParentFormatVersion)
+ throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({ParentFormatVersion}).");
+ Manifest = manifest;
+ }
+ else if (manifest is null && !File.Exists(path) && !HoldsProjects(Root))
+ {
+ Manifest = CreateSplit(path);
+ }
+ else
+ {
+ // The 1.0 layout (or a manifest the store makes again or refuses): one store for every home until it is sorted.
+ _legacy = new WorkspaceStore(Root);
+ Manifest = _legacy.Manifest;
+ }
+ if (IsSplit && HoldsProjects(Root)) _legacy = new WorkspaceStore(Root, Manifest);
+ }
+
+ /// The parent folder (Settings › Workspace › Folder).
+ public string Root { get; }
+
+ /// The parent's manifest: a split one, or the 1.0 store's.
+ public WorkspaceManifest Manifest { get; }
+
+ /// The parent is split into homes; false while it is in the 1.0 layout (one store for every home).
+ public bool IsSplit => Manifest.Layout == HomesLayout;
+
+ /// The servers known by id and their aliases: a server home's folder is named by its canonical key.
+ public ServerIdentity Identity
+ {
+ get => Volatile.Read(ref _identity);
+ set => Volatile.Write(ref _identity, value ?? ServerIdentity.None);
+ }
+
+ /// The folder of this PC's home (whether it exists or not).
+ public string LocalRoot => HomeFolders.LocalPath(Root);
+
+ /// The folder of the home of server (whether it exists or not).
+ public string ServerRoot(string serverKey)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
+ return Path.Combine(Root, HomeFolders.Servers, Identity.FolderName(serverKey));
+ }
+
+ /// The folder of the store a project of belongs in: its home's, or the parent while it is not split.
+ public string RootFor(BundleHome home)
+ {
+ ArgumentNullException.ThrowIfNull(home);
+ if (!IsSplit) return Root;
+ return home.Kind == BundleHome.ServerKind && home.Server is { Length: > 0 } server ? ServerRoot(server) : LocalRoot;
+ }
+
+ ///
+ /// The store a project of is checked out into: its home's (made with its manifest, and for a server
+ /// its , when it is not there), or the parent's while it is not split.
+ ///
+ public WorkspaceStore StoreFor(BundleHome home)
+ {
+ ArgumentNullException.ThrowIfNull(home);
+ if (!IsSplit) return _legacy!;
+ var root = RootFor(home);
+ var store = Open(root);
+ if (home.Kind == BundleHome.ServerKind && home.Server is { Length: > 0 } server && ServerHomeRecord.Read(root) is null)
+ ServerHomeRecord.Write(root, ServerHomeRecord.Of(Identity.Canonical(server), null, ServerIdentity.IsIdKey(server) ? null : server, null, DateTimeOffset.UtcNow));
+ return store;
+ }
+
+ /// The store of this PC's home (the parent's while it is not split).
+ public WorkspaceStore Local => StoreFor(new BundleHome(BundleHome.ArchiveKind, Guid.Empty));
+
+ ///
+ /// Records what is known of server in its home's (made with the
+ /// home when it is not there; its first sighting kept); nothing while the parent is not split.
+ ///
+ public ServerHomeRecord? Describe(string serverKey, string? name, string? address, string? tlsFingerprint, DateTimeOffset now)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
+ if (!IsSplit) return null;
+ var root = ServerRoot(serverKey);
+ Open(root);
+ var key = Identity.Canonical(serverKey);
+ var known = ServerHomeRecord.Read(root);
+ var record = ServerHomeRecord.Of(key, name ?? known?.Name, address ?? known?.Address, tlsFingerprint ?? known?.TlsFingerprint, now) with
+ {
+ FirstSeen = known?.FirstSeen ?? now,
+ };
+ ServerHomeRecord.Write(root, record);
+ return record;
+ }
+
+ ///
+ /// Every home that has a folder (this PC's first, then the servers' by folder name), and the parent's projects not moved
+ /// into their home yet; while the parent is not split, the parent's store (and any home a sorting stopped half-way made).
+ ///
+ public IReadOnlyList Homes()
+ {
+ var homes = new List();
+ if (_legacy is not null) homes.Add(new WorkspaceHome(string.Empty, _legacy, null, null));
+ if (Directory.Exists(LocalRoot) && HasManifest(LocalRoot)) homes.Add(new WorkspaceHome(HomeFolders.Local, Open(LocalRoot), null, null));
+ var servers = Path.Combine(Root, HomeFolders.Servers);
+ if (Directory.Exists(servers))
+ {
+ foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
+ {
+ var name = Path.GetFileName(folder);
+ if (!HomeFolders.IsServerFolder(name) || !HasManifest(folder)) continue;
+ var record = ServerHomeRecord.Read(folder);
+ var key = record?.Key ?? (HomeFolders.IdOfFolder(name) is { } id ? ServerIdentity.IdKey(id) : null);
+ homes.Add(new WorkspaceHome(name, Open(folder), key, record));
+ }
+ }
+ return homes;
+ }
+
+ /// The stores of every home that has a folder ().
+ public IReadOnlyList All() => [.. Homes().Select(h => h.Store)];
+
+ /// The projects of every home.
+ public IReadOnlyList List() => [.. All().SelectMany(s => s.List())];
+
+ /// The working states of every home's projects (one unreadable is left out, and logged).
+ public IReadOnlyList<(WorkspaceProject Project, ProjectBundle Bundle)> ListBundles() => [.. All().SelectMany(s => s.ListBundles())];
+
+ /// The project's folder in whichever home holds it; null when none does.
+ public WorkspaceProject? Find(Guid projectId)
+ {
+ foreach (var store in All())
+ {
+ if (store.Find(projectId) is { } project) return project;
+ }
+ return null;
+ }
+
+ /// The trash of every home (), each listed with its own fingerprint.
+ /// A trash cannot be read.
+ public IReadOnlyList Trash(CancellationToken cancellationToken = default) =>
+ [.. All().Select(s => WorkspaceTrash.List(s.Root, cancellationToken))];
+
+ /// The folder at is the parent of a workspace split into homes (its manifest says so).
+ public static bool IsSplitRoot(string root)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(root);
+ var path = Path.Combine(WorkspaceStore.FullRoot(root), WorkspaceStore.ManifestFile);
+ return File.Exists(path) && WorkspaceStore.TryRead(path) is { Layout: HomesLayout };
+ }
+
+ /// The folder holds a folder named by a project id with a working state (the 1.0 layout).
+ internal static bool HoldsProjects(string root) =>
+ Directory.Exists(root) && Directory.EnumerateDirectories(root).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
+ && File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
+
+ /// The manifest of a split parent, made now; another program's made at the same moment wins.
+ internal static WorkspaceManifest CreateSplit(string path)
+ {
+ var manifest = new WorkspaceManifest(WorkspaceStore.FormatName, ParentFormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow, HomesLayout);
+ var temp = AtomicFile.TempPathFor(path);
+ try
+ {
+ File.WriteAllText(temp, JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest));
+ try
+ {
+ File.Move(temp, path, overwrite: false);
+ }
+ catch (IOException) when (File.Exists(path))
+ {
+ if (WorkspaceStore.TryRead(path) is { Layout: HomesLayout } first) return first;
+ throw new InvalidDataException($"{path} was made by another program meanwhile and is not a workspace of homes.");
+ }
+ }
+ finally
+ {
+ if (File.Exists(temp)) File.Delete(temp);
+ }
+ return manifest;
+ }
+
+ private static bool HasManifest(string folder) => File.Exists(Path.Combine(folder, WorkspaceStore.ManifestFile));
+
+ private WorkspaceStore Open(string root)
+ {
+ lock (_gate)
+ {
+ if (_stores.TryGetValue(root, out var store)) return store;
+ store = new WorkspaceStore(root);
+ _stores[root] = store;
+ return store;
+ }
+ }
+}
diff --git a/src/Chronos.Data/Workspaces/WorkspaceJobs.cs b/src/Chronos.Data/Workspaces/WorkspaceJobs.cs
index 9f19fb31..6f55e2dd 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceJobs.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceJobs.cs
@@ -1,5 +1,6 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
@@ -30,10 +31,21 @@ namespace Chronos.Data.Workspaces;
///
/// The workspace folder in use now (the desktop's Settings › Workspace): a copy, render or send queued before the workspace
/// moved finds its project there when the folder its parameters name no longer holds it; null where only that one counts.
+/// A workspace split into homes (owner review 5, ) is searched in every home, so a job queued
+/// before its folders were sorted, or before its server's home was re-keyed, finds its project in the home it went to.
+///
+///
+/// Whether two server keys name one server ( over the desktop's alias table, owner review
+/// 5): a job queued under an address key the server was reached under works on a project whose home names its id key. Null
+/// compares the keys ignoring case ().
///
public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func HoldTransfers, Func? Moved = null,
- Func? CurrentRoot = null)
+ Func? CurrentRoot = null, Func? SameServer = null)
{
+ /// Both keys name one server (, else equal ignoring case; null equals only null).
+ public bool IsSameServer(string? a, string? b) =>
+ SameServer is { } same ? same(a, b) : string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
+
/// The options of an engine without a processing service of its own: the archive engine's decoders, nothing held, no move followed.
public static WorkspaceJobOptions For(ArchiveService archives)
{
@@ -204,10 +216,16 @@ internal static class WorkspaceJobRoots
/// resource key) when no folder holds the project.
///
/// The workspace is being moved, or no folder holds the project.
+ ///
+ /// A folder that is a home of a workspace split into homes (owner review 5: <parent>\local,
+ /// <parent>\servers\<folder>) is moved with its parent, whose journal counts for it; and a split parent is
+ /// searched in each of its homes (and in itself, for a project not moved into its home yet), so a job queued with the 1.0
+ /// folder, or with a server's home before it was re-keyed, finds the project in the home it went to.
+ ///
public static string Resolve(string named, Guid projectId, Func? current, string missing)
{
ArgumentException.ThrowIfNullOrWhiteSpace(named);
- var candidates = new List();
+ var folders = new List();
string? currentRoot = null;
try
{
@@ -220,23 +238,60 @@ internal static class WorkspaceJobRoots
foreach (var root in new[] { WorkspaceStore.FullRoot(named), currentRoot })
{
if (root is null) continue;
- if (WorkspaceMover.HasJournal(root))
+ foreach (var folder in new[] { root, SplitParentOf(root) })
{
- // Past its switch the move's target is the workspace, and what is left here is a source still to clear.
- if (WorkspaceMover.ReadJournal(root) is not { Stage: WorkspaceMoveStage.Switched } journal) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
- candidates.Add(WorkspaceStore.FullRoot(journal.To));
- continue;
+ if (folder is null) continue;
+ if (WorkspaceMover.HasJournal(folder))
+ {
+ // Past its switch the move's target is the workspace, and what is left here is a source still to clear.
+ if (WorkspaceMover.ReadJournal(folder) is not { Stage: WorkspaceMoveStage.Switched } journal)
+ throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
+ folders.Add(WorkspaceStore.FullRoot(journal.To));
+ continue;
+ }
+ folders.Add(folder);
}
- candidates.Add(root);
+ }
+ var candidates = new List();
+ foreach (var folder in folders.Distinct(StringComparer.OrdinalIgnoreCase))
+ {
+ candidates.Add(folder);
+ if (WorkspaceHomes.IsSplitRoot(folder)) candidates.AddRange(HomesOf(folder));
}
foreach (var root in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (!File.Exists(Path.Combine(root, projectId.ToString("N"), WorkspaceProject.BundleFile))) continue;
- if (WorkspaceMover.HasJournal(root)) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
+ if (WorkspaceMover.HasJournal(root) || (SplitParentOf(root) is { } parent && WorkspaceMover.HasJournal(parent)))
+ throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
if (!string.Equals(root, WorkspaceStore.FullRoot(named), StringComparison.OrdinalIgnoreCase))
Log.Info("workspace", $"Project {projectId} is no longer in {named}: the job works in {root}, where the workspace is now");
return root;
}
throw new InvalidOperationException(Loc.L(missing));
}
+
+ /// The split parent is a home of (local, or a folder in servers); null for any other folder.
+ internal static string? SplitParentOf(string root)
+ {
+ var name = Path.GetFileName(root);
+ var up = Path.GetDirectoryName(root);
+ if (up is null) return null;
+ string? parent = name == HomeFolders.Local ? up
+ : HomeFolders.IsServerFolder(name) && Path.GetFileName(up) == HomeFolders.Servers ? Path.GetDirectoryName(up)
+ : null;
+ return parent is not null && WorkspaceHomes.IsSplitRoot(parent) ? WorkspaceStore.FullRoot(parent) : null;
+ }
+
+ /// The homes of the split parent that have a folder: this PC's, then the servers'.
+ private static IEnumerable HomesOf(string parent)
+ {
+ var local = HomeFolders.LocalPath(parent);
+ if (Directory.Exists(local)) yield return local;
+ var servers = Path.Combine(parent, HomeFolders.Servers);
+ if (!Directory.Exists(servers)) yield break;
+ foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
+ {
+ if (HomeFolders.IsServerFolder(Path.GetFileName(folder))) yield return folder;
+ }
+ }
}
diff --git a/src/Chronos.Data/Workspaces/WorkspaceMover.cs b/src/Chronos.Data/Workspaces/WorkspaceMover.cs
index 53317149..5955e7ce 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceMover.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceMover.cs
@@ -79,8 +79,9 @@ internal sealed partial class WorkspaceMoveJson : JsonSerializerContext;
///
/// Moves a workspace folder with its projects (phase 5c, ). What moves: every
-/// folder named by a project id, then workspace.json, then .trash, in that order; anything else in the folder
-/// stays where it is. On one volume each entry is renamed into the target ();
+/// folder named by a project id, then the homes' folders of a workspace split into homes (local, servers,
+/// owner review 5), then workspace.json, then .trash, in that order; anything else in the folder stays where it
+/// is. On one volume each entry is renamed into the target ();
/// across volumes each file is copied into a .part beside its place, hashed as it is read and read back to hash the
/// copy, and only once both SHA-256 agree renamed into place (with the source's time), so a file at its final name in the
/// target is always one verified. The source is the workspace until every entry is at the target: then the desktop is told
@@ -185,6 +186,21 @@ public sealed class WorkspaceMover
entries.Add(name);
(files, bytes) = (files + count, bytes + size);
}
+ // A workspace split into homes (owner review 5): each home's folder moves whole, its projects counted one by one.
+ foreach (var home in HomeEntries)
+ {
+ var folder = Path.Combine(From, home);
+ if (!Directory.Exists(folder)) continue;
+ var (count, size) = Read(folder, home, fingerprint);
+ foreach (var project in ProjectFolders(folder))
+ {
+ var listed = Listed(project);
+ projects.Add(new WorkspaceMoveFolder(Guid.ParseExact(Path.GetFileName(project), "N"), File.Exists(Path.Combine(project, WorkspaceProject.BundleFile)),
+ listed.Count, listed.Sum(f => new FileInfo(Path.Combine(project, f)).Length)));
+ }
+ entries.Add(home);
+ (files, bytes) = (files + count, bytes + size);
+ }
var manifest = Path.Combine(From, WorkspaceStore.ManifestFile);
if (File.Exists(manifest))
{
@@ -303,7 +319,7 @@ public sealed class WorkspaceMover
if (switched is not null) await switched(From, To).ConfigureAwait(false);
Cut?.Invoke("switched", To);
var left = Clean(journal);
- log?.Invoke(Loc.L("Archive.Log.WorkspaceMoved", To, journal.Entries.Count(e => Guid.TryParseExact(e, "N", out _)), survey.Files));
+ log?.Invoke(Loc.L("Archive.Log.WorkspaceMoved", To, MovedProjects(journal), survey.Files));
if (left > 0) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveLeft", From, left));
Log.Info("workspace", $"The workspace moved from {From} to {To}" + (left > 0 ? $"; {left} entr(ies) of the old folder stay there" : string.Empty));
return (survey, resumed);
@@ -383,7 +399,7 @@ public sealed class WorkspaceMover
Cut?.Invoke("rename", source);
Rename(source, target);
Cut?.Invoke("moved", target);
- if (Guid.TryParseExact(entry, "N", out _)) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveProject", Name(target)));
+ LogProjects(entry, target, log);
}
else if (!Exists(target))
{
@@ -435,7 +451,7 @@ public sealed class WorkspaceMover
if (durable) clock.Restart();
if (progress is not null) await progress(done, total, durable).ConfigureAwait(false);
}
- if (Guid.TryParseExact(entry, "N", out _)) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveProject", Name(source)));
+ LogProjects(entry, source, log);
}
journal = journal with { Verified = [.. journal.Verified, entry] };
WriteJournal(journal);
@@ -600,6 +616,40 @@ public sealed class WorkspaceMover
private const string TrashFolder = ".trash";
+ /// The homes' folders of a workspace split into homes, which move whole after the 1.0 project folders and before the manifest.
+ private static readonly string[] HomeEntries = [HomeFolders.Local, HomeFolders.Servers];
+
+ /// The project folders in a home's folder: local's own, or those of every server home in servers.
+ private static IEnumerable ProjectFolders(string home)
+ {
+ var homes = Path.GetFileName(home) == HomeFolders.Servers
+ ? Directory.EnumerateDirectories(home).Where(d => HomeFolders.IsServerFolder(Path.GetFileName(d))).Order(StringComparer.Ordinal)
+ : Enumerable.Repeat(home, 1);
+ foreach (var store in homes)
+ {
+ foreach (var folder in Directory.EnumerateDirectories(store).Order(StringComparer.Ordinal))
+ {
+ if (Guid.TryParseExact(Path.GetFileName(folder), "N", out _)) yield return folder;
+ }
+ }
+ }
+
+ /// The projects a move took: its 1.0 project folders, and the project folders of the homes it moved (now at the target).
+ private int MovedProjects(WorkspaceMoveJournal journal) =>
+ journal.Entries.Count(e => Guid.TryParseExact(e, "N", out _))
+ + journal.Entries.Where(e => HomeEntries.Contains(e) && Directory.Exists(Path.Combine(To, e))).Sum(e => ProjectFolders(Path.Combine(To, e)).Count());
+
+ /// The log line of each project an entry moved: the entry's own, or those of a home's folder.
+ private static void LogProjects(string entry, string folder, Action? log)
+ {
+ if (log is null) return;
+ if (Guid.TryParseExact(entry, "N", out _)) log(Loc.L("Archive.Log.WorkspaceMoveProject", Name(folder)));
+ else if (HomeEntries.Contains(entry) && Directory.Exists(folder))
+ {
+ foreach (var project in ProjectFolders(folder)) log(Loc.L("Archive.Log.WorkspaceMoveProject", Name(project)));
+ }
+ }
+
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
diff --git a/src/Chronos.Data/Workspaces/WorkspaceStore.cs b/src/Chronos.Data/Workspaces/WorkspaceStore.cs
index ce74bc6f..cc2477f6 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceStore.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceStore.cs
@@ -11,7 +11,12 @@ using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces;
/// The manifest of a workspace folder (workspace.json).
-public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created);
+///
+/// in the manifest of format of a
+/// workspace split into homes (owner review 5, #66): the folder holds no projects of its own but one store per home; null
+/// for a store.
+///
+public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created, string? Layout = null);
///
/// A workspace's sync state of one project besides its versions (sync.json): a restore to record, a conflict to
@@ -133,13 +138,15 @@ public sealed record WorkspaceMoveParameters(string From, string To, string Plan
[JsonSerializable(typeof(WorkspaceSendParameters))]
[JsonSerializable(typeof(WorkspaceMoveParameters))]
[JsonSerializable(typeof(WorkspaceRenders))]
+[JsonSerializable(typeof(ServerHomeRecord))]
internal sealed partial class WorkspaceJson : JsonSerializerContext;
///
/// The workspace of this PC (owner review 2, R8): a folder on a fast disk where projects are edited, never inside the
/// library. <root>/workspace.json names it; each project has a folder named by its id
/// (). There is no index: the store lists the folders holding a project.chronos. The
-/// desktop puts it in %LOCALAPPDATA%\Chronos\workspace unless set otherwise; the store takes any folder.
+/// store takes any folder; the desktop's workspace (%LOCALAPPDATA%\Chronos\workspace unless set otherwise) is split
+/// into one store per home since owner review 5 (: local, servers\<id>).
///
public sealed class WorkspaceStore
{
@@ -168,6 +175,17 @@ public sealed class WorkspaceStore
Manifest = Read(path);
}
+ ///
+ /// The projects a workspace split into homes still holds where 1.0 kept them (<parent>/<project id>: one in
+ /// use when the folders were sorted, owner review 5): a view of the parent with its manifest, which makes and writes nothing
+ /// ().
+ ///
+ internal WorkspaceStore(string root, WorkspaceManifest manifest)
+ {
+ Root = FullRoot(root);
+ Manifest = manifest;
+ }
+
public string Root { get; }
public WorkspaceManifest Manifest { get; }
@@ -319,6 +337,25 @@ public sealed class WorkspaceStore
}
}
+ /// The manifest of the folder names, of any format (a store's or a parent's of homes); null when it is not one.
+ internal static WorkspaceManifest? TryRead(string path)
+ {
+ try
+ {
+ return JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.WorkspaceManifest) is { Format: FormatName } manifest && manifest.Id != Guid.Empty
+ ? manifest
+ : null;
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ /// Writes whole to a temporary file and moves it into place.
+ internal static void Write(string path, WorkspaceManifest manifest) =>
+ AtomicFile.WriteAllText(path, JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest));
+
private static WorkspaceManifest Read(string path)
{
WorkspaceManifest? manifest;
@@ -331,6 +368,8 @@ public sealed class WorkspaceStore
throw new InvalidDataException($"{path} is not a workspace manifest.", ex);
}
if (manifest is null || manifest.Format != FormatName || manifest.Id == Guid.Empty) throw new InvalidDataException($"{path} is not a workspace manifest.");
+ if (manifest.Layout == WorkspaceHomes.HomesLayout)
+ throw new InvalidDataException($"{path} is the manifest of a workspace split into homes, whose projects are in its home folders ({HomeFolders.Local}, {HomeFolders.Servers}).");
if (manifest.FormatVersion > FormatVersion)
throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({FormatVersion}).");
return manifest;
diff --git a/src/Chronos.Protocol/Dtos.cs b/src/Chronos.Protocol/Dtos.cs
index d94ef267..86d61b69 100644
--- a/src/Chronos.Protocol/Dtos.cs
+++ b/src/Chronos.Protocol/Dtos.cs
@@ -17,6 +17,11 @@ public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int P
/// The highest project settings format the server reads and renders (ProjectSettings.CurrentVersion, owner review 1,
/// phase 4); null from an older server, which reads format 1 only. The desktop holds back a push or a render that needs more.
///
+///
+/// The server's stable id (owner review 5, #66): made once, kept in its database, the same whatever address or name it is
+/// reached by. A desktop keys the server's homes, links and folders by it. Null from an older server, which a desktop keys by
+/// its address.
+///
public sealed record ServerInfo(
string Name,
string Version,
@@ -26,7 +31,8 @@ public sealed record ServerInfo(
IReadOnlyList Formats,
ServerLimits Limits,
IReadOnlyList? Extensions = null,
- int? SettingsFormat = null);
+ int? SettingsFormat = null,
+ Guid? ServerId = null);
/// Names of that clients act on.
public static class ServerCapabilities
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 readonly ChronosDatabase _db;
private readonly EventHub _events;
private readonly HashSet _kinds;
+ private readonly bool _ownsEngine = true;
+ private int _subscribed;
public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options,
EventHub events, TimeProvider time)
{
- _db = db;
_events = events;
Gate = new ProgressGate(time);
// A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
@@ -39,8 +42,21 @@ 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, TimeProvider time)
+ {
+ ArgumentNullException.ThrowIfNull(engine);
+ _events = events;
+ Gate = new ProgressGate(time);
+ _ownsEngine = false;
+ _kinds = [];
+ Engine = engine;
}
/// Node id stamped on jobs this server runs.
@@ -51,15 +67,60 @@ public sealed class JobEngineHost : IHostedService
/// The pace of every job's progress events, the server's own jobs and render nodes' alike.
public ProgressGate Gate { 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.App.Tests/Workspace/ServerHomeTests.cs b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
index a2fd9cc2..3841b2a9 100644
--- a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using System.IO;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
@@ -50,7 +51,7 @@ public sealed class ServerHomeTests(TestContext context)
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
- var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
+ var bundle = host.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
@@ -83,8 +84,8 @@ public sealed class ServerHomeTests(TestContext context)
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
- var session = await other.Sync.OpenAsync(projectId, bed.Ct);
- await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
+ var session = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
+ await other.SyncOf(projectId).SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
@@ -109,13 +110,46 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
- Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
+ Assert.NotNull(host.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
+ [Test]
+ public async Task EachHomeChecksOutIntoItsOwnFolderAndTheServerIsOneByItsId()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
+ var serverId = Guid.CreateVersion7();
+ var idKey = Chronos.Core.IO.HomeFolders.IdKey(serverId);
+ var host = bed.Host();
+ host.Identity = () => new Chronos.Data.Sync.ServerIdentity([new Chronos.Data.Sync.KnownServerKey(serverId, [Server])]);
+ var server = new FakeServer(bed);
+ host.ServerHomes = home => host.SameServer(home.Server, idKey) && home.SequenceId == server.Inner.SequenceId ? server : null;
+
+ // A server project goes into the server's folder, named by its id even though the project names its address.
+ var checkout = await host.CheckoutAsync(ServerHome(bed), null, null, cancellationToken: bed.Ct);
+ var folder = host.Find(checkout.Project.Id)!;
+ Assert.Equal(Path.Combine(host.Root, "servers", serverId.ToString("N")), folder.Store.Root);
+ Assert.Equal(Server, folder.ReadBundle().Workspace!.Home.Server);
+ Assert.True(host.SameServer(Server, idKey), "the address is an alias of the id");
+ Assert.False(host.SameServer("https://elsewhere:8443", idKey));
+
+ // The server told by its id reaches the project that names its address.
+ var told = new List();
+ host.HomeChanged += told.Add;
+ host.OnServerProjectChanged(idKey, new ProjectChangedEvent(bed.SequenceId, checkout.Project.Id, ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
+ Assert.Equal(checkout.Project.Id, told.Single().ProjectId);
+
+ // A project of this PC's archive goes into local\, and the picker lists both.
+ var other = bed.Host(name: "second");
+ var localId = await bed.CheckoutAsync(other);
+ Assert.Equal(Path.Combine(other.Root, "local"), other.Find(localId)!.Store.Root);
+ Assert.SequenceEqual([checkout.Project.Id], host.Homes.List().Select(p => p.ProjectId).ToArray());
+ Assert.Count(1, (await host.ListAsync(bed.Ct)).Where(e => e.ProjectId == checkout.Project.Id));
+ }
+
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
@@ -146,7 +180,7 @@ public sealed class ServerHomeTests(TestContext context)
// Opened signed out; the sign-in made later is the one the source connects with.
FakeRemoteSequenceApi? signedIn = null;
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => signedIn, () => signedIn));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -181,7 +215,7 @@ public sealed class ServerHomeTests(TestContext context)
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
- var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
+ var basis = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
@@ -198,7 +232,7 @@ public sealed class ServerHomeTests(TestContext context)
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
- var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
+ var sent = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
@@ -219,8 +253,8 @@ public sealed class ServerHomeTests(TestContext context)
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
- var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
- await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
+ var theirs = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
+ await other.SyncOf(projectId).SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
@@ -240,7 +274,7 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
- Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
+ Assert.NotNull(host.Find(projectId)?.ReadMedia());
}
}
@@ -260,7 +294,7 @@ public sealed class ServerHomeTests(TestContext context)
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -282,9 +316,9 @@ public sealed class ServerHomeTests(TestContext context)
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
- var before = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
+ var before = host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
- Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
+ Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// Saved as a version with the turn, then turned back: the working state is of the base format, but the version
// waiting to be sent is not. Sync stays disabled, and the workspace itself never sends it (Send first, Delete,
@@ -300,7 +334,7 @@ public sealed class ServerHomeTests(TestContext context)
var refused = await Assert.ThrowsAsync(() => host.SyncAsync(projectId, bed.Ct));
Assert.True(refused.HomeReadsOlderFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), WorkspaceText.Failure(refused, server: true));
- Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
+ Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
@@ -323,7 +357,7 @@ public sealed class ServerHomeTests(TestContext context)
private static async Task CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
index 2863b2fe..3972c44e 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
@@ -36,7 +36,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var host = bed.Host(settings);
var mainId = await bed.CheckoutAsync(host);
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
// Open in Edit: kept, with why.
@@ -66,7 +66,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
- Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
+ Assert.True(host.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
}
@@ -76,7 +76,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
@@ -90,7 +90,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
- Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(host.Find(mainId), "nothing was removed");
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
@@ -102,7 +102,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host();
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
- var folder = WorkspaceTrash.FolderOf(host.Root);
+ var folder = WorkspaceTrash.FolderOf(host.Homes.Local.Root);
foreach (var name in new[] { "a", "b" })
{
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
index 12ff6d73..077927b6 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
@@ -50,7 +50,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
Assert.Equal(0.4, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.Equal(libraryBefore, (await bed.RowAsync()).SettingsJson, "editing never writes the library");
Assert.Equal(WorkspaceState.Modified, (await host.StatusAsync(projectId)).State);
@@ -72,12 +72,12 @@ public sealed class WorkspaceEditorTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var host = bed.Host();
var projectId = await bed.CheckoutAsync(host);
- var impatient = new WorkspaceSync(host.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
+ var impatient = new WorkspaceSync(host.Find(projectId)!.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
var source = new WorkspaceSequenceSource(impatient, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine);
await using (source)
{
// A long sync or copy holds the project: the editor says so in words, and nothing was read.
- using (await host.Store.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
+ using (await host.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
{
var busy = await Assert.ThrowsAsync(() => source.LoadAsync(bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Busy"), busy.Message);
@@ -328,7 +328,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.Equal(excluded, session.Content.Frames[3].Id);
Assert.True(session.Edit(p => Exposure(p, 0.2)));
Assert.True(await session.FlushAsync(), "saves go on over the new frames");
- Assert.SequenceEqual([3], host.Store.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
+ Assert.SequenceEqual([3], host.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
}
}
}
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
index 31953661..09fd4aec 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
@@ -62,7 +62,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.Equal((Path.GetFullPath(other), before + 1), (settings.WorkspaceFolder, saves));
Assert.Equal(Path.GetFullPath(other), host.Root);
Assert.Empty(await host.ListAsync());
- Assert.FileExists(Path.Combine(first, mainId.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.FileExists(Path.Combine(first, "local", mainId.ToString("N"), WorkspaceProject.BundleFile));
// Chosen back, the default is named by no setting and its project is listed again.
Assert.Equal(new WorkspaceFolderPlan(Path.GetFullPath(other), first, 0, 1, false), await host.PlanFolderAsync(first));
@@ -155,7 +155,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.True(await session.FlushAsync());
}
var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
// A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too.
await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct);
@@ -195,11 +195,11 @@ public sealed class WorkspaceFallbackTests(TestContext context)
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
- Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(host.Find(mainId), "nothing was removed");
await host.RemoveLocalCopyAsync(mainId, discard: true);
- Assert.Null(host.Store.Find(mainId));
- var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
+ Assert.Null(host.Find(mainId));
+ var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones");
@@ -215,7 +215,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
// A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since).
var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject();
json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1;
@@ -330,7 +330,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
Assert.SequenceEqual([1, 2, 3, 4, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
// The library's file of version 2 is damaged: the workspace's copy is the only good one left, so it stays.
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
index 218f4e98..908d385b 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
@@ -43,7 +43,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var elsewhere = Path.Combine(context.CreateTempDirectory("fast-disk"), "Chronos workspace");
settings.WorkspaceFolder = elsewhere;
Assert.Equal(elsewhere, host.Root);
- Assert.Equal(elsewhere, host.Store.Root, "the store follows the folder");
+ Assert.Equal(elsewhere, host.Homes.Root, "the homes follow the folder");
Assert.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
// A capture (sample data without an engine) edits its library as before.
@@ -142,6 +142,60 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Count(1, imported.WorkspaceOpened);
}
+ [Test]
+ public void TheKnownServersStayOnThisPc()
+ {
+ var id = Guid.CreateVersion7();
+ var originals = Guid.CreateVersion7();
+ var mine = new AppSettings
+ {
+ KnownServers = [new KnownServer { Id = id, Name = "Studio NAS", LastAddress = "https://nas.local:8443", Aliases = ["https://nas.local:8443"], OriginalsArchiveId = originals }],
+ };
+ var copy = AppSettings.Parse(mine.ToJson())!;
+ Assert.Equal(("Studio NAS", originals, "https://nas.local:8443"), (copy.KnownServers.Single().Name, copy.KnownServers.Single().OriginalsArchiveId, copy.KnownServers.Single().Aliases.Single()));
+ Assert.Equal(id, copy.FindKnownServer(id)?.Id);
+ Assert.True(copy.KnownIdentity().Same("https://nas.local:8443", Chronos.Core.IO.HomeFolders.IdKey(id)), "an alias names the server by its id");
+
+ // Reset and Import keep what this PC knows of its servers; Export leaves it out.
+ Assert.Equal(id, mine.ResetKeepingState().KnownServers.Single().Id);
+ Assert.Empty(AppSettings.Parse(mine.ForExport().ToJson())!.KnownServers);
+ Assert.Equal(id, mine.KeepLocalIn(AppSettings.Parse(new AppSettings().ToJson())!).KnownServers.Single().Id);
+ }
+
+ [Test]
+ public async Task TheTrashOfEveryHomeIsPlannedAndEmptiedTogether()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
+ var host = bed.Host(name: "homes");
+ var homes = host.Homes;
+ Assert.True(homes.IsSplit, "a new workspace is split into homes");
+ var server = homes.StoreFor(new BundleHome(BundleHome.ServerKind, Guid.CreateVersion7(), null, "https://nas.test:8443")).Root;
+ foreach (var (root, name) in new[] { (homes.Local.Root, "a"), (server, "b") })
+ {
+ var entry = Directory.CreateDirectory(Path.Combine(WorkspaceTrash.FolderOf(root), $"{Guid.CreateVersion7():N}-{name}"));
+ File.WriteAllBytes(Path.Combine(entry.FullName, "file.bin"), new byte[100]);
+ }
+
+ // Settings › Workspace › Home folders: this PC first, then the server by what its folder records.
+ var rows = HomeFolderRow.Of(homes, [], _ => { });
+ Assert.SequenceEqual([Loc.L("Settings.Workspace.ThisPc"), "https://nas.test:8443"], rows.Select(r => r.Name).ToArray());
+ Assert.Equal(server, rows[1].Path);
+
+ var usage = await host.UsageAsync(bed.Ct);
+ Assert.Equal((2, 200L), (usage.TrashItems, usage.TrashBytes));
+ var plan = await host.PlanTrashAsync(bed.Ct);
+ Assert.Equal((2, 200L, 2), (plan.Items.Count, plan.Bytes, plan.Listings.Count));
+
+ // One home's trash changed since the plan: nothing is erased, in either.
+ File.WriteAllBytes(Path.Combine(WorkspaceTrash.FolderOf(server), "late.bin"), new byte[5]);
+ await Assert.ThrowsAsync(() => host.EmptyTrashAsync(plan, bed.Ct));
+ Assert.Equal(3, (await host.UsageAsync(bed.Ct)).TrashItems, "nothing was erased");
+
+ var again = await host.PlanTrashAsync(bed.Ct);
+ Assert.Equal(new WorkspaceTrashResult(3, 205), await host.EmptyTrashAsync(again, bed.Ct));
+ Assert.Equal(0, (await host.UsageAsync(bed.Ct)).TrashItems);
+ }
+
[Test]
public void OpeningAProjectRecordsWhenAndSavesIt()
{
@@ -309,7 +363,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var verticalId2 = (await host.HomeProjectsAsync(bed.SequenceId)).Single(p => !p.IsMain).Id;
await bed.CheckoutAsync(host, verticalId2);
Assert.Equal("Vertical", await host.RenameAsync(verticalId2, " Vertical "));
- Assert.Equal("Vertical", host.Store.Find(verticalId2)!.ReadBundle().Workspace!.Name);
+ Assert.Equal("Vertical", host.Find(verticalId2)!.ReadBundle().Workspace!.Name);
Assert.Contains((await host.HomeProjectsAsync(bed.SequenceId)), p => p.Name == "Vertical");
// Delete project…: confirmed, sent first, then gone from the library's list and from the workspace (kept in the library's trash).
@@ -329,7 +383,7 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Equal(1, deleting.Closed);
}
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
- Assert.Null(host.Store.Find(verticalId2));
+ Assert.Null(host.Find(verticalId2));
var row = await bed.RowAsync();
var trash = Path.Combine(new Chronos.Core.Archiving.ArchivePaths((await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath).Sequence(row.Folder).ProjectsTrashDirectory);
Assert.True(Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(verticalId2.ToString("N"), StringComparison.Ordinal)),
@@ -375,15 +429,15 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
- Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(host.Find(mainId), "nothing was removed");
// Send first: saved and sent, then the library's copy is read back and checked before the local one goes.
await host.SaveVersionAsync(mainId, "Before removal");
await host.SyncAsync(mainId);
Assert.True((await host.PlanRemovalAsync(mainId)).IsSafe);
- var folder = host.Store.Find(mainId)!.Folder;
+ var folder = host.Find(mainId)!.Folder;
await host.RemoveLocalCopyAsync(mainId, discard: false);
- Assert.Null(host.Store.Find(mainId));
+ Assert.Null(host.Find(mainId));
Assert.False(Directory.Exists(Path.Combine(folder, WorkspaceProject.MediaFolder)), "the copied photos are gone");
Assert.Equal(0.3, ProjectSettings.FromJson((await bed.RowAsync()).SettingsJson!).Exposure.ExposureOffsetEv, "the work is in the library");
@@ -397,14 +451,14 @@ public sealed class WorkspaceHostTests(TestContext context)
}
var unsent = (await host.SaveVersionAsync(vertical, "Not sent")).Version!;
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
- var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
+ Assert.Null(host.Find(vertical));
+ var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal));
Assert.FileExists(Path.Combine(aside, WorkspaceProject.BundleFile));
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)
|| f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the photos, copies the library can make again, are not");
- Assert.Empty(host.Store.List());
+ Assert.Empty(host.Homes.List());
}
[Test]
@@ -413,7 +467,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
var basis = project.ReadBundle().Workspace!.Base!;
var conflict = $$"""
"conflict": { "theirsVersionId": "{{basis.VersionId}}", "theirsNumber": {{basis.Number}}, "baseVersionId": "{{Guid.CreateVersion7()}}",
@@ -449,9 +503,9 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(vertical, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
- Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
+ Assert.NotNull(host.Find(vertical), "nothing was removed");
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
+ Assert.Null(host.Find(vertical));
}
[Test]
@@ -460,7 +514,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
- var project = host.Store.Find(vertical)!;
+ var project = host.Find(vertical)!;
var bundle = File.ReadAllBytes(project.BundlePath);
var held = Path.Combine(project.Folder, "notes.txt");
File.WriteAllText(held, "mine");
@@ -471,13 +525,13 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
- var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
+ var trash = Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder);
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
"nothing is left aside");
// The file let go: removed.
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
+ Assert.Null(host.Find(vertical));
}
[Test]
@@ -496,7 +550,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
var kept = project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order().ToList();
Assert.SequenceEqual([5, 6], kept, "the base and the one before it");
var history = await host.HistoryAsync(mainId);
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
index 6827ef9d..b78ad19d 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
@@ -44,13 +44,13 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -62,7 +62,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
- Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
+ Assert.Equal((projectId, host.Find(projectId)!.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
@@ -108,7 +108,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi { ConfirmAnswer = false };
await using (session)
@@ -155,7 +155,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var projectId = await bed.CheckoutAsync(host);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
@@ -171,7 +171,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
Assert.Equal(1, sends.Count);
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
- Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
+ Assert.Equal((projectId, host.Find(projectId)!.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
Assert.Empty(parameters.RenderIds);
}
@@ -189,7 +189,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
index 2a017ff3..bfc20ec1 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
@@ -35,7 +35,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
session.ConflictFound += conflicts.Add;
await using (session)
{
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
// A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
@@ -102,7 +102,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.True(sessionB.Undo());
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
Assert.True(await sessionB.FlushAsync());
- var working = here.Store.Find(mainId)!.ReadBundle().Project;
+ var working = here.Find(mainId)!.ReadBundle().Project;
Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
}
}
@@ -172,7 +172,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
removing.SendFirstCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
Assert.Equal(0, uiB.Closed, "the editor stays open");
- Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(here.Find(mainId), "nothing was removed");
}
}
@@ -211,7 +211,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
- Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
+ Assert.Equal(0.7, here.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
}
}
@@ -254,7 +254,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
await using (session)
{
Assert.False(session.IsReadOnly);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
index f1d736a2..3bac16f3 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
@@ -32,7 +32,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.History.CanUndo);
// A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings.
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
@@ -64,7 +64,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
// A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync).
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
@@ -86,7 +86,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv);
Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo");
Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent");
- Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id));
+ Assert.Empty(host.SyncOf(projectId).Unpushed(projectId).Where(v => v.Id == aside.Id));
// Read again: no throw, nothing more kept aside, the editor as it is.
await session.ReloadAsync();
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
index 8bb07ec5..20c7301f 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
@@ -97,7 +97,7 @@ public sealed class WorkspaceOpenPolicyTests(TestContext context)
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
- var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
+ var media = services.Workspace.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
index aeaebcac..e6094bfb 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
@@ -65,7 +65,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await WorkspaceTestBed.UntilAsync(() => project.Status is not null, "its state is read");
Assert.Equal(WorkspaceState.InSync, project.Status!.State);
Assert.Equal(section.OpenProjectId!.Value, settings.WorkspaceRecent[sequenceId]);
- Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
+ Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), "local", section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
"the project lives in the workspace beside the index");
// Edited in the workspace; the library takes it with the version saved.
@@ -231,7 +231,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
- var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
+ var folder = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
@@ -298,7 +298,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await section.CloseAsync();
shell.KeepSequence(null);
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
- var bundle = Path.Combine(services.Workspace.Root, mainId.ToString("N"), WorkspaceProject.BundleFile);
+ var bundle = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"), WorkspaceProject.BundleFile);
// Damaged: the sequence has another project, so it is asked which; Main is listed, disabled, why in its tooltip.
await WriteWhenFreeAsync(bundle, "{ not a project");
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
index 2b46ac08..153e478e 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
@@ -120,7 +120,7 @@ internal sealed class WorkspaceTestBed : IAsyncDisposable
/// The project open in an editor session over the workspace (saves 20 ms after each edit).
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
{
- var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, Db, DecoderFactory.CreateClient(null), Engine);
var content = await source.LoadAsync(Ct);
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
}
diff --git a/tests/Chronos.Core.Tests/Foundation/HomeFoldersTests.cs b/tests/Chronos.Core.Tests/Foundation/HomeFoldersTests.cs
new file mode 100644
index 00000000..23145373
--- /dev/null
+++ b/tests/Chronos.Core.Tests/Foundation/HomeFoldersTests.cs
@@ -0,0 +1,90 @@
+using System.Security.Cryptography;
+using System.Text;
+using Chronos.Core.IO;
+using Chronos.Testing;
+
+namespace Chronos.Core.Tests.Foundation;
+
+/// The folders of the homes (owner review 5, #66): this PC's, a server's by id, a server's by address hash.
+public sealed class HomeFoldersTests(TestContext context)
+{
+ private static readonly Guid ServerId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ [Test]
+ public void AnIdKeyNamesItsFolderByTheId()
+ {
+ var key = HomeFolders.IdKey(ServerId);
+ Assert.Equal("id:0192a4c17b3e7cc08a512f9d0e6b1a01", key);
+ Assert.Equal("0192a4c17b3e7cc08a512f9d0e6b1a01", HomeFolders.ServerFolder(key));
+ Assert.Equal(ServerId, HomeFolders.IdOfKey(key));
+ Assert.Equal(ServerId, HomeFolders.IdOfKey("ID:0192A4C17B3E7CC08A512F9D0E6B1A01"));
+ Assert.Equal(ServerId, HomeFolders.IdOfFolder(HomeFolders.ServerFolder(key)));
+ Assert.Throws(() => HomeFolders.IdKey(Guid.Empty));
+ }
+
+ [Test]
+ public void AnAddressKeyNamesItsFolderAsTheProxyCacheOf10Did()
+ {
+ const string key = "https://nas.local:8443";
+ // ProxyCache 1.0: Convert.ToHexStringLower(SHA256(UTF-8 key))[..16].
+ var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(key)))[..16];
+ Assert.Equal(hash, HomeFolders.AddressHash(key));
+ Assert.Equal("addr-" + hash, HomeFolders.ServerFolder(key));
+ Assert.Null(HomeFolders.IdOfKey(key));
+ Assert.True(HomeFolders.IsAddressFolder("addr-" + hash));
+ Assert.True(HomeFolders.IsServerFolder("addr-" + hash));
+ Assert.Null(HomeFolders.IdOfFolder("addr-" + hash));
+ // "id:" with no id after it is an address key like any other.
+ Assert.Equal("addr-" + HomeFolders.AddressHash("id:nothing"), HomeFolders.ServerFolder("id:nothing"));
+ }
+
+ [Test]
+ public void OnlyAHomeFolderNameIsAServerHome()
+ {
+ Assert.True(HomeFolders.IsServerFolder(ServerId.ToString("N")));
+ foreach (var name in new[] { null, "", "local", "servers", ".trash", ServerId.ToString("N").ToUpperInvariant(), ServerId.ToString("D"), "addr-", "addr-0123",
+ "addr-0123456789ABCDEF", "addr-0123456789abcdefa", "xaddr-0123456789abcdef", Guid.Empty.ToString("N") })
+ Assert.False(HomeFolders.IsServerFolder(name), name ?? "null");
+ }
+
+ [Test]
+ public void HomePathsLieUnderTheirRoot()
+ {
+ var root = context.CreateTempDirectory("homes");
+ Assert.Equal(Path.Combine(root, "local"), HomeFolders.LocalPath(root));
+ Assert.Equal(Path.Combine(root, "servers", ServerId.ToString("N")), HomeFolders.ServerPath(root, HomeFolders.IdKey(ServerId)));
+ Assert.Equal(Path.Combine(root, "servers", "addr-" + HomeFolders.AddressHash("https://x")), HomeFolders.ServerPath(root, "https://x"));
+ }
+
+ [Test]
+ public void TheOriginalsOfAServerGetAnArchiveBesideThisPcs()
+ {
+ var parent = context.CreateTempDirectory("originals");
+ var archive = Path.Combine(parent, "ChronosArchive");
+ Directory.CreateDirectory(archive);
+ Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS"), HomeFolders.OriginalsArchiveRoot(archive, "Studio NAS", Path.Combine(parent, "fallback")));
+
+ // Taken: " (2)"; a name Windows refuses is made safe.
+ Directory.CreateDirectory(Path.Combine(parent, "ChronosArchive - Studio NAS"));
+ Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS (2)"), HomeFolders.OriginalsArchiveRoot(archive + Path.DirectorySeparatorChar, "Studio NAS", "unused"));
+ Assert.Equal(Path.Combine(parent, "ChronosArchive - A B C"), HomeFolders.OriginalsArchiveRoot(archive, "A:B/C", "unused"));
+ Assert.Equal(Path.Combine(parent, "ChronosArchive - Taken (3)"),
+ HomeFolders.OriginalsArchiveRoot(archive, "Taken", "unused", path => !path.EndsWith("(3)", StringComparison.Ordinal)));
+
+ // No archive of this PC's: beside where its first one would go.
+ var fallback = Path.Combine(parent, "Pictures", "ChronosArchive");
+ Assert.Equal(Path.Combine(parent, "Pictures", "ChronosArchive - NAS"), HomeFolders.OriginalsArchiveRoot(null, "NAS", fallback));
+ }
+
+ [Test]
+ public void ASafeNameIsAFolderNameEveryDriveTakes()
+ {
+ Assert.Equal("Studio NAS", HomeFolders.SafeName(" Studio \t NAS. "));
+ Assert.Equal("a b", HomeFolders.SafeName("a<>:\"|?*b"));
+ Assert.Equal("CON_", HomeFolders.SafeName("con".ToUpperInvariant()));
+ Assert.Equal("nul.box_", HomeFolders.SafeName("nul.box"));
+ Assert.Equal("Server", HomeFolders.SafeName("..."));
+ Assert.Equal("Server", HomeFolders.SafeName(null));
+ Assert.Equal(HomeFolders.MaxNameLength, HomeFolders.SafeName(new string('x', 200)).Length);
+ }
+}
diff --git a/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs b/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
index e3e61913..1798d1ce 100644
--- a/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
+++ b/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
@@ -18,11 +18,8 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(app, "data", "chronos.db"), paths.DatabasePath);
Assert.False(paths.IsInSyncedFolder);
Assert.Null(paths.PortableSyncRoot);
-
- paths.CreateDirectories();
- Assert.True(Directory.Exists(paths.LogsDirectory));
- Assert.True(Directory.Exists(paths.CacheDirectory));
- Assert.True(Directory.Exists(paths.ThumbnailsDirectory));
+ Assert.Equal(Path.Combine(app, "data", "logs"), paths.LogsDirectory);
+ Assert.Equal(Path.Combine(app, "data", "cache"), paths.CacheDirectory);
}
[Test]
@@ -50,22 +47,19 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(local, "Chronos"), paths.DataRoot);
Assert.Equal(oneDrive, paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
- paths.CreateDirectories();
- Assert.True(Directory.Exists(paths.LogsDirectory));
- Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
+ Assert.Equal(Path.Combine(local, "Chronos", "logs"), paths.LogsDirectory);
}
[Test]
- public void DataInsideOneDriveIsReportedAndRefused()
+ public void DataInsideOneDriveIsReported()
{
- // Local application data inside a sync root: nowhere is safe, so nothing is created.
+ // Local application data inside a sync root: nowhere is safe, and the app tells the user.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]);
Assert.True(paths.IsInSyncedFolder);
Assert.Equal(oneDrive, paths.SyncedFolder);
- Assert.Throws(paths.CreateDirectories);
Assert.False(Directory.Exists(paths.DataRoot));
}
diff --git a/tests/Chronos.Data.Tests/Homes/HomeFixtures.cs b/tests/Chronos.Data.Tests/Homes/HomeFixtures.cs
new file mode 100644
index 00000000..648a4344
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Homes/HomeFixtures.cs
@@ -0,0 +1,122 @@
+using System.Security.Cryptography;
+using System.Text;
+using Chronos.Core.Archiving;
+using Chronos.Core.Project;
+using Chronos.Data.Workspaces;
+
+namespace Chronos.Data.Tests.Homes;
+
+/// Workspaces and caches laid out as 1.0 left them, for the sorting into homes (owner review 5, #66).
+internal static class HomeFixtures
+{
+ public const string Nas = "https://nas.local:8443";
+ public const string NasByIp = "https://192.168.1.5:8443";
+ public const string Other = "https://other.example:8443";
+
+ /// A working state of written into <root>/<id> with some media, versions and a render.
+ public static Guid Project(string root, BundleHome home, string name = "Main", DateTimeOffset? saved = null, Guid? id = null, int proxies = 3)
+ {
+ var projectId = id ?? Guid.CreateVersion7();
+ var folder = Path.Combine(root, projectId.ToString("N"));
+ Directory.CreateDirectory(folder);
+ var archive = home.IsArchive
+ ? new BundleArchive(home.ArchiveId ?? Guid.CreateVersion7(), "This PC", @"D:\ChronosArchive")
+ : new BundleArchive(Data.Projects.ServerProjectHome.ArchiveIdOf(home.Server!), "Studio NAS", null);
+ var bundle = new ProjectBundle(archive, new BundleSequence(home.SequenceId, "2026/2026-11-15 Harbour", "Harbour", proxies), new ProjectSettings(),
+ saved ?? DateTimeOffset.UtcNow)
+ {
+ Workspace = new BundleWorkspace(projectId, name, true, home, null, new BundleMedia(BundleMedia.Proxies, 1)),
+ };
+ bundle.Save(Path.Combine(folder, WorkspaceProject.BundleFile));
+ var media = Path.Combine(folder, WorkspaceProject.MediaFolder, WorkspaceProject.ProxiesFolder);
+ Directory.CreateDirectory(media);
+ for (var i = 0; i < proxies; i++) File.WriteAllBytes(Path.Combine(media, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(projectId, i, 500 + i));
+ Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.VersionsFolder));
+ File.WriteAllText(Path.Combine(folder, WorkspaceProject.VersionsFolder, "1-" + Guid.CreateVersion7().ToString("N") + ".json"), "{}");
+ Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.ExportsFolder));
+ File.WriteAllBytes(Path.Combine(folder, WorkspaceProject.ExportsFolder, "render.mp4"), Bytes(projectId, 99, 2048));
+ return projectId;
+ }
+
+ public static BundleHome Local() => new(BundleHome.ArchiveKind, Guid.CreateVersion7(), Guid.CreateVersion7());
+
+ public static BundleHome Server(string key) => new(BundleHome.ServerKind, Guid.CreateVersion7(), null, key);
+
+ /// A 1.0 workspace: its manifest (format 1) and the folder.
+ public static string LegacyWorkspace(string parent)
+ {
+ var root = Path.Combine(parent, "workspace");
+ _ = new WorkspaceStore(root);
+ return root;
+ }
+
+ /// A trash entry of holding a working state, as a removal leaves it.
+ public static string TrashEntry(string root, Guid projectId, BundleHome home)
+ {
+ var trash = Path.Combine(root, WorkspaceTrash.FolderName);
+ var staging = Path.Combine(trash, "staging");
+ Directory.CreateDirectory(staging);
+ Project(staging, home, id: projectId, proxies: 1);
+ var entry = Path.Combine(trash, projectId.ToString("N") + "-638000000000000000");
+ Directory.Move(Path.Combine(staging, projectId.ToString("N")), entry);
+ Directory.Delete(staging);
+ return entry;
+ }
+
+ /// The 1.0 proxy cache of 's sequence .
+ public static string LegacyProxies(string cache, string key, Guid remoteId, int frames = 2)
+ {
+ var folder = Data.Sync.ProxyCache.LegacyFolder(Path.Combine(cache, "proxies"), key, remoteId);
+ Directory.CreateDirectory(folder);
+ File.WriteAllText(Path.Combine(folder, "remote.json"), "{}");
+ for (var i = 0; i < frames; i++) File.WriteAllBytes(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(remoteId, i, 300));
+ return folder;
+ }
+
+ /// A live lease on a project folder, as another Chronos working on the same workspace holds it.
+ public static LeaseFile Hold(string projectFolder) =>
+ LeaseFile.TryAcquire(projectFolder, ".lock", "workspace@other", TimeSpan.FromMinutes(5)) ?? throw new InvalidOperationException("The lease is held.");
+
+ ///
+ /// The SHA-256 of every file under by its name relative to the project or entry it belongs to,
+ /// whatever home folder holds it: the same before and after a sorting that only renames (the test-only proof).
+ ///
+ public static SortedDictionary Manifest(string root)
+ {
+ var manifest = new SortedDictionary(StringComparer.Ordinal);
+ if (!Directory.Exists(root)) return manifest;
+ foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories))
+ {
+ var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
+ var name = Path.GetFileName(file);
+ if (name is WorkspaceStore.ManifestFile or "server.json" && !relative.Contains('/', StringComparison.Ordinal)) continue;
+ if (name is WorkspaceStore.ManifestFile or "server.json" && IsHomeLevel(relative)) continue;
+ manifest[Strip(relative)] = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(file))) + "|" + new FileInfo(file).Length;
+ }
+ return manifest;
+ }
+
+ /// A path without the home folders it lies in (local/, servers/<folder>/).
+ private static string Strip(string relative)
+ {
+ if (relative.StartsWith("local/", StringComparison.Ordinal)) return relative["local/".Length..];
+ if (relative.StartsWith("servers/", StringComparison.Ordinal))
+ {
+ var rest = relative["servers/".Length..];
+ var slash = rest.IndexOf('/', StringComparison.Ordinal);
+ return slash < 0 ? rest : rest[(slash + 1)..];
+ }
+ return relative;
+ }
+
+ private static bool IsHomeLevel(string relative) =>
+ relative.Split('/') is { Length: 2 } parts && parts[0] == "local" || relative.Split('/') is { Length: 3 } more && more[0] == "servers";
+
+ private static byte[] Bytes(Guid seed, int index, int length)
+ {
+ var bytes = new byte[length];
+ var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed.ToString("N") + index));
+ for (var i = 0; i < length; i++) bytes[i] = hash[i % hash.Length];
+ return bytes;
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs b/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs
new file mode 100644
index 00000000..ad5404bc
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs
@@ -0,0 +1,297 @@
+using Chronos.Core.IO;
+using Chronos.Core.Project;
+using Chronos.Data.Homes;
+using Chronos.Data.Sync;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Homes;
+
+/// The one-time sorting of a 1.0 workspace and cache into homes (owner review 5, #66).
+[Category("homes")]
+public sealed class HomeLayoutMigrationTests(TestContext context)
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ /// A 1.0 data folder: a workspace with local, server and damaged projects and a trash, and a cache with proxies, render-node files and a staged import.
+ private sealed class Legacy
+ {
+ public required string Data { get; init; }
+ public required string Workspace { get; init; }
+ public required string Cache { get; init; }
+ public required Guid Local { get; init; }
+ public required Guid OnNas { get; init; }
+ public required Guid OnOther { get; init; }
+ public required Guid Damaged { get; init; }
+ public required Guid NasRemote { get; init; }
+
+ public HomeLayoutMigration Migration(ServerIdentity? identity = null, Action? cut = null) =>
+ new(new HomeLayoutOptions
+ {
+ DataDirectory = Data,
+ WorkspaceRoot = Workspace,
+ CacheRoot = Cache,
+ Identity = identity ?? ServerIdentity.None,
+ CurrentServer = HomeFixtures.Nas,
+ })
+ { Cut = cut };
+ }
+
+ private Legacy Make()
+ {
+ var data = context.CreateTempDirectory("data");
+ var workspace = HomeFixtures.LegacyWorkspace(data);
+ var local = HomeFixtures.Project(workspace, HomeFixtures.Local());
+ var onNas = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Nas));
+ var onOther = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Other));
+ var damaged = Guid.CreateVersion7();
+ Directory.CreateDirectory(Path.Combine(workspace, damaged.ToString("N")));
+ File.WriteAllText(Path.Combine(workspace, damaged.ToString("N"), WorkspaceProject.BundleFile), "{ not json");
+ HomeFixtures.TrashEntry(workspace, onNas, HomeFixtures.Server(HomeFixtures.Nas));
+ File.WriteAllText(Path.Combine(workspace, WorkspaceTrash.FolderName, "loose.txt"), "kept");
+ var cache = Path.Combine(data, "cache");
+ var nasRemote = Guid.CreateVersion7();
+ HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, nasRemote);
+ HomeFixtures.LegacyProxies(cache, HomeFixtures.Other, Guid.CreateVersion7());
+ Directory.CreateDirectory(Path.Combine(cache, "render-node", "job1"));
+ File.WriteAllText(Path.Combine(cache, "render-node", "job1", "frame.jpg"), "rn");
+ Directory.CreateDirectory(Path.Combine(cache, "server-import"));
+ File.WriteAllText(Path.Combine(cache, "server-import", "card.part"), "import");
+ return new Legacy
+ {
+ Data = data,
+ Workspace = workspace,
+ Cache = cache,
+ Local = local,
+ OnNas = onNas,
+ OnOther = onOther,
+ Damaged = damaged,
+ NasRemote = nasRemote,
+ };
+ }
+
+ /// Every file and folder under with its size and time: what a dry run must leave as it was.
+ private static List Snapshot(string root) =>
+ [.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
+ .Select(e => Path.GetRelativePath(root, e.FullName) + "|" + (e is FileInfo f ? f.Length + "|" + f.LastWriteTimeUtc.Ticks : "dir"))
+ .Order(StringComparer.Ordinal)];
+
+ private static string Home(string workspace, string key) => Path.Combine(workspace, "servers", HomeFolders.ServerFolder(key));
+
+ private static void AssertSorted(Legacy legacy, string nasFolder)
+ {
+ var ws = legacy.Workspace;
+ Assert.True(WorkspaceHomes.IsSplitRoot(ws));
+ Assert.FileExists(Path.Combine(ws, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.FileExists(Path.Combine(ws, "local", legacy.Damaged.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.FileExists(Path.Combine(ws, "servers", nasFolder, legacy.OnNas.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.FileExists(Path.Combine(Home(ws, HomeFixtures.Other), legacy.OnOther.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.FileExists(Path.Combine(ws, "local", WorkspaceTrash.FolderName, "loose.txt"));
+ Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(ws, "servers", nasFolder, WorkspaceTrash.FolderName)));
+ Assert.False(Directory.EnumerateDirectories(ws).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)), "no project is left in the parent");
+ Assert.False(Directory.Exists(Path.Combine(ws, WorkspaceTrash.FolderName)), "the parent's emptied trash went");
+ Assert.Equal("Studio NAS", Assert.NotNull(ServerHomeRecord.Read(Path.Combine(ws, "servers", nasFolder))).Name);
+ Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
+ Assert.True(Directory.Exists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Other), "proxies")));
+ Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "render-node", "job1", "frame.jpg"));
+ Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "import", "card.part"));
+ Assert.False(Directory.Exists(Path.Combine(legacy.Cache, "render-node")));
+ Assert.FileMissing(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
+ var homes = new WorkspaceHomes(ws);
+ Assert.True(homes.IsSplit);
+ Assert.Equal(4, homes.List().Count);
+ }
+
+ [Test]
+ public async Task ThePlanWritesNothing()
+ {
+ var legacy = Make();
+ var before = Snapshot(legacy.Data);
+ var plan = await legacy.Migration().PlanAsync(context.Cancellation);
+ Assert.SequenceEqual(before, Snapshot(legacy.Data));
+ Assert.True(plan.SplitsWorkspace);
+ Assert.Null(plan.Deferred);
+ Assert.Equal(4, plan.Projects);
+ Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Trash));
+ Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Proxies));
+ Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.RenderNode));
+ Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.Import));
+ var damaged = plan.Entries.Single(e => e.Source.EndsWith(legacy.Damaged.ToString("N"), StringComparison.Ordinal));
+ Assert.Equal(Path.Combine(legacy.Workspace, "local", legacy.Damaged.ToString("N")), damaged.Target);
+ Assert.Equal(plan.Fingerprint, (await legacy.Migration().PlanAsync(context.Cancellation)).Fingerprint);
+ }
+
+ [Test]
+ public async Task SortingMovesEveryHomeAndRenamesOnly()
+ {
+ var legacy = Make();
+ var before = HomeFixtures.Manifest(legacy.Workspace);
+ var cacheBefore = HomeFixtures.Manifest(legacy.Cache);
+ var result = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal((4, 0, false, true), (result.ProjectsMoved, result.InUse, result.Resumed, result.Split));
+ AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
+ // Every file is there with the same name relative to its project and the same bytes: the sorting only renamed.
+ Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
+ Assert.SequenceEqual(cacheBefore.Values.Order(), HomeFixtures.Manifest(legacy.Cache).Values.Order());
+
+ // A second run does nothing.
+ var again = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal(HomeLayoutResult.Nothing, again);
+ Assert.True((await legacy.Migration().PlanAsync(context.Cancellation)).IsEmpty);
+ }
+
+ [Test]
+ public async Task AServerKnownByIdGetsItsIdHome()
+ {
+ var legacy = Make();
+ await legacy.Migration(new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])])).ApplyAsync(context.Cancellation);
+ AssertSorted(legacy, Id.ToString("N"));
+ Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(Path.Combine(legacy.Workspace, "servers", Id.ToString("N")))).Key);
+ }
+
+ [Test]
+ public async Task ACrashAtAnyStepIsTakenUpToTheSameEnd()
+ {
+ var entries = (await Make().Migration().PlanAsync(context.Cancellation)).Entries.Count;
+ var cuts = new List<(string Step, int Occurrence)> { ("journal", 1), ("commit", 1) };
+ for (var i = 1; i <= entries; i++) cuts.AddRange([("rename", i), ("renamed", i)]);
+ foreach (var (step, occurrence) in cuts)
+ {
+ var legacy = Make();
+ var before = HomeFixtures.Manifest(legacy.Workspace);
+ var seen = 0;
+ var crashing = legacy.Migration(cut: (name, _) =>
+ {
+ if (name == step && ++seen == occurrence) throw new IOException("cut at " + step);
+ });
+ await Assert.ThrowsAsync(() => crashing.ApplyAsync(context.Cancellation));
+ Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
+ var resumed = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.True(resumed.Resumed, $"{step} #{occurrence}");
+ AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
+ Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace), $"{step} #{occurrence}");
+ Assert.Equal(HomeLayoutResult.Nothing, await legacy.Migration().ApplyAsync(context.Cancellation));
+ }
+ }
+
+ [Test]
+ public async Task AProjectInUseIsLeftAndMovedAtALaterStart()
+ {
+ var legacy = Make();
+ var held = HomeFixtures.Hold(Path.Combine(legacy.Workspace, legacy.Local.ToString("N")));
+ HomeLayoutResult result;
+ using (held)
+ {
+ var plan = await legacy.Migration().PlanAsync(context.Cancellation);
+ Assert.SequenceEqual(new[] { legacy.Local }, plan.InUse);
+ result = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal((3, 1, true), (result.ProjectsMoved, result.InUse, result.Split));
+ Assert.True(WorkspaceHomes.IsSplitRoot(legacy.Workspace));
+ var homes = new WorkspaceHomes(legacy.Workspace);
+ Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(legacy.Local)).Folder));
+ Assert.Equal(4, homes.List().Count);
+ }
+ result = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal((1, 0), (result.ProjectsMoved, result.InUse));
+ Assert.FileExists(Path.Combine(legacy.Workspace, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.Null(new WorkspaceHomes(legacy.Workspace).Homes().FirstOrDefault(h => h.IsLegacy));
+ }
+
+ [Test]
+ public async Task AnUnfinishedMoveDefersTheWorkspaceWhileTheCacheIsSorted()
+ {
+ var legacy = Make();
+ File.WriteAllText(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile), "{}");
+ var before = Snapshot(legacy.Workspace);
+ var result = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Moving, result.Deferred);
+ Assert.False(result.Split);
+ Assert.SequenceEqual(before, Snapshot(legacy.Workspace));
+ Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
+
+ File.Delete(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile));
+ await legacy.Migration().ApplyAsync(context.Cancellation);
+ AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
+ }
+
+ [Test]
+ public async Task AWorkspaceThatWentOfflineWaitsWithItsJournal()
+ {
+ var legacy = Make();
+ var before = HomeFixtures.Manifest(legacy.Workspace);
+ await Assert.ThrowsAsync(() => legacy.Migration(cut: (name, _) =>
+ {
+ if (name == "journal") throw new IOException("cut");
+ }).ApplyAsync(context.Cancellation));
+ // The drive goes before the next start.
+ var away = legacy.Workspace + "-unplugged";
+ Directory.Move(legacy.Workspace, away);
+ var waiting = await legacy.Migration().ApplyAsync(context.Cancellation);
+ Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Offline, waiting.Deferred);
+ Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
+ Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "import", "card.part"));
+ // Back: the workspace is sorted, the cache left as it is now.
+ Directory.Move(away, legacy.Workspace);
+ await legacy.Migration().ApplyAsync(context.Cancellation);
+ AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
+ Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
+ }
+
+ [Test]
+ public async Task AProjectInBothPlacesKeepsTheCopySavedLastAndTrashesTheOther()
+ {
+ var data = context.CreateTempDirectory("data");
+ var workspace = HomeFixtures.LegacyWorkspace(data);
+ var id = Guid.CreateVersion7();
+ var home = HomeFixtures.Local();
+ HomeFixtures.Project(workspace, home, "newer", DateTimeOffset.UtcNow, id);
+ HomeFixtures.Project(Path.Combine(workspace, "local"), home, "older", DateTimeOffset.UtcNow.AddDays(-1), id);
+ var files = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories).Count(f => Path.GetFileName(f) != WorkspaceStore.ManifestFile);
+ var result = await new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace }).ApplyAsync(context.Cancellation);
+ Assert.Equal(1, result.Clashes);
+ var kept = ProjectBundle.Load(Path.Combine(workspace, "local", id.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.Equal("newer", kept.Workspace!.Name);
+ var trashed = Assert.NotNull(Directory.EnumerateDirectories(Path.Combine(workspace, "local", WorkspaceTrash.FolderName)).SingleOrDefault());
+ Assert.Equal("older", ProjectBundle.Load(Path.Combine(trashed, WorkspaceProject.BundleFile)).Workspace!.Name);
+ Assert.Equal(files, Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories)
+ .Count(f => Path.GetFileName(f) is not (WorkspaceStore.ManifestFile or "server.json")), "nothing was deleted");
+ }
+
+ [Test]
+ public async Task ARenameThatDoesNotCheckStopsWithItsJournal()
+ {
+ var legacy = Make();
+ var tampered = false;
+ var migration = legacy.Migration(cut: (name, path) =>
+ {
+ if (name != "renamed" || tampered || !Directory.Exists(path)) return;
+ tampered = true;
+ File.WriteAllText(Path.Combine(path, "stray.txt"), "written meanwhile");
+ });
+ await Assert.ThrowsAsync(() => migration.ApplyAsync(context.Cancellation));
+ Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
+ // The next start takes it up; the entry found renamed is taken as moved.
+ await legacy.Migration().ApplyAsync(context.Cancellation);
+ AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
+ }
+
+ [Test]
+ public async Task AWorkspaceNeverMadeOrAlreadySortedHasNothingToDo()
+ {
+ var data = context.CreateTempDirectory("data");
+ var options = new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = Path.Combine(data, "workspace"), CacheRoot = Path.Combine(data, "cache") };
+ Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
+ Assert.Equal(HomeLayoutResult.Nothing, await new HomeLayoutMigration(options).ApplyAsync(context.Cancellation));
+ Assert.False(Directory.Exists(options.WorkspaceRoot));
+
+ _ = new WorkspaceHomes(options.WorkspaceRoot);
+ Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
+
+ // An empty 1.0 workspace is split by its manifest alone.
+ var empty = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("empty"));
+ var split = await new HomeLayoutMigration(options with { WorkspaceRoot = empty }).ApplyAsync(context.Cancellation);
+ Assert.True(split.Split);
+ Assert.True(WorkspaceHomes.IsSplitRoot(empty));
+ Assert.Equal(WorkspaceStore.FormatVersion, new WorkspaceStore(Path.Combine(empty, "local")).Manifest.FormatVersion);
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Homes/HomeRekeyTests.cs b/tests/Chronos.Data.Tests/Homes/HomeRekeyTests.cs
new file mode 100644
index 00000000..caa6eb29
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Homes/HomeRekeyTests.cs
@@ -0,0 +1,215 @@
+using Chronos.Core.IO;
+using Chronos.Core.Project;
+using Chronos.Data.Homes;
+using Chronos.Data.Projects;
+using Chronos.Data.Sync;
+using Chronos.Data.Tests.Infrastructure;
+using Chronos.Data.Tests.Repositories;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Homes;
+
+/// A server's home moves from its address to its id when it first announces one (owner review 5, #66).
+[Category("homes")]
+public sealed class HomeRekeyTests(TestContext context)
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+ private static string IdFolder => Id.ToString("N");
+
+ private (string Data, WorkspaceHomes Homes, string Cache) Make()
+ {
+ var data = context.CreateTempDirectory("data");
+ return (data, new WorkspaceHomes(Path.Combine(data, "workspace")), Path.Combine(data, "cache"));
+ }
+
+ private static HomeLayoutMigration Migration(string data, WorkspaceHomes homes, string cache) =>
+ new(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = homes.Root, CacheRoot = cache });
+
+ private static string AddressHome(string root, string key) => Path.Combine(root, "servers", HomeFolders.ServerFolder(key));
+
+ private static ProjectBundle Bundle(string home, Guid id) => ProjectBundle.Load(Path.Combine(home, id.ToString("N"), WorkspaceProject.BundleFile));
+
+ [Test]
+ public async Task TheHomeOfTheAddressBecomesTheHomeOfTheId()
+ {
+ var (data, homes, cache) = Make();
+ var home = HomeFixtures.Server(HomeFixtures.Nas);
+ var store = homes.StoreFor(home);
+ var (a, b) = (HomeFixtures.Project(store.Root, home), HomeFixtures.Project(store.Root, HomeFixtures.Server(HomeFixtures.Nas)));
+ HomeFixtures.TrashEntry(store.Root, a, home);
+ var before = HomeFixtures.Manifest(homes.Root);
+ var (sorted, old) = (Guid.CreateVersion7(), Guid.CreateVersion7());
+ var cached = Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", sorted.ToString("N"));
+ Directory.CreateDirectory(cached);
+ File.WriteAllText(Path.Combine(cached, "remote.json"), "{}");
+ HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, old);
+
+ var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
+ Assert.Equal(new HomeRekeyResult(2, 0, 0, 2, 0, 0, 0), result);
+ var idHome = Path.Combine(homes.Root, "servers", IdFolder);
+ Assert.False(Directory.Exists(AddressHome(homes.Root, HomeFixtures.Nas)));
+ var idKey = ServerIdentity.IdKey(Id);
+ foreach (var id in new[] { a, b })
+ {
+ var bundle = Bundle(idHome, id);
+ Assert.Equal(idKey, bundle.Workspace!.Home!.Server);
+ Assert.Equal(ServerProjectHome.ArchiveIdOf(idKey), bundle.Archive.Id);
+ }
+ var record = Assert.NotNull(ServerHomeRecord.Read(idHome));
+ Assert.Equal((idKey, (Guid?)Id, HomeFixtures.Nas), (record.Key, record.Id, record.Address));
+ Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)));
+ // Only the working states were rewritten: every other file is as it was.
+ var after = HomeFixtures.Manifest(homes.Root);
+ Assert.SequenceEqual(before.Keys, after.Keys);
+ Assert.SequenceEqual(before.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)),
+ after.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)));
+
+ Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", sorted.ToString("N"), "remote.json"));
+ Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", old.ToString("N"), "remote.json"));
+ Assert.False(Directory.Exists(AddressHome(cache, HomeFixtures.Nas)));
+ // The store now finds the id home by either key.
+ var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
+ Assert.Equal(idHome, new WorkspaceHomes(homes.Root, identity).ServerRoot(HomeFixtures.Nas));
+
+ // Again: nothing left to do.
+ Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation));
+ }
+
+ [Test]
+ public async Task TwoAddressesOfOneServerMergeAndTheOlderCopyGoesToTheTrash()
+ {
+ var (data, homes, cache) = Make();
+ var byName = HomeFixtures.Server(HomeFixtures.Nas);
+ var byIp = HomeFixtures.Server(HomeFixtures.NasByIp);
+ var first = homes.StoreFor(byName).Root;
+ var second = homes.StoreFor(byIp).Root;
+ var both = Guid.CreateVersion7();
+ HomeFixtures.Project(first, byName, "older", DateTimeOffset.UtcNow.AddDays(-1), both);
+ HomeFixtures.Project(second, byIp, "newer", DateTimeOffset.UtcNow, both);
+ var onlyFirst = HomeFixtures.Project(first, byName);
+ var onlySecond = HomeFixtures.Project(second, byIp);
+ HomeFixtures.TrashEntry(first, onlyFirst, byName);
+ HomeFixtures.TrashEntry(second, onlyFirst, byIp);
+ var files = Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile);
+ // Each address had a proxy cache too.
+ Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", "a"));
+ Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "a"));
+ Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "b"));
+
+ var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], context.Cancellation);
+ Assert.Equal((2, 2, 1, 3), (result.HomesMoved, result.ProjectsMoved, result.ProjectsTrashed, result.BundlesRewritten));
+ var idHome = Path.Combine(homes.Root, "servers", IdFolder);
+ Assert.Equal("newer", Bundle(idHome, both).Workspace!.Name);
+ foreach (var id in new[] { onlyFirst, onlySecond }) Assert.FileExists(Path.Combine(idHome, id.ToString("N"), WorkspaceProject.BundleFile));
+ var trash = Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)).ToList();
+ Assert.Equal(3, trash.Count);
+ Assert.Contains(trash, t => ProjectBundle.Load(Path.Combine(t, WorkspaceProject.BundleFile)).Workspace!.Name == "older");
+ // The second address's home held only its manifest and record afterwards: it went. Nothing else was deleted.
+ Assert.False(Directory.Exists(second));
+ Assert.Equal(files, Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile));
+ Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(homes.Root, "servers")));
+ Assert.True(Directory.Exists(Path.Combine(cache, "servers", IdFolder, "proxies", "b")));
+ }
+
+ [Test]
+ public async Task AProjectInUseStaysAndKeepsItsAliasWhichStillMatches()
+ {
+ var (data, homes, cache) = Make();
+ var home = HomeFixtures.Server(HomeFixtures.Nas);
+ var root = homes.StoreFor(home).Root;
+ var (held, free) = (HomeFixtures.Project(root, home), HomeFixtures.Project(root, HomeFixtures.Server(HomeFixtures.Nas)));
+ HomeRekeyResult result;
+ using (HomeFixtures.Hold(Path.Combine(root, held.ToString("N"))))
+ {
+ // A project in use keeps the whole home where it is until a later re-key; the id home is made beside it.
+ _ = new WorkspaceStore(Path.Combine(homes.Root, "servers", IdFolder));
+ result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
+ }
+ Assert.Equal((0, 1, 1), (result.HomesMoved, result.ProjectsMoved, result.BundlesRewritten));
+ Assert.FileExists(Path.Combine(root, held.ToString("N"), WorkspaceProject.BundleFile));
+ Assert.Equal(HomeFixtures.Nas, Bundle(root, held).Workspace!.Home!.Server);
+ var idHome = Path.Combine(homes.Root, "servers", IdFolder);
+ Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, free).Workspace!.Home!.Server);
+ Assert.True(ServerProjectHome.IsArchiveIdOf(Bundle(root, held).Archive.Id, [ServerIdentity.IdKey(Id), HomeFixtures.Nas]));
+ Assert.NotNull(homes.Find(held));
+
+ result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
+ Assert.Equal((1, 1), (result.ProjectsMoved, result.BundlesRewritten));
+ Assert.False(Directory.Exists(root));
+ Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, held).Workspace!.Home!.Server);
+ }
+
+ [Test]
+ public async Task AWorkingStateInUseInTheIdHomeIsLeftNamingTheAlias()
+ {
+ var (data, homes, cache) = Make();
+ var home = HomeFixtures.Server(HomeFixtures.Nas);
+ var root = homes.StoreFor(home).Root;
+ var id = HomeFixtures.Project(root, home);
+ // Renamed whole first (nothing held), then held while its working state would be rewritten.
+ var idHome = Path.Combine(homes.Root, "servers", IdFolder);
+ Directory.Move(root, idHome);
+ HomeRekeyResult result;
+ using (HomeFixtures.Hold(Path.Combine(idHome, id.ToString("N"))))
+ result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
+ Assert.Equal((0, 1), (result.BundlesRewritten, result.BundlesInUse));
+ Assert.Equal(HomeFixtures.Nas, Bundle(idHome, id).Workspace!.Home!.Server);
+ Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(idHome)).Key);
+ }
+
+ [Test]
+ public async Task AnIdKeyIsNeverAnAliasAndAnEmptyIdIsRefused()
+ {
+ var (data, homes, cache) = Make();
+ await Assert.ThrowsAsync(() => Migration(data, homes, cache).RekeyAsync(Guid.Empty, [HomeFixtures.Nas], context.Cancellation));
+ var other = ServerIdentity.IdKey(Guid.CreateVersion7());
+ var otherHome = homes.StoreFor(HomeFixtures.Server(other)).Root;
+ Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [other], context.Cancellation));
+ Assert.True(Directory.Exists(otherHome));
+ }
+
+ private static bool IsProjectFile(string path) => Path.GetFileName(path) is not (WorkspaceStore.ManifestFile or HomeFolders.ServerFile);
+}
+
+/// A re-key moves the server's links in the index too.
+[Category("homes")]
+public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(context)
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ [Test]
+ public async Task TheLinksOfEveryAliasMoveToTheId()
+ {
+ var db = await OpenChronosAsync();
+ var store = new SyncLinkStore(db);
+ foreach (var key in new[] { HomeFixtures.Nas, HomeFixtures.NasByIp, HomeFixtures.Other })
+ {
+ await store.UpsertAsync(new SyncLink
+ {
+ Server = key,
+ RemoteId = Guid.CreateVersion7(),
+ Title = "Harbour",
+ RemoteUpdatedAt = TestData.Now,
+ SyncedAt = TestData.Now,
+ }, Ct);
+ }
+ var data = Context.CreateTempDirectory("data");
+ var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, Database = db });
+ var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
+ Assert.Equal((2, 0), (result.LinksMoved, result.LinksDropped));
+ Assert.Count(2, await store.ListAsync(ServerIdentity.IdKey(Id), Ct));
+ Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
+ Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
+ }
+}
+
+public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
+{
+ protected override Backend Backend => Backend.SqliteMemory;
+}
+
+public sealed class PostgresHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
+{
+ protected override Backend Backend => Backend.Postgres;
+}
diff --git a/tests/Chronos.Data.Tests/Sync/ProxyCacheTests.cs b/tests/Chronos.Data.Tests/Sync/ProxyCacheTests.cs
new file mode 100644
index 00000000..35e93d19
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Sync/ProxyCacheTests.cs
@@ -0,0 +1,58 @@
+using Chronos.Core.IO;
+using Chronos.Data.Sync;
+using Chronos.Data.Tests.Homes;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Sync;
+
+/// Where the proxies of a server's sequence live (owner review 5, #66): its home in the cache, else where an earlier layout left them.
+[Category("sync")]
+public sealed class ProxyCacheTests(TestContext context)
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ [Test]
+ public void WithoutAServersRootTheLayoutIs10s()
+ {
+ var root = context.CreateTempDirectory("proxies");
+ var remote = Guid.CreateVersion7();
+ var cache = new ProxyCache(root);
+ Assert.Equal(Path.Combine(root, HomeFolders.AddressHash(HomeFixtures.Nas), remote.ToString("N")), cache.Folder(HomeFixtures.Nas, remote));
+ }
+
+ [Test]
+ public void ANewSequenceGoesToItsServersHomeAndAnOldOneIsReadWhereItIs()
+ {
+ var cacheRoot = context.CreateTempDirectory("cache");
+ var (legacyRoot, servers) = (Path.Combine(cacheRoot, "proxies"), Path.Combine(cacheRoot, "servers"));
+ var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
+ var cache = new ProxyCache(legacyRoot, servers, () => identity);
+ var idKey = ServerIdentity.IdKey(Id);
+
+ var fresh = Guid.CreateVersion7();
+ Assert.Equal(Path.Combine(servers, Id.ToString("N"), "proxies", fresh.ToString("N")), cache.Folder(idKey, fresh));
+ Assert.Equal(cache.Folder(idKey, fresh), cache.Folder(HomeFixtures.Nas, fresh), "an alias names the same home");
+
+ // A sequence cached by 1.0 under the address is used where it is until it is moved.
+ var old = Guid.CreateVersion7();
+ var legacy = HomeFixtures.LegacyProxies(cacheRoot, HomeFixtures.Nas, old);
+ Assert.Equal(legacy, cache.Folder(idKey, old));
+ Assert.True(cache.Exists(idKey, old));
+
+ // In the home of the address (sorted before the server announced its id): used there too.
+ var sorted = Guid.CreateVersion7();
+ var byAddress = Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", sorted.ToString("N"));
+ Directory.CreateDirectory(byAddress);
+ Assert.Equal(byAddress, cache.Folder(idKey, sorted));
+
+ // Once in its home, that is where it is.
+ var home = Path.Combine(servers, Id.ToString("N"), "proxies", old.ToString("N"));
+ Directory.CreateDirectory(Path.GetDirectoryName(home)!);
+ Directory.Move(legacy, home);
+ Assert.Equal(home, cache.Folder(HomeFixtures.Nas, old));
+
+ // A server known by its address only has an address home.
+ var other = Guid.CreateVersion7();
+ Assert.Equal(Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Other), "proxies", other.ToString("N")), cache.Folder(HomeFixtures.Other, other));
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Sync/ServerIdentityTests.cs b/tests/Chronos.Data.Tests/Sync/ServerIdentityTests.cs
new file mode 100644
index 00000000..f5bd09b7
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Sync/ServerIdentityTests.cs
@@ -0,0 +1,84 @@
+using Chronos.Core.IO;
+using Chronos.Data.Projects;
+using Chronos.Data.Sync;
+using Chronos.Protocol;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Sync;
+
+/// How the desktop names a server (owner review 5, #66): by its announced id, its address keys kept as aliases.
+[Category("sync")]
+public sealed class ServerIdentityTests
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ private static ServerInfo Info(Guid? id) => new("Studio NAS", "1.1.0", 1, [], null, [], new ServerLimits(1, 1), null, null, id);
+
+ [Test]
+ public void AServerThatAnnouncesAnIdIsKeyedByIt()
+ {
+ var key = ServerIdentity.Key(Info(Id), new Uri("https://NAS.local:8443/"));
+ Assert.Equal("id:" + Id.ToString("N"), key);
+ Assert.True(ServerIdentity.IsIdKey(key));
+ Assert.Equal(Id, ServerIdentity.IdOf(key));
+ // Another address of the same server: the same key.
+ Assert.Equal(key, ServerIdentity.Key(Info(Id), new Uri("https://192.168.1.5:8443")));
+ }
+
+ [Test]
+ public void AnOlderServerKeepsItsAddressKey()
+ {
+ var address = new Uri("https://NAS.local:8443/");
+ Assert.Equal("https://nas.local:8443", ServerIdentity.Key(Info(null), address));
+ Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key((ServerInfo?)null, address));
+ Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key(Guid.Empty, address));
+ Assert.False(ServerIdentity.IsIdKey(SyncService.ServerKey(address)));
+ }
+
+ [Test]
+ public void AliasesNameTheServerOfTheirId()
+ {
+ var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443", "https://192.168.1.5:8443"])]);
+ var key = ServerIdentity.IdKey(Id);
+ Assert.Equal(key, identity.Canonical("https://NAS.local:8443"));
+ Assert.Equal(key, identity.Canonical(key.ToUpperInvariant()));
+ Assert.Equal("https://other:1", identity.Canonical("https://other:1"));
+ Assert.True(identity.Same("https://nas.local:8443", "https://192.168.1.5:8443"));
+ Assert.True(identity.Same(key, "https://192.168.1.5:8443"));
+ Assert.False(identity.Same(key, "https://other:1"));
+ Assert.True(identity.Same(null, null));
+ Assert.False(identity.Same(key, null));
+ Assert.Equal(Id.ToString("N"), identity.FolderName("https://192.168.1.5:8443"));
+ Assert.Equal(HomeFolders.ServerFolder("https://other:1"), identity.FolderName("https://other:1"));
+ Assert.SequenceEqual(new[] { key, "https://nas.local:8443", "https://192.168.1.5:8443" }, identity.KeysOf("https://192.168.1.5:8443"));
+ Assert.SequenceEqual(new[] { "https://other:1" }, identity.KeysOf("https://other:1"));
+ Assert.Equal(2, identity.AliasesOf(Id).Count);
+
+ // Without the table every key is its own.
+ Assert.False(ServerIdentity.None.Same(key, "https://nas.local:8443"));
+ }
+
+ [Test]
+ public void AnAddressChangeKeepsTheKeyOnceTheAliasIsKnown()
+ {
+ var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443"])]);
+ var widened = identity.With(Id, "https://nas.local:9443");
+ Assert.True(widened.Same("https://nas.local:8443", "https://nas.local:9443"));
+ Assert.Same(widened, widened.With(Id, "HTTPS://nas.local:9443"));
+ Assert.False(identity.Same("https://nas.local:8443", "https://nas.local:9443"), "the table it came from is unchanged");
+ var other = Guid.CreateVersion7();
+ Assert.Equal(ServerIdentity.IdKey(other), widened.With(other, "https://second:1").Canonical("https://second:1"));
+ // An address two ids claim stays with the first one listed.
+ var clash = new ServerIdentity([new KnownServerKey(Id, ["https://x"]), new KnownServerKey(other, ["https://x"])]);
+ Assert.Equal(ServerIdentity.IdKey(Id), clash.Canonical("https://x"));
+ }
+
+ [Test]
+ public void TheArchiveIdOfAnyAliasIsTheServers()
+ {
+ string[] keys = [ServerIdentity.IdKey(Id), "https://nas.local:8443"];
+ Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), keys));
+ Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf(keys[0]), keys));
+ Assert.False(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://other:1"), keys));
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs b/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs
new file mode 100644
index 00000000..0d751b17
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs
@@ -0,0 +1,72 @@
+using Chronos.Data.Sync;
+using Chronos.Data.Tests.Infrastructure;
+using Chronos.Data.Tests.Repositories;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Sync;
+
+/// A server's links move from its address key to its id key (owner review 5, #66), the newer row winning a clash.
+[Category("sync")]
+public abstract class SyncLinkRekeyTests(TestContext context) : RepositoryTest(context)
+{
+ private const string Address = "https://nas.local:8443";
+ private static readonly string IdKey = ServerIdentity.IdKey(Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01"));
+
+ private static SyncLink Link(string server, Guid remoteId, Guid? localId, DateTimeOffset? synced, string title = "Harbour") => new()
+ {
+ Server = server,
+ RemoteId = remoteId,
+ LocalId = localId,
+ Title = title,
+ RemoteUpdatedAt = TestData.Now,
+ SyncedAt = synced,
+ };
+
+ [Test]
+ public async Task TheLinksOfAnAddressMoveToTheIdAndTheNewerRowWinsAClash()
+ {
+ var db = await OpenChronosAsync();
+ var archive = TestData.Archive();
+ await db.Archives.UpsertAsync(archive, Ct);
+ var (a, b, c) = (TestData.Sequence(archive.Id), TestData.Sequence(archive.Id), TestData.Sequence(archive.Id));
+ foreach (var sequence in new[] { a, b, c }) await db.Sequences.UpsertAsync(sequence, Ct);
+ var store = new SyncLinkStore(db);
+ var (plain, sameRemote, sameLocal, stale) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
+ // Only under the address: it moves.
+ await store.UpsertAsync(Link(Address, plain, a.Id, TestData.Now), Ct);
+ // Under both keys for one server sequence: the address's row is newer, so it replaces the id's.
+ await store.UpsertAsync(Link(Address, sameRemote, null, TestData.Now.AddHours(2), "newer"), Ct);
+ await store.UpsertAsync(Link(IdKey, sameRemote, null, TestData.Now.AddHours(1), "older"), Ct);
+ // Both keys link local copy b to different server sequences: the id's row is newer, so the address's goes.
+ await store.UpsertAsync(Link(Address, sameLocal, b.Id, TestData.Now), Ct);
+ await store.UpsertAsync(Link(IdKey, Guid.CreateVersion7(), b.Id, TestData.Now.AddDays(1)), Ct);
+ // Never compared under the address, compared under the id: the id's stays.
+ await store.UpsertAsync(Link(Address, stale, c.Id, null), Ct);
+ await store.UpsertAsync(Link(IdKey, stale, null, TestData.Now), Ct);
+
+ var (moved, dropped) = await store.RekeyAsync(Address, IdKey, Ct);
+ Assert.Equal((2, 3), (moved, dropped));
+ Assert.Empty(await store.ListAsync(Address, Ct));
+ var links = (await store.ListAsync(IdKey, Ct)).ToDictionary(l => l.RemoteId);
+ Assert.Equal(4, links.Count);
+ Assert.Equal(a.Id, links[plain].LocalId);
+ Assert.Equal("newer", links[sameRemote].Title);
+ Assert.False(links.ContainsKey(sameLocal));
+ Assert.Null(links[stale].LocalId);
+ Assert.Equal(b.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, b.Id, Ct)).LocalId);
+
+ // Again: nothing left to move; and a key onto itself does nothing.
+ Assert.Equal((0, 0), await store.RekeyAsync(Address, IdKey, Ct));
+ Assert.Equal((0, 0), await store.RekeyAsync(IdKey, IdKey, Ct));
+ }
+}
+
+public sealed class SqliteSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
+{
+ protected override Backend Backend => Backend.SqliteMemory;
+}
+
+public sealed class PostgresSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
+{
+ protected override Backend Backend => Backend.Postgres;
+}
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceHomesTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceHomesTests.cs
new file mode 100644
index 00000000..a3f6ee29
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceHomesTests.cs
@@ -0,0 +1,172 @@
+using Chronos.Core.IO;
+using Chronos.Core.Localization;
+using Chronos.Core.Project;
+using Chronos.Data.Sync;
+using Chronos.Data.Tests.Homes;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Workspaces;
+
+/// The workspace split into one store per home (owner review 5, #66).
+[Category("workspace")]
+public sealed class WorkspaceHomesTests(TestContext context)
+{
+ private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+
+ [Test]
+ public void ANewWorkspaceIsSplitAndEachHomeGetsItsStore()
+ {
+ var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
+ var homes = new WorkspaceHomes(root, new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]));
+ Assert.True(homes.IsSplit);
+ Assert.True(WorkspaceHomes.IsSplitRoot(root));
+ Assert.Equal((WorkspaceHomes.ParentFormatVersion, WorkspaceHomes.HomesLayout), (homes.Manifest.FormatVersion, homes.Manifest.Layout));
+ Assert.Empty(homes.Homes());
+ // A 1.0 Chronos (store format 1) refuses the parent: it never shows the workspace empty.
+ Assert.Throws(() => new WorkspaceStore(root));
+
+ var local = homes.StoreFor(HomeFixtures.Local());
+ Assert.Equal(Path.Combine(homes.Root, "local"), local.Root);
+ var server = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas));
+ Assert.Equal(Path.Combine(homes.Root, "servers", Id.ToString("N")), server.Root);
+ Assert.Same(server, homes.StoreFor(HomeFixtures.Server(ServerIdentity.IdKey(Id))));
+ var record = Assert.NotNull(ServerHomeRecord.Read(server.Root));
+ Assert.Equal((ServerIdentity.IdKey(Id), (Guid?)Id), (record.Key, record.Id));
+ var other = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other));
+ Assert.Equal(Path.Combine(homes.Root, "servers", HomeFolders.ServerFolder(HomeFixtures.Other)), other.Root);
+ Assert.Equal(HomeFixtures.Other, Assert.NotNull(ServerHomeRecord.Read(other.Root)).Address);
+ Assert.NotEqual(local.Id, server.Id);
+
+ var described = Assert.NotNull(homes.Describe(HomeFixtures.Nas, "Studio NAS", HomeFixtures.Nas, "AA:BB", DateTimeOffset.UtcNow));
+ Assert.Equal(("Studio NAS", HomeFixtures.Nas, "AA:BB"), (described.Name, described.Address, described.TlsFingerprint));
+ Assert.Equal(record.FirstSeen, described.FirstSeen);
+
+ var listed = homes.Homes();
+ Assert.Equal(3, listed.Count);
+ Assert.True(listed[0].IsLocal);
+ Assert.Contains(listed, h => h.ServerKey == ServerIdentity.IdKey(Id) && h.Server?.Name == "Studio NAS");
+ }
+
+ [Test]
+ public void ProjectsAreFoundInEveryHomeAndTheTrashIsListedPerHome()
+ {
+ var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
+ var homes = new WorkspaceHomes(root);
+ var a = HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local());
+ var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
+ var b = HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome);
+ Assert.Equal(homes.LocalRoot, Path.GetDirectoryName(Assert.NotNull(homes.Find(a)).Folder));
+ Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), Path.GetDirectoryName(Assert.NotNull(homes.Find(b)).Folder));
+ Assert.Null(homes.Find(Guid.CreateVersion7()));
+ Assert.Equal(2, homes.List().Count);
+ Assert.Equal(2, homes.ListBundles().Count);
+
+ HomeFixtures.TrashEntry(homes.ServerRoot(HomeFixtures.Nas), b, serverHome);
+ var trash = homes.Trash();
+ Assert.Equal(2, trash.Count);
+ Assert.Equal(1, trash.Sum(t => t.Entries.Count));
+ }
+
+ [Test]
+ public void A10WorkspaceStaysOneStoreUntilItIsSorted()
+ {
+ var root = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("ws"));
+ var a = HomeFixtures.Project(root, HomeFixtures.Local());
+ var homes = new WorkspaceHomes(root);
+ Assert.False(homes.IsSplit);
+ Assert.Equal(1, homes.Manifest.FormatVersion);
+ Assert.Equal(homes.Root, homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas)).Root);
+ Assert.Equal(homes.Root, homes.Local.Root);
+ Assert.True(Assert.NotNull(homes.Find(a)).Exists);
+ Assert.True(homes.Homes().Single().IsLegacy);
+ Assert.False(Directory.Exists(homes.LocalRoot), "nothing is made beside the 1.0 projects");
+
+ // A folder with projects and no manifest is a 1.0 workspace too, never a new split one.
+ var bare = Path.Combine(context.CreateTempDirectory("bare"), "workspace");
+ HomeFixtures.Project(bare, HomeFixtures.Local());
+ Assert.False(new WorkspaceHomes(bare).IsSplit);
+ }
+
+ [Test]
+ public void AProjectNotSortedYetIsListedWhereItIs()
+ {
+ var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
+ _ = new WorkspaceHomes(root);
+ var left = HomeFixtures.Project(root, HomeFixtures.Local());
+ var homes = new WorkspaceHomes(root);
+ Assert.True(homes.IsSplit);
+ Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(left)).Folder));
+ Assert.True(homes.Homes()[0].IsLegacy);
+ Assert.Equal(homes.LocalRoot, homes.Local.Root);
+ }
+
+ [Test]
+ public void AJobQueuedBeforeTheSortingFindsItsProjectInItsHome()
+ {
+ var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
+ var homes = new WorkspaceHomes(root);
+ var home = HomeFixtures.Server(HomeFixtures.Nas);
+ var id = HomeFixtures.Project(homes.ServerRoot(HomeFixtures.Nas), home);
+ _ = homes.StoreFor(home);
+ // Queued with the 1.0 folder (the parent): found in the server's home.
+ Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), WorkspaceJobRoots.Resolve(root, id, null, "Errors.Workspace.NotCheckedOut"));
+ // Queued with the home of the address, which was re-keyed to the id since.
+ var rekeyed = Path.Combine(root, "servers", Id.ToString("N"));
+ Directory.Move(homes.ServerRoot(HomeFixtures.Nas), rekeyed);
+ Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(root, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas)), id, null, "Errors.Workspace.NotCheckedOut"));
+ // With the parent in use now (Settings › Workspace) and an older folder named.
+ Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(context.CreateTempDirectory("gone"), "workspace"), id, () => root, "Errors.Workspace.NotCheckedOut"));
+ // While the parent is being moved nothing runs.
+ File.WriteAllText(Path.Combine(root, WorkspaceMover.JournalFile), "{}");
+ var moving = Assert.Throws(() => WorkspaceJobRoots.Resolve(rekeyed, id, null, "Errors.Workspace.NotCheckedOut"));
+ Assert.Equal(Loc.L("Errors.Workspace.Moving"), moving.Message);
+ File.Delete(Path.Combine(root, WorkspaceMover.JournalFile));
+ Assert.Throws(() => WorkspaceJobRoots.Resolve(root, Guid.CreateVersion7(), null, "Errors.Workspace.NotCheckedOut"));
+ }
+
+ [Test]
+ public void SameServerGoesThroughTheAliases()
+ {
+ var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
+ var options = new WorkspaceJobOptions(new Chronos.Data.Processing.ProcessingOptions(), () => false);
+ Assert.True(options.IsSameServer("https://NAS.local:8443", HomeFixtures.Nas));
+ Assert.False(options.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
+ var aliased = options with { SameServer = identity.Same };
+ Assert.True(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
+ Assert.False(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Other));
+ }
+
+ [Test]
+ public async Task MovingASplitWorkspaceMovesEveryHome()
+ {
+ foreach (var sameVolume in new[] { true, false })
+ {
+ var parent = context.CreateTempDirectory("move");
+ var from = Path.Combine(parent, "workspace");
+ var homes = new WorkspaceHomes(from);
+ var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
+ var ids = new[]
+ {
+ HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local()),
+ HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome),
+ HomeFixtures.Project(homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other)).Root, HomeFixtures.Server(HomeFixtures.Other)),
+ };
+ var before = HomeFixtures.Manifest(from);
+ var to = Path.Combine(parent, "moved");
+ var mover = new WorkspaceMover(from, to) { SameVolume = sameVolume };
+ var survey = mover.Survey();
+ Assert.Equal(3, survey.Projects.Count);
+ Assert.SequenceEqual(new[] { "local", "servers", WorkspaceStore.ManifestFile }, survey.Entries);
+ var lines = new List();
+ await mover.MoveAsync(survey.Fingerprint, log: lines.Add, cancellationToken: context.Cancellation);
+ Assert.False(Directory.Exists(from), "the old folder went");
+ var moved = new WorkspaceHomes(to);
+ Assert.True(moved.IsSplit);
+ Assert.Equal(3, moved.List().Count);
+ foreach (var id in ids) Assert.NotNull(moved.Find(id));
+ Assert.SequenceEqual(before, HomeFixtures.Manifest(to));
+ Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 3, survey.Files), lines);
+ }
+ }
+}
diff --git a/tests/Chronos.Server.Tests/Api/ServerInfoIdTests.cs b/tests/Chronos.Server.Tests/Api/ServerInfoIdTests.cs
new file mode 100644
index 00000000..2c5c17d8
--- /dev/null
+++ b/tests/Chronos.Server.Tests/Api/ServerInfoIdTests.cs
@@ -0,0 +1,117 @@
+using System.Text.Json;
+using Chronos.Data;
+using Chronos.Data.Repositories;
+using Chronos.Protocol;
+using Chronos.Server.Hosting;
+using Chronos.Testing;
+
+namespace Chronos.Server.Tests.Api;
+
+/// The server's stable id announced by /server/info (owner review 5, #66).
+[Category("server")]
+public sealed class ServerInfoIdTests(TestContext context)
+{
+ private static async Task InfoAsync(TestServer server)
+ {
+ using var response = await server.Client.GetAsync("/api/v1/server/info");
+ return await response.ReadAsync(ProtocolJson.Default.ServerInfo);
+ }
+
+ [Test]
+ public async Task TheIdIsMadeOnceAndKeptAcrossRestarts()
+ {
+ var root = context.CreateTempDirectory("kept");
+ void Same(Configuration.ServerOptions o)
+ {
+ o.DataPath = Path.Combine(root, "data");
+ o.ArchivePath = Path.Combine(root, "archive");
+ }
+ Guid first;
+ await using (var server = await TestServer.StartAsync(context, Same))
+ {
+ first = Assert.NotNull((await InfoAsync(server)).ServerId);
+ Assert.NotEqual(Guid.Empty, first);
+ var stored = await server.Database.Settings.GetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, context.Cancellation);
+ Assert.Equal("\"" + first.ToString("D") + "\"", stored);
+ }
+ await using (var again = await TestServer.StartAsync(context, Same))
+ Assert.Equal((Guid?)first, (await InfoAsync(again)).ServerId);
+ // Another server (another database) has another id.
+ await using (var other = await TestServer.StartAsync(context))
+ Assert.NotEqual((Guid?)first, (await InfoAsync(other)).ServerId);
+ }
+
+ [Test]
+ public async Task TheIdSurvivesARestoreOfTheIndex()
+ {
+ var folder = context.CreateTempDirectory("restore");
+ Guid id;
+ string backup;
+ await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation))
+ {
+ id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
+ backup = await db.BackupAsync(Path.Combine(folder, "backups"), cancellationToken: context.Cancellation);
+ }
+ // A new index (the disk replaced), then the backup put back.
+ await using var restored = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "new.db")), context.Cancellation);
+ await restored.RestoreAsync(backup, context.Cancellation);
+ Assert.Equal(id, await ServerHost.ServerIdAsync(restored, null, context.Cancellation));
+ }
+
+ [Test]
+ public async Task AStoredIdThatIsNotOneIsMadeAgain()
+ {
+ var folder = context.CreateTempDirectory("damaged");
+ await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
+ foreach (var damaged in new[] { "\"not a guid\"", "\"" + Guid.Empty.ToString("D") + "\"", "42" })
+ {
+ await db.Settings.SetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, damaged, context.Cancellation);
+ var made = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
+ Assert.NotEqual(Guid.Empty, made);
+ Assert.Equal(made, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
+ }
+ }
+
+ [Test]
+ [RequiresEnvironment("CHRONOS_TEST_PG")]
+ public async Task TheIdIsKeptOnPostgres()
+ {
+ var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
+ var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
+ var schema = "chronos_s_" + Guid.NewGuid().ToString("N")[..16];
+ await using (var session = await admin.OpenAsync(context.Cancellation))
+ await session.ExecuteScriptAsync($"CREATE SCHEMA {schema}", context.Cancellation);
+ try
+ {
+ var options = DatabaseOptions.Postgres(baseConnection.TrimEnd(';', ' ') + $";Search Path={schema}");
+ Guid id;
+ await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
+ id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
+ await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
+ Assert.Equal(id, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
+ }
+ finally
+ {
+ await using (var session = await admin.OpenAsync(CancellationToken.None))
+ await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {schema} CASCADE", CancellationToken.None);
+ await admin.DisposeAsync();
+ }
+ }
+
+ [Test]
+ public void AnOlderClientAndAnOlderServerReadEachOther()
+ {
+ var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
+ var info = new ServerInfo("Studio NAS", "1.1.0", 1, ["sync"], null, ["jpeg"], new ServerLimits(1, 1), null, 3, id);
+ var json = JsonSerializer.Serialize(info, ProtocolJson.Default.ServerInfo);
+ Assert.Contains("\"serverId\":\"" + id.ToString("D") + "\"", json);
+ Assert.Equal(info.ServerId, Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerInfo)).ServerId);
+
+ // A 1.0 server sends no id: it reads as null, and a 1.0 client ignores the member it does not know.
+ const string older = """{"name":"NAS","version":"1.0.0","apiVersion":1,"capabilities":["sync"],"formats":["jpeg"],"limits":{"maxUploadBytes":1,"chunkSizeBytes":1}}""";
+ Assert.Null(Assert.NotNull(JsonSerializer.Deserialize(older, ProtocolJson.Default.ServerInfo)).ServerId);
+ Assert.False(JsonSerializer.Serialize(info with { ServerId = null }, ProtocolJson.Default.ServerInfo).Contains("serverId", StringComparison.Ordinal));
+ using var parsed = JsonDocument.Parse(json);
+ Assert.Equal("Studio NAS", parsed.RootElement.GetProperty("name").GetString());
+ }
+}
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);
- }
-}