diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index af4f5ff6..3d0afd64 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -54,7 +54,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|---|---|
| `Sqlite`, `Postgres` | SQLite P/Invoke binding (winsqlite3 / libsqlite3), in-house PostgreSQL wire protocol v3 client with pool and LISTEN |
| `Migrations/{sqlite,postgres}/NNNN_name.sql` | Embedded, applied in one transaction at open (`MigrationRunner`) |
-| `Repositories` | `TitanoDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit; `DatabaseBackups` (daily `VACUUM INTO` copies of an SQLite index kept ×3, restore staged for the next open) |
+| `Repositories` | `TitanoDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit; `DatabaseBackups` (daily `VACUUM INTO` copies of an SQLite index kept ×3, restore staged for the next start and carried out before the index opens, so it also recovers one that no longer opens) |
| `Jobs` | `JobEngine` (its number of workers can change while it runs), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs) |
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages`, `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails), job handlers |
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `SequenceRender`, `ProjectStore`, `RenderNodeClient`, job handlers |
diff --git a/i18n/ar/Tooltips.ar.resx b/i18n/ar/Tooltips.ar.resx
index c9cfcc9a..1a865acf 100644
--- a/i18n/ar/Tooltips.ar.resx
+++ b/i18n/ar/Tooltips.ar.resx
@@ -566,8 +566,6 @@
الخادم الافتراضي، وعقدة التصيير، والشهادات الموثوقةمجلد التخزين المؤقت، والصور المصغرة في الذاكرة، وحد التخزين المؤقتالتحقق من التحديثات عند البدء
- تلقائي: عدد الأنوية ناقص أربعة لتبقى الواجهة سريعة الاستجابة
- العودة إلى «تلقائي»: عدد الأنوية ناقص أربعةمفعّل عند وجود portable.txt بجانب Titano.exe: تبقى كل البيانات في مجلد البيانات الخاص بهاستخدام مرمّز عتادي عندما يدعم الإعداد المسبق، وإلا فالمرمّز البرمجيأول ثلاثة أسماء لاستيراد تجريبي بهذه القوالب
diff --git a/i18n/bg/Tooltips.bg.resx b/i18n/bg/Tooltips.bg.resx
index dcfe8de7..f8d1c859 100644
--- a/i18n/bg/Tooltips.bg.resx
+++ b/i18n/bg/Tooltips.bg.resx
@@ -536,8 +536,6 @@
Сървър по подразбиране, възел за рендериране, доверени сертификатиПапка на кеша, миниатюри в паметта, лимит на кешаПроверка за актуализации при стартиране
- Авто: броят ядра минус четири, за да остане интерфейсът отзивчив
- Връщане към „Авто“: броят ядра минус четириВключен, когато portable.txt е до Titano.exe: всички данни остават в неговата папка с данниИзползва хардуерен кодер, когато някой поддържа пресета; иначе софтуеренПървите три имена от примерно импортиране с тези шаблони
diff --git a/i18n/cs/Tooltips.cs.resx b/i18n/cs/Tooltips.cs.resx
index 1e9d8ebf..e2d5f579 100644
--- a/i18n/cs/Tooltips.cs.resx
+++ b/i18n/cs/Tooltips.cs.resx
@@ -551,8 +551,6 @@
Výchozí server, renderovací uzel, důvěryhodné certifikátySložka mezipaměti, miniatury v paměti, limit mezipamětiKontrola aktualizací při spuštění
- Auto: počet jader minus čtyři, aby rozhraní zůstalo svižné
- Zpět na Auto: počet jader minus čtyřiZapnuto, když vedle souboru Titano.exe leží portable.txt: všechna data zůstávají v jeho datové složcePoužije hardwarový kodér, pokud předvolbu podporuje; jinak softwarovýPrvní tři názvy ukázkového importu s těmito šablonami
diff --git a/i18n/da/Tooltips.da.resx b/i18n/da/Tooltips.da.resx
index 50528e14..666a1dae 100644
--- a/i18n/da/Tooltips.da.resx
+++ b/i18n/da/Tooltips.da.resx
@@ -536,8 +536,6 @@
Standardserver, renderingsnode, betroede certifikaterCachemappe, miniaturer i hukommelsen, cachegrænseSøg efter opdateringer ved start
- Auto: antal kerner minus fire, så brugerfladen forbliver responsiv
- Tilbage til Auto: antal kerner minus fireTil, når portable.txt ligger ved siden af Titano.exe: alle data bliver i programmets datamappeBrug en hardwareencoder, når en understøtter forudindstillingen; ellers softwareDe tre første navne fra en prøveimport med disse skabeloner
diff --git a/i18n/de/Tooltips.de.resx b/i18n/de/Tooltips.de.resx
index c540ebc2..b0f4c22c 100644
--- a/i18n/de/Tooltips.de.resx
+++ b/i18n/de/Tooltips.de.resx
@@ -536,8 +536,6 @@
Standardserver, Render-Knoten, vertrauenswürdige ZertifikateCache-Ordner, Miniaturansichten im Arbeitsspeicher, Cache-LimitUpdateprüfung beim Start
- Auto: Kerne minus vier, damit die Oberfläche reaktionsfähig bleibt
- Zurück zu Auto: Kerne minus vierAktiv, wenn portable.txt neben Titano.exe liegt: Alle Daten bleiben im Datenordner danebenEinen Hardware-Encoder verwenden, wenn einer die Vorgabe unterstützt, sonst SoftwareDie ersten drei Namen eines Beispielimports mit diesen Vorlagen
diff --git a/i18n/el/Tooltips.el.resx b/i18n/el/Tooltips.el.resx
index 6e2b4e3c..c037cf84 100644
--- a/i18n/el/Tooltips.el.resx
+++ b/i18n/el/Tooltips.el.resx
@@ -536,8 +536,6 @@
Προεπιλεγμένος διακομιστής, κόμβος απόδοσης, αξιόπιστα πιστοποιητικάΦάκελος κρυφής μνήμης, μικρογραφίες στη μνήμη, όριο κρυφής μνήμηςΈλεγχος για ενημερώσεις κατά την εκκίνηση
- Αυτόματο: πυρήνες μείον τέσσερις, ώστε το περιβάλλον εργασίας να ανταποκρίνεται
- Επαναφορά σε Αυτόματο: πυρήνες μείον τέσσεριςΕνεργή όταν το portable.txt βρίσκεται δίπλα στο Titano.exe: όλα τα δεδομένα μένουν στον φάκελο δεδομένων τουΧρήση κωδικοποιητή υλικού όταν κάποιος υποστηρίζει την προρύθμιση, διαφορετικά κωδικοποιητή λογισμικούΤα τρία πρώτα ονόματα μιας δοκιμαστικής εισαγωγής με αυτά τα πρότυπα
diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index b0fa151b..cdc3820a 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -140,6 +140,7 @@
Dry runRebuild proxiesRelink moved archive…
+ Restore database…Run maintenanceTrash…{0:N0} issue
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 543c7626..d21c9f01 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -26,6 +26,8 @@
DisconnectNot connected to a serverToo many failed sign-ins; the account is locked for a while.long
+ Another program is changing the archive's settings; try again shortly.long
+ The archive's archive.json is damaged, from a newer Titano or of another archive; check the archive folder.longThe archive is offline or read-only; try again when it is back.longIts photos are the archive's root folder, which never moves to the trash.longWrong user name or password.long
diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx
index b67cd880..5175d1c5 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -35,6 +35,7 @@
Waiting for restartRestore readyRestore the index of {0}?long
+ Now: unreadableIndex restored from a backuplongAfter importAfter a scan
@@ -55,6 +56,9 @@
Rescan everyPreviewProxy size
+ Reset archive
+ Its naming templates, proxy size and thumbnail size return to their defaults for every PC and server that uses it. Folders and files already in the archive keep their names.long
+ Reset the settings of {0}?long; {0} archive nameArchive folderThumbnail sizeBack to Auto
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 2de80576..3275731e 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -74,6 +74,7 @@
Queue the rebuild · the archive stays usable meanwhileChoose the new folder of an archive you moved; its sequences followMake exactly these changes to folders, sidecars and index · resumes after a crash
+ Choose a daily backup of the index in Settings › Advanced; it replaces the index at the next startChange the tags of these sequences in sidecars and indexRun the same action againIncremental scan: new, changed and removed files by modification time and size
@@ -530,6 +531,7 @@
Load 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 Titano is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses
+ Leave this archive's settings as they areKeep the cache as it isKeep the index as it isKeep every setting as it is
@@ -551,8 +553,6 @@
Default server, render node, trusted certificatesCache folder, thumbnails in memory, cache limitUpdate check on start
- Auto: cores minus four so the interface stays responsive
- Back to Auto: cores minus fourHow often Titano rescans the archive for changes made elsewhere, such as by a server sharing itOn when portable.txt sits next to Titano.exe: all data stays in its data folderUse a hardware encoder when one supports the preset; software otherwise
@@ -563,6 +563,7 @@
List the encoders again after a driver or codec installLook for codec extensions again after installing one; the next jobs use themReturn every setting of this PC to its default; asks first
+ Write the default templates and sizes into this archive's archive.json nowReset every setting nowReturn every control of this section to its defaultCompare the chosen backup with the index, then restore it at the next start; asks first
@@ -584,6 +585,8 @@
No decoder on this PC reads its pixels; such frames are left out of rendersSend a daily anonymous count of versions and languages in use; nothing else, off by defaultJobs and frames processed at once; fewer leave more room to other programs · Enter applies, Esc reverts
+ Auto: half the logical cores run jobs at once, each with its own number of threads
+ Back to Auto: half the logical coresInstall in Program Files for every account · asks for administrator approvalReturn to the options without changing anythingChoose the installation folder
diff --git a/i18n/es/Tooltips.es.resx b/i18n/es/Tooltips.es.resx
index ab490a8e..03521147 100644
--- a/i18n/es/Tooltips.es.resx
+++ b/i18n/es/Tooltips.es.resx
@@ -536,8 +536,6 @@
Servidor predeterminado, nodo de renderizado, certificados de confianzaCarpeta de caché, miniaturas en memoria, límite de cachéBúsqueda de actualizaciones al iniciar
- Auto: núcleos menos cuatro para que la interfaz siga respondiendo
- Volver a Auto: núcleos menos cuatroActivado cuando portable.txt está junto a Titano.exe: todos los datos se quedan en su carpeta de datosUsa un codificador por hardware cuando alguno admite el preajuste; si no, por softwarePrimeros tres nombres de una importación de ejemplo con estas plantillas
diff --git a/i18n/et/Tooltips.et.resx b/i18n/et/Tooltips.et.resx
index c7859b3b..4a397d82 100644
--- a/i18n/et/Tooltips.et.resx
+++ b/i18n/et/Tooltips.et.resx
@@ -536,8 +536,6 @@
Vaikeserver, renderdussõlm, usaldatud sertifikaadidVahemälu kaust, pisipildid mälus, vahemälu piirangVärskenduste otsimine käivitamisel
- Auto: tuumade arv miinus neli, et liides jääks reageerivaks
- Tagasi režiimile Auto: tuumade arv miinus neliSees, kui portable.txt asub Titano.exe kõrval: kõik andmed jäävad selle andmekaustaKasutab riistvarakodeerijat, kui see toetab eelseadistust; muul juhul tarkvaraNende mallidega näidisimpordi kolm esimest nime
diff --git a/i18n/fi/Tooltips.fi.resx b/i18n/fi/Tooltips.fi.resx
index 930d8980..14cdea9d 100644
--- a/i18n/fi/Tooltips.fi.resx
+++ b/i18n/fi/Tooltips.fi.resx
@@ -536,8 +536,6 @@
Oletuspalvelin, renderöintisolmu, luotetut varmenteetVälimuistikansio, pikkukuvat muistissa, välimuistin rajaPäivitysten tarkistus käynnistettäessä
- Automaattinen: ytimet miinus neljä, jotta käyttöliittymä pysyy reagoivana
- Palauta automaattinen: ytimet miinus neljäKäytössä, kun portable.txt on Titano.exe-tiedoston vieressä: kaikki tiedot pysyvät sen datakansiossaKäytä laitteistokooderia, kun jokin tukee esiasetusta; muuten ohjelmistoaNäillä malleilla tehdyn esimerkkituonnin kolme ensimmäistä nimeä
diff --git a/i18n/fr/Tooltips.fr.resx b/i18n/fr/Tooltips.fr.resx
index 481b6e65..416d39e8 100644
--- a/i18n/fr/Tooltips.fr.resx
+++ b/i18n/fr/Tooltips.fr.resx
@@ -536,8 +536,6 @@
Serveur par défaut, nœud de rendu, certificats approuvésDossier du cache, miniatures en mémoire, limite du cacheRecherche de mises à jour au démarrage
- Auto : nombre de cœurs moins quatre, pour que l'interface reste réactive
- Revenir à Auto : nombre de cœurs moins quatreActivé quand portable.txt se trouve à côté de Titano.exe : toutes les données restent dans son dossier de donnéesUtiliser un encodeur matériel s'il prend en charge le préréglage, sinon l'encodeur logicielTrois premiers noms d'un exemple d'importation avec ces modèles
diff --git a/i18n/he/Tooltips.he.resx b/i18n/he/Tooltips.he.resx
index 961c17ec..1f59d5c7 100644
--- a/i18n/he/Tooltips.he.resx
+++ b/i18n/he/Tooltips.he.resx
@@ -551,8 +551,6 @@
שרת ברירת מחדל, צומת רינדור, תעודות מהימנותתיקיית מטמון, תמונות ממוזערות בזיכרון, מגבלת מטמוןבדיקת עדכונים בעת ההפעלה
- אוטומטי: מספר הליבות פחות ארבע, כדי שהממשק יישאר מגיב
- חזרה לאוטומטי: מספר הליבות פחות ארבעפעיל כאשר portable.txt נמצא לצד Titano.exe: כל הנתונים נשמרים בתיקיית הנתונים שלושימוש במקודד חומרה כאשר יש כזה שתומך בפריסט; אחרת, קידוד בתוכנהשלושת השמות הראשונים בייבוא לדוגמה עם התבניות האלה
diff --git a/i18n/hi/Tooltips.hi.resx b/i18n/hi/Tooltips.hi.resx
index 1f8fa9e2..09e7d7c0 100644
--- a/i18n/hi/Tooltips.hi.resx
+++ b/i18n/hi/Tooltips.hi.resx
@@ -536,8 +536,6 @@
डिफ़ॉल्ट सर्वर, रेंडर नोड, विश्वसनीय प्रमाणपत्रकैश फ़ोल्डर, मेमोरी में थंबनेल, कैश सीमाशुरू होने पर अपडेट की जाँच
- ऑटो: कोर की संख्या में से चार कम, ताकि इंटरफ़ेस प्रतिक्रियाशील रहे
- ऑटो पर लौटें: कोर की संख्या में से चार कमजब portable.txt, Titano.exe के बगल में हो तब चालू: सारा डेटा उसके डेटा फ़ोल्डर में रहता हैजब कोई हार्डवेयर एनकोडर प्रीसेट को सपोर्ट करे तो उसका उपयोग करें; अन्यथा सॉफ़्टवेयरइन टेम्पलेट के साथ नमूना आयात के पहले तीन नाम
diff --git a/i18n/hr/Tooltips.hr.resx b/i18n/hr/Tooltips.hr.resx
index d103788a..91e4ba6b 100644
--- a/i18n/hr/Tooltips.hr.resx
+++ b/i18n/hr/Tooltips.hr.resx
@@ -551,8 +551,6 @@
Zadani poslužitelj, čvor za renderiranje, pouzdani certifikatiMapa predmemorije, minijature u memoriji, ograničenje predmemorijeProvjera ažuriranja pri pokretanju
- Auto: broj jezgri umanjen za četiri kako bi sučelje ostalo responzivno
- Vraća na Auto: broj jezgri umanjen za četiriUključeno kada se portable.txt nalazi pokraj datoteke Titano.exe: svi podaci ostaju u njezinoj mapi dataUpotrebljava hardverski koder kada podržava preset; inače softverskiPrva tri naziva oglednog uvoza s ovim predlošcima
diff --git a/i18n/hu/Tooltips.hu.resx b/i18n/hu/Tooltips.hu.resx
index cf0759f3..f86e6521 100644
--- a/i18n/hu/Tooltips.hu.resx
+++ b/i18n/hu/Tooltips.hu.resx
@@ -536,8 +536,6 @@
Alapértelmezett szerver, renderelő csomópont, megbízható tanúsítványokGyorsítótár mappája, miniatűrök a memóriában, gyorsítótár korlátjaFrissítések keresése indításkor
- Auto: a magok száma mínusz négy, így a felület gyorsan reagál
- Vissza Auto értékre: a magok száma mínusz négyBekapcsolva, ha a portable.txt a Titano.exe mellett van: minden adat a saját data mappájában maradHardveres kódolót használ, ha valamelyik támogatja az előbeállítást; egyébként szoftverestEgy mintaimportálás első három neve ezekkel a sablonokkal
diff --git a/i18n/id/Tooltips.id.resx b/i18n/id/Tooltips.id.resx
index 939c91b5..6312dc7e 100644
--- a/i18n/id/Tooltips.id.resx
+++ b/i18n/id/Tooltips.id.resx
@@ -536,8 +536,6 @@
Server default, node render, sertifikat tepercayaFolder cache, gambar mini di memori, batas cachePemeriksaan pembaruan saat mulai
- Otomatis: jumlah inti dikurangi empat agar antarmuka tetap responsif
- Kembali ke Otomatis: jumlah inti dikurangi empatAktif bila portable.txt berada di samping Titano.exe: semua data tetap di folder data miliknyaGunakan encoder perangkat keras jika ada yang mendukung preset; jika tidak, gunakan perangkat lunakTiga nama pertama dari contoh impor dengan templat ini
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index c1126ee8..8c2c51d1 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -135,6 +135,7 @@
SimulazioneRicrea proxyRicollega archivio spostato…
+ Ripristina database…Esegui manutenzioneCestino…{0:N0} problema
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 8baccf97..f5bc4e1e 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -24,6 +24,8 @@
DisconnettiNon connesso a un serverTroppi accessi falliti; l'account è bloccato per un po'.
+ Un altro programma sta modificando le impostazioni dell'archivio; riprova tra poco.
+ Il file archive.json dell'archivio è danneggiato, di un Titano più recente o di un altro archivio; controlla la cartella dell'archivio.L'archivio non è raggiungibile o è di sola lettura; riprova quando torna disponibile.Le sue foto sono la cartella principale dell'archivio, che non va mai nel cestino.Nome utente o password errati.
diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx
index d3ffd928..8a7369cf 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -35,6 +35,7 @@
In attesa di riavvioRipristino prontoRipristinare l'indice del {0}?
+ Ora: illeggibileIndice ripristinato da una copiaDopo l'importazioneDopo una scansione
@@ -55,6 +56,9 @@
Riscansiona ogniAnteprimaDimensione proxy
+ Reimposta archivio
+ I modelli di nome, la dimensione dei proxy e quella delle miniature tornano ai valori predefiniti per ogni PC e server che lo usa. Le cartelle e i file già nell'archivio mantengono i loro nomi.
+ Reimpostare le impostazioni di {0}?Cartella archivioDimensione miniatureTorna ad Auto
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 932ee8f3..fa89d2e0 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -74,6 +74,7 @@
Metti in coda la ricostruzione · l'archivio resta utilizzabileScegli la nuova cartella di un archivio spostato; le sequenze lo seguonoApplica esattamente queste modifiche a cartelle, sidecar e indice · riprende dopo un arresto
+ Scegli una copia giornaliera dell'indice in Impostazioni › Avanzate; sostituisce l'indice al prossimo avvioCambia i tag di queste sequenze in sidecar e indiceEsegui di nuovo la stessa azioneScansione incrementale: file nuovi, modificati e rimossi per data e dimensione
@@ -530,6 +531,7 @@
Carica 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 Titano è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi
+ Lascia le impostazioni dell'archivio come sonoLascia la cache com'èLascia l'indice com'èLascia ogni impostazione com'è
@@ -551,8 +553,6 @@
Server predefinito, nodo di rendering, certificati attendibiliCartella della cache, miniature in memoria, limite della cacheControllo degli aggiornamenti all'avvio
- Auto: core meno quattro, così l'interfaccia resta reattiva
- Torna ad Auto: core meno quattroOgni quanto Titano riscansiona l'archivio per le modifiche fatte altrove, per esempio da un server che lo condivideAttiva quando portable.txt si trova accanto a Titano.exe: tutti i dati restano nella sua cartella dataUsa un encoder hardware quando supporta il preset; altrimenti il software
@@ -563,6 +563,7 @@
Elenca di nuovo gli encoder dopo l'installazione di un driver o di un codecCerca di nuovo le estensioni codec dopo averne installata una; le prossime attività le usanoRiporta ogni impostazione di questo PC al valore predefinito; chiede prima
+ Scrivi ora i modelli e le dimensioni predefiniti nel file archive.json dell'archivioReimposta ora ogni impostazioneRiporta ogni controllo di questa sezione al valore predefinitoConfronta la copia scelta con l'indice, poi la ripristina al prossimo avvio; chiede prima
@@ -584,6 +585,8 @@
Nessun decodificatore su questo PC ne legge i pixel; questi fotogrammi restano fuori dai renderingInvia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinitaAttività e fotogrammi elaborati insieme; meno lasciano più spazio agli altri programmi · Invio applica, Esc annulla
+ Auto: metà dei core logici esegue attività insieme, ognuna con il proprio numero di thread
+ Torna ad Auto: metà dei core logiciInstalla in Programmi per tutti gli account · chiede l'autorizzazione di amministratoreTorna alle opzioni senza modificare nullaScegli la cartella di installazione
diff --git a/i18n/ja/Tooltips.ja.resx b/i18n/ja/Tooltips.ja.resx
index 7cc372f8..9c05b606 100644
--- a/i18n/ja/Tooltips.ja.resx
+++ b/i18n/ja/Tooltips.ja.resx
@@ -536,8 +536,6 @@
既定のサーバー、レンダリングノード、信頼済みの証明書キャッシュフォルダー、メモリ内のサムネイル、キャッシュの上限起動時のアップデート確認
- 自動: インターフェイスの応答性を保つため、コア数から 4 を引いた値
- 自動に戻す: コア数から 4 を引いた値Titano.exe と同じ場所に portable.txt があるとオンになります。すべてのデータはそのデータフォルダーに保存されます。プリセットに対応するハードウェアエンコーダーがあればそれを使用し、なければソフトウェアを使用します。これらのテンプレートでインポートした場合の、最初の 3 つの名前の例
diff --git a/i18n/ko/Tooltips.ko.resx b/i18n/ko/Tooltips.ko.resx
index 7c250700..c88c44c0 100644
--- a/i18n/ko/Tooltips.ko.resx
+++ b/i18n/ko/Tooltips.ko.resx
@@ -536,8 +536,6 @@
기본 서버, 렌더링 노드, 신뢰하는 인증서캐시 폴더, 메모리 내 썸네일, 캐시 한도시작할 때 업데이트 확인
- 자동: 인터페이스가 원활하도록 코어 수에서 4를 뺀 값
- 자동으로 되돌리기: 코어 수에서 4를 뺀 값Titano.exe 옆에 portable.txt가 있으면 켜집니다. 모든 데이터가 해당 데이터 폴더에 보관됩니다.프리셋을 지원하는 하드웨어 인코더가 있으면 사용하고, 없으면 소프트웨어를 사용합니다.이 템플릿으로 가져올 때의 처음 세 이름 예시
diff --git a/i18n/lt/Tooltips.lt.resx b/i18n/lt/Tooltips.lt.resx
index 7b0482f7..c7d79a02 100644
--- a/i18n/lt/Tooltips.lt.resx
+++ b/i18n/lt/Tooltips.lt.resx
@@ -551,8 +551,6 @@
Numatytasis serveris, atvaizdavimo mazgas, patikimi sertifikataiTalpyklos aplankas, miniatiūros atmintyje, talpyklos ribaNaujinimų tikrinimas paleidžiant
- Auto: branduolių skaičius minus keturi, kad sąsaja greitai reaguotų
- Grįžti į Auto: branduolių skaičius minus keturiĮjungta, kai šalia Titano.exe yra portable.txt: visi duomenys lieka programos duomenų aplankeNaudoti aparatinį koduotuvą, kai jis palaiko išankstinę nuostatą; kitu atveju – programinįPirmieji trys pavyzdinio importavimo pavadinimai pagal šiuos šablonus
diff --git a/i18n/lv/Tooltips.lv.resx b/i18n/lv/Tooltips.lv.resx
index 813a6a2d..438d99c8 100644
--- a/i18n/lv/Tooltips.lv.resx
+++ b/i18n/lv/Tooltips.lv.resx
@@ -551,8 +551,6 @@
Noklusējuma serveris, renderēšanas mezgls, uzticamie sertifikātiKešatmiņas mape, sīktēli atmiņā, kešatmiņas ierobežojumsAtjauninājumu pārbaude startējot
- Auto: kodoli mīnus četri, lai saskarne paliktu atsaucīga
- Atpakaļ uz Auto: kodoli mīnus četriIeslēgts, ja blakus Titano.exe atrodas portable.txt: visi dati paliek tā datu mapēIzmantot aparatūras kodētāju, ja kāds atbalsta priekšiestatījumu; citādi programmatūrasPirmie trīs nosaukumi parauga importēšanai ar šīm veidnēm
diff --git a/i18n/ms/Tooltips.ms.resx b/i18n/ms/Tooltips.ms.resx
index 339db12a..cb749353 100644
--- a/i18n/ms/Tooltips.ms.resx
+++ b/i18n/ms/Tooltips.ms.resx
@@ -536,8 +536,6 @@
Pelayan lalai, nod render, sijil dipercayaiFolder cache, lakaran kecil dalam memori, had cacheSemakan kemas kini semasa mula
- Auto: bilangan teras tolak empat supaya antara muka kekal responsif
- Kembali ke Auto: bilangan teras tolak empatHidup apabila portable.txt terletak di sebelah Titano.exe: semua data kekal dalam folder datanyaGunakan pengekod perkakasan apabila ada yang menyokong praset; jika tidak, gunakan perisianTiga nama pertama bagi contoh import dengan templat ini
diff --git a/i18n/nb/Tooltips.nb.resx b/i18n/nb/Tooltips.nb.resx
index d50e2d90..0ca5581a 100644
--- a/i18n/nb/Tooltips.nb.resx
+++ b/i18n/nb/Tooltips.nb.resx
@@ -536,8 +536,6 @@
Standardserver, renderingsnode, klarerte sertifikaterHurtigbuffermappe, miniatyrbilder i minnet, hurtigbuffergrenseSe etter oppdateringer ved oppstart
- Auto: antall kjerner minus fire, slik at grensesnittet reagerer raskt
- Tilbake til Auto: antall kjerner minus firePå når portable.txt ligger ved siden av Titano.exe: alle data blir liggende i programmets egen datamappeBruk en maskinvarekoder når en støtter forhåndsinnstillingen, ellers programvareDe tre første navnene fra en eksempelimport med disse malene
diff --git a/i18n/nl/Tooltips.nl.resx b/i18n/nl/Tooltips.nl.resx
index 367ddcb3..48cb65f4 100644
--- a/i18n/nl/Tooltips.nl.resx
+++ b/i18n/nl/Tooltips.nl.resx
@@ -536,8 +536,6 @@
Standaardserver, renderknooppunt, vertrouwde certificatenCachemap, miniaturen in geheugen, cachelimietControleren op updates bij starten
- Auto: aantal kernen min vier, zodat de interface responsief blijft
- Terug naar Auto: aantal kernen min vierAan wanneer portable.txt naast Titano.exe staat: alle gegevens blijven in de bijbehorende gegevensmapGebruik een hardware-encoder als die de voorinstelling ondersteunt; anders softwareEerste drie namen van een voorbeeldimport met deze sjablonen
diff --git a/i18n/pl/Tooltips.pl.resx b/i18n/pl/Tooltips.pl.resx
index 7ce08783..f2db21ee 100644
--- a/i18n/pl/Tooltips.pl.resx
+++ b/i18n/pl/Tooltips.pl.resx
@@ -566,8 +566,6 @@
Serwer domyślny, węzeł renderowania, zaufane certyfikatyFolder pamięci podręcznej, miniatury w pamięci, limit pamięci podręcznejSprawdzanie aktualizacji przy uruchomieniu
- Auto: liczba rdzeni minus cztery, aby interfejs pozostał responsywny
- Przywróć Auto: liczba rdzeni minus czteryWłączony, gdy obok Titano.exe znajduje się plik portable.txt: wszystkie dane pozostają w jego folderze danychUżywaj enkodera sprzętowego, jeśli obsługuje on preset; w przeciwnym razie programowegoPierwsze trzy nazwy przykładowego importu z tymi szablonami
diff --git a/i18n/pt-BR/Tooltips.pt-BR.resx b/i18n/pt-BR/Tooltips.pt-BR.resx
index 246101a2..ab90ad41 100644
--- a/i18n/pt-BR/Tooltips.pt-BR.resx
+++ b/i18n/pt-BR/Tooltips.pt-BR.resx
@@ -536,8 +536,6 @@
Servidor padrão, nó de renderização, certificados confiáveisPasta do cache, miniaturas na memória, limite do cacheVerificação de atualizações ao iniciar
- Auto: núcleos menos quatro, para a interface continuar responsiva
- Volta para Auto: núcleos menos quatroAtivado quando portable.txt está ao lado de Titano.exe: todos os dados ficam na pasta data deleUsa um codificador de hardware quando algum suporta a predefinição; caso contrário, softwareOs três primeiros nomes de uma importação de exemplo com estes modelos
diff --git a/i18n/pt-PT/Tooltips.pt-PT.resx b/i18n/pt-PT/Tooltips.pt-PT.resx
index fbb8b59d..483b5380 100644
--- a/i18n/pt-PT/Tooltips.pt-PT.resx
+++ b/i18n/pt-PT/Tooltips.pt-PT.resx
@@ -536,8 +536,6 @@
Servidor predefinido, nó de renderização, certificados fidedignosPasta da cache, miniaturas em memória, limite da cacheVerificação de atualizações ao iniciar
- Auto: número de núcleos menos quatro, para que a interface continue a responder
- Voltar a Auto: número de núcleos menos quatroAtivado quando o portable.txt está junto ao Titano.exe: todos os dados ficam na respetiva pasta de dadosUtilizar um codificador de hardware quando algum suporta a predefinição; caso contrário, softwareOs três primeiros nomes de uma importação de exemplo com estes modelos
diff --git a/i18n/ro/Tooltips.ro.resx b/i18n/ro/Tooltips.ro.resx
index aab545ee..ae17f31f 100644
--- a/i18n/ro/Tooltips.ro.resx
+++ b/i18n/ro/Tooltips.ro.resx
@@ -551,8 +551,6 @@
Server implicit, nod de randare, certificate de încredereFolderul cache, miniaturi în memorie, limita cacheVerificarea actualizărilor la pornire
- Auto: numărul de nuclee minus patru, pentru ca interfața să rămână receptivă
- Revenire la Auto: numărul de nuclee minus patruActivat când portable.txt se află lângă Titano.exe: toate datele rămân în folderul său de dateFolosiți un codificator hardware când acesta acceptă presetarea; altfel, softwarePrimele trei nume ale unui import de probă cu aceste șabloane
diff --git a/i18n/ru/Tooltips.ru.resx b/i18n/ru/Tooltips.ru.resx
index 13957f60..ed6358e1 100644
--- a/i18n/ru/Tooltips.ru.resx
+++ b/i18n/ru/Tooltips.ru.resx
@@ -566,8 +566,6 @@
Сервер по умолчанию, узел рендеринга, доверенные сертификатыПапка кэша, эскизы в памяти, лимит кэшаПроверка обновлений при запуске
- Авто: число ядер минус четыре, чтобы интерфейс оставался отзывчивым
- Вернуть «Авто»: число ядер минус четыреВключён, если рядом с Titano.exe лежит portable.txt: все данные хранятся в его папке данныхИспользовать аппаратный кодировщик, если он поддерживает пресет; иначе программныйПервые три имени примерного импорта с этими шаблонами
diff --git a/i18n/sk/Tooltips.sk.resx b/i18n/sk/Tooltips.sk.resx
index 911557b5..f7219a62 100644
--- a/i18n/sk/Tooltips.sk.resx
+++ b/i18n/sk/Tooltips.sk.resx
@@ -551,8 +551,6 @@
Predvolený server, renderovací uzol, dôveryhodné certifikátyPriečinok vyrovnávacej pamäte, miniatúry v pamäti, limit vyrovnávacej pamäteKontrola aktualizácií pri spustení
- Auto: počet jadier mínus štyri, aby rozhranie pohotovo reagovalo
- Späť na Auto: počet jadier mínus štyriZapnutý, keď je vedľa Titano.exe súbor portable.txt: všetky údaje zostávajú v jeho priečinku údajovPoužije hardvérový kodér, ak niektorý podporuje predvoľbu; inak softvérovýPrvé tri názvy vzorového importu s týmito šablónami
diff --git a/i18n/sl/Tooltips.sl.resx b/i18n/sl/Tooltips.sl.resx
index 7bc2c18f..87fd46fb 100644
--- a/i18n/sl/Tooltips.sl.resx
+++ b/i18n/sl/Tooltips.sl.resx
@@ -551,8 +551,6 @@
Privzeti strežnik, vozlišče za upodabljanje, zaupanja vredna potrdilaMapa predpomnilnika, miniature v pomnilniku, omejitev predpomnilnikaPreverjanje posodobitev ob zagonu
- Samodejno: jedra minus štiri, da se vmesnik še naprej odziva
- Nazaj na samodejno: jedra minus štiriVklopljeno, ko je portable.txt poleg Titano.exe: vsi podatki ostanejo v njegovi mapi s podatkiUporabi strojni kodirnik, kadar podpira prednastavitev, sicer programskegaPrva tri imena vzorčnega uvoza s temi predlogami
diff --git a/i18n/sv/Tooltips.sv.resx b/i18n/sv/Tooltips.sv.resx
index 11a55726..9f11a173 100644
--- a/i18n/sv/Tooltips.sv.resx
+++ b/i18n/sv/Tooltips.sv.resx
@@ -536,8 +536,6 @@
Standardserver, renderingsnod, betrodda certifikatCachemapp, miniatyrer i minnet, cachegränsSök efter uppdateringar vid start
- Auto: antal kärnor minus fyra så att gränssnittet förblir responsivt
- Tillbaka till Auto: antal kärnor minus fyraPå när portable.txt ligger bredvid Titano.exe: alla data stannar i dess datamappAnvänd en maskinvarukodare när någon stöder förinställningen; annars programvaraDe tre första namnen i en exempelimport med de här mallarna
diff --git a/i18n/th/Tooltips.th.resx b/i18n/th/Tooltips.th.resx
index 0f4ca9e7..32ce6383 100644
--- a/i18n/th/Tooltips.th.resx
+++ b/i18n/th/Tooltips.th.resx
@@ -536,8 +536,6 @@
เซิร์ฟเวอร์เริ่มต้น โหนดเรนเดอร์ ใบรับรองที่เชื่อถือโฟลเดอร์แคช ภาพขนาดย่อในหน่วยความจำ ขีดจำกัดแคชตรวจหาการอัปเดตเมื่อเริ่มต้น
- อัตโนมัติ: จำนวนคอร์ลบสี่ เพื่อให้อินเทอร์เฟซตอบสนองได้ดี
- กลับเป็นอัตโนมัติ: จำนวนคอร์ลบสี่เปิดเมื่อมี portable.txt อยู่ข้าง Titano.exe: ข้อมูลทั้งหมดจะอยู่ในโฟลเดอร์ข้อมูลของโปรแกรมใช้ตัวเข้ารหัสฮาร์ดแวร์เมื่อมีตัวที่รองรับพรีเซ็ต มิฉะนั้นใช้ซอฟต์แวร์สามชื่อแรกของการนำเข้าตัวอย่างด้วยเทมเพลตเหล่านี้
diff --git a/i18n/tr/Tooltips.tr.resx b/i18n/tr/Tooltips.tr.resx
index 1cdc2ae6..b6b0bba3 100644
--- a/i18n/tr/Tooltips.tr.resx
+++ b/i18n/tr/Tooltips.tr.resx
@@ -536,8 +536,6 @@
Varsayılan sunucu, işleme düğümü, güvenilen sertifikalarÖnbellek klasörü, bellekteki küçük resimler, önbellek sınırıBaşlangıçta güncelleme denetimi
- Otomatik: arayüz duyarlı kalsın diye çekirdek sayısı eksi dört
- Otomatiğe dön: çekirdek sayısı eksi dörtTitano.exe dosyasının yanında portable.txt varsa açıktır: tüm veriler onun veri klasöründe kalırHazır ayarı destekleyen bir donanım kodlayıcısı varsa onu, yoksa yazılımı kullanırBu şablonlarla örnek bir içe aktarmanın ilk üç adı
diff --git a/i18n/uk/Tooltips.uk.resx b/i18n/uk/Tooltips.uk.resx
index 63e5d89d..30c72305 100644
--- a/i18n/uk/Tooltips.uk.resx
+++ b/i18n/uk/Tooltips.uk.resx
@@ -566,8 +566,6 @@
Сервер за замовчуванням, вузол рендерингу, довірені сертифікатиПапка кешу, мініатюри в пам’яті, ліміт кешуПеревірка оновлень під час запуску
- Авто: кількість ядер мінус чотири, щоб інтерфейс залишався чутливим
- Повернути «Авто»: кількість ядер мінус чотириУвімкнено, коли portable.txt лежить поруч із Titano.exe: усі дані зберігаються в його папці данихВикористовувати апаратний кодувальник, якщо він підтримує пресет; інакше — програмнийПерші три імені зразкового імпорту з цими шаблонами
diff --git a/i18n/vi/Tooltips.vi.resx b/i18n/vi/Tooltips.vi.resx
index 69d7b16e..f50e9d49 100644
--- a/i18n/vi/Tooltips.vi.resx
+++ b/i18n/vi/Tooltips.vi.resx
@@ -536,8 +536,6 @@
Máy chủ mặc định, nút kết xuất, chứng chỉ tin cậyThư mục bộ nhớ đệm, hình thu nhỏ trong bộ nhớ, giới hạn bộ nhớ đệmKiểm tra cập nhật khi khởi động
- Tự động: số lõi trừ bốn để giao diện luôn phản hồi nhanh
- Về Tự động: số lõi trừ bốnBật khi có portable.txt nằm cạnh Titano.exe: mọi dữ liệu nằm trong thư mục dữ liệu của nóDùng bộ mã hóa phần cứng khi có bộ hỗ trợ cài đặt sẵn; nếu không thì dùng phần mềmBa tên đầu tiên của một lượt nhập mẫu với các mẫu này
diff --git a/i18n/zh-Hans/Tooltips.zh-Hans.resx b/i18n/zh-Hans/Tooltips.zh-Hans.resx
index 42702e75..57bd7cf3 100644
--- a/i18n/zh-Hans/Tooltips.zh-Hans.resx
+++ b/i18n/zh-Hans/Tooltips.zh-Hans.resx
@@ -536,8 +536,6 @@
默认服务器、渲染节点、受信任的证书缓存文件夹、内存中的缩略图、缓存上限启动时检查更新
- 自动:核心数减四,使界面保持响应
- 恢复自动:核心数减四当 portable.txt 与 Titano.exe 位于同一文件夹时开启:所有数据都保存在其数据文件夹中有硬件编码器支持该预设时使用硬件编码器,否则使用软件编码使用这些模板时示例导入的前三个名称
diff --git a/i18n/zh-Hant/Tooltips.zh-Hant.resx b/i18n/zh-Hant/Tooltips.zh-Hant.resx
index 15791c61..4d6aab39 100644
--- a/i18n/zh-Hant/Tooltips.zh-Hant.resx
+++ b/i18n/zh-Hant/Tooltips.zh-Hant.resx
@@ -536,8 +536,6 @@
預設伺服器、算圖節點、信任的憑證快取資料夾、記憶體中的縮圖、快取上限啟動時檢查更新
- 自動:核心數減四,讓介面保持回應
- 恢復自動:核心數減四當 portable.txt 與 Titano.exe 位於同一資料夾時開啟:所有資料都保留在其 data 資料夾中預設集支援時使用硬體編碼器;否則使用軟體以這些範本進行範例匯入時的前三個名稱
diff --git a/src/Titano.App/Archive/CurrentArchive.cs b/src/Titano.App/Archive/CurrentArchive.cs
index b4357c93..ddd5f54d 100644
--- a/src/Titano.App/Archive/CurrentArchive.cs
+++ b/src/Titano.App/Archive/CurrentArchive.cs
@@ -10,8 +10,14 @@ public static class CurrentArchive
{
if (archives.Count == 0) return null;
if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
- var wanted = Normalize(lastRoot);
- return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase)) ?? archives[0];
+ return At(archives, lastRoot) ?? archives[0];
+ }
+
+ /// The archive indexed at ; null when none is (Settings › Archive never edits another one).
+ public static Core.Model.Archive? At(IReadOnlyList archives, string root)
+ {
+ var wanted = Normalize(root);
+ return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase));
}
public static async Task FindAsync(TitanoDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
index 83891860..699422bf 100644
--- a/src/Titano.App/Infrastructure/AppServices.cs
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -188,7 +188,7 @@ public sealed class AppServices : IAsyncDisposable
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
}
- /// Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: cores minus four).
+ /// Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: half the logical cores).
public int Parallelism => ProcessingTuning.Parallelism(Settings, System.Environment.ProcessorCount);
/// Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).
@@ -206,10 +206,12 @@ public sealed class AppServices : IAsyncDisposable
///
/// Opens (or creates) the index at , migrates it (after a restore staged in Settings ›
- /// Advanced replaced it), starts the job engine and the daily backups.
+ /// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
+ /// and the daily backups.
///
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
{
+ await RestoreStagedAsync(databasePath, ct);
try
{
Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
@@ -221,7 +223,6 @@ public sealed class AppServices : IAsyncDisposable
Log.Error("app", "The index could not be opened", ex);
return;
}
- await RestoreStagedAsync(Database, ct);
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
Devices.Start();
@@ -286,15 +287,18 @@ public sealed class AppServices : IAsyncDisposable
}
}
- /// A restore staged in Settings › Advanced replaces the index before anything reads it ().
- private async Task RestoreStagedAsync(TitanoDatabase database, CancellationToken ct)
+ ///
+ /// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an
+ /// index that no longer opens ().
+ ///
+ private async Task RestoreStagedAsync(string databasePath, CancellationToken ct)
{
try
{
- if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(database, Environment.BackupDirectory, ct), ct))
+ if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(databasePath, Environment.BackupDirectory, ct), ct))
{
StagedRestore = StagedRestoreResult.Restored;
- Log.Info("app", $"Index restored (schema {database.SchemaVersion})");
+ Log.Info("app", $"Index at {databasePath} restored from the staged copy");
}
}
catch (InvalidDataException ex)
@@ -302,7 +306,7 @@ public sealed class AppServices : IAsyncDisposable
StagedRestore = StagedRestoreResult.Unreadable;
Log.Error("app", "The staged index copy failed its checks; it was set aside and the index kept", ex);
}
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or DllNotFoundException)
{
StagedRestore = StagedRestoreResult.Deferred;
Log.Error("app", "The staged index restore could not run; the index was kept and the restore stays staged", ex);
diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs
index 6dfc120b..d40907a6 100644
--- a/src/Titano.App/Infrastructure/AppSettings.cs
+++ b/src/Titano.App/Infrastructure/AppSettings.cs
@@ -125,7 +125,7 @@ public sealed class AppSettings
/// Frame memory budget in GB; null = Auto (a quarter of installed memory).
public int? MemoryBudgetGb { get; set; }
- /// Worker threads; null = Auto (cores minus four, at least one).
+ /// Jobs run at once, also capping their decode and analysis threads; null = Auto (half the logical cores, at least one, with the jobs' own thread counts).
public int? Parallelism { get; set; }
public bool BackgroundPriority { get; set; } = true;
diff --git a/src/Titano.App/Infrastructure/ArchiveSetup.cs b/src/Titano.App/Infrastructure/ArchiveSetup.cs
index 71380e74..feaa7e42 100644
--- a/src/Titano.App/Infrastructure/ArchiveSetup.cs
+++ b/src/Titano.App/Infrastructure/ArchiveSetup.cs
@@ -68,11 +68,12 @@ public static class ArchiveActions
}
///
- /// Why creating or opening an archive failed: the archive's own sentences for files, access and the index
- /// (), otherwise (a catalog sentence, or "Something went wrong").
+ /// Why creating, opening or changing an archive failed: the archive's own sentences for files (an unreadable
+ /// archive.json included), access and the index (), otherwise
+ /// (a catalog sentence, or "Something went wrong").
///
public static string Cause(Exception ex) =>
- ex is IOException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
+ ex is IOException or InvalidDataException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
}
/// Archive roots offered by default and their free space.
diff --git a/src/Titano.App/Sections/ArchiveView.xaml b/src/Titano.App/Sections/ArchiveView.xaml
index a0d1f5d5..4dd396da 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml
+++ b/src/Titano.App/Sections/ArchiveView.xaml
@@ -85,6 +85,7 @@
+
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
index c73a7674..9f4cf246 100644
--- a/src/Titano.App/Sections/ArchiveViewModel.cs
+++ b/src/Titano.App/Sections/ArchiveViewModel.cs
@@ -83,6 +83,11 @@ public sealed class ArchiveViewModel : SectionViewModel
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
BackupCommand = new AsyncRelayCommand(BackupAsync, () => Services.Database is not null);
+ RestoreCommand = new RelayCommand(() =>
+ {
+ Shell.Settings.Page = Titano.App.Settings.SettingsPage.Advanced;
+ Shell.Navigate(SectionKey.Settings);
+ });
MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, _archive!.Name, force: true), All()), IsOnline);
@@ -176,6 +181,10 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
+
+ /// "Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a daily copy is compared and restored (§6.2).
+ public ICommand RestoreCommand { get; }
+
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
diff --git a/src/Titano.App/Sections/SettingsView.xaml b/src/Titano.App/Sections/SettingsView.xaml
index b40ff0d6..4cdde826 100644
--- a/src/Titano.App/Sections/SettingsView.xaml
+++ b/src/Titano.App/Sections/SettingsView.xaml
@@ -283,11 +283,11 @@
-
-
Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
@@ -334,12 +335,13 @@ public sealed class SettingsViewModel : SectionViewModel
private set => Set(ref _previewNames, value);
}
- /// BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose.
+ ///
+ /// BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose. A size the
+ /// archive got elsewhere (the admin panel also offers 3840) is listed with its number, never shown as another size.
+ ///
public IReadOnlyList> ProxySizes =>
[
- new(1280, "1280"),
- new(1920, "1920"),
- new(2560, "2560"),
+ .. Sizes([1280, 1920, 2560], _s.ProxyLongEdge is ProxyPolicy.FullSize or ProxyPolicy.Disabled ? null : _s.ProxyLongEdge),
new(ProxyPolicy.FullSize, Loc.L("Settings.Archive.FullSize")),
new(ProxyPolicy.Disabled, Loc.L("Settings.Archive.NoProxies")),
];
@@ -347,7 +349,7 @@ public sealed class SettingsViewModel : SectionViewModel
/// The open archive's proxy size (archive.json), and the one of new archives.
public SettingsOption SelectedProxySize
{
- get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
+ get => ProxySizes.First(p => p.Value == _s.ProxyLongEdge);
set
{
if (value is null || value.Value == _s.ProxyLongEdge) return;
@@ -358,12 +360,13 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
- public IReadOnlyList> ThumbnailSizes => [.. new[] { 240, 320, 480, 640 }.Select(n => new SettingsOption(n, n.ToString(CultureInfo.InvariantCulture)))];
+ /// 240, 320 (default), 480 or 640; another size of the archive (160 to 1024 are valid) is listed with its number.
+ public IReadOnlyList> ThumbnailSizes => Sizes([240, 320, 480, 640], _s.ThumbnailLongEdge);
/// The open archive's thumbnail size (archive.json), and the one of new archives.
public SettingsOption SelectedThumbnailSize
{
- get => ThumbnailSizes.FirstOrDefault(p => p.Value == _s.ThumbnailLongEdge) ?? ThumbnailSizes[1];
+ get => ThumbnailSizes.First(p => p.Value == _s.ThumbnailLongEdge);
set
{
if (value is null || value.Value == _s.ThumbnailLongEdge) return;
@@ -549,7 +552,7 @@ public sealed class SettingsViewModel : SectionViewModel
public int LogicalCores => Environment.ProcessorCount;
- /// Auto: cores minus four so the UI stays responsive.
+ /// Auto: half the logical cores, the job engine's default (BRIEF §14.6).
public int ParallelismAuto => ProcessingTuning.ParallelismAuto(LogicalCores);
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
@@ -713,7 +716,8 @@ public sealed class SettingsViewModel : SectionViewModel
/// A restore waits for the next start of Titano.
public bool IsRestoreStaged => DatabaseBackups.HasStagedRestore(Shell.Services.Environment.DatabasePath);
- private bool CanRestore => !_isRestoring && _selectedBackup is not null && Shell.Services.Database is not null && !IsRestoreStaged;
+ /// Also while the index cannot be opened: that is the case a restore exists for (BRIEF §6.2).
+ private bool CanRestore => !_isRestoring && _selectedBackup is not null && !IsRestoreStaged;
public ICommand RestoreDatabaseCommand { get; }
public ICommand CancelRestoreCommand { get; }
@@ -840,14 +844,17 @@ public sealed class SettingsViewModel : SectionViewModel
///
/// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is
- /// offline) unless a field holds an edit; they also become the defaults of new archives.
+ /// offline) unless a field holds an edit; they also become the defaults of new archives. The open archive is the one
+ /// at the archive folder of this PC, never another one of the index: with none registered there, the rows edit only
+ /// this PC's defaults.
///
private async Task LoadArchiveAsync()
{
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return;
try
{
- var archive = await CurrentArchive.FindAsync(db, _s.LastArchivePath);
+ var registered = await db.Archives.ListAsync();
+ var archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : CurrentArchive.Pick(registered, null);
_archive = archive;
if (archive is null) return;
var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id));
@@ -860,6 +867,9 @@ public sealed class SettingsViewModel : SectionViewModel
_s.ProxyLongEdge = settings.Proxies.LongEdge;
_s.ThumbnailLongEdge = settings.Thumbnails.LongEdge;
if (changed) Save();
+ // The lists first: a size the archive got elsewhere joins them before it is selected.
+ OnPropertyChanged(nameof(ProxySizes));
+ OnPropertyChanged(nameof(ThumbnailSizes));
OnPropertyChanged(nameof(SelectedProxySize));
OnPropertyChanged(nameof(SelectedThumbnailSize));
UpdatePreview();
@@ -879,9 +889,12 @@ public sealed class SettingsViewModel : SectionViewModel
if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return;
try
{
- _archive = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
+ var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
+ // The archive folder may have changed meanwhile: the rows then belong to another archive.
+ if (_archive?.Id == updated.Id) _archive = updated;
}
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
+ or DatabaseException)
{
Log.Warning("settings", "The archive settings were not saved", ex);
Shell.Notify(Loc.L("Settings.Archive.NotSaved"), ArchiveActions.Cause(ex), isError: true);
@@ -889,7 +902,7 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
- /// All of Settings › Archive into the open archive (after a reset or an import of settings).
+ /// Every archive row into the open archive: Archive › Reset section, after the user confirmed it for that archive.
private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with
{
Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate },
@@ -897,6 +910,45 @@ public sealed class SettingsViewModel : SectionViewModel
Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge },
});
+ ///
+ /// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given
+ /// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives.
+ /// Later edits never reach the archive shown before.
+ ///
+ private async Task RetargetArchiveAsync()
+ {
+ _archive = null;
+ if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives)
+ {
+ try
+ {
+ var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null);
+ if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ Log.Warning("settings", $"The archive at {root} could not be opened", ex);
+ Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true);
+ }
+ }
+ await LoadArchiveAsync();
+ }
+
+ ///
+ /// Archive › Reset section with an archive open writes the defaults into that archive's archive.json, which the server
+ /// and the other PCs share: the user confirms it for that archive by name first.
+ ///
+ private bool ConfirmArchiveReset(Archive archive) => Shell.Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Settings.Archive.ResetTitle", archive.Name),
+ Message = Loc.L("Settings.Archive.ResetMessage"),
+ SafeText = Loc.L("Settings.Storage.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Settings.KeepArchiveSettings"),
+ ActionText = Loc.L("Settings.Archive.ResetAction"),
+ ActionToolTip = Loc.L("Tooltips.Settings.ResetArchiveConfirm"),
+ IsDestructive = true,
+ });
+
private void OnServerChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
LoadCertificates();
@@ -911,6 +963,13 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
}
+ /// The preset sizes in order, with among them when it is none of them.
+ private static IReadOnlyList> Sizes(int[] presets, int? current)
+ {
+ var values = current is { } size && !presets.Contains(size) ? presets.Append(size) : presets;
+ return [.. values.Order().Select(n => new SettingsOption(n, n.ToString(CultureInfo.InvariantCulture)))];
+ }
+
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
private static string? ValidateInt(string text, int min, int max) =>
@@ -1104,24 +1163,24 @@ public sealed class SettingsViewModel : SectionViewModel
}
///
- /// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now; after the user's
- /// destructive confirmation the copy is staged beside the index for the next start, where the index as it is then is
- /// backed up first (; the staged copy is out of reach of the pruning
- /// to three copies). Nothing replaces the index while Titano runs.
+ /// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now (shown as unreadable
+ /// when the index did not open, the case a restore exists for); after the user's destructive confirmation the copy is
+ /// staged beside the index for the next start, where the index as it is then is kept first and replaced before it is
+ /// opened (; the staged copy is out of reach of the pruning to three
+ /// copies). Nothing replaces the index while Titano runs.
///
private async Task RestoreDatabaseAsync()
{
- if (_selectedBackup is not { } option || Shell.Services.Database is not { } db) return;
+ if (_selectedBackup is not { } option) return;
var backup = option.Backup;
var environment = Shell.Services.Environment;
_isRestoring = true;
CommandManager.InvalidateRequerySuggested();
try
{
- DatabaseSummary current, restored;
+ DatabaseSummary restored;
try
{
- current = await DatabaseBackups.SummarizeAsync(db);
restored = await Task.Run(() => DatabaseBackups.SummarizeBackupAsync(backup.Path, environment.DataDirectory));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException or DatabaseException)
@@ -1130,13 +1189,28 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Errors.Backup.Unreadable"), isError: true);
return;
}
+ DatabaseSummary? current = null;
+ if (Shell.Services.Database is { } db)
+ {
+ try
+ {
+ current = await DatabaseBackups.SummarizeAsync(db);
+ }
+ catch (DatabaseException ex)
+ {
+ // A damaged index may open and still fail to count: it is shown as unreadable, and the restore remains possible.
+ Log.Warning("settings", "The current index could not be summarized", ex);
+ }
+ }
+ var currentLine = current is { } now
+ ? Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(now.Sequences), Formatting.Count(now.Photos))
+ : Loc.L("Settings.Advanced.RestoreUnreadable");
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.RestoreTitle", option.Label),
Message = Loc.L("Settings.Advanced.RestoreMessage"),
Detail = string.Join(Environment.NewLine,
- Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)),
- Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(current.Sequences), Formatting.Count(current.Photos))),
+ Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)), currentLine),
IsDetailMonospaced = false,
DetailToolTip = Formatting.LeftToRight(backup.Path),
SafeText = Loc.L("Settings.Storage.Keep"),
@@ -1193,6 +1267,9 @@ public sealed class SettingsViewModel : SectionViewModel
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
+ // The rows are the open archive's own: resetting them changes it for everyone sharing it, so only when confirmed.
+ var open = _archive;
+ if (open is not null && !ConfirmArchiveReset(open)) return;
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
@@ -1201,7 +1278,7 @@ public sealed class SettingsViewModel : SectionViewModel
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
- _ = PushArchiveSettingsAsync();
+ if (open is not null) _ = PushArchiveSettingsAsync();
break;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
@@ -1264,9 +1341,10 @@ public sealed class SettingsViewModel : SectionViewModel
}
///
- /// Advanced › Reset: every preference back to its default after a destructive confirmation. What identifies this PC's
- /// data and session stays: the archive folder, the server, its session and trusted certificates, the window and the
- /// first-run choice. The open archive takes the default templates and sizes.
+ /// Advanced › Reset: every preference of this PC back to its default after a destructive confirmation. What identifies
+ /// this PC's data and session stays: the archive folder, the server, its session and trusted certificates, the window
+ /// and the first-run choice. The open archive's own settings (archive.json, shared with the server and other PCs) are
+ /// not touched: the Archive rows show them again (with no archive open, they show the reset defaults of new archives).
///
private void ResetAll()
{
@@ -1294,7 +1372,7 @@ public sealed class SettingsViewModel : SectionViewModel
JobsClearedAt = _s.JobsClearedAt,
};
ApplyAll(defaults);
- _ = PushArchiveSettingsAsync();
+ _ = LoadArchiveAsync();
Log.Info("settings", "Every setting reset to its default");
Shell.Notify(Loc.L("Settings.Advanced.ResetDone"));
}
@@ -1363,8 +1441,9 @@ public sealed class SettingsViewModel : SectionViewModel
imported.Window = _s.Window;
imported.FirstRunCompleted = _s.FirstRunCompleted;
ApplyAll(imported);
- // The imported templates and sizes become the open archive's, as when typed in Settings › Archive.
- _ = PushArchiveSettingsAsync();
+ // Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
+ // archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
+ _ = RetargetArchiveAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
diff --git a/src/Titano.App/Settings/ProcessingTuning.cs b/src/Titano.App/Settings/ProcessingTuning.cs
index aa2560f3..b4b25a6b 100644
--- a/src/Titano.App/Settings/ProcessingTuning.cs
+++ b/src/Titano.App/Settings/ProcessingTuning.cs
@@ -31,38 +31,43 @@ public static class ProcessingTuning
/// Frames decoded ahead of the render position, per quality profile (Best keeps more in flight, within the budget).
public static int ReadAhead(QualityProfile quality) => quality == QualityProfile.Best ? 8 : 4;
- /// Auto parallelism: logical cores minus four, so the interface stays responsive (at least one).
- public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores - 4);
+ /// Auto parallelism: the job engine's default, half the logical cores (BRIEF §14.6), at least one.
+ public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores / 2);
- /// Workers and threads this PC's jobs use: the user's value, or Auto.
+ /// Workers of this PC's job engine: the user's value, or Auto.
public static int Parallelism(AppSettings settings, int logicalCores) => settings.Parallelism is { } n and > 0 ? n : ParallelismAuto(logicalCores);
- /// The frame memory budget in bytes: the user's GB, or Auto (a quarter of ).
+ /// The frame memory budget of this PC in bytes: the user's GB, or Auto (a quarter of ).
public static long MemoryBudget(AppSettings settings, long installedBytes) =>
settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : long.Max(1L << 30, installedBytes / 4);
- /// with the user's current Rendering and Analysis settings.
+ ///
+ /// with the user's current Rendering and Analysis settings. The memory budget is shared by the
+ /// jobs that can run at once: each job's frame window gets its share (budget ÷ workers). Auto keeps the engine's own
+ /// thread counts per job; a value the user set also caps the background decodes and the deep analysis's threads.
+ ///
public static ProcessingOptions Apply(ProcessingOptions basis, AppSettings settings, long installedBytes, int logicalCores, string spillDirectory)
{
- var parallelism = Parallelism(settings, logicalCores);
+ var workers = Parallelism(settings, logicalCores);
+ int? cap = settings.Parallelism is { } n and > 0 ? n : null;
+ var analysis = settings.DeepAnalysis(basis.DeepAnalysis);
return basis with
{
FrameWindow = basis.FrameWindow with
{
- MemoryBudget = MemoryBudget(settings, installedBytes),
+ MemoryBudget = long.Max(1, MemoryBudget(settings, installedBytes) / workers),
SpillDirectory = spillDirectory,
Ahead = ReadAhead(settings.Quality),
- MaxConcurrentLoads = int.Clamp(parallelism, 1, basis.FrameWindow.MaxConcurrentLoads),
+ MaxConcurrentLoads = cap is { } loads ? int.Clamp(loads, 1, basis.FrameWindow.MaxConcurrentLoads) : basis.FrameWindow.MaxConcurrentLoads,
},
Render = basis.Render with
{
AnalysisLongEdge = PreparationLongEdge(settings.Quality),
DefaultFlowQuality = FlowQuality(settings.Quality),
},
- DeepAnalysis = settings.DeepAnalysis(basis.DeepAnalysis) with
- {
- MaxDegreeOfParallelism = int.Clamp(parallelism, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism),
- },
+ DeepAnalysis = cap is { } threads
+ ? analysis with { MaxDegreeOfParallelism = int.Clamp(threads, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism) }
+ : analysis,
};
}
}
diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs
index d782fd3e..8aa03df3 100644
--- a/src/Titano.Data/Archiving/ArchiveService.cs
+++ b/src/Titano.Data/Archiving/ArchiveService.cs
@@ -79,8 +79,7 @@ public sealed class ArchiveService : IJobHandlerProvider
{
ArgumentNullException.ThrowIfNull(settings);
var paths = new ArchivePaths(root);
- var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
- settings = settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
+ settings = WithUsableName(settings, paths);
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Titano archive.");
Directory.CreateDirectory(paths.MetaDirectory);
@@ -166,6 +165,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// receives the settings read from the file under the archive's settings lease, so a server and
/// a client sharing the archive never undo each other's change; the file is replaced atomically. Folders and files
/// already in the archive keep their names: templates and policies apply to the next imports, proxies and thumbnails.
+ /// A blank or overlong name in the file (archives made at a drive root, or before names were checked) is made usable
+ /// as does, instead of failing every edit.
///
/// An edited setting is invalid ( names it).
/// The archive is offline or read-only.
@@ -182,7 +183,8 @@ public sealed class ArchiveService : IJobHandlerProvider
{
var current = ManifestStore.ReadArchive(paths.ManifestPath);
if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}.");
- var settings = edit(ArchiveSettings.Of(current));
+ // The name read is made usable before the edit sees it; a name the edit sets is checked as given.
+ var settings = edit(WithUsableName(ArchiveSettings.Of(current), paths));
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
manifest = current with
{
@@ -296,6 +298,16 @@ public sealed class ArchiveService : IJobHandlerProvider
await Imports.PlanEraseAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cardId, sourceRoot, progress,
cancellationToken).ConfigureAwait(false);
+ ///
+ /// with a name an archive can keep: a blank one becomes the folder's name (the root itself
+ /// for a drive root), one longer than is shortened.
+ ///
+ private static ArchiveSettings WithUsableName(ArchiveSettings settings, ArchivePaths paths)
+ {
+ var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
+ return settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
+ }
+
private async Task RegisterAsync(ArchivePaths paths, ArchiveManifest manifest, CancellationToken cancellationToken)
{
var archive = new Archive
diff --git a/src/Titano.Data/DatabaseBackups.cs b/src/Titano.Data/DatabaseBackups.cs
index 25dd8c88..353da56e 100644
--- a/src/Titano.Data/DatabaseBackups.cs
+++ b/src/Titano.Data/DatabaseBackups.cs
@@ -16,8 +16,8 @@ public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequen
/// Backups of the SQLite index (BRIEF §6.2): a VACUUM INTO copy made once a day while the host runs (at start
/// when the newest copy is a day old, then checked every hour), the three newest kept; and their restore from
/// Settings › Advanced. A restore never swaps the file under a running host: the chosen copy is staged next to the
-/// index and replaces it the next time the host opens it, before anything reads it and after a fresh copy of the index
-/// it replaces.
+/// index and replaces it at the next start, before the host opens the index (so it also recovers an index that no
+/// longer opens), once the index it replaces has been kept.
///
public static partial class DatabaseBackups
{
@@ -101,10 +101,11 @@ public static partial class DatabaseBackups
}
///
- /// The restore's dry run: what holds, read from a scratch copy in
- /// (opened and migrated there, so the backup itself is never written).
+ /// The restore's dry run and check: what holds, read from a scratch copy in
+ /// (so the backup itself is never written) that first passes
+ /// PRAGMA quick_check, then opens and migrates.
///
- /// The file is not a readable Titano index.
+ /// The file is not a sound Titano index this build can open.
public static async Task SummarizeBackupAsync(string backupPath, string scratchDirectory, CancellationToken cancellationToken = default)
{
var folder = Path.Combine(scratchDirectory, "restore-check-" + Guid.NewGuid().ToString("N")[..8]);
@@ -115,6 +116,8 @@ public static partial class DatabaseBackups
File.Copy(backupPath, copy);
try
{
+ // Before the migration writes to it: a damaged page in a table the counts never read must not pass.
+ await CheckIntegrityAsync(copy, cancellationToken).ConfigureAwait(false);
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(copy), cancellationToken).ConfigureAwait(false);
return await SummarizeAsync(db, cancellationToken).ConfigureAwait(false);
}
@@ -167,22 +170,25 @@ public static partial class DatabaseBackups
public static void CancelStagedRestore(string databasePath) => File.Delete(StagedPath(databasePath));
///
- /// Carries out a staged restore on the index the host has just opened, before anything else uses it: the staged copy
- /// is checked (it opens in a scratch copy and passes quick_check), the index as it is now is copied into
- /// , and only then is it replaced by the staged copy, migrated to this build's
- /// schema. False when none was staged.
+ /// Carries out a staged restore before the host opens the index at , so it also
+ /// recovers an index that no longer opens. The staged copy is checked first (:
+ /// quick_check, open, migration). The index as it is now is kept in : as a
+ /// fresh VACUUM INTO copy among the daily ones, or, when it cannot be read, copied there whole (with its WAL) as
+ /// <name>-replaced-<stamp>.db, outside the rotation, so it never pushes a good copy out. Only then is
+ /// the staged copy renamed over the index: the rename consumes it, so it is never applied twice. The host's open then
+ /// migrates it to this build's schema. False when none was staged.
///
/// The staged copy failed its checks; it is set aside as .failed and the index is unchanged.
- /// The index could not be backed up or replaced (also ,
- /// ): it is unchanged and the restore stays staged for the next start.
- public static async Task RestoreStagedAsync(TitanoDatabase db, string backupDirectory, CancellationToken cancellationToken = default)
+ /// The index could not be kept or replaced (also ):
+ /// the restore stays staged for the next start.
+ public static async Task RestoreStagedAsync(string databasePath, string backupDirectory, CancellationToken cancellationToken = default)
{
- if (db.Database is not SqliteDatabase { Path: { } path }) return false;
+ var path = Path.GetFullPath(databasePath);
var staged = StagedPath(path);
if (!File.Exists(staged)) return false;
try
{
- // A copy this build cannot open (damaged, or made by a newer Titano) must never replace a working index.
+ // A copy this build cannot open (damaged, or made by a newer Titano) must never replace the index.
await SummarizeBackupAsync(staged, Path.GetDirectoryName(path) ?? ".", cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException)
@@ -190,14 +196,52 @@ public static partial class DatabaseBackups
File.Move(staged, staged + ".failed", overwrite: true);
throw;
}
- // What the index holds up to this start stays recoverable: no restore without a fresh copy first.
- var before = await db.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
- await db.RestoreAsync(staged, cancellationToken).ConfigureAwait(false);
- File.Delete(staged);
- Log.Info("backup", $"Index restored from the staged copy; the index it replaced is {before}");
+ // What the index holds up to this start stays recoverable: no restore without keeping it first.
+ var kept = File.Exists(path) ? await KeepAsync(path, backupDirectory, cancellationToken).ConfigureAwait(false) : null;
+ // A WAL left behind belongs to the replaced file and would be replayed onto the restored one.
+ File.Delete(path + "-wal");
+ File.Delete(path + "-shm");
+ AtomicFile.Commit(staged, path);
+ Log.Info("backup", kept is null ? "Index restored from the staged copy" : $"Index restored from the staged copy; the index it replaced is {kept}");
return true;
}
+ ///
+ /// The index about to be replaced, kept in : a VACUUM INTO copy when it opens,
+ /// else the file itself with its WAL, set aside under a name the pruning of the daily copies never matches.
+ ///
+ private static async Task KeepAsync(string path, string backupDirectory, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await using var current = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), cancellationToken).ConfigureAwait(false);
+ return await current.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
+ {
+ Log.Warning("backup", $"The index at {path} cannot be read; it is set aside whole", ex);
+ }
+ Directory.CreateDirectory(backupDirectory);
+ var target = Path.Combine(backupDirectory, string.Create(CultureInfo.InvariantCulture,
+ $"{Path.GetFileNameWithoutExtension(path)}-replaced-{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}.db"));
+ // Copied, not moved: should the swap fail, the index stays where the next start looks for it.
+ File.Copy(path, target);
+ // SQLite finds a WAL by the database's name: copied alongside, the file set aside keeps its last transactions.
+ if (File.Exists(path + "-wal")) File.Copy(path + "-wal", target + "-wal");
+ return target;
+ }
+
+ /// PRAGMA quick_check of the SQLite file at , opened without migrating it.
+ /// The check reported damage.
+ /// The file is not a database SQLite can read.
+ private static async Task CheckIntegrityAsync(string path, CancellationToken cancellationToken)
+ {
+ await using var database = DatabaseFactory.Open(DatabaseOptions.Sqlite(path));
+ await using var session = await database.OpenAsync(cancellationToken).ConfigureAwait(false);
+ var result = await session.ScalarAsync("PRAGMA quick_check", [], cancellationToken).ConfigureAwait(false);
+ if (result != "ok") throw new InvalidDataException($"The copy failed its integrity check: {result}");
+ }
+
[GeneratedRegex(@"^(?.+)-(?\d{8}-\d{6}-\d{3})\.db$", RegexOptions.CultureInvariant)]
private static partial Regex Stamp();
}
diff --git a/src/Titano.Server/Api/ArchiveEndpoints.cs b/src/Titano.Server/Api/ArchiveEndpoints.cs
index c0b16b23..953df725 100644
--- a/src/Titano.Server/Api/ArchiveEndpoints.cs
+++ b/src/Titano.Server/Api/ArchiveEndpoints.cs
@@ -66,7 +66,8 @@ public static class ArchiveEndpoints
///
/// Writes the name, templates and proxy policy into the archive's archive.json through the archive engine (so a
/// restart and the proxy jobs see them), then into the index. 503 archive_offline while the archive cannot be
- /// written; 409 sequence_busy while another process holds its settings.
+ /// written; 409 archive_busy while another process holds its settings; 409 archive_manifest when its
+ /// archive.json is damaged, written by a newer Titano or of another archive (nothing is written).
///
private static async Task UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, AuditLog audit)
@@ -92,7 +93,11 @@ public static class ArchiveEndpoints
}
catch (LeaseUnavailableException)
{
- return ApiErrors.Conflict(context, "sequence_busy");
+ return ApiErrors.Conflict(context, "archive_busy");
+ }
+ catch (Exception ex) when (ex is InvalidDataException or NewerFormatException)
+ {
+ return ApiErrors.Conflict(context, "archive_manifest");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
diff --git a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs
index 9d2268d2..7d442036 100644
--- a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs
+++ b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs
@@ -50,4 +50,47 @@ public sealed class AppServicesTests
environment.DeleteCaptureData();
}
}
+
+ /// BRIEF §6.2: a restore staged in Settings › Advanced recovers an index that no longer opens.
+ [Test]
+ [WindowsOnly]
+ public void AStagedRestoreRecoversAnIndexThatNoLongerOpens()
+ {
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ await using (var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)))
+ {
+ await db.Archives.UpsertAsync(new Archive { Id = Guid.CreateVersion7(), Name = "Kept", RootPath = @"C:\Kept", Created = DateTimeOffset.UtcNow });
+ var backup = await db.BackupAsync(environment.BackupDirectory, DatabaseBackups.Keep);
+ await DatabaseBackups.StageRestoreAsync(backup, environment.DatabasePath);
+ }
+ // The index is damaged beyond opening ("file is not a database").
+ File.Delete(environment.DatabasePath + "-wal");
+ File.Delete(environment.DatabasePath + "-shm");
+ await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
+
+ var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
+ try
+ {
+ await services.OpenAsync(environment.DatabasePath);
+
+ Assert.Null(services.OpenError);
+ Assert.Equal(StagedRestoreResult.Restored, services.StagedRestore);
+ Assert.SequenceEqual(["Kept"], (await services.Database!.Archives.ListAsync()).Select(a => a.Name));
+ Assert.False(DatabaseBackups.HasStagedRestore(environment.DatabasePath));
+ }
+ finally
+ {
+ Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
+ }
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
}
diff --git a/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs b/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
index cf623a4d..63f27905 100644
--- a/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
+++ b/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
@@ -181,27 +181,35 @@ public sealed class SettingsLogicTests
var settings = new Titano.App.Infrastructure.AppSettings { Quality = Titano.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Titano.Data.Processing.ProcessingOptions();
+ // Three jobs at once share the 6 GB: 2 GB each; the user's 3 also caps the decodes and the analysis threads.
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
- Assert.Equal((6L << 30, @"C:\cache", 8, 2), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
+ Assert.Equal((2L << 30, @"C:\cache", 8, 2), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((1024, Titano.Core.Project.FlowQualitySetting.Best), (best.Render.AnalysisLongEdge, best.Render.DefaultFlowQuality));
Assert.Equal(int.Min(3, Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.MaxDegreeOfParallelism), best.DeepAnalysis.MaxDegreeOfParallelism);
+ settings.Parallelism = 1;
+ var single = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
+ Assert.Equal((6L << 30, 1, 1), (single.FrameWindow.MemoryBudget, single.FrameWindow.MaxConcurrentLoads, single.DeepAnalysis.MaxDegreeOfParallelism));
+ // Auto: a quarter of 32 GB shared by the engine's 8 workers on 16 cores; the jobs keep their own thread counts.
settings.Quality = Titano.App.Infrastructure.QualityProfile.Fast;
settings.MemoryBudgetGb = null;
settings.Parallelism = null;
var fast = ProcessingTuning.Apply(basis, settings, 32L << 30, 16, @"C:\cache");
- Assert.Equal((8L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
+ Assert.Equal((1L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
+ Assert.Equal((basis.FrameWindow.MaxConcurrentLoads, basis.DeepAnalysis.MaxDegreeOfParallelism), (fast.FrameWindow.MaxConcurrentLoads, fast.DeepAnalysis.MaxDegreeOfParallelism));
Assert.Equal((256, Titano.Core.Project.FlowQualitySetting.Draft), (fast.Render.AnalysisLongEdge, fast.Render.DefaultFlowQuality));
Assert.Equal(512, ProcessingTuning.PreparationLongEdge(Titano.App.Infrastructure.QualityProfile.Balanced));
}
[Test]
- public void ParallelismAutoLeavesFourCoresToTheInterface()
+ public void ParallelismAutoIsTheJobEnginesDefault()
{
- Assert.Equal(12, ProcessingTuning.ParallelismAuto(16));
- Assert.Equal(1, ProcessingTuning.ParallelismAuto(4));
- Assert.Equal(1, ProcessingTuning.ParallelismAuto(2));
- Assert.Equal(12, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
+ // BRIEF §14.6: workers default to half the cores; a 4-core laptop keeps two, so a long render never blocks a scan.
+ Assert.Equal(8, ProcessingTuning.ParallelismAuto(16));
+ Assert.Equal(2, ProcessingTuning.ParallelismAuto(4));
+ Assert.Equal(1, ProcessingTuning.ParallelismAuto(1));
+ Assert.Equal(new Titano.Data.Jobs.JobEngineOptions().Workers, ProcessingTuning.ParallelismAuto(Environment.ProcessorCount));
+ Assert.Equal(8, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
@@ -249,6 +257,18 @@ public sealed class SettingsLogicTests
Assert.Null((new Titano.App.Infrastructure.AppSettings().ArchiveDefaults() with { Name = "Archive" }).Problem());
}
+ [Test]
+ public void TheArchiveRowsEditOnlyTheArchiveAtTheArchiveFolder()
+ {
+ var main = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive", Created = DateTimeOffset.UtcNow };
+ var travel = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Travel", RootPath = "/media/travel", Created = DateTimeOffset.UtcNow };
+
+ Assert.Equal(travel.Id, Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/travel/")!.Id);
+ // A folder no archive of the index is at: no archive at all, never the first one (its archive.json is someone else's).
+ Assert.Null(Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/new"));
+ Assert.Equal(main.Id, Titano.App.Archiving.CurrentArchive.Pick([main, travel], "/media/new")!.Id);
+ }
+
[Test]
public void SettingsSurviveARoundTripWithTheNewSections()
{
diff --git a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
index 84575297..c9c8877d 100644
--- a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
+++ b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
@@ -117,6 +117,22 @@ public sealed class SettingsScreenSmokeTests
await WaitAsync(() => Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge == 480, "written into archive.json");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
+ // A proxy size the admin panel set (3840 is none of the presets) is shown as it is, not as 1920.
+ manifest = Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath);
+ Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, manifest with { ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 3840 } });
+ shell.Navigate(SectionKey.Library);
+ shell.Navigate(SectionKey.Settings);
+ await WaitAsync(() => settings.SelectedProxySize.Value == 3840, "the archive's own proxy size is shown");
+ Assert.Equal("3840", settings.SelectedProxySize.Label);
+ Assert.SequenceEqual([1280, 1920, 2560, 3840, Titano.Core.Archiving.ProxyPolicy.FullSize, Titano.Core.Archiving.ProxyPolicy.Disabled],
+ settings.ProxySizes.Select(s => s.Value));
+
+ // Reset section on Archive changes the archive everyone shares: it asks first, and a "no" leaves archive.json alone.
+ settings.ResetSectionCommand.Execute(null);
+ Assert.Equal((480, 3840), (Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge,
+ Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ProxyPolicy.LongEdge));
+ Assert.Equal(480, settings.SelectedThumbnailSize.Value);
+
// Import: the defaults of new cards.
settings.Page = SettingsPage.Import;
await app.ExpectAsync("settings-import");
diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs
index a94148fb..258b2bd7 100644
--- a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs
+++ b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs
@@ -62,6 +62,25 @@ public sealed class ArchiveSettingsTests(TestContext context)
Assert.Equal("{date}_{n:0000}", (string)written["layoutTemplates"]!["file"]!);
}
+ [Test]
+ public async Task AnArchiveWhoseFileHasNoUsableNameCanStillBeEdited()
+ {
+ await using var fx = await ArchiveFixture.CreateAsync(context);
+ var folder = Path.GetFileName(fx.Paths.Root);
+ // Archives made at a drive root before names were checked carry an empty name; others one over the limit.
+ foreach (var (stored, expected) in new[] { (string.Empty, folder), (new string('n', ArchiveSettings.MaxNameLength + 20), new string('n', ArchiveSettings.MaxNameLength)) })
+ {
+ var json = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!.AsObject();
+ json["name"] = stored;
+ await File.WriteAllTextAsync(fx.Paths.ManifestPath, json.ToJsonString(), fx.Ct);
+
+ var updated = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct);
+
+ Assert.Equal((expected, "{date}_{n:0000}"), (updated.Name, updated.FileTemplate));
+ Assert.Equal(expected, ManifestStore.ReadArchive(fx.Paths.ManifestPath).Name);
+ }
+ }
+
[Test]
public async Task InvalidSettingsAreRefusedAndNothingIsWritten()
{
diff --git a/tests/Titano.Data.Tests/Sqlite/DatabaseBackupsTests.cs b/tests/Titano.Data.Tests/Sqlite/DatabaseBackupsTests.cs
index 0986abfc..26509cad 100644
--- a/tests/Titano.Data.Tests/Sqlite/DatabaseBackupsTests.cs
+++ b/tests/Titano.Data.Tests/Sqlite/DatabaseBackupsTests.cs
@@ -6,7 +6,8 @@ namespace Titano.Data.Tests.Sqlite;
///
/// BRIEF §6.2: a VACUUM INTO copy of the SQLite index once a day, the newest three kept, and a restore from Settings ›
-/// Advanced that waits for the next start, checks the copy first and never replaces a working index with a broken one.
+/// Advanced that waits for the next start, runs before the index opens (so it recovers one that no longer opens), checks
+/// the copy first (quick_check included) and never replaces a working index with a broken one.
///
[Category("sqlite")]
public sealed class DatabaseBackupsTests(TestContext context)
@@ -106,50 +107,127 @@ public sealed class DatabaseBackupsTests(TestContext context)
Assert.True(DatabaseBackups.HasStagedRestore(path));
await db.DisposeAsync();
- // The next start: the index as it was is copied first, then it is the chosen copy and the staged file is gone.
+ // The next start, before the index opens: the index as it was is copied first, then it is the chosen copy and
+ // the staged file is gone (consumed by the swap, so it can never be applied twice).
+ Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
- Assert.True(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation));
Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(path));
var copies = DatabaseBackups.List(directory, path);
Assert.Count(2, copies);
var replaced = await DatabaseBackups.SummarizeBackupAsync(copies[0].Path, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(2, replaced.Archives);
- Assert.False(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation), "nothing staged any more");
+ Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation), "nothing staged any more");
+ }
+
+ [Test]
+ public async Task AStagedRestoreRecoversAnIndexThatNoLongerOpens()
+ {
+ var (db, path) = await OpenAsync();
+ var directory = context.CreateTempDirectory("backups");
+ await AddArchiveAsync(db, "kept");
+ await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
+ var newest = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
+ var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
+ await DatabaseBackups.StageRestoreAsync(newest, path, context.Cancellation);
+ await db.DisposeAsync();
+
+ // The index is damaged beyond opening ("file is not a database").
+ File.Delete(path + "-wal");
+ File.Delete(path + "-shm");
+ var garbage = new byte[16384];
+ new Random(7).NextBytes(garbage);
+ await File.WriteAllBytesAsync(path, garbage, context.Cancellation);
+ await Assert.ThrowsAsync(async () => await (await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation)).DisposeAsync());
+
+ Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
+
+ await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
+ Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
+ Assert.False(DatabaseBackups.HasStagedRestore(path));
+ // The damaged index is kept whole beside the daily copies, outside their rotation: none of them was pushed out.
+ Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
+ var aside = Assert.Contains(Directory.GetFiles(directory), f => Path.GetFileName(f).StartsWith("titano-replaced-", StringComparison.Ordinal));
+ Assert.SequenceEqual(garbage, await File.ReadAllBytesAsync(aside, context.Cancellation));
}
[Test]
public async Task ABrokenStagedCopyIsSetAsideAndTheIndexKept()
{
var (db, path) = await OpenAsync();
- await using var _ = db;
await AddArchiveAsync(db, "current");
+ await db.DisposeAsync();
await File.WriteAllTextAsync(DatabaseBackups.StagedPath(path), "this is not a database", context.Cancellation);
var backups = context.CreateTempDirectory("backups");
- await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(db, backups, context.Cancellation));
+ await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(path, backups, context.Cancellation));
Assert.False(DatabaseBackups.HasStagedRestore(path));
Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
- Assert.Empty(DatabaseBackups.List(backups, path));
- Assert.SequenceEqual(["current"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
+ Assert.Empty(Directory.GetFiles(backups));
+ await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
+ Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
await Assert.ThrowsAsync(() =>
DatabaseBackups.SummarizeBackupAsync(DatabaseBackups.StagedPath(path) + ".failed", context.CreateTempDirectory("scratch"), context.Cancellation));
}
+ [Test]
+ public async Task AStagedCopyThatFailsItsIntegrityCheckIsSetAsideBeforeAnyCopyIsMade()
+ {
+ var (db, path) = await OpenAsync();
+ var directory = context.CreateTempDirectory("backups");
+ await AddArchiveAsync(db, "current");
+ // A table the summary never reads, filled so its pages come last in a VACUUM INTO copy.
+ await using (var session = await db.Database.OpenAsync(context.Cancellation))
+ {
+ await session.ExecuteScriptAsync("""
+ CREATE TABLE filler (id INTEGER PRIMARY KEY, data BLOB);
+ WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200) INSERT INTO filler (data) SELECT randomblob(1000) FROM n;
+ """, context.Cancellation);
+ }
+ for (var i = 0; i < DatabaseBackups.Keep; i++) await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
+ var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
+ await db.DisposeAsync();
+
+ // One damaged page in the filler table of the copy: the header, the schema and every counted table are intact.
+ var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "copy.db");
+ File.Copy(daily[0], damaged);
+ var bytes = await File.ReadAllBytesAsync(damaged, context.Cancellation);
+ var pageSize = (bytes[16] << 8) | bytes[17];
+ if (pageSize == 1) pageSize = 65536;
+ bytes[bytes.Length - pageSize] = 0xFF;
+ await File.WriteAllBytesAsync(damaged, bytes, context.Cancellation);
+ // Opening, migrating and counting do not notice it: only quick_check does.
+ var probe = Path.Combine(context.CreateTempDirectory("probe"), "titano.db");
+ File.Copy(damaged, probe);
+ await using (var opened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(probe), context.Cancellation))
+ Assert.Equal(1, (await DatabaseBackups.SummarizeAsync(opened, context.Cancellation)).Archives);
+ await Assert.ThrowsAsync(() => DatabaseBackups.SummarizeBackupAsync(damaged, context.CreateTempDirectory("scratch"), context.Cancellation));
+
+ await DatabaseBackups.StageRestoreAsync(damaged, path, context.Cancellation);
+ await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
+
+ Assert.False(DatabaseBackups.HasStagedRestore(path), "set aside: the next start neither retries it nor makes another copy");
+ Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
+ Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
+ Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
+ await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
+ Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
+ }
+
[Test]
public async Task CancellingAStagedRestoreKeepsTheIndex()
{
var (db, path) = await OpenAsync();
- await using var _ = db;
var directory = context.CreateTempDirectory("backups");
var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
+ await db.DisposeAsync();
DatabaseBackups.CancelStagedRestore(path);
Assert.False(DatabaseBackups.HasStagedRestore(path));
- Assert.False(await DatabaseBackups.RestoreStagedAsync(db, directory, context.Cancellation));
+ Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
Assert.FileExists(backup);
}
@@ -157,17 +235,18 @@ public sealed class DatabaseBackupsTests(TestContext context)
public async Task ARestoreWaitsWhenTheIndexCannotBeBackedUpFirst()
{
var (db, path) = await OpenAsync();
- await using var _ = db;
var backup = await db.BackupAsync(context.CreateTempDirectory("backups"), DatabaseBackups.Keep, context.Cancellation);
await AddArchiveAsync(db, "since the backup");
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
+ await db.DisposeAsync();
// The backups folder cannot be created: a file is in its way.
var blocked = Path.Combine(context.CreateTempDirectory("blocked"), "backups");
await File.WriteAllTextAsync(blocked, "not a folder", context.Cancellation);
- await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(db, blocked, context.Cancellation));
+ await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(path, blocked, context.Cancellation));
- Assert.SequenceEqual(["since the backup"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.True(DatabaseBackups.HasStagedRestore(path), "the restore stays staged for the next start");
+ await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
+ Assert.SequenceEqual(["since the backup"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
}
}
diff --git a/tests/Titano.Server.Tests/Api/AdminTests.cs b/tests/Titano.Server.Tests/Api/AdminTests.cs
index 3a366277..ea8aebd3 100644
--- a/tests/Titano.Server.Tests/Api/AdminTests.cs
+++ b/tests/Titano.Server.Tests/Api/AdminTests.cs
@@ -163,5 +163,19 @@ public sealed class AdminTests(TestContext context)
File.Move(path + ".away", path);
}
Assert.Equal(-1, Titano.Core.Archiving.ManifestStore.ReadArchive(path).ProxyPolicy.LongEdge);
+
+ // A damaged archive.json is reported as such (not as an internal error) and left as it is.
+ var saved = await File.ReadAllBytesAsync(path, context.Cancellation);
+ await File.WriteAllTextAsync(path, "{ not json", context.Cancellation);
+ try
+ {
+ using var damaged = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
+ await damaged.ExpectErrorAsync(HttpStatusCode.Conflict, "archive_manifest");
+ Assert.Equal("{ not json", await File.ReadAllTextAsync(path, context.Cancellation));
+ }
+ finally
+ {
+ await File.WriteAllBytesAsync(path, saved, context.Cancellation);
+ }
}
}