From f2568b5d8838d7085c8dae8cea957d02104d6b27 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 13:21:56 +0100 Subject: [PATCH] =?UTF-8?q?E5:=20archivio=20delle=20copie=20automatiche,?= =?UTF-8?q?=20segnale=20e=20domande=2048=E2=80=9355?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La tappa E5 copia da sola i file nuovi nelle cartelle con «Automatica». Questo pacchetto (WP2) dà al motore che verrà ciò che gli serve dal database, senza migrazioni: - ExportSelection.Automatic: i file dovuti, non copiati («Tolto» e «Superato» mai), nuovi dal «Solo i nuovi», di elementi assestati (niente file da scaricare, riga del giornale scritta); i «Non riuscito» solo al giro di recupero, tutti e ogni giro (risposta 50 di Alberto), così un file che non riesce mai non fa un lavoro ogni due minuti. - HasAutomaticCandidatesAsync, CountAutomaticBacklogAsync (la domanda «Copia anche gli N», i file in più, una cartella nuova), i candidati di «Riconosci le copie già presenti» (un «Tolto» resta «Tolto», risposta 51) e i byte del primo file in attesa di un lavoro in pausa. - La pausa di una destinazione si scrive solo con metodi suoi, così un salvataggio dall'interfaccia non la annulla; l'evento resta uno per passaggio. - AutoExportSignal, un'istanza per le prove, Default per l'applicazione. Prove nuove su un database vero, confrontate con il piano di «Copia in…», e misure su 200.000 elementi entro 2 s senza indici nuovi. Documenti: in §16 le righe 48–55 con le risposte del 4 dicembre 2026 e in decisioni.md la riga con le risposte e le tre letture del progetto. Co-Authored-By: Claude Opus 5.5 --- docs/SPECIFICA.md | 8 + docs/decisioni.md | 1 + src/Febe.Core/Export/AutoExportSignal.cs | 52 ++ src/Febe.Core/Export/ExportModels.cs | 18 + src/Febe.Core/Export/ExportPause.cs | 45 +- src/Febe.Core/Export/ExportText.cs | 11 + src/Febe.Core/Storage/IExportStore.cs | 86 ++- src/Febe.Data/Stores/ExportFilterSql.cs | 135 +++- src/Febe.Data/Stores/ExportStore.cs | 224 +++++- tests/Febe.Tests/Data/ExportStoreTests.cs | 2 + tests/Febe.Tests/Data/LibraryScaleTests.cs | 51 +- .../Export/ExportStoreAutomaticTests.cs | 642 ++++++++++++++++++ 12 files changed, 1212 insertions(+), 63 deletions(-) create mode 100644 src/Febe.Core/Export/AutoExportSignal.cs create mode 100644 tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index b6567d8..771e14f 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -1210,6 +1210,14 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 45 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: quale fotogramma salva «Salva il fotogramma»: il più nitido fra quelli guardati o sempre quello a metà del video? | E4, prima di cominciare | Risposta: il più nitido fra quelli guardati dall'analisi, mai uno nero di una dissolvenza; PNG `…_fotogramma.png`; «Scarica» o «Nella cartella delle copie»; la finestra dice «Il fotogramma non ha l'audio» | | 46 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: «Salva il fotogramma» solo dal visualizzatore, o anche per più video fermi insieme, dalla selezione? | E4, prima di cominciare | Risposta: per ora solo dal visualizzatore, uno per volta | | 47 | **Risposta di Alberto del 29 novembre 2026: «Fermo» se la parte che si muove è piccola** (§4.10). Domanda di allora: una foto con un piccolo adesivo animato o una scritta che si muove è «In movimento», così «basta un fotogramma» è sempre vero (proposta), o «Fermo» quando la parte che si muove è piccola? | E4, prima di cominciare | Risposta: «Fermo» quando la parte che si muove copre al più una piccola frazione dell'immagine, misurata a blocchi (5 %, §4.10), e il pannello File lo dice («una piccola parte si muove»); il fotogramma salvato resta il più nitido | +| 48 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: una copia avviata a mano con «Copia in…» e rimasta «In pausa» (chiavetta staccata, condivisione caduta) resta di Alberto quando il giro di recupero trova di nuovo la cartella (proposta), o riparte da sola come le copie automatiche? | E5, prima di cominciare | Risposta: resta di Alberto: la Dashboard dice «la cartella risponde di nuovo, riprendi quando vuoi», e la copia riparte solo con «Riprendi» o «Riprova» | +| 49 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: precedenza fra le copie automatiche e i lavori di Alberto: la copia automatica cede sempre il passo (proposta), o è un lavoro come gli altri, che fa rifiutare importazione, ricostruzione, «Copia in…» e zip finché non la si interrompe? | E5, prima di cominciare | Risposta: cede sempre il passo a importazione, ricostruzione, «Copia in…», «Riprendi», «Riconosci le copie già presenti», zip di fotogrammi e «Cerca i video fermi», e riparte da sola dopo, da dove era; non parte durante una sessione del motore e, se era già partita, aspetta la fine della sessione senza bloccare nessun lavoro di Alberto | +| 50 | **Risposta di Alberto del 4 dicembre 2026: ogni giro di recupero riprova tutti i «Non riuscito»; non la proposta** (§4.10). Domanda di allora: «Non riuscito» nelle copie automatiche (un disco pieno non lo dà: mette la cartella in pausa): quelli che non possono cambiare (un file oltre 4 GB su FAT32, un percorso troppo lungo) non si riprovano mai da soli e gli altri una volta al giorno (proposta), ogni giro di recupero li riprova tutti, o il giro non ne riprova nessuno? | E5, prima di cominciare | Risposta: ogni giro di recupero (all'avvio e ogni ora) riprova tutti i «Non riuscito» delle copie automatiche, anche quelli che non possono cambiare: nessuna classe di errori che non si riprovano da soli, nessun ritmo giornaliero. Alberto accetta il lavoro ripetuto e i resoconti con gli stessi errori | +| 51 | **Risposta di Alberto del 4 dicembre 2026: come proposto, ma un «Tolto» resta «Tolto»; non la proposta** (§4.10). Domanda di allora: «Riconosci le copie già presenti»: che cosa guarda e che cosa fa? La proposta: ogni file dovuto della cartella non ancora «Copiato», compresi «Tolto», «Superato» e «Non riuscito» (con «Una copia sola» salta quelli già copiati per l'altro account); cerca nel percorso dello schema e in «nome (2)»… fino a «(50)», nella forma di adesso e come originale; adotta solo se coincidono la lunghezza e poi lo SHA-256; un «Tolto» il cui file è tornato identico torna «Copiato»; dei fotogrammi solo quelli già registrati; non scrive né toglie file. Le altre: un «Tolto» resta «Tolto», oppure solo la forma di adesso | E5, prima di cominciare | Risposta: come la proposta, ma un «Tolto» resta «Tolto» anche se il file è tornato identico: «Riconosci» non adotta mai un file la cui ultima copia in quella cartella è «Tolto», che si ricopia solo con «Copia di nuovo». «Superato» e «Non riuscito» si riconoscono (un «Superato» ha nella libreria un file nuovo, quindi la copia vecchia non coincide comunque) | +| 52 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: spegnere «Automatica» mentre copia ferma subito la copia automatica di quella cartella (proposta), o lascia finire ciò che era già in coda? | E5, prima di cominciare | Risposta: si ferma subito e i file che restavano non si copiano più da soli; quelli già copiati restano, le copie fatte a mano non si toccano; la finestra lo dice prima di salvare | +| 53 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: «Interrompi» su una copia automatica ferma le copie automatiche fino al giro di recupero dopo (proposta), finché Alberto non preme «Riprendi ora» anche dopo un riavvio, o solo quella copia? | E5, prima di cominciare | Risposta: fino al giro di recupero dopo, almeno un'ora; la Dashboard dice fino a che ora e ha «Riprendi ora»; se Febe si riavvia prima, ripartono all'avvio | +| 54 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: quanti lavori automatici e quanti eventi: un lavoro per cartella ogni volta che parte una copia, con l'evento solo se ha fatto qualcosa (proposta), al più un lavoro all'ora per cartella, o nessun evento in cronologia? | E5, prima di cominciare | Risposta: un lavoro per cartella due minuti dopo l'ultimo file salvato, e comunque al giro di recupero; in cronologia «Copia automatica in … finita» solo se ha copiato qualcosa o qualcosa non è riuscito: un lavoro che non ha fatto nulla non lascia traccia | +| 55 | **Risposta di Alberto del 4 dicembre 2026: sì, come proposto** (§4.10). Domanda di allora: quando si allarga ciò che va da solo in una cartella automatica (un tipo di contenuto in più, «Esporta questo account» riacceso, un account nuovo, la cartella propria di un account tolta mentre la generale è automatica) vale la scelta fatta all'accensione (proposta), o si chiede di nuovo «Solo i nuovi / Copia anche gli N»? | E5, prima di cominciare | Risposta: nessuna domanda nuova: vale la scelta fatta all'accensione; la finestra, la conferma o l'avviso dice quanti file in più partiranno da soli | --- diff --git a/docs/decisioni.md b/docs/decisioni.md index f5d7f49..09e49d3 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -678,3 +678,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-12-01 | Tappa E4, **errori di lettura**: il flusso dell'analisi ricorda la prima `IOException` (non `EndOfStreamException`) o `UnauthorizedAccessException` e `Analyse` la rilancia: dal visualizzatore «file assente», dalla selezione «saltato», niente salvato. **Troppo lento**: una riga `TooSlow` non vale come già analizzata (`IsSettled`), ogni avvio la riprova una volta; il visualizzatore oltre i 30 s dice «avviala dalla selezione» solo se la selezione lo analizzerebbe, altrimenti «resta l'esito di prima» (`TooSlowKept`). **File**: se quello in coda non è sul disco si usa un altro della libreria con lo stesso SHA-256. **In coda**: `added` nella risposta di `/start`. **Chiusura**: `FebeApp` aspetta al più 5 s il video al lavoro (l'esito non si salverebbe comunque); `FebeAppHooks.StillVideoAnalyser` per le prove | Un disco di rete staccato a metà lasciava «non si legge» per sempre; «avviala dalla selezione» mandava a una selezione che saltava il video; una lettura ferma teneva fermi motore e browser alla chiusura | | 2026-12-01 | Tappa E4, **eventi `libreria`**: in attesa uno per motivo (`PendingLibraryChanges`, riempito direttamente, non dal canale che scarta), e a ogni giro un evento per ognuno: Dashboard e Account saltano `fermi`, che non cambia nulla lì. **Visualizzatore**: un evento `fermi` conta se l'elemento ha un video (l'esito è del file, non dell'account); conta solo l'ultima rilettura; si chiude quando cambia la pagina sotto (`febe:pagina`). **Copie**: `ExportCopyRequest.Still` dal nome `_fotogramma` (anche « (2)»); un lavoro «Fermo» il cui file è cambiato prende l'istante dell'analisi nuova o salta con la nota `NotStill` (l'istante dell'elemento del lavoro non cambia: è la sua identità) | Un evento solo, l'ultimo, faceva perdere la fine di una copia durante «Cerca i video fermi»; un fotogramma qualunque di un file nuovo non è quello che Alberto ha scelto | | 2026-12-01 | Tappa E4, **seconda revisione dell'analisi** (sempre algoritmo 1: non è ancora uscito) e di ciò che le sta intorno. (a) `Offsets` = 0,54, 0,865, 0,417, 0,253, 0,432, 0,45, 0,46, trovati con una ricerca: di un filmato ripetuto da 1,9 a 40 volte, anche non un numero intero, i sette istanti abbracciano almeno il 49 % del giro (la prova chiede il 48 %); con quelli di prima il 28 %, e a quasi sette ripetizioni cadevano tutti insieme. Fra fotogrammi veri (18.054 coppie di numero di fotogrammi e periodo) i sette stanno entro mezzo giro in 5 casi (prima 820) ed entro il 40 % in nessuno (prima 338); il tratto più lungo non guardato è di 1,32 parti, il primo e l'ultimo istante restano lontani dalle estremità. Limite dichiarato: un'immagine mostrata per meno di metà giro può sfuggire. (b) Guadagno di una dissolvenza: per blocco il canale più forte non bruciato (non la luma: un blu puro ne ha poca), da 8 in su (`GainFloor`, era 16), almeno 10 blocchi (`GainBlocks`); mediana dei rapporti pesata sulla luce, e concordano se almeno metà della luce sta entro ±5 % (`GainAgreement` 0,1 in tutto) o 1,5 livelli, se sono di più (`GainNoise`); poi il rapporto fra le somme dei blocchi concordi; campo da 1/16 a 16 (`GainRange`, era 8). Prima con i soli blocchi non bruciati, poi con tutti, poi nessun guadagno. (c) Un fotogramma scuro fra due che non lo sono si confronta con l'ultimo chiaro (movimento con la media oltre 3 o l'area oltre il 15 %) e poi con la mediana, e non si sceglie mai. (d) Stesso colore: il canale più forte non bruciato del fotogramma più chiaro, guadagno entro 1/16–16, sul fotogramma come un blocco solo. (e) Un elemento «Fermo» di un lavoro tiene sempre lo SHA-256 sul quale il suo istante è stato scelto: registrarvi quello del file nuovo prima di scriverlo faceva credere, alla ripresa, che il file non fosse cambiato. (f) Anche ogni dialogo si chiude quando cambia la pagina sotto (`febe:pagina`), come se fosse annullato. Misure: 26 immagini × 11 dissolvenze × 2 grane, tutte «Fermo» (prima circa 150 no); scritta, marchio e banda sul nero, foto scure al 10, 14 e 18 %, cartello blu, dissolvenze da 0,5 a 2 s, sempre «Fermo» con D ≤ 0,59 e A 0; sfumature e scritte intorno alla soglia del nero con grana fino a ±10, mai «In movimento»; due immagini in un giro ripetuto circa 7 volte, sempre «In movimento». Resta «In movimento» ciò che ricomprime ogni fotogramma a blocchi 8 × 8 con passo da 8 in su, come prima | Un'immagine ferma su nero, un cartello blu o una foto scura che si dissolvono, o scure quanto la soglia, risultavano «In movimento», e un filmato di due immagini ripetuto circa 7 volte «Fermo»; «Salva il fotogramma» ripreso dopo una pausa salvava l'istante vecchio; una finestra aperta dal visualizzatore o dalla selezione restava sopra la pagina nuova, con i bottoni di ciò che non si vede più | +| 2026-12-04 | Tappa E5, **risposte di Alberto del 4 dicembre 2026 alle domande 48–55 di §16**, date prima del codice. 48: una copia fatta a mano rimasta «In pausa» resta di Alberto anche quando il giro di recupero trova di nuovo la cartella: la Dashboard dice «la cartella risponde di nuovo, riprendi quando vuoi» e riparte solo con «Riprendi» o «Riprova». 49: la copia automatica cede sempre il passo a importazione, ricostruzione, «Copia in…», «Riprendi», «Riconosci le copie già presenti», zip di fotogrammi e «Cerca i video fermi», e riparte da sola dopo; mai durante una sessione del motore, e se era già partita aspetta senza bloccare nulla. 50 (**non la proposta**): ogni giro di recupero, all'avvio e ogni ora, riprova tutti i «Non riuscito» delle copie automatiche, anche quelli che non possono cambiare (oltre 4 GB su FAT32, percorso troppo lungo): niente classe di errori permanenti, niente ritmo giornaliero; fra un giro e l'altro, i passaggi che partono dopo un salvataggio in libreria non li riprovano. 51 (**non la proposta**): «Riconosci le copie già presenti» come proposto (file dovuti non «Copiato», percorso dello schema e «nome (2)»…«(50)», forma di adesso e originale, lunghezza e poi SHA-256, nessun file scritto o tolto, fotogrammi solo se già registrati), ma un «Tolto» resta «Tolto» anche se il file è tornato identico: non adotta mai un file, o un fotogramma, la cui ultima copia in quella cartella è «Tolto»; «Superato» e «Non riuscito» sì. 52: spegnere «Automatica» ferma subito la copia automatica di quella cartella; i file già copiati restano, le copie a mano non si toccano. 53: «Interrompi» su una copia automatica ferma le copie automatiche fino al giro di recupero dopo (almeno un'ora), con «Riprendi ora»; dopo un riavvio ripartono all'avvio. 54: un lavoro per cartella due minuti dopo l'ultimo file salvato, e comunque al giro; «Copia automatica in … finita» in cronologia solo se ha copiato qualcosa o qualcosa non è riuscito. 55: allargare ciò che spetta a una cartella automatica non chiede di nuovo: vale la scelta dell'accensione, e la finestra, la conferma o l'avviso dice quanti file in più partiranno. **Letture** che il progetto della tappa ha fatto di tre punti che sembravano in contrasto: (a) la riga del 27/11 sulle copie rimaste «In corso» («si riprendono dalla Dashboard, mai da sole») vale per le copie fatte a mano; i lavori automatici riprendono da soli (§4.10, «il giro orario riprova»); (b) «alla prima accensione» della risposta 6 del 18/11 vuol dire a ogni passaggio da spenta ad accesa, come dicono già la riga del 26/11 («la prossima accensione chiede di nuovo»), §4.10 e §8.3; (c) nella riga del 26/11 su «Solo i nuovi», `media.downloaded_at` non è «l'ora della riga di `_febe.jsonl`» ma l'ora in cui Febe ha salvato il file in libreria, scaricato o importato (`MediaStore`, `ImportCopier`), che la ricostruzione rimette dalla riga: «nuovo» vuol dire salvato in libreria dopo l'accensione, anche un file arrivato in ritardo (righe del 28/11) | Le domande 48–55 sono le scelte che la tappa E5 non poteva prendere da sola (§16); le tre letture tolgono contraddizioni solo apparenti fra specifica, decisioni e schema, senza cambiare nulla di deciso. 50: Alberto preferisce il lavoro ripetuto e i resoconti con gli stessi errori a una classe di errori da tenere aggiornata; fuori dal giro i «Non riuscito» aspettano perché ogni lavoro finito risveglia la copia automatica, e un file che non riesce mai farebbe un lavoro ogni due minuti invece che ogni ora. 51: un «Tolto» è una scelta di Alberto, che un file rimesso nella cartella non deve annullare | diff --git a/src/Febe.Core/Export/AutoExportSignal.cs b/src/Febe.Core/Export/AutoExportSignal.cs new file mode 100644 index 0000000..a226756 --- /dev/null +++ b/src/Febe.Core/Export/AutoExportSignal.cs @@ -0,0 +1,52 @@ +namespace Febe.Core.Export; + +/// +/// Wakes the automatic export (tappa E5, decision D4): a line of _febe.jsonl was written, a rebuild ended, a +/// destination was turned on, a job ended. The signal only makes the next pass sooner: what to copy always comes from +/// the database. An instance, not a static, so parallel tests give their worker one of their own and cannot wake each +/// other; production code uses . +/// +public sealed class AutoExportSignal +{ + private readonly Lock _gate = new(); + private TaskCompletionSource _next = NewSignal(); + private long _count; + + /// The signal of the application (the journal hook, the rebuild, the API). + public static AutoExportSignal Default { get; } = new(); + + /// How many times was called (monotonic, for tests). + public long Count => Interlocked.Read(ref _count); + + /// + /// Completes the task of with and arms a new one. Urgent (a destination + /// turned on, «Riprendi ora») means the worker skips its settle wait. + /// + public void Signal(bool urgent = false) + { + TaskCompletionSource fired; + lock (_gate) + { + fired = _next; + _next = NewSignal(); + _count++; + } + + fired.TrySetResult(urgent); + } + + /// + /// A task that completes at the next , with whether that signal was urgent. Take it before a pass, + /// so a signal that arrives during the pass is not lost; a second signal before the task is awaited arms a new task + /// (take again to see it, for example during the settle wait). + /// + public Task Next() + { + lock (_gate) + { + return _next.Task; + } + } + + private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); +} diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index b6ff08d..4c11ec5 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -21,6 +21,24 @@ public abstract record ExportSelection /// Every file of an account (the account card). public sealed record Account(long AccountId) : ExportSelection; + + /// + /// The automatic export (tappa E5, D4 and D5): per automatic destination, the files it is the effective destination + /// of, not copied («Tolto» and «Superato» never), new since its «Solo i nuovi» instant, and settled (no file of the + /// entry still to download, the entry not in ). + /// + /// The automatic destinations of the pass; one not in use (retired, unknown) gives nothing. + /// Entries whose line of _febe.jsonl is still to be written (libreria.giornale-da-scrivere). + /// + /// A recovery round (start-up and every hour): files whose last copy in the destination is «Non riuscito» are + /// candidates too, every round, whatever the error (answer 50 of 4 December 2026). Outside a round they wait for it, + /// so a file that keeps failing does not make a job at every signal. + /// + public sealed record Automatic(IReadOnlyList Destinations, IReadOnlyList HeldEntryIds, bool Round) : ExportSelection; + + /// One automatic destination and its «Solo i nuovi» instant (null: everything due, saved before or after). + /// Files saved in the library at or after it (media.downloaded_at); a file without that time is not new. + public sealed record AutomaticScope(long DestinationId, DateTimeOffset? Since); } /// How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»). diff --git a/src/Febe.Core/Export/ExportPause.cs b/src/Febe.Core/Export/ExportPause.cs index cf2fdf6..2d4de78 100644 --- a/src/Febe.Core/Export/ExportPause.cs +++ b/src/Febe.Core/Export/ExportPause.cs @@ -13,29 +13,20 @@ public static class ExportPause public const string PausedEventCode = "esportazione-in-pausa"; /// - /// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it - /// is). The event is written only on the transition from running to paused. Returns the stored row. + /// Pauses a destination with an Italian reason. Only the pause and its reason are written, in one statement (tappa + /// E5, D10), so a save of the destination from the interface and a copy or a round never undo each other's writes; a + /// retired row is left as it is. The event is written only on the transition from running to paused. Returns the + /// stored row. /// public static async Task PauseAsync(ExportEnvironment env, ExportDestination destination, string message) { ArgumentNullException.ThrowIfNull(env); ArgumentNullException.ThrowIfNull(destination); ArgumentException.ThrowIfNullOrWhiteSpace(message); - var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; - if (stored.IsRetired) - { - return stored; - } - - var wasPaused = stored.PausedAt is not null; - if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal)) - { - return stored; - } - - var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message }; - await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false); - if (!wasPaused) + var exports = env.Storage.Exports; + var paused = await exports.SetDestinationPausedAsync(destination.Id, env.Clock.Now, message, CancellationToken.None).ConfigureAwait(false); + var stored = await exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; + if (paused) { await env.Storage.Events.AppendAsync( new EventRecord @@ -43,28 +34,22 @@ public static class ExportPause At = env.Clock.Now, Code = PausedEventCode, Severity = EventSeverity.Warning, - Message = $"{ExportDestinations.Label(paused)} in pausa: {message}", - AccountId = paused.AccountId, + Message = $"{ExportDestinations.Label(stored)} in pausa: {message}", + AccountId = stored.AccountId, }, CancellationToken.None).ConfigureAwait(false); } - return paused; + return stored; } - /// Clears the pause of a destination after a check succeeded. Returns the stored row. + /// Clears the pause of a destination after a check succeeded (only the pause and its reason). Returns the stored row. public static async Task ClearAsync(ExportEnvironment env, ExportDestination destination) { ArgumentNullException.ThrowIfNull(env); ArgumentNullException.ThrowIfNull(destination); - var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; - if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null)) - { - return stored; - } - - var cleared = stored with { PausedAt = null, LastError = null }; - await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false); - return cleared; + var exports = env.Storage.Exports; + await exports.ClearDestinationPauseAsync(destination.Id, CancellationToken.None).ConfigureAwait(false); + return await exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; } } diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index 7d4e183..0d3c1f9 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -46,6 +46,14 @@ public static class ExportText public const string CopiedInAnotherFormat = "CopiedInAnotherFormat"; public const string LostTracks = Mp4Remuxer.LostTracks; public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata; + + // Tappa E5. A path too long for the destination: «Non riuscito» like any other, retried by every recovery round + // (answer 50 of 4 December 2026: no class of failures that never retry by themselves). + public const string PathTooLong = "PathTooLong"; + + // «Riconosci le copie già presenti» (tappa E5, D13): nothing at the paths looked at, or another file there. + public const string NotFound = "NotFound"; + public const string Different = "Different"; } /// Name of the state of a file of a job. @@ -148,6 +156,9 @@ public static class ExportText Notes.NotStill => "Il video è cambiato: il file di adesso non è un video fermo, o non è stato analizzato", Notes.TransparencyWhite => "La trasparenza è diventata bianco", Notes.CopiedInAnotherFormat => "Già copiato in un altro formato", + Notes.PathTooLong => "Percorso troppo lungo per la cartella", + Notes.NotFound => "Non c'è nella cartella", + Notes.Different => "Nel percorso c'è un altro file", ImageConversionLosses.LostTexts => "Non tenuti: testi", ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore", ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC", diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index eacc66a..749c0e9 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -21,7 +21,9 @@ public interface IExportStore Task AddDestinationAsync(ExportDestination destination, CancellationToken ct = default); /// - /// Writes label, content types, formats, naming schemes, «Automatica» and its answer, pause and error. + /// Writes label, content types, formats, naming schemes, «Automatica» and its answer. Never the pause and its error + /// (tappa E5, D10): those change only with and + /// , so a save from the interface cannot undo a pause written meanwhile. /// for a missing id; if scope, account or root /// differ from the stored row, the row is retired, or «Automatica» is turned on for an own folder whose account was /// removed (it is attached to an account first). @@ -39,6 +41,16 @@ public interface IExportStore /// The general folder first, then by id; retired rows only when asked. Task> ListDestinationsAsync(bool includeRetired = false, CancellationToken ct = default); + /// + /// Pauses a destination in use (tappa E5, D10): keeps the instant of a pause already there, writes the problem. + /// True only on the transition from not paused to paused (the caller writes the event then); false for a retired or + /// missing row and for one already paused. + /// + Task SetDestinationPausedAsync(long id, DateTimeOffset at, string problem, CancellationToken ct = default); + + /// Clears the pause and its problem of a destination in use; true when there was one to clear. + Task ClearDestinationPauseAsync(long id, CancellationToken ct = default); + /// /// Retires a destination (removed by Alberto, or replaced by another folder): sets the removal time and turns /// «Automatica» off. No row and no file is deleted. for a missing id. @@ -238,10 +250,46 @@ public interface IExportStore /// /// The library files of a «Copia in…», by media id, a page at a time (after ), present /// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter - /// the files of its entries (with «Tutte le foto», only the files it shows). + /// the files of its entries (with «Tutte le foto», only the files it shows). The automatic export + /// (, tappa E5) gives only due files to copy: see that record. /// Task> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default); + // Tappa E5: the automatic export and «Riconosci le copie già presenti» ------------------------------------------- + + /// + /// Whether would give any file for this automatic selection (one EXISTS): a pass + /// with nothing to copy takes no lease and never stops the conversion of the library. + /// + Task HasAutomaticCandidatesAsync(ExportSelection.Automatic selection, CancellationToken ct = default); + + /// + /// What an automatic destination would copy by itself (the question «Solo i nuovi / Copia anche gli N», the files + /// in more when it takes more, the files waiting for a paused folder): due files not copied, «Tolto» and «Superato» + /// left out, «Non riuscito» in, each file once as the plan counts it (per account, or once with «Una copia sola»), + /// with their bytes. The destination may be one not stored yet (see ). + /// for an own folder without account, or a history destination that is not the + /// one in use for that scope and account. + /// + Task CountAutomaticBacklogAsync(ExportBacklogQuery query, CancellationToken ct = default); + + /// + /// «Riconosci le copie già presenti» (tappa E5, D13 and answer 51), a page of at most library + /// files after , by media id. For each due file of the destination (its effective + /// destination in use): the file itself, when it is not «Copiato» (with «Una copia sola», copied for another account + /// counts) and its newest row there in any form but a frame is not «Tolto»; then its frames already recorded there + /// whose newest row is «Non riuscito» or «Superato», or an orphan's (account removed) that is not «Tolto» when the + /// account has no row of that frame. A «Tolto» stays «Tolto»: only «Copia di nuovo» copies it again. Empty for a + /// destination not in use. + /// + Task> ListRecognizeCandidatesAsync(long destinationId, long afterMediaId, int limit, CancellationToken ct = default); + + /// + /// The bytes of the library file of the first item still «In attesa» of the oldest paused job of a destination (D11: + /// a pause for space is cleared only when it fits); null without such an item or without its size. + /// + Task GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default); + /// Jobs for the Dashboard: newest first, at most . Task> ListRecentRunsAsync(int limit, CancellationToken ct = default); @@ -280,6 +328,40 @@ public sealed record ExportCandidate( bool InHighlight, TimeSpan? Duration = null); +/// +/// A file «Riconosci le copie già presenti» looks for (tappa E5, D13): the file in the form the destination asks now +/// ( null), or one of its frames already recorded in the destination. +/// +/// The library file. +/// The newest row of that frame in the destination (format and instant), or null for the file itself. +public sealed record ExportRecognizeCandidate(ExportCandidate File, ExportCopy? Frame = null); + +/// +/// What counts: one destination as it is, or as it would be. +/// +/// The general folder, or the own folder of . +/// +/// For an own folder, its account (required). For the general folder, only that account's files (null: every account +/// the general folder is the effective destination of). +/// +/// The content types the destination takes (as it would be saved). +/// +/// The destination in use whose copies count (the folder is the same); null for a new destination or a new folder, +/// whose copies are none: then nothing is «Copiato», «Tolto» or «Superato» there. +/// +/// «Solo i nuovi»: only files saved in the library at or after it; null: every due file. +/// The own folder of this account is counted as gone (its files go to the general folder). +public sealed record ExportBacklogQuery( + ExportScope Scope, + long? AccountId, + ContentTypes Types, + long? HistoryDestinationId, + DateTimeOffset? Since, + long? IgnoreOwnFolderOfAccount = null); + +/// Files an automatic destination would copy by itself, and their bytes. +public sealed record ExportBacklog(int Files, long Bytes); + /// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». public enum ExportMark { diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs index 20b1c5f..f7aead4 100644 --- a/src/Febe.Data/Stores/ExportFilterSql.cs +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -161,7 +161,7 @@ internal static class ExportFilterSql /// The term is evaluated on every file of the library (see ). public static string Replaced(ExportFilterContext x, bool bulk = false) => !x.HasHistory ? "0" - : $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {Failed(x)})"; + : $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {FailedTerm(x, bulk)})"; /// /// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). The same partition @@ -177,10 +177,131 @@ internal static class ExportFilterSql } return x.HasFailed - ? $"(NOT {CopiedTerm(x, bulk)} AND ({Failed(x)} OR NOT {History(x, bulk)}))" + ? $"(NOT {CopiedTerm(x, bulk)} AND ({FailedTerm(x, bulk)} OR NOT {History(x, bulk)}))" : $"(NOT {CopiedTerm(x, bulk)} AND NOT {History(x, bulk)})"; } + /// + /// The id a destination not stored yet takes in a context built by : no copy has it, so nothing + /// is copied, removed or superseded there. + /// + internal const long NewDestinationId = -1; + + /// + /// The automatic export of tappa E5 (decision D4) on m with its entry e: the effective destination of + /// the file is one of the selection's (and, with «Solo i nuovi», the file was saved at or after its instant: a file + /// without that time is not new), the file is due and not copied («Tolto» and «Superato» never: ), + /// its entry is settled (no file still to download, its line of _febe.jsonl written), and outside a round its + /// last copy did not fail (answer 50: every round retries every «Non riuscito»). Null when no destination of the + /// selection is in use. The cheap terms come first; the copy terms are the bulk ones, as the counts over the library. + /// + public static string? Automatic(ExportFilterContext x, ExportSelection.Automatic selection) + { + ArgumentNullException.ThrowIfNull(selection); + var inUse = x.InUse.ToHashSet(); + var scopes = selection.Destinations.Where(s => inUse.Contains(s.DestinationId)).ToList(); + if (scopes.Count == 0) + { + return null; + } + + var destination = DestinationOf(x); + var branches = scopes.Select(s => $"({destination} = {Literal(s.DestinationId)}{(s.Since is { } since ? $" AND {NewSince(since)}" : string.Empty)})").ToList(); + var terms = new List + { + branches.Count == 1 ? branches[0] : $"({string.Join(" OR ", branches)})", + DueFile(x), + Settled(selection.HeldEntryIds), + NotCopied(x, bulk: true), + }; + if (!selection.Round && x.HasFailed) + { + terms.Add($"NOT {FailedTerm(x, bulk: true)}"); + } + + return string.Join(" AND ", terms); + } + + /// + /// The context of : the stored one with the destination of the + /// query as it would be saved (its types; a new one, or a new folder, as ), and the + /// own folder of gone. Also gives the destination id to + /// count for. + /// + /// An own folder without account, or a history destination not in use there. + public static (ExportFilterContext Context, long DestinationId) Backlog(ExportFilterContext x, ExportBacklogQuery query) + { + ArgumentNullException.ThrowIfNull(query); + var own = x.Own.Where(o => o.AccountId != query.IgnoreOwnFolderOfAccount).ToList(); + var id = query.HistoryDestinationId ?? NewDestinationId; + if (query.Scope == ExportScope.General) + { + if (query.HistoryDestinationId is { } general && general != x.GeneralId) + { + throw new ArgumentException($"La destinazione {general} non è la cartella generale in uso.", nameof(query)); + } + + return (x with { GeneralId = id, GeneralTypes = query.Types, Own = own }, id); + } + + if (query.AccountId is not { } account) + { + throw new ArgumentException("La cartella di un account si conta con il suo account.", nameof(query)); + } + + if (query.HistoryDestinationId is { } history && !own.Any(o => o.AccountId == account && o.DestinationId == history)) + { + throw new ArgumentException($"La destinazione {history} non è la cartella in uso dell'account {account}.", nameof(query)); + } + + own.RemoveAll(o => o.AccountId == account); + own.Add((account, id, query.Types)); + return (x with { Own = own }, id); + } + + /// Saved in the library at or after (media.downloaded_at); a file without that time is not new. + public static string NewSince(DateTimeOffset since) => + $"(m.downloaded_at IS NOT NULL AND m.downloaded_at >= {Literal(since.ToUnixTimeMilliseconds())})"; + + /// + /// The entry of m is settled (D4): none of its files is still to download (an expired one does not hold it: + /// its line is never written), and it is not among (its line of _febe.jsonl waits). + /// The list of the entries with a file to download is read once, from ix_media_state. + /// + public static string Settled(IReadOnlyCollection held) + { + ArgumentNullException.ThrowIfNull(held); + var term = "m.entry_id NOT IN (SELECT td.entry_id FROM media td WHERE td.state = 'ToDownload')"; + return held.Count == 0 ? term : $"{term} AND m.entry_id NOT IN ({string.Join(", ", held.Distinct().Select(Literal))})"; + } + + /// + /// «Riconosci le copie già presenti» (D13, answer 51) for the file itself on m with e, in destination + /// : not copied (: with «Una copia sola» a copy for another account + /// counts), and its newest row there in any form but a frame is not «Tolto». «Superato» and «Non riuscito» are + /// recognised; a «Tolto» stays «Tolto». + /// + public static string RecognizeFile(ExportFilterContext x, long destinationId) => + $"(NOT {Copied(x)} AND ifnull((SELECT c.state FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {Literal(destinationId)} " + + "AND c.account_id = e.account_id AND c.variant <> 'Frame' ORDER BY c.id DESC LIMIT 1), '') <> 'Removed')"; + + /// + /// «Riconosci» for a frame row c of the file m with e in destination : + /// the newest row of that frame (format and instant) of the account, when «Non riuscito» or «Superato»; or, when the + /// account has no row of that frame, the newest orphan row (account removed) when it is not «Tolto». Frames never + /// recorded are not looked for: their instants are unknown. + /// + public static string RecognizeFrame(long destinationId) + { + var d = Literal(destinationId); + const string SameFrame = "c2.source_sha256 = c.source_sha256 AND c2.destination_id = c.destination_id AND c2.variant = 'Frame' " + + "AND c2.format = c.format AND ifnull(c2.frame_at_ms, -1) = ifnull(c.frame_at_ms, -1)"; + return $"(c.source_sha256 = m.sha256 AND c.destination_id = {d} AND c.variant = 'Frame' AND (" + + $"(c.account_id = e.account_id AND c.state IN ('Failed', 'Superseded') AND c.id = (SELECT max(c2.id) FROM export_copy c2 WHERE {SameFrame} AND c2.account_id = c.account_id)) " + + $"OR (c.account_id IS NULL AND c.state <> 'Removed' AND c.id = (SELECT max(c2.id) FROM export_copy c2 WHERE {SameFrame} AND c2.account_id IS NULL) " + + $"AND NOT EXISTS (SELECT 1 FROM export_copy c2 WHERE {SameFrame} AND c2.account_id = e.account_id))))"; + } + /// The term of «Tutte le foto» on m (with e its entry): a due file of the chosen class. /// The context of the query. /// The class. @@ -286,6 +407,16 @@ internal static class ExportFilterSql ? $"(m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied') AND {Copied(x)})" : Copied(x); + /// + /// «Non riuscito» (); in bulk behind the list of the SHA-256 that failed in a destination in use, + /// so a file that never failed anywhere needs no lookup of its own. + /// + private static string FailedTerm(ExportFilterContext x, bool bulk) => !x.HasFailed + ? "0" + : bulk + ? $"(m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Failed') AND {Failed(x)})" + : Failed(x); + /// /// The removed or superseded part of : a copy of this very file in the effective destination /// was removed or superseded (whether or not it names the file that replaced it: the file can be back in the library diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index 3492326..4ff2aab 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -75,25 +75,28 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore RemovedAt = r.GetTimeOrNull(17), }; - private static ExportCopy ReadCopy(SqliteDataReader r) => new() + private static ExportCopy ReadCopy(SqliteDataReader r) => ReadCopy(r, 0); + + /// A copy row whose columns () start at . + private static ExportCopy ReadCopy(SqliteDataReader r, int at) => new() { - Id = r.GetInt64(0), - DestinationId = r.GetInt64(1), - AccountId = r.GetInt64OrNull(2), - MediaId = r.GetInt64OrNull(3), - SourceSha256 = r.GetString(4), - Variant = r.GetEnum(5), - Format = r.GetEnum(6), - FrameAt = r.GetDurationOrNull(7), - State = r.GetEnum(8), - SupersededBySha256 = r.GetTextOrNull(9), - Origin = r.GetEnum(10), - RelativePath = r.GetTextOrNull(11), - Bytes = r.GetInt64OrNull(12), - CopySha256 = r.GetTextOrNull(13), - CopiedAt = r.GetTime(14), - StateChangedAt = r.GetTimeOrNull(15), - LastError = r.GetTextOrNull(16), + Id = r.GetInt64(at), + DestinationId = r.GetInt64(at + 1), + AccountId = r.GetInt64OrNull(at + 2), + MediaId = r.GetInt64OrNull(at + 3), + SourceSha256 = r.GetString(at + 4), + Variant = r.GetEnum(at + 5), + Format = r.GetEnum(at + 6), + FrameAt = r.GetDurationOrNull(at + 7), + State = r.GetEnum(at + 8), + SupersededBySha256 = r.GetTextOrNull(at + 9), + Origin = r.GetEnum(at + 10), + RelativePath = r.GetTextOrNull(at + 11), + Bytes = r.GetInt64OrNull(at + 12), + CopySha256 = r.GetTextOrNull(at + 13), + CopiedAt = r.GetTime(at + 14), + StateChangedAt = r.GetTimeOrNull(at + 15), + LastError = r.GetTextOrNull(at + 16), }; private static ExportRun ReadRun(SqliteDataReader r) => new() @@ -153,9 +156,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore .With("@highlight_naming_scheme", Sql.Text(d.HighlightNamingScheme)) .With("@profile_naming_scheme", Sql.Text(d.ProfileNamingScheme)) .With("@automatic", Sql.Bool(d.Automatic)) - .With("@automatic_since", Sql.Time(d.AutomaticSince)) - .With("@paused_at", Sql.Time(d.PausedAt)) - .With("@last_error", Sql.Text(d.LastError)); + .With("@automatic_since", Sql.Time(d.AutomaticSince)); private static void BindCopyState(SqliteCommand c, ExportCopy copy) => c.With("@media_id", Sql.Int(copy.MediaId)) @@ -265,7 +266,9 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore @naming_scheme, @highlight_naming_scheme, @profile_naming_scheme, @automatic, @automatic_since, @paused_at, @last_error, @created_at) """); BindDestinationSettings(c, destination); - c.With("@scope", Sql.Enum(destination.Scope)) + c.With("@paused_at", Sql.Time(destination.PausedAt)) + .With("@last_error", Sql.Text(destination.LastError)) + .With("@scope", Sql.Enum(destination.Scope)) .With("@account_id", Sql.Int(destination.AccountId)) .With("@root_path", destination.RootPath) .With("@created_at", Sql.Time(destination.CreatedAt)); @@ -308,11 +311,12 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore nameof(destination)); } + // The pause is not written here (tappa E5, D10): a save from the interface read the row before a copy or a + // round paused or cleared it, and must not undo that. var c = w.Command(""" UPDATE export_destination SET label = @label, content_types = @content_types, photo_format = @photo_format, video_format = @video_format, naming_scheme = @naming_scheme, highlight_naming_scheme = @highlight_naming_scheme, - profile_naming_scheme = @profile_naming_scheme, automatic = @automatic, automatic_since = @automatic_since, - paused_at = @paused_at, last_error = @last_error + profile_naming_scheme = @profile_naming_scheme, automatic = @automatic, automatic_since = @automatic_since WHERE id = @id """); BindDestinationSettings(c, destination); @@ -346,6 +350,35 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore ReadDestination), ct); + public Task SetDestinationPausedAsync(long id, DateTimeOffset at, string problem, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(problem); + return db.WriteAsync( + w => + { + // One transaction: the pause already there (if any) keeps its instant, and only the transition says so. + var wasPaused = w.Command("SELECT paused_at IS NOT NULL FROM export_destination WHERE id = @id AND removed_at IS NULL") + .With("@id", id).ExecuteScalar() is long paused ? paused != 0 : (bool?)null; + if (wasPaused is null) + { + return false; + } + + w.Command("UPDATE export_destination SET paused_at = coalesce(paused_at, @at), last_error = @e WHERE id = @id AND removed_at IS NULL") + .With("@at", Sql.Time(at)).With("@e", problem).With("@id", id).ExecuteNonQuery(); + return wasPaused == false; + }, + ct); + } + + public Task ClearDestinationPauseAsync(long id, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command(""" + UPDATE export_destination SET paused_at = NULL, last_error = NULL + WHERE id = @id AND removed_at IS NULL AND (paused_at IS NOT NULL OR last_error IS NOT NULL) + """).With("@id", id).ExecuteNonQuery() > 0, + ct); + public Task RetireDestinationAsync(long id, DateTimeOffset at, CancellationToken ct = default) => db.WriteAsync( w => @@ -1191,12 +1224,155 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore // «Tutte le foto»: only the files the mosaic shows (EntryStore.FileTerms, on m with its entry e). return filter.Mode == MosaicMode.Files ? $"{where} AND {EntryStore.FileTerms(c, filter.LibraryFilter)}" : where; }), + // Tappa E5: the terms are literals (ExportFilterSql), read with the context of this very read. + ExportSelection.Automatic automatic => ExportFilterSql.Automatic(ExportFilterSql.Load(c), automatic) is { } terms + ? Page(_ => terms) + : [], _ => throw new ArgumentOutOfRangeException(nameof(selection)), }; }, ct); } + public Task HasAutomaticCandidatesAsync(ExportSelection.Automatic selection, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(selection); + // CROSS JOIN keeps the files outside (one pass over media, the entry by its key): with nothing to copy every file + // is read, and without statistics the planner otherwise walks the entries and seeks their files. + return db.ReadAsync( + c => ExportFilterSql.Automatic(ExportFilterSql.Load(c), selection) is { } terms + && c.Command($"SELECT EXISTS (SELECT 1 FROM media m CROSS JOIN entry e ON e.id = m.entry_id WHERE {terms})").ScalarInt64() != 0, + ct); + } + + public Task CountAutomaticBacklogAsync(ExportBacklogQuery query, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(query); + return db.ReadAsync( + c => + { + var (x, destination) = ExportFilterSql.Backlog(ExportFilterSql.Load(c), query); + var terms = new List { $"{ExportFilterSql.DestinationOf(x)} = {destination.ToString(CultureInfo.InvariantCulture)}" }; + if (query.AccountId is { } account) + { + terms.Add($"e.account_id = {account.ToString(CultureInfo.InvariantCulture)}"); + } + + if (query.Since is { } since) + { + terms.Add(ExportFilterSql.NewSince(since)); + } + + terms.Add(ExportFilterSql.DueFile(x)); + terms.Add(ExportFilterSql.NotCopied(x, bulk: true)); + var where = string.Join(" AND ", terms); + + // Each file once, as the plan counts it: per account, or once in all with «Una copia sola». A file counts + // when no file before it (by id) with the same SHA-256 (and account) counts too: a seek on ix_media_sha256 + // per file, with the terms only for the rare duplicates. A GROUP BY on the SHA-256 took twice as long over + // 200,000 entries, and with ANALYZE statistics 4 s. CROSS JOIN: one pass over media (see above), except + // for one account, whose entries the planner then reads first (ix_entry_account_*; 0.2 s instead of 1.4 s). + var sameKey = x.SamePost == SamePostCopies.OneOnly ? string.Empty : " AND e.account_id = k.account"; + var join = query.AccountId is null ? "CROSS JOIN" : "JOIN"; + using var r = c.Command($""" + SELECT COUNT(*), ifnull(SUM(k.bytes), 0) FROM ( + SELECT m.id AS id, m.sha256 AS sha, e.account_id AS account, ifnull(m.bytes, 0) AS bytes + FROM media m {join} entry e ON e.id = m.entry_id WHERE {where}) AS k + WHERE NOT EXISTS ( + SELECT 1 FROM media m CROSS JOIN entry e ON e.id = m.entry_id + WHERE m.sha256 = k.sha AND m.id < k.id{sameKey} AND {where}) + """).ExecuteReader(); + r.Read(); + return new ExportBacklog(r.GetInt32(0), r.GetInt64(1)); + }, + ct); + } + + /// The columns of a copy row on the alias c, in the order of . + private static readonly string CopyColumnsOfC = string.Join(", ", CopyColumns.Split(", ").Select(column => "c." + column)); + + public Task> ListRecognizeCandidatesAsync(long destinationId, long afterMediaId, int limit, CancellationToken ct = default) + { + var n = Math.Clamp(limit, 1, 10_000); + return db.ReadAsync>( + c => + { + var x = ExportFilterSql.Load(c); + if (!x.InUse.Contains(destinationId)) + { + return []; + } + + // The files first, a page of at most n by media id (each has something to look for), then their frames. + var d = destinationId.ToString(CultureInfo.InvariantCulture); + var file = ExportFilterSql.RecognizeFile(x, destinationId); + var frame = ExportFilterSql.RecognizeFrame(destinationId); + var where = $"{ExportFilterSql.DestinationOf(x)} = {d} AND {ExportFilterSql.DueFile(x)}"; + var files = new List<(ExportCandidate File, bool Itself)>(); + using (var command = c.Command($""" + SELECT {CandidateColumns}, {file} FROM media m JOIN entry e ON e.id = m.entry_id + WHERE {where} AND ({file} OR EXISTS (SELECT 1 FROM export_copy c WHERE {frame})) AND m.id > @after + ORDER BY m.id LIMIT @n + """).With("@after", afterMediaId).With("@n", (long)n)) + using (var r = command.ExecuteReader()) + { + while (r.Read()) + { + files.Add((ReadCandidate(r), r.GetBool(12))); + } + } + + var frames = new Dictionary>(); + foreach (var chunk in files.Select(f => f.File.MediaId).Chunk(IdChunk)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("x", chunk); + command.CommandText = $""" + SELECT m.id, {CopyColumnsOfC} FROM media m JOIN entry e ON e.id = m.entry_id JOIN export_copy c ON {frame} + WHERE m.id IN ({list}) + ORDER BY m.id, c.format, c.frame_at_ms, c.id + """; + using var r = command.ExecuteReader(); + while (r.Read()) + { + var mediaId = r.GetInt64(0); + if (!frames.TryGetValue(mediaId, out var rows)) + { + frames[mediaId] = rows = []; + } + + rows.Add(ReadCopy(r, 1)); + } + } + + var result = new List(); + foreach (var (candidate, itself) in files) + { + if (itself) + { + result.Add(new ExportRecognizeCandidate(candidate)); + } + + result.AddRange(frames.GetValueOrDefault(candidate.MediaId, []).Select(row => new ExportRecognizeCandidate(candidate, row))); + } + + return result; + }, + ct); + } + + /// The bytes of the first pending item of the oldest paused job of a destination (@d). + internal const string FirstPendingBytesSql = """ + SELECT m.bytes FROM export_run r JOIN export_item i ON i.run_id = r.id JOIN media m ON m.id = i.media_id + WHERE r.destination_id = @d AND r.state = 'Paused' AND i.state = 'Pending' + ORDER BY r.id, i.id LIMIT 1 + """; + + public Task GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default) => + db.ReadAsync( + c => c.Command(FirstPendingBytesSql).With("@d", destinationId).ExecuteScalar() is long bytes ? bytes : (long?)null, + ct); + public Task> ListRecentRunsAsync(int limit, CancellationToken ct = default) => db.ReadAsync>( c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun), diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs index 1eb0e20..46fe69d 100644 --- a/tests/Febe.Tests/Data/ExportStoreTests.cs +++ b/tests/Febe.Tests/Data/ExportStoreTests.cs @@ -56,6 +56,8 @@ public sealed class ExportStoreTests var paused = read with { Automatic = false, AutomaticSince = null, PausedAt = Make.T0.AddDays(4), LastError = "Disco non raggiungibile", Label = null, VideoFormat = null }; await db.Exports.UpdateDestinationAsync(paused); + Assert.IsNull((await db.Exports.GetDestinationAsync(luca.Id))!.PausedAt, "la pausa ha i suoi metodi (tappa E5, D10)"); + Assert.IsTrue(await db.Exports.SetDestinationPausedAsync(luca.Id, Make.T0.AddDays(4), "Disco non raggiungibile")); Assert.AreEqual(paused, await db.Exports.GetDestinationAsync(luca.Id)); await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(5)); diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index e3f8b0e..53b6084 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -33,6 +33,10 @@ public sealed class LibraryScaleTests // «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail. private const double FilteredAggregateBoundMs = 600; + // The automatic export (tappa E5, D1): each pass and each count reads every file with the bulk terms of «Copie», + // without an index on media.downloaded_at; 2 s each, or a migration with that index is a question for Alberto. + private const double AutomaticBoundMs = 2000; + // «Copie» over the whole library (tappa E2, WP5b): every due file is classified against the copies, 240,000 files // at about 4 µs each; measured 0.23-1.1 s (docs/decisioni.md), «Non ancora copiati» the slowest. The design asked for // the 600 ms of the filtered aggregates: not reachable without a column of state per file, which E2 does not add. @@ -84,7 +88,7 @@ public sealed class LibraryScaleTests var still = await FillStillVideosAsync(db, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); - TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); + TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Failed:N0} non riuscite, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); TestContext.WriteLine($"Video fermi: {still.Analyses:N0} analisi, {still.Still:N0} «Fermo» (di cui {still.Overruled:N0} superati da un algoritmo più nuovo), {still.Entries:N0} elementi e {still.Files:N0} file nel filtro"); Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill"); Assert.IsGreaterThan(0, copies.Frames, "frames in the fill"); @@ -144,7 +148,10 @@ public sealed class LibraryScaleTests var superseded = Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"); var frames = Insert(w, "Copied", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 50 = 7", frame) + Insert(w, "Removed", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 100 = 9", frame); - return new CopiesWorld(whole + convertedCopies, removed, superseded, DueFiles(), accountIds[OwnAccount], convertedCopies, frames); + // Tappa E5: 1 % of the files not copied failed («Non riuscito»): still «Non ancora copiati», retried by + // every round of the automatic export and left out of its passes in between. + var failed = Insert(w, "Failed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 5"); + return new CopiesWorld(whole + convertedCopies, removed, superseded, DueFiles(), accountIds[OwnAccount], convertedCopies, frames, failed, general.Id, own.Id); }, ct); } @@ -320,6 +327,7 @@ public sealed class LibraryScaleTests try { await MeasureCopiesAsync(Measure, db, accountIds, copies); + await MeasureAutomaticAsync(Measure, db, copies); } catch (AssertFailedException e) { @@ -384,8 +392,41 @@ public sealed class LibraryScaleTests } /// - /// What the export fill wrote: copies by state ( with the converted ones), the due files, the - /// account with its own folder, and of tappa E3 the converted copies and the frames (copied and «Tolto»). + /// The automatic export (tappa E5, D1 and D4): a page of candidates as a job plans them, the pre-check of a pass with + /// something and with nothing to copy (every file read), the count of the question «Copia anche gli N» for each + /// folder, and for a new folder. The counts of the two folders add up to the files not copied of the fill. /// - private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId, int Converted, int Frames); + private static async Task MeasureAutomaticAsync(Func>, Task> measure, FebeDatabase db, CopiesWorld copies) + { + var round = new ExportSelection.Automatic([new(copies.GeneralId, null)], [], Round: true); + var page = (IReadOnlyList)await measure("automatica: una pagina", AutomaticBoundMs, async () => await db.Exports.ListCandidatesAsync(round, 0, 2000)); + Assert.HasCount(2000, page); + Assert.IsFalse(page.Any(c => c.AccountId == copies.OwnAccountId), "i file di un account con la sua cartella non vanno nella generale"); + var pass = (IReadOnlyList)await measure("automatica: una pagina fuori dal giro", AutomaticBoundMs, async () => await db.Exports.ListCandidatesAsync(round with { Round = false }, 0, 2000)); + Assert.HasCount(2000, pass); + Assert.IsTrue((bool)await measure("automatica: c'è da copiare", AutomaticBoundMs, async () => await db.Exports.HasAutomaticCandidatesAsync(round))); + var nothingNew = round with { Destinations = [new(copies.GeneralId, new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero)), new(copies.OwnId, new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero))] }; + Assert.IsFalse((bool)await measure("automatica: niente di nuovo", AutomaticBoundMs, async () => await db.Exports.HasAutomaticCandidatesAsync(nothingNew))); + + var general = (ExportBacklog)await measure("automatica: arretrato della generale", AutomaticBoundMs, async () => + await db.Exports.CountAutomaticBacklogAsync(new ExportBacklogQuery(ExportScope.General, null, ContentTypes.All, copies.GeneralId, null))); + var own = (ExportBacklog)await measure("automatica: arretrato di una cartella propria", AutomaticBoundMs, async () => + await db.Exports.CountAutomaticBacklogAsync(new ExportBacklogQuery(ExportScope.Account, copies.OwnAccountId, ContentTypes.PostPhotos, copies.OwnId, null))); + var notCopied = copies.Due - copies.Copied - copies.Removed - copies.Superseded; + Assert.AreEqual(notCopied, general.Files + own.Files); + Assert.AreEqual(notCopied * 1000L, general.Bytes + own.Bytes); + Assert.IsGreaterThan(0, own.Files); + + var moved = (ExportBacklog)await measure("automatica: arretrato di una cartella nuova", AutomaticBoundMs, async () => + await db.Exports.CountAutomaticBacklogAsync(new ExportBacklogQuery(ExportScope.General, null, ContentTypes.All, null, null))); + var ownDue = Enumerable.Range(0, Entries).Where(n => n % Accounts == OwnAccount).Sum(n => (n % 7 != 0 ? 1 : 0) + (n % 5 == 0 ? 1 : 0)); + Assert.AreEqual(copies.Due - ownDue, moved.Files); + } + + /// + /// What the export fill wrote: copies by state ( with the converted ones), the due files, the + /// account with its own folder, of tappa E3 the converted copies and the frames (copied and «Tolto»), and of tappa E5 + /// the «Non riuscito» copies and the two destinations. + /// + private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId, int Converted, int Frames, int Failed, long GeneralId, long OwnId); } diff --git a/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs b/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs new file mode 100644 index 0000000..dc7bf34 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs @@ -0,0 +1,642 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Data; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The store side of the automatic export (tappa E5, WP2): the candidates of a pass and of a round, the backlog the +/// question «Solo i nuovi / Copia anche gli N» counts, the candidates of «Riconosci le copie già presenti», the pause +/// writes that do not overwrite each other, and the signal. Database only: no file is copied here, and the planner of +/// «Copia in…» is the reference of what is due and not copied. +/// +[TestClass] +public sealed class ExportStoreAutomaticTests +{ + public TestContext TestContext { get; set; } = null!; + + // The automatic candidates -------------------------------------------------------------------------------------- + + /// + /// On a mixed library (two folders, a type the own folder does not take, an account switched off, copied, «Tolto», + /// «Superato», «Non riuscito», the same file twice, a file still to download) the automatic candidates of a round are + /// exactly what «Copia in…» of the whole library would write, folder by folder; outside a round the «Non riuscito» + /// wait for it. + /// + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task AutomaticCandidatesAreDueNotCopiedAndOfTheirEffectiveDestination(bool oneOnly) + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var w = await MixedAsync(bed, oneOnly, ct); + + var planned = await PlannedWritesAsync(bed, new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped), ct); + var general = await KeysAsync(bed, new([new(w.General, null)], [], Round: true), ct); + var own = await KeysAsync(bed, new([new(w.Own, null)], [], Round: true), ct); + Assert.IsTrue(planned[w.General].SetEquals(general), $"cartella generale: {string.Join(", ", general)}"); + Assert.IsTrue(planned[w.Own].SetEquals(own), $"cartella di marta: {string.Join(", ", own)}"); + + var expected = new HashSet<(long, string)> { (w.Luca, Make.Sha(4)), (w.Luca, Make.Sha(8)), (w.Luca, Make.Sha(11)), (w.Luca, Make.Sha(12)) }; + if (!oneOnly) + { + expected.Add((w.Luca, Make.Sha(1))); + } + + Assert.IsTrue(expected.SetEquals(general), $"cartella generale: {string.Join(", ", general)}"); + Assert.IsTrue(new HashSet<(long, string)> { (w.Marta, Make.Sha(9)) }.SetEquals(own)); + + // Both folders in one selection: each file only for its own folder. + var both = await KeysAsync(bed, new([new(w.General, null), new(w.Own, null)], [], Round: true), ct); + Assert.IsTrue(both.SetEquals(general.Union(own))); + + // Outside a round a file whose last copy failed waits for the round (answer 50: the round retries every one). + var pass = await KeysAsync(bed, new([new(w.General, null)], [], Round: false), ct); + Assert.IsTrue(general.Except([(w.Luca, Make.Sha(8))]).ToHashSet().SetEquals(pass)); + + // A destination not in use gives nothing. + await bed.Service.Destinations.RetireAsync(w.Own, ct); + Assert.IsEmpty(await bed.Db.Exports.ListCandidatesAsync(new ExportSelection.Automatic([new(w.Own, null)], [], true), 0, 100, ct)); + Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(new ExportSelection.Automatic([new(w.Own, null), new(9999, null)], [], true), ct)); + } + + /// «Solo i nuovi»: saved in the library at or after the instant of the switch; a file without that time is not new. + [TestMethod] + public async Task SinceKeepsFilesSavedAtOrAfterIt_NullDownloadedAtIsNotNew() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var since = Make.T0.AddDays(2).AddMilliseconds(500); + await FileAsync(bed, bed.Luca, "before", 1, since.AddMilliseconds(-1), ct: ct); + var at = await FileAsync(bed, bed.Luca, "at", 2, since, ct: ct); + var after = await FileAsync(bed, bed.Luca, "after", 3, since.AddDays(1), ct: ct); + await FileAsync(bed, bed.Luca, "unknown", 4, null, ct: ct); + + var candidates = await CandidatesAsync(bed, new([new(general, since)], [], Round: true), ct); + CollectionAssert.AreEquivalent(new[] { at.Media, after.Media }, candidates.Select(c => c.MediaId).ToArray()); + Assert.HasCount(4, await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct), "senza «Solo i nuovi» tutti i file dovuti"); + Assert.AreEqual(new ExportBacklog(2, 2000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, since), ct)); + } + + /// + /// An entry is copied when it is settled: none of its files is still to download (an expired one never will be, so + /// it does not hold the others). + /// + [TestMethod] + public async Task EntriesWithAFileToDownloadAreHeld_ExpiredDoesNotHold() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var waiting = await bed.Db.Entries.AddAsync( + Make.Entry(bed.Luca.Id, "waiting", Make.T0), + [Stored(Make.Photo(1), 1), Make.Photo(2)], + ct); + var expired = await bed.Db.Entries.AddAsync( + Make.Entry(bed.Luca.Id, "expired", Make.T0), + [Stored(Make.Photo(1), 2), Make.Photo(2, MediaState.Expired)], + ct); + + var candidates = await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct); + CollectionAssert.AreEqual(new[] { expired.Stored.Media[0].Id }, candidates.Select(c => c.MediaId).ToArray()); + + // When the second file is saved the entry is settled. + await bed.Db.WriteAsync( + x => x.Command("UPDATE media SET state = 'Downloaded', sha256 = @h, relative_path = 'p/w2.jpg', bytes = 1000 WHERE id = @id") + .With("@h", Make.Sha(3)).With("@id", waiting.Stored.Media[1].Id).ExecuteNonQuery(), + ct); + Assert.HasCount(3, await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct)); + } + + /// An entry whose line of _febe.jsonl is still to be written waits. + [TestMethod] + public async Task HeldEntryIdsAreLeftOut() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var held = await FileAsync(bed, bed.Luca, "held", 1, ct: ct); + var free = await FileAsync(bed, bed.Luca, "free", 2, ct: ct); + + var selection = new ExportSelection.Automatic([new(general, null)], [held.Entry, 424242], Round: true); + CollectionAssert.AreEqual(new[] { free.Media }, (await CandidatesAsync(bed, selection, ct)).Select(c => c.MediaId).ToArray()); + Assert.IsTrue(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct)); + Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection with { HeldEntryIds = [held.Entry, free.Entry] }, ct)); + } + + /// + /// «Tolto» and «Superato» are never copied again by themselves (spec §4.10, §15 E5): neither the file whose copy was + /// removed or superseded, nor the new file that superseded a copy, even when it is new. + /// + [TestMethod] + public async Task RemovedAndSupersededAreNotCandidates() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var removed = await FileAsync(bed, bed.Luca, "removed", 1, ct: ct); + var replaced = await FileAsync(bed, bed.Luca, "replaced", 2, ct: ct); + var replacement = await FileAsync(bed, bed.Luca, "replacement", 3, Make.T0.AddDays(5), ct: ct); + await CopyAsync(bed, general, bed.Luca, removed.Media, 1, ExportCopyState.Removed, ct: ct); + await CopyAsync(bed, general, bed.Luca, replaced.Media, 2, ExportCopyState.Superseded, supersededBy: 9, ct: ct); + // The old file of an entry whose library file is now sha 3 («Tieni il più grande»): its copy was superseded by it. + await CopyAsync(bed, general, bed.Luca, null, 30, ExportCopyState.Superseded, supersededBy: 3, ct: ct); + + foreach (var since in new DateTimeOffset?[] { null, Make.T0.AddDays(1) }) + { + var selection = new ExportSelection.Automatic([new(general, since)], [], Round: true); + Assert.IsEmpty(await CandidatesAsync(bed, selection, ct), $"da {since}"); + Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct)); + } + + Assert.AreEqual(new ExportBacklog(0, 0), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, null), ct)); + // A new folder has no history: there everything is to copy. + Assert.AreEqual(new ExportBacklog(3, 3000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, null, null), ct)); + } + + /// «Una copia sola»: a file copied for another account is not copied again by itself. + [TestMethod] + public async Task OneOnlyCopiedForAnotherAccountIsNotACandidate() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var marta = await FileAsync(bed, bed.Marta, "post", 1, ct: ct); + var luca = await FileAsync(bed, bed.Luca, "tagged", 1, kind: EntryKind.Tagged, ct: ct); + await CopyAsync(bed, general, bed.Marta, marta.Media, 1, ExportCopyState.Copied, ct: ct); + var selection = new ExportSelection.Automatic([new(general, null)], [], Round: true); + + CollectionAssert.AreEqual(new[] { luca.Media }, (await CandidatesAsync(bed, selection, ct)).Select(c => c.MediaId).ToArray(), "una copia per account"); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + Assert.IsEmpty(await CandidatesAsync(bed, selection, ct), "una copia sola"); + Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct)); + } + + /// + /// Answer 50 of 4 December 2026: every round retries every «Non riuscito», whatever the error (over 4 GB on FAT32, a + /// path too long, a read error); outside a round none. + /// + [TestMethod] + public async Task FailedCopiesAreCandidatesOfEveryRoundWhateverTheError_OutsideARoundTheyWait() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var notes = new[] { ExportText.Notes.TooLargeForFileSystem, ExportText.Notes.PathTooLong, null }; + var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = general, State = ExportRunState.Completed, StartedAt = Make.T0 }, ct); + var failed = new List(); + for (var i = 0; i < notes.Length; i++) + { + var file = await FileAsync(bed, bed.Luca, $"failed{i}", i + 1, ct: ct); + var copy = await CopyAsync(bed, general, bed.Luca, file.Media, i + 1, ExportCopyState.Failed, ct: ct); + await bed.Db.Exports.AddItemsAsync( + [new ExportItem { RunId = run.Id, MediaId = file.Media, AccountId = bed.Luca.Id, SourceSha256 = Make.Sha(i + 1), State = ExportItemState.Failed, Note = notes[i], CopyId = copy.Id }], + ct); + failed.Add(file.Media); + } + + var fresh = await FileAsync(bed, bed.Luca, "fresh", 10, ct: ct); + + var round = new ExportSelection.Automatic([new(general, null)], [], Round: true); + CollectionAssert.AreEquivalent(failed.Append(fresh.Media).ToArray(), (await CandidatesAsync(bed, round, ct)).Select(c => c.MediaId).ToArray()); + CollectionAssert.AreEqual(new[] { fresh.Media }, (await CandidatesAsync(bed, round with { Round = false }, ct)).Select(c => c.MediaId).ToArray()); + Assert.AreEqual(new ExportBacklog(4, 4000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, null), ct)); + + await bed.Db.WriteAsync(x => x.Command("DELETE FROM media WHERE id = @id").With("@id", fresh.Media).ExecuteNonQuery(), ct); + Assert.IsTrue(await bed.Db.Exports.HasAutomaticCandidatesAsync(round, ct)); + Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(round with { Round = false }, ct)); + } + + /// The pre-check of a pass says what the list would give, for each case of the mixed library. + [TestMethod] + public async Task HasAutomaticCandidatesMatchesTheList() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var w = await MixedAsync(bed, oneOnly: false, ct); + var selections = new List(); + foreach (var scopes in new ExportSelection.AutomaticScope[][] + { + [new(w.General, null)], [new(w.Own, null)], [new(w.General, Make.T0.AddYears(1))], [new(w.Own, null), new(w.General, null)], [], + }) + { + selections.Add(new(scopes, [], Round: true)); + selections.Add(new(scopes, [], Round: false)); + selections.Add(new(scopes, [w.MartaEntry9], Round: true)); + } + + foreach (var selection in selections) + { + var any = (await CandidatesAsync(bed, selection, ct)).Count > 0; + Assert.AreEqual(any, await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct), string.Join(", ", selection.Destinations)); + } + } + + // The backlog -------------------------------------------------------------------------------------------------- + + /// + /// The count of the question «Copia anche gli N» and of the files in more is what the plan of «Copia in…» writes once + /// the change is saved: a wider type for an automatic own folder, an own folder taken away (its files go to the + /// general folder), and the general folder moved to a new folder (no history there). Files and bytes, each file + /// once as the plan counts it. + /// + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task CountAutomaticBacklogMatchesThePlanner(bool oneOnly) + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var w = await MixedAsync(bed, oneOnly, ct); + var everything = new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped); + + // As things are. + var plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct); + Assert.AreEqual(Of(plan, w.General), await Backlog(new(ExportScope.General, null, ContentTypes.All, w.General, null))); + Assert.AreEqual(Of(plan, w.Own), await Backlog(new(ExportScope.Account, bed.Marta.Id, ContentTypes.PostPhotos, w.Own, null))); + + // «widen»: marta's own folder takes every type. + var before = Of(plan, w.Own); + var widened = await Backlog(new(ExportScope.Account, bed.Marta.Id, ContentTypes.All, w.Own, null)); + var own = (await bed.Db.Exports.GetDestinationAsync(w.Own, ct))!; + await bed.Service.Destinations.UpdateAsync(w.Own, new DestinationSpec(ExportScope.Account, bed.Marta.Id, own.RootPath, null, ContentTypes.All, null, null, null), ct); + plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct); + Assert.AreEqual(Of(plan, w.Own), widened); + Assert.IsGreaterThan(before.Files, widened.Files, "i tipi in più aggiungono file"); + + // «removeOwn»: marta's files go to the general folder. + var removeOwn = await Backlog(new(ExportScope.General, bed.Marta.Id, ContentTypes.All, w.General, null, IgnoreOwnFolderOfAccount: bed.Marta.Id)); + await bed.Service.Destinations.RetireAsync(w.Own, ct); + plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual(Of(plan, w.General), removeOwn); + Assert.IsGreaterThan(0, removeOwn.Files); + + // «switchOn» with a new folder: nothing is copied there yet. + var moved = await Backlog(new(ExportScope.General, null, ContentTypes.All, null, null)); + var folder = bed.Temp.Combine("usb2"); + Directory.CreateDirectory(folder); + var general = (await bed.Service.Destinations.UpdateAsync(w.General, new DestinationSpec(ExportScope.General, null, folder, "Disco nuovo", ContentTypes.All, null, null, null), ct)).Destination; + plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct); + Assert.AreEqual(Of(plan, general.Id), moved); + + // A wrong question is refused. + await Assert.ThrowsExactlyAsync(() => bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.Account, null, ContentTypes.All, null, null), ct)); + await Assert.ThrowsExactlyAsync(() => bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, w.General, null), ct)); + + Task Backlog(ExportBacklogQuery query) => bed.Db.Exports.CountAutomaticBacklogAsync(query, ct); + static ExportBacklog Of(ExportPlan plan, long destination) => + plan.Destinations.FirstOrDefault(d => d.DestinationId == destination) is { } d ? new(d.Files, d.Bytes) : new(0, 0); + } + + // «Riconosci le copie già presenti» ---------------------------------------------------------------------------- + + /// + /// The files «Riconosci» looks for (D13 with answer 51 of 4 December 2026): due files not «Copiato» whose newest row + /// is not «Tolto» («Non riuscito» and «Superato» yes; a «Tolto» stays «Tolto», even after a «Copia di nuovo» that + /// failed it is the newest row that decides), and the frames Febe already recorded with the same rule; frames never + /// recorded are not looked for. + /// + [TestMethod] + public async Task RecognizeCandidatesAreDueFilesNotCopied_RemovedStaysRemoved_WithFramesThatHaveRows() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var never = await FileAsync(bed, bed.Luca, "never", 1, ct: ct); + var copied = await FileAsync(bed, bed.Luca, "copied", 2, ct: ct); + var removed = await FileAsync(bed, bed.Luca, "removed", 3, ct: ct); + var removedThenFailed = await FileAsync(bed, bed.Luca, "again", 4, ct: ct); + var superseded = await FileAsync(bed, bed.Luca, "superseded", 5, ct: ct); + var failed = await FileAsync(bed, bed.Luca, "failed", 6, ct: ct); + var video = await FileAsync(bed, bed.Luca, "video", 7, video: true, ct: ct); + var otherAccount = await FileAsync(bed, bed.Marta, "marta", 8, ct: ct); + await CopyAsync(bed, general, bed.Luca, copied.Media, 2, ExportCopyState.Copied, ct: ct); + await CopyAsync(bed, general, bed.Luca, removed.Media, 3, ExportCopyState.Removed, ct: ct); + await CopyAsync(bed, general, bed.Luca, removedThenFailed.Media, 4, ExportCopyState.Removed, ct: ct); + await CopyAsync(bed, general, bed.Luca, removedThenFailed.Media, 4, ExportCopyState.Failed, ct: ct); + await CopyAsync(bed, general, bed.Luca, superseded.Media, 5, ExportCopyState.Superseded, supersededBy: 50, ct: ct); + await CopyAsync(bed, general, bed.Luca, failed.Media, 6, ExportCopyState.Failed, ct: ct); + await CopyAsync(bed, general, bed.Luca, video.Media, 7, ExportCopyState.Copied, ct: ct); + // A «Tolto» of marta's own: removed for her only (one copy per account). + await CopyAsync(bed, general, bed.Marta, otherAccount.Media, 8, ExportCopyState.Removed, ct: ct); + + // Frames of the video: 1 s failed, 2 s removed, 3 s copied, 4 s an orphan copied (account removed), 5 s an + // orphan removed, 6 s an orphan copied whose identity luca removed himself. + var f1 = await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 1, ExportCopyState.Failed, ct); + await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 2, ExportCopyState.Removed, ct); + await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 3, ExportCopyState.Copied, ct); + var f4 = await FrameAsync(bed, general, null, null, 7, 4, ExportCopyState.Copied, ct); + await FrameAsync(bed, general, null, null, 7, 5, ExportCopyState.Removed, ct); + await FrameAsync(bed, general, null, null, 7, 6, ExportCopyState.Copied, ct); + await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 6, ExportCopyState.Removed, ct); + + var found = await RecognizeAsync(bed, general, 1000, ct); + var expected = new (long, long?)[] + { + (never.Media, null), (removedThenFailed.Media, null), (superseded.Media, null), (failed.Media, null), + (video.Media, f1), (video.Media, f4), + }; + CollectionAssert.AreEqual(expected, found.Select(c => (c.File.MediaId, c.Frame?.Id)).ToArray(), string.Join(", ", found.Select(c => (c.File.MediaId, c.Frame?.FrameAt)))); + Assert.AreEqual(TimeSpan.FromSeconds(1), found.Single(c => c.Frame?.Id == f1).Frame!.FrameAt); + + // A page at a time by file: a page never ends inside the frames of a file. + var paged = new List(); + long after = 0; + while (await bed.Db.Exports.ListRecognizeCandidatesAsync(general, after, 1, ct) is { Count: > 0 } page) + { + Assert.AreEqual(1, page.Select(c => c.File.MediaId).Distinct().Count()); + paged.AddRange(page); + after = page[^1].File.MediaId; + } + + CollectionAssert.AreEqual(expected, paged.Select(c => (c.File.MediaId, c.Frame?.Id)).ToArray()); + + // «Una copia sola»: a file copied for another account is not looked for. + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + var shared = await FileAsync(bed, bed.Marta, "shared", 1, kind: EntryKind.Tagged, ct: ct); + Assert.IsTrue((await RecognizeAsync(bed, general, 1000, ct)).Any(c => c.File.MediaId == shared.Media), "nessuna copia di luca.demo: si cerca"); + await CopyAsync(bed, general, bed.Luca, never.Media, 1, ExportCopyState.Copied, ct: ct); + Assert.IsFalse((await RecognizeAsync(bed, general, 1000, ct)).Any(c => c.File.MediaId == shared.Media || c.File.MediaId == never.Media)); + + // A destination that is not in use has nothing to recognise. + Assert.IsEmpty(await bed.Db.Exports.ListRecognizeCandidatesAsync(9999, 0, 100, ct)); + } + + // Pauses ------------------------------------------------------------------------------------------------------- + + /// D10: the pause keeps its first instant, takes the latest problem and says only the transition. + [TestMethod] + public async Task SetDestinationPausedReturnsTrueOnlyOnTheTransition() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var exports = bed.Db.Exports; + + Assert.IsTrue(await exports.SetDestinationPausedAsync(general, Make.T0, "Disco non raggiungibile", ct)); + Assert.IsFalse(await exports.SetDestinationPausedAsync(general, Make.T0.AddHours(1), "Disco pieno", ct)); + var paused = (await exports.GetDestinationAsync(general, ct))!; + Assert.AreEqual((Make.T0, "Disco pieno"), (paused.PausedAt, paused.LastError)); + + Assert.IsTrue(await exports.ClearDestinationPauseAsync(general, ct)); + Assert.IsFalse(await exports.ClearDestinationPauseAsync(general, ct)); + Assert.IsNull((await exports.GetDestinationAsync(general, ct))!.PausedAt); + Assert.IsTrue(await exports.SetDestinationPausedAsync(general, Make.T0.AddDays(1), "Di nuovo", ct)); + + await bed.Service.Destinations.RetireAsync(general, ct); + Assert.IsFalse(await exports.ClearDestinationPauseAsync(general, ct), "una destinazione ritirata resta com'è"); + Assert.IsFalse(await exports.SetDestinationPausedAsync(general, Make.T0.AddDays(2), "Altro", ct)); + Assert.AreEqual("Di nuovo", (await exports.GetDestinationAsync(general, ct))!.LastError); + Assert.IsFalse(await exports.SetDestinationPausedAsync(9999, Make.T0, "Nessuna", ct)); + } + + /// D10: a save of the destination read before a pause (or before its end) does not undo it. + [TestMethod] + public async Task UpdateDestinationKeepsThePause() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var exports = bed.Db.Exports; + var stale = await bed.GeneralAsync(ct: ct); + + await exports.SetDestinationPausedAsync(stale.Id, Make.T0, "Disco non raggiungibile", ct); + await exports.UpdateDestinationAsync(stale with { Label = "Disco nuovo" }, ct); + var stored = (await exports.GetDestinationAsync(stale.Id, ct))!; + Assert.AreEqual(("Disco nuovo", Make.T0, "Disco non raggiungibile"), (stored.Label, stored.PausedAt, stored.LastError)); + + await exports.ClearDestinationPauseAsync(stale.Id, ct); + await exports.UpdateDestinationAsync(stored with { Label = "Disco" }, ct); + stored = (await exports.GetDestinationAsync(stale.Id, ct))!; + Assert.AreEqual(("Disco", (DateTimeOffset?)null, (string?)null), (stored.Label, stored.PausedAt, stored.LastError)); + } + + /// The pause of writes its event once per transition, through the store's own writes. + [TestMethod] + public async Task ExportPauseWritesTheEventOncePerTransition() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = await bed.GeneralAsync(ct: ct); + + var first = await ExportPause.PauseAsync(bed.Environment, general, "Disco non raggiungibile"); + var second = await ExportPause.PauseAsync(bed.Environment, general, "Disco pieno"); + Assert.AreEqual((first.PausedAt, "Disco pieno"), (second.PausedAt, second.LastError)); + Assert.IsNull((await ExportPause.ClearAsync(bed.Environment, general)).PausedAt); + await ExportPause.PauseAsync(bed.Environment, general, "Di nuovo"); + + var events = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportPause.PausedEventCode).ToList(); + Assert.HasCount(2, events); + } + + /// D11: the first file still to copy of the oldest paused job of a destination. + [TestMethod] + public async Task FirstPendingBytesOfAPausedRun() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = (await bed.GeneralAsync(ct: ct)).Id; + var own = (await bed.OwnAsync(bed.Marta, "marta", ct: ct)).Id; + var a = await FileAsync(bed, bed.Luca, "a", 1, bytes: 111, ct: ct); + var b = await FileAsync(bed, bed.Luca, "b", 2, bytes: 222, ct: ct); + var c = await FileAsync(bed, bed.Luca, "c", 3, bytes: 333, ct: ct); + Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(general, ct)); + + var running = await RunAsync(bed, general, ExportRunState.Interrupted, ct, (c.Media, ExportItemState.Pending)); + Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(general, ct), "solo un lavoro in pausa"); + await RunAsync(bed, general, ExportRunState.Paused, ct, (a.Media, ExportItemState.Copied), (b.Media, ExportItemState.Pending), (c.Media, ExportItemState.Pending)); + await RunAsync(bed, general, ExportRunState.Paused, ct, (a.Media, ExportItemState.Pending)); + Assert.AreEqual(222L, await bed.Db.Exports.GetFirstPendingBytesAsync(general, ct)); + Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(own, ct)); + Assert.IsNotNull(running); + } + + // The signal --------------------------------------------------------------------------------------------------- + + /// D4/D8: a signal completes the task taken before it, with its urgency, and is counted; each instance apart. + [TestMethod] + public async Task TheSignalWakesWhatWasTakenBeforeIt() + { + var signal = new AutoExportSignal(); + var other = new AutoExportSignal(); + var first = signal.Next(); + var elsewhere = other.Next(); + Assert.IsFalse(first.IsCompleted); + + signal.Signal(); + Assert.IsFalse(await first, "non urgente"); + var second = signal.Next(); + Assert.IsFalse(second.IsCompleted, "un segnale già dato non sveglia il compito preso dopo"); + signal.Signal(urgent: true); + Assert.IsTrue(await second); + Assert.AreEqual(2, signal.Count); + Assert.IsFalse(elsewhere.IsCompleted, "un'altra istanza non si sveglia"); + Assert.AreEqual(0, other.Count); + } + + // Support ------------------------------------------------------------------------------------------------------ + + /// The ids of the mixed library of . + private sealed record Mixed(long General, long Own, long Marta, long Luca, long MartaEntry9); + + /// + /// The general folder (every type) and marta's own folder (post photos only); anna.demo switched off. Files (SHA-256 + /// n, n × 100 bytes): marta 1 copied in her folder, 2 a video and 3 a story her folder does not take, 9 to copy; + /// luca 4 twice (a post and a tagged post), 5 copied, 6 «Tolto», 7 the file that superseded a copy, 8 «Non + /// riuscito», 1 (copied for marta: «Una copia sola»), 11 a story, 12 a video, and a post still to download; anna 10. + /// + private static async Task MixedAsync(ExportTestBed bed, bool oneOnly, CancellationToken ct) + { + var general = (await bed.GeneralAsync(ct: ct)).Id; + var own = (await bed.OwnAsync(bed.Marta, "marta", ContentTypes.PostPhotos, ct)).Id; + var anna = await bed.Db.Accounts.AddAsync(Make.Account("anna.demo", "300"), ct); + await bed.Db.Exports.SetAccountExportEnabledAsync(anna.Id, false, ct); + if (oneOnly) + { + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + } + + var m1 = await FileAsync(bed, bed.Marta, "m1", 1, bytes: 100, ct: ct); + await FileAsync(bed, bed.Marta, "m2", 2, video: true, bytes: 200, ct: ct); + await FileAsync(bed, bed.Marta, "m3", 3, kind: EntryKind.Story, bytes: 300, ct: ct); + var m9 = await FileAsync(bed, bed.Marta, "m9", 9, bytes: 900, ct: ct); + await FileAsync(bed, bed.Luca, "l4", 4, bytes: 400, ct: ct); + await FileAsync(bed, bed.Luca, "l4t", 4, kind: EntryKind.Tagged, bytes: 400, ct: ct); + var l5 = await FileAsync(bed, bed.Luca, "l5", 5, bytes: 500, ct: ct); + var l6 = await FileAsync(bed, bed.Luca, "l6", 6, bytes: 600, ct: ct); + await FileAsync(bed, bed.Luca, "l7", 7, bytes: 700, ct: ct); + var l8 = await FileAsync(bed, bed.Luca, "l8", 8, bytes: 800, ct: ct); + await FileAsync(bed, bed.Luca, "l1", 1, kind: EntryKind.Tagged, bytes: 100, ct: ct); + await FileAsync(bed, bed.Luca, "l11", 11, kind: EntryKind.Story, bytes: 1100, ct: ct); + await FileAsync(bed, bed.Luca, "l12", 12, video: true, bytes: 1200, ct: ct); + await bed.Db.Entries.AddAsync(Make.Entry(bed.Luca.Id, "todo", Make.T0), [Make.Photo()], ct); + await FileAsync(bed, anna, "a10", 10, bytes: 1000, ct: ct); + + await CopyAsync(bed, own, bed.Marta, m1.Media, 1, ExportCopyState.Copied, ct: ct); + await CopyAsync(bed, general, bed.Luca, l5.Media, 5, ExportCopyState.Copied, ct: ct); + await CopyAsync(bed, general, bed.Luca, l6.Media, 6, ExportCopyState.Removed, ct: ct); + await CopyAsync(bed, general, bed.Luca, null, 70, ExportCopyState.Superseded, supersededBy: 7, ct: ct); + await CopyAsync(bed, general, bed.Luca, l8.Media, 8, ExportCopyState.Failed, ct: ct); + return new Mixed(general, own, bed.Marta.Id, bed.Luca.Id, m9.Entry); + } + + /// A file in an entry of its own, saved at . + private static async Task<(long Entry, long Media)> FileAsync( + ExportTestBed bed, + Account account, + string code, + int sha, + DateTimeOffset? savedAt = null, + EntryKind kind = EntryKind.Post, + bool video = false, + long bytes = 1000, + CancellationToken ct = default) + { + var media = Stored(video ? Make.Video() : Make.Photo(), sha, video ? $"p/{code}.mp4" : $"p/{code}.jpg") with { Bytes = bytes, DownloadedAt = savedAt }; + var added = await bed.Db.Entries.AddAsync(Make.Entry(account.Id, code, Make.T0, kind), [media], ct); + return (added.Stored.Entry.Id, added.Stored.Media[0].Id); + } + + private static Media Stored(Media media, int sha, string? path = null) => Make.Stored(media, Make.Sha(sha), path ?? $"p/{sha}.jpg"); + + /// A whole copy row (a «Non riuscito» one without file). + private static Task CopyAsync( + ExportTestBed bed, long destination, Account account, long? media, int sha, ExportCopyState state, int? supersededBy = null, CancellationToken ct = default) + { + var written = state != ExportCopyState.Failed; + return bed.Db.Exports.AddCopyAsync( + new ExportCopy + { + DestinationId = destination, + AccountId = account.Id, + MediaId = media, + SourceSha256 = Make.Sha(sha), + Variant = ExportVariant.Whole, + State = state, + SupersededBySha256 = supersededBy is { } by ? Make.Sha(by) : null, + RelativePath = written ? $"{account.Username}/{sha}-{state}.jpg" : null, + Bytes = written ? 1000 : null, + CopySha256 = written ? Make.Sha(sha) : null, + CopiedAt = Make.T0, + StateChangedAt = Make.T0, + }, + ct); + } + + /// A PNG frame row at ; without account an orphan (its account was removed). + private static Task FrameAsync(ExportTestBed bed, long destination, long? account, long? media, int sha, int second, ExportCopyState state, CancellationToken ct) => + ExportWorld.InsertAsync(bed.Db, "export_copy", new Dictionary + { + ["destination_id"] = destination, + ["account_id"] = account, + ["removed_account_username"] = account is null ? "via.demo" : null, + ["media_id"] = media, + ["source_sha256"] = Make.Sha(sha), + ["variant"] = "Frame", + ["format"] = "Png", + ["frame_at_ms"] = second * 1000L, + ["state"] = state.ToString(), + ["origin"] = "Written", + ["relative_path"] = state == ExportCopyState.Failed ? null : $"f/{sha}_{second}_{account}_{state}.png", + ["bytes"] = state == ExportCopyState.Failed ? null : 10L, + ["copy_sha256"] = state == ExportCopyState.Failed ? null : Make.Sha(5000 + second), + ["copied_at"] = 0L, + }); + + private static async Task RunAsync(ExportTestBed bed, long destination, ExportRunState state, CancellationToken ct, params (long Media, ExportItemState State)[] items) + { + var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = destination, State = state, StartedAt = Make.T0 }, ct); + await bed.Db.Exports.AddItemsAsync( + [.. items.Select(i => new ExportItem { RunId = run.Id, MediaId = i.Media, AccountId = bed.Luca.Id, State = i.State })], + ct); + return run; + } + + private static Task> CandidatesAsync(ExportTestBed bed, ExportSelection.Automatic selection, CancellationToken ct) => + bed.Db.Exports.ListCandidatesAsync(selection, 0, 10_000, ct); + + private static async Task> KeysAsync(ExportTestBed bed, ExportSelection.Automatic selection, CancellationToken ct) + { + // Two pages at most of one file each first, to see the paging by media id. + var all = new List(); + long after = 0; + while (await bed.Db.Exports.ListCandidatesAsync(selection, after, 2, ct) is { Count: > 0 } page) + { + all.AddRange(page); + after = page[^1].MediaId; + } + + CollectionAssert.AreEqual((await CandidatesAsync(bed, selection, ct)).ToArray(), all.ToArray(), "a pagine come in una volta"); + return all.Select(c => (c.AccountId, c.Sha256!)).ToHashSet(); + } + + private static async Task> RecognizeAsync(ExportTestBed bed, long destination, int limit, CancellationToken ct) => + await bed.Db.Exports.ListRecognizeCandidatesAsync(destination, 0, limit, ct); + + /// What «Copia in…» of the selection writes, per destination, as (account, SHA-256). + private static async Task>> PlannedWritesAsync(ExportTestBed bed, ExportSelection selection, CancellationToken ct) + { + var effective = await bed.Service.Destinations.ResolveAllAsync(ct); + var settings = await ExportSettings.LoadAsync(bed.Db.Settings, ct); + var writes = new Dictionary>(); + await foreach (var file in bed.Service.Planner.EnumerateAsync(new ExportJobRequest(selection), effective, settings, ct)) + { + if (file.Action == PlannedCopy.Write) + { + if (!writes.TryGetValue(file.DestinationId!.Value, out var set)) + { + writes[file.DestinationId.Value] = set = []; + } + + set.Add((file.Candidate.AccountId, file.Candidate.Sha256!)); + } + } + + return writes; + } +}