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