E5: il lavoratore delle copie automatiche, all'avvio e ogni ora
AutoExportWorker copia da solo nelle cartelle con «Automatica» accesa: il giro di recupero all'avvio e ogni ora (IClock), una passata due minuti dopo l'ultima riga di _febe.jsonl (il segnale parte da LibraryIngest, anche per le righe scritte in ritardo), subito con un segnale urgente. Mai durante una sessione del motore: aspetta e dice perché; i lavori di Alberto vengono prima e, finiti, il lavoro automatico spostato riprende da solo (risposta 49). Al giro riprova le cartelle in pausa (una copia manuale «In pausa» resta di Alberto, risposta 48) e tutti i «Non riuscito» (risposta 50b); «Interrompi» lo ferma fino alla fine della sosta (risposta 53). Un lavoro finito non ne fa partire un altro da solo, così un file che non cambia torna solo al giro. La composizione lo avvia solo nell'avvio normale (mai nella dimostrazione) e lo ferma per primo alla chiusura. Prove: AutoExportWorkerTests (le prove di accettazione di §15: «Tolto» e «Superato» non si ricopiano, una cartella irraggiungibile va in pausa e un giro dopo riprende, nessuna copia durante una sessione), il segnale del giornale, la composizione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0ff4a0d632
commit
e66e322d35
12 files changed
+1821
-5
No files matched your search
@@ -682,3 +682,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
|||||||
| 2026-12-04 | Tappa E5: la copia automatica prende il cancello dei lavori lunghi (`LongWorkGate`) con un **permesso che cede** (`TryEnterYielding`): esclude gli altri come ogni permesso, e la conversione della libreria la aspetta come aspetta le copie. Importazione, ricostruzione, zip di fotogrammi (e, con la tappa, «Copia in…», «Riprendi», «Riconosci») lo prendono con `EnterAsync` **prima del proprio lucchetto e prima di registrare qualcosa**: chi entra diventa subito il titolare, la copia automatica riceve l'ordine di fermarsi e si aspetta che lasci, in tempo reale, al più `YieldWait` = 15 s; passato il limite il lavoro è rifiutato con il messaggio della copia e la copia resta titolare finché non lascia. «Cerca i video fermi», che non prende permessi, la ferma con `CancelYielding` e aspetta come per ogni lavoro lungo. `TryEnter` sincrono resta e rifiuta anche un titolare che cede; `BusyFirm` (il titolare se non cede) decide i rifiuti anticipati, `Busy` resta per chi aspetta. La sonda del controllo delle cartelle è riservata come i file temporanei della scrittura sicura | Risposta 49 di Alberto (la copia automatica cede sempre il passo). Un'attesa bloccante dentro `TryEnter` sotto i lucchetti di chi chiama avrebbe bloccato le richieste e rischiato lo stallo con chi pubblica l'avanzamento; installare subito il nuovo titolare chiude la finestra in cui il lavoro automatico potrebbe ripartire. Il tempo reale è un limite di consegna, non una misura del motore (come l'attesa del salvataggio della conversione e la risposta della radice delle copie); lasciare la copia titolare dopo il limite evita di partire sopra una copia che, ferma su una condivisione caduta, potrebbe ancora scrivere. La riserva della sonda impedisce che la pulizia dei resti di un altro lavoro nella stessa cartella la tolga mentre è in uso |
|
| 2026-12-04 | Tappa E5: la copia automatica prende il cancello dei lavori lunghi (`LongWorkGate`) con un **permesso che cede** (`TryEnterYielding`): esclude gli altri come ogni permesso, e la conversione della libreria la aspetta come aspetta le copie. Importazione, ricostruzione, zip di fotogrammi (e, con la tappa, «Copia in…», «Riprendi», «Riconosci») lo prendono con `EnterAsync` **prima del proprio lucchetto e prima di registrare qualcosa**: chi entra diventa subito il titolare, la copia automatica riceve l'ordine di fermarsi e si aspetta che lasci, in tempo reale, al più `YieldWait` = 15 s; passato il limite il lavoro è rifiutato con il messaggio della copia e la copia resta titolare finché non lascia. «Cerca i video fermi», che non prende permessi, la ferma con `CancelYielding` e aspetta come per ogni lavoro lungo. `TryEnter` sincrono resta e rifiuta anche un titolare che cede; `BusyFirm` (il titolare se non cede) decide i rifiuti anticipati, `Busy` resta per chi aspetta. La sonda del controllo delle cartelle è riservata come i file temporanei della scrittura sicura | Risposta 49 di Alberto (la copia automatica cede sempre il passo). Un'attesa bloccante dentro `TryEnter` sotto i lucchetti di chi chiama avrebbe bloccato le richieste e rischiato lo stallo con chi pubblica l'avanzamento; installare subito il nuovo titolare chiude la finestra in cui il lavoro automatico potrebbe ripartire. Il tempo reale è un limite di consegna, non una misura del motore (come l'attesa del salvataggio della conversione e la risposta della radice delle copie); lasciare la copia titolare dopo il limite evita di partire sopra una copia che, ferma su una condivisione caduta, potrebbe ancora scrivere. La riserva della sonda impedisce che la pulizia dei resti di un altro lavoro nella stessa cartella la tolga mentre è in uso |
|
||||||
| 2026-12-04 | Tappa E5, il servizio delle copie (`ExportService`): le partenze automatiche (`TryStartAutomaticAsync`, `TryResumeAutomaticAsync`) **non lanciano mai eccezioni perché Febe è occupata**: rispondono «occupato» (un lavoro, una sessione del motore, un cambio di cartella, un altro lavoro lungo), «niente da fare» (senza prendere il cancello, così la conversione della libreria non si ferma per nulla) o «ferme»; registrano solo i file da scrivere (niente «già copiato», «Tolto», «Superato»), un lavoro per cartella, e riprendono solo lavori automatici di cartelle ancora automatiche e non in pausa. Le partenze di Alberto («Copia in…», «Riprendi», «Controlla le copie», «Riprova») prendono il cancello con `EnterAsync` e aspettano che il lavoro automatico spostato abbia salvato i suoi stati (al più `StopWait` = 10 s, tempo reale). **I cambi di cartella passano da `ChangeDestinationAsync`**: le partenze automatiche stanno lontane dal primo momento, il lavoro automatico di quella cartella si ferma, poi il cambio, poi i lavori automatici di cartelle non più automatiche o tolte diventano «annullato»; un lavoro automatico non finito non blocca più il cambio di cartella né «Togli la cartella» (uno di Alberto sì). La copia stessa annulla un lavoro automatico la cui cartella non è più automatica, all'inizio e a ogni gruppo. **«Interrompi»** di una copia automatica ferma le copie automatiche per un'ora (`AutomaticHoldTime`), in memoria nel servizio; «Riprendi ora» toglie la sosta. Una cartella in pausa con un lavoro in pausa torna disponibile solo se il disco ha posto per il prossimo file più il margine; senza misura dello spazio la pausa si toglie come prima. «Copia automatica in … finita» solo se il lavoro ha copiato, adottato o non è riuscito qualcosa. Il segnale della copia automatica parte dal nucleo quando una cartella si accende, prende tipi in più, si toglie una cartella propria o si riaccende «Esporta questo account» (`ExportEnvironment.AutoSignal`), non dall'API. Un percorso troppo lungo dà la nota `PathTooLong`. La fine di Febe aspetta il lavoro al più `StopWait` | Risposte 48, 49, 50, 52, 53 e 54 di Alberto. Un rifiuto con eccezione non serve a chi riprova da solo a ogni passata; una partenza che non trova nulla non deve fermare la conversione. Serializzare i cambi nel nucleo chiude la finestra in cui la copia automatica potrebbe ripartire fra l'arresto e il salvataggio. La sosta sta nel servizio, che le partenze consultano, perché il servizio è l'unico punto da cui partono; in memoria come chiede la risposta 53. Riprendere una pausa per spazio senza posto la rimetterebbe subito in pausa. Il segnale nel nucleo vale per ogni via di salvataggio, non solo per l'API, e le prove lo osservano con un'istanza loro. Un limite in tempo reale alla chiusura evita che una lettura bloccata su una condivisione caduta tenga aperta Febe; il lavoro rimasto «in corso» diventa «interrotto» all'avvio dopo, come dopo un arresto improvviso |
|
| 2026-12-04 | Tappa E5, il servizio delle copie (`ExportService`): le partenze automatiche (`TryStartAutomaticAsync`, `TryResumeAutomaticAsync`) **non lanciano mai eccezioni perché Febe è occupata**: rispondono «occupato» (un lavoro, una sessione del motore, un cambio di cartella, un altro lavoro lungo), «niente da fare» (senza prendere il cancello, così la conversione della libreria non si ferma per nulla) o «ferme»; registrano solo i file da scrivere (niente «già copiato», «Tolto», «Superato»), un lavoro per cartella, e riprendono solo lavori automatici di cartelle ancora automatiche e non in pausa. Le partenze di Alberto («Copia in…», «Riprendi», «Controlla le copie», «Riprova») prendono il cancello con `EnterAsync` e aspettano che il lavoro automatico spostato abbia salvato i suoi stati (al più `StopWait` = 10 s, tempo reale). **I cambi di cartella passano da `ChangeDestinationAsync`**: le partenze automatiche stanno lontane dal primo momento, il lavoro automatico di quella cartella si ferma, poi il cambio, poi i lavori automatici di cartelle non più automatiche o tolte diventano «annullato»; un lavoro automatico non finito non blocca più il cambio di cartella né «Togli la cartella» (uno di Alberto sì). La copia stessa annulla un lavoro automatico la cui cartella non è più automatica, all'inizio e a ogni gruppo. **«Interrompi»** di una copia automatica ferma le copie automatiche per un'ora (`AutomaticHoldTime`), in memoria nel servizio; «Riprendi ora» toglie la sosta. Una cartella in pausa con un lavoro in pausa torna disponibile solo se il disco ha posto per il prossimo file più il margine; senza misura dello spazio la pausa si toglie come prima. «Copia automatica in … finita» solo se il lavoro ha copiato, adottato o non è riuscito qualcosa. Il segnale della copia automatica parte dal nucleo quando una cartella si accende, prende tipi in più, si toglie una cartella propria o si riaccende «Esporta questo account» (`ExportEnvironment.AutoSignal`), non dall'API. Un percorso troppo lungo dà la nota `PathTooLong`. La fine di Febe aspetta il lavoro al più `StopWait` | Risposte 48, 49, 50, 52, 53 e 54 di Alberto. Un rifiuto con eccezione non serve a chi riprova da solo a ogni passata; una partenza che non trova nulla non deve fermare la conversione. Serializzare i cambi nel nucleo chiude la finestra in cui la copia automatica potrebbe ripartire fra l'arresto e il salvataggio. La sosta sta nel servizio, che le partenze consultano, perché il servizio è l'unico punto da cui partono; in memoria come chiede la risposta 53. Riprendere una pausa per spazio senza posto la rimetterebbe subito in pausa. Il segnale nel nucleo vale per ogni via di salvataggio, non solo per l'API, e le prove lo osservano con un'istanza loro. Un limite in tempo reale alla chiusura evita che una lettura bloccata su una condivisione caduta tenga aperta Febe; il lavoro rimasto «in corso» diventa «interrotto» all'avvio dopo, come dopo un arresto improvviso |
|
||||||
| 2026-12-04 | Tappa E5, «Riconosci le copie già presenti» (`ExportService.RecognizeAsync`, partenza di Alberto da una cartella): un lavoro di tipo «Riconosci», riprendibile, su ogni file dovuto alla cartella che non è «Copiato» (senza «da quando»; «Una copia sola» vale) e sui fotogrammi che hanno già una riga lì. Per ogni file Febe guarda il percorso dello schema e «nome (2)» … «nome (50)», nella forma che la cartella chiede adesso e come originale, ciascuna con la sua identità (una copia byte per byte si registra Intera/Originale); prima i percorsi, poi la lunghezza, poi lo SHA-256 (con la conversione rifatta solo se un file c'è), mai per dimensione o nome soltanto. Un file uguale si registra «Adottato»: la riga «Non riuscito» della stessa identità diventa la copia, una riga orfana si ricollega, una «Superato» con gli stessi byte torna «Copiato». **Un «Tolto» resta «Tolto»** anche se il file è tornato identico (non si guarda nemmeno; un lavoro ripreso dopo un «Tolto» lo salta). Un fotogramma si confronta con i byte che la sua riga ha registrato, altrimenti si ricava di nuovo dal video; i fotogrammi mai registrati non si cercano. Non scrive, non rinomina e non toglie file (neppure i `.part` lasciati da altri), una cartella che non risponde mette in pausa senza segnare nulla, e scrive solo il suo evento (`esportazione-riconosci`: «Riconosciute N copie già presenti in …», informazione quando nessuna). Il resoconto conta «Non c'è nella cartella» e «Nel percorso c'è un altro file»; solo il secondo è fra i problemi. Lo spazio libero non si chiede per un «Riconosci» in pausa | Risposta 51 di Alberto (b: come proposto, ma un «Tolto» resta «Tolto»). Provare prima i percorsi evita letture e conversioni dove non c'è nulla; ogni forma con la sua identità rispetta il vincolo fra variante e SHA-256 della copia; riusare la riga «Non riuscito» evita una seconda riga corrente. Contare «Non c'è» fra i problemi riempirebbe il resoconto di una cartella che non ha mai avuto copie. Una conversione fatta da codificatori più vecchi esce «diversa»: la copia successiva scrive il file accanto, con un nome libero, e quello che c'era resta |
|
| 2026-12-04 | Tappa E5, «Riconosci le copie già presenti» (`ExportService.RecognizeAsync`, partenza di Alberto da una cartella): un lavoro di tipo «Riconosci», riprendibile, su ogni file dovuto alla cartella che non è «Copiato» (senza «da quando»; «Una copia sola» vale) e sui fotogrammi che hanno già una riga lì. Per ogni file Febe guarda il percorso dello schema e «nome (2)» … «nome (50)», nella forma che la cartella chiede adesso e come originale, ciascuna con la sua identità (una copia byte per byte si registra Intera/Originale); prima i percorsi, poi la lunghezza, poi lo SHA-256 (con la conversione rifatta solo se un file c'è), mai per dimensione o nome soltanto. Un file uguale si registra «Adottato»: la riga «Non riuscito» della stessa identità diventa la copia, una riga orfana si ricollega, una «Superato» con gli stessi byte torna «Copiato». **Un «Tolto» resta «Tolto»** anche se il file è tornato identico (non si guarda nemmeno; un lavoro ripreso dopo un «Tolto» lo salta). Un fotogramma si confronta con i byte che la sua riga ha registrato, altrimenti si ricava di nuovo dal video; i fotogrammi mai registrati non si cercano. Non scrive, non rinomina e non toglie file (neppure i `.part` lasciati da altri), una cartella che non risponde mette in pausa senza segnare nulla, e scrive solo il suo evento (`esportazione-riconosci`: «Riconosciute N copie già presenti in …», informazione quando nessuna). Il resoconto conta «Non c'è nella cartella» e «Nel percorso c'è un altro file»; solo il secondo è fra i problemi. Lo spazio libero non si chiede per un «Riconosci» in pausa | Risposta 51 di Alberto (b: come proposto, ma un «Tolto» resta «Tolto»). Provare prima i percorsi evita letture e conversioni dove non c'è nulla; ogni forma con la sua identità rispetta il vincolo fra variante e SHA-256 della copia; riusare la riga «Non riuscito» evita una seconda riga corrente. Contare «Non c'è» fra i problemi riempirebbe il resoconto di una cartella che non ha mai avuto copie. Una conversione fatta da codificatori più vecchi esce «diversa»: la copia successiva scrive il file accanto, con un nome libero, e quello che c'era resta |
|
||||||
|
| 2026-12-04 | Tappa E5, il lavoratore delle copie automatiche (`AutoExportWorker`, in `Febe.Core/Export`): un ciclo solo, avviato dalla composizione nell'avvio normale (mai nella dimostrazione, mai in un avvio con problemi), fermato **per primo** alla chiusura, prima dell'interfaccia e del motore, con il lavoro automatico interrotto (al più 5 s, tempo reale). Il giro di recupero gira all'avvio e poi ogni ora (`IClock`, nessuna variazione casuale: il lavoratore non tocca Instagram); il sonno dura al più 5 minuti, così dopo una sospensione del PC il giro arriva in ritardo una volta sola. Ogni riga di `_febe.jsonl` dà un segnale (in `LibraryIngest`, anche per le righe scritte in ritardo, un'istanza propria nelle prove): la passata parte **due minuti dopo l'ultimo segnale** (al più 15 minuti di rinvio se i file continuano ad arrivare), subito con un segnale urgente (cartella accesa, «Riprendi ora»); un segnale che arriva durante una passata non si perde. Una passata, in ordine: al giro i lavori automatici orfani diventano «annullato»; la sosta di «Interrompi» la ferma fino alla sua fine (il giro dovuto resta in attesa e parte allora); una sessione del motore, un lavoro lungo di Alberto, «Cerca i video fermi» o una sua copia la fanno aspettare (riprova ogni 5 s e la Dashboard dice perché); al giro ogni cartella in pausa si riprova (le copie fatte a mano «In pausa» restano di Alberto); poi riprende i lavori automatici non finiti (quelli fermati da un errore o in pausa solo al giro), altrimenti un lavoro per ogni cartella automatica non in pausa e senza un lavoro automatico non finito, con le voci la cui riga del giornale è ancora da scrivere tenute fuori. Finito un lavoro automatico, una passata segue **solo** se il lavoro è stato fermato (i suoi lavori «interrotto» senza errore) o se aveva ripreso lavori invece di cercare file nuovi; il lavoratore aspetta la fine del lavoro (`ExportService.AutomaticWork`) invece di riprovare. Un lavoro finito non ne fa partire un altro da solo | Risposte 49, 50, 53 e 54 di Alberto; come la conversione della libreria (decisione del 30/11) niente `BackgroundService` e niente lavoratore nella dimostrazione. Il segnale alla fine di ogni lavoro proposto dal progetto, con un file che c'è nella base dati ma non sul disco (o un «Non riuscito» che non cambia), avrebbe fatto un lavoro ogni due minuti per sempre: così quei file tornano solo al giro, una volta all'ora, la conseguenza accettata con la risposta 50. Riprendere da soli i lavori fermati dai lavori di Alberto è la risposta 49 («riparte da sola dopo»), senza aspettare il giro. Fermare il lavoratore per primo evita che una sessione che finisce durante la chiusura faccia partire una copia |
|
||||||
@@ -45,6 +45,9 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
/// <summary>How long a stop waits for «Cerca i video fermi» to give up the video it analyses.</summary>
|
/// <summary>How long a stop waits for «Cerca i video fermi» to give up the video it analyses.</summary>
|
||||||
private static readonly TimeSpan StillVideosWait = TimeSpan.FromSeconds(5);
|
private static readonly TimeSpan StillVideosWait = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
|
/// <summary>The longest wait at the stop for an automatic copy to let go (real time: a share may not answer).</summary>
|
||||||
|
private static readonly TimeSpan ExportStopWait = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
private readonly FebeAppOptions _options;
|
private readonly FebeAppOptions _options;
|
||||||
private readonly IFebePlatform _platform;
|
private readonly IFebePlatform _platform;
|
||||||
private readonly CancellationTokenSource _lifetime = new();
|
private readonly CancellationTokenSource _lifetime = new();
|
||||||
@@ -58,6 +61,7 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
private string? _temporaryFolder;
|
private string? _temporaryFolder;
|
||||||
private RequestCatalog? _requestCatalog;
|
private RequestCatalog? _requestCatalog;
|
||||||
private ISessionCopier? _copier;
|
private ISessionCopier? _copier;
|
||||||
|
private AutoExportWorker? _autoExport;
|
||||||
private int _disposed;
|
private int _disposed;
|
||||||
|
|
||||||
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
|
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
|
||||||
@@ -428,6 +432,12 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||||
InBackground(() => conversion.RunAsync(lifetime));
|
InBackground(() => conversion.RunAsync(lifetime));
|
||||||
|
|
||||||
|
// The automatic export (tappa E5, D8): the start-up round at once, then a pass after each file saved in the
|
||||||
|
// library and every hour. Only in a normal start: never in the demo, nor in a start with problems.
|
||||||
|
var autoExport = Web.Services.GetRequiredService<AutoExportWorker>();
|
||||||
|
_autoExport = autoExport;
|
||||||
|
InBackground(() => autoExport.RunAsync(lifetime));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||||
@@ -948,6 +958,18 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
Log.Info("arresto", "Arresto in corso.");
|
Log.Info("arresto", "Arresto in corso.");
|
||||||
await Quietly(_platform.StoppingAsync).ConfigureAwait(false);
|
await Quietly(_platform.StoppingAsync).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (_autoExport is { } autoExport && Web is { } host)
|
||||||
|
{
|
||||||
|
// First the automatic export (tappa E5, D8): a session that ends while Febe stops must not start a copy. Its
|
||||||
|
// job is interrupted (its runs resume at the next start); a copy of Alberto's stops with the web host.
|
||||||
|
await Quietly(autoExport.StopAsync).ConfigureAwait(false);
|
||||||
|
await Quietly(async () =>
|
||||||
|
{
|
||||||
|
var exports = await host.Services.GetRequiredService<Febe.Web.Export.ExportHub>().GetAsync(CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await exports.InterruptAutomaticAsync(CancellationToken.None).WaitAsync(ExportStopWait).ConfigureAwait(false);
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
if (Web is { } web)
|
if (Web is { } web)
|
||||||
{
|
{
|
||||||
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
|
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using Febe.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Why the automatic export waits (tappa E5, D8), as the Dashboard shows it: one line, Italian, never a path. The
|
||||||
|
/// interface never says a bare «giro» here, which names the engine's «Giro dei seguiti».
|
||||||
|
/// </summary>
|
||||||
|
public static class AutoExportText
|
||||||
|
{
|
||||||
|
/// <summary>An engine session is under way: nothing is copied during it.</summary>
|
||||||
|
public const string InSession = "Copie automatiche: riprendono alla fine della sessione del motore.";
|
||||||
|
|
||||||
|
/// <summary>«Cerca i video fermi» is at work: it never runs together with copies.</summary>
|
||||||
|
public const string StillVideos = "Copie automatiche: aspettano la fine di «Cerca i video fermi».";
|
||||||
|
|
||||||
|
/// <summary>A copy started by Alberto («Copia in…», «Riprendi», «Controlla le copie», «Riconosci») is at work.</summary>
|
||||||
|
public const string ManualJob = "Copie automatiche: aspettano la fine della copia in corso.";
|
||||||
|
|
||||||
|
/// <summary>Alberto's long work holds the gate (import, rebuild, a zip of frames).</summary>
|
||||||
|
public static string LongWork(LongWorkKind kind) => kind switch
|
||||||
|
{
|
||||||
|
LongWorkKind.Import => "Copie automatiche: aspettano la fine di un'importazione.",
|
||||||
|
LongWorkKind.Rebuild => "Copie automatiche: aspettano la fine della ricostruzione.",
|
||||||
|
LongWorkKind.FrameDownload => "Copie automatiche: aspettano la fine di uno zip di fotogrammi.",
|
||||||
|
LongWorkKind.Export => ManualJob,
|
||||||
|
_ => "Copie automatiche: aspettano la fine di un lavoro lungo.",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The worker's loop met an unexpected error (the log gets the type only, rule 10).</summary>
|
||||||
|
public static string Error(Exception ex)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ex);
|
||||||
|
return $"Le copie automatiche si sono fermate per un errore ({ex.GetType().Name}): riprovano al prossimo giro di recupero.";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,570 @@
|
|||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>What the automatic export needs from the rest of Febe (tappa E5, D8).</summary>
|
||||||
|
public sealed record AutoExportEnvironment
|
||||||
|
{
|
||||||
|
public required IFebeStorage Storage { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Engine timing: rounds, settle, polls and sleeps (never DateTime.Now or Task.Delay).</summary>
|
||||||
|
public required IClock Clock { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The export service of the application (the web host's ExportHub builds it at the first use).</summary>
|
||||||
|
public required Func<CancellationToken, Task<ExportService>> Service { get; init; }
|
||||||
|
|
||||||
|
/// <summary>What wakes the worker: journal lines, a rebuild, a destination turned on, «Riprendi ora».</summary>
|
||||||
|
public AutoExportSignal Signal { get; init; } = AutoExportSignal.Default;
|
||||||
|
|
||||||
|
/// <summary>No copy starts during an engine session.</summary>
|
||||||
|
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
|
||||||
|
|
||||||
|
/// <summary>The gate of long work: Alberto's import, rebuild and zip of frames come first. Null: none (tests).</summary>
|
||||||
|
public LongWorkGate? Gate { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Other work the copies never run with: «Cerca i video fermi» (its progress says it runs).</summary>
|
||||||
|
public Func<bool> OtherWorkRunning { get; init; } = () => false;
|
||||||
|
|
||||||
|
/// <summary>The recovery round: at start-up and then every this long (answer 54: «e comunque al giro»).</summary>
|
||||||
|
public TimeSpan Round { get; init; } = TimeSpan.FromHours(1);
|
||||||
|
|
||||||
|
/// <summary>A pass starts this long after the last file saved in the library (answer 54).</summary>
|
||||||
|
public TimeSpan Settle { get; init; } = TimeSpan.FromMinutes(2);
|
||||||
|
|
||||||
|
/// <summary>The longest the settle can be pushed on by files that keep arriving.</summary>
|
||||||
|
public TimeSpan SettleLimit { get; init; } = TimeSpan.FromMinutes(15);
|
||||||
|
|
||||||
|
/// <summary>How often the worker looks again while it waits for a session or Alberto's work to end.</summary>
|
||||||
|
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The longest sleep without looking at the clock: after a sleep or hibernation of the PC the round runs at most this
|
||||||
|
/// late (engineering B10).
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan MaxSleep { get; init; } = TimeSpan.FromMinutes(5);
|
||||||
|
|
||||||
|
/// <summary>The longest wait for the loop to end at the stop, in real time (a safety bound, not engine timing).</summary>
|
||||||
|
public TimeSpan StopWait { get; init; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
|
/// <summary>One line for the log: Italian text and exception type names only, never paths (rule 10).</summary>
|
||||||
|
public Action<string>? Log { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What one pass of the automatic export did.</summary>
|
||||||
|
public enum AutoExportPass
|
||||||
|
{
|
||||||
|
/// <summary>Nothing looked at (an error, logged).</summary>
|
||||||
|
Idle,
|
||||||
|
|
||||||
|
/// <summary>«Interrompi» holds the automatic copies (answer 53): the pass is due again when the hold ends.</summary>
|
||||||
|
Held,
|
||||||
|
|
||||||
|
/// <summary>An engine session or Alberto's work: the pass is due again after <see cref="AutoExportEnvironment.Poll"/>.</summary>
|
||||||
|
Waiting,
|
||||||
|
|
||||||
|
/// <summary>An automatic job is already at work: the pass is due again when it ends.</summary>
|
||||||
|
Running,
|
||||||
|
|
||||||
|
/// <summary>An automatic job started (new files, or unfinished automatic runs resumed).</summary>
|
||||||
|
Started,
|
||||||
|
|
||||||
|
/// <summary>Nothing to copy.</summary>
|
||||||
|
NothingToDo,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The automatic export as the Dashboard shows it.</summary>
|
||||||
|
/// <param name="Running">The worker's loop runs (never in the demo, nor in a start with problems).</param>
|
||||||
|
/// <param name="AnyAutomatic">At least one destination in use has «Automatica» on.</param>
|
||||||
|
/// <param name="Waiting">Why the copies wait now (<see cref="AutoExportText"/>), or null.</param>
|
||||||
|
/// <param name="LastRound">When the last recovery round ran.</param>
|
||||||
|
/// <param name="NextRound">When the next recovery round is due.</param>
|
||||||
|
/// <param name="HeldUntil">Until when «Interrompi» holds the automatic copies.</param>
|
||||||
|
public sealed record AutoExportStatus(bool Running, bool AnyAutomatic, string? Waiting, DateTimeOffset? LastRound, DateTimeOffset? NextRound, DateTimeOffset? HeldUntil);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The automatic export (tappa E5, spec §4.10, D8): copies by itself, into each destination with «Automatica» on, the
|
||||||
|
/// files due there and not copied yet (from the database, <see cref="ExportSelection.Automatic"/>). A pass runs a little
|
||||||
|
/// after a file is saved in the library (<see cref="AutoExportEnvironment.Settle"/> after its <c>_febe.jsonl</c> line,
|
||||||
|
/// answer 54), at start-up and at every recovery round (every hour). One job per destination per pass; never during an
|
||||||
|
/// engine session; Alberto's work comes first (answer 49: the job's lease yields and the worker waits, then resumes
|
||||||
|
/// the interrupted runs); «Tolto» and «Superato» are never copied again. The round also tries every paused destination
|
||||||
|
/// again: one that answers is no longer paused, and its automatic runs resume (a manual «In pausa» stays Alberto's,
|
||||||
|
/// answer 48); every «Non riuscito» is tried again by each round (answer 50). Started by the composition, never in the
|
||||||
|
/// demo (as decision r.644 for the library conversion). Touches nothing but the disk: no Instagram, no Governatore.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AutoExportWorker
|
||||||
|
{
|
||||||
|
private readonly AutoExportEnvironment _env;
|
||||||
|
private readonly Lock _gate = new();
|
||||||
|
private readonly SemaphoreSlim _pass = new(1, 1);
|
||||||
|
private ExportService? _service;
|
||||||
|
private CancellationTokenSource? _stop;
|
||||||
|
private Task _loop = Task.CompletedTask;
|
||||||
|
private bool _running;
|
||||||
|
private string? _waiting;
|
||||||
|
private DateTimeOffset? _lastRound;
|
||||||
|
private DateTimeOffset? _nextRound;
|
||||||
|
private long _passes;
|
||||||
|
|
||||||
|
// The last Started pass resumed runs instead of looking for new files: a pass follows once that job ends.
|
||||||
|
private bool _resumed;
|
||||||
|
|
||||||
|
public AutoExportWorker(AutoExportEnvironment env)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(env);
|
||||||
|
_env = env;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True while <see cref="RunAsync"/> runs.</summary>
|
||||||
|
public bool Running
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
return _running;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Tests only: how many passes ended (however they ended).</summary>
|
||||||
|
internal long Passes => Interlocked.Read(ref _passes);
|
||||||
|
|
||||||
|
/// <summary>The automatic export now: whether any destination is automatic is read from the database.</summary>
|
||||||
|
public async Task<AutoExportStatus> StatusAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||||
|
var any = destinations.Any(d => d is { Automatic: true, IsOrphan: false });
|
||||||
|
DateTimeOffset? held;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
held = _service?.AutomaticHeldUntil;
|
||||||
|
return new AutoExportStatus(_running, any, _waiting, _lastRound, _nextRound, held);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Riprendi ora» (answer 53): the automatic copies are no longer held, and a pass runs at once (no settle).
|
||||||
|
/// </summary>
|
||||||
|
public async Task ResumeNowAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||||
|
service.ReleaseAutomaticHold();
|
||||||
|
_env.Signal.Signal(urgent: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The loop: the start-up round at once, then a pass at each signal (after the settle) and at each recovery round.
|
||||||
|
/// An error of a pass is logged by type and the loop goes on. Ends, without throwing, when <paramref name="ct"/> is
|
||||||
|
/// cancelled or <see cref="StopAsync"/> is called.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The loop already runs.</exception>
|
||||||
|
public async Task RunAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
CancellationTokenSource stop;
|
||||||
|
Task loop;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_running)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Le copie automatiche sono già al lavoro.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_running = true;
|
||||||
|
stop = _stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
loop = _loop = Task.Run(() => LoopAsync(stop.Token), CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await loop.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (stop.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
// Stopped.
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_running = false;
|
||||||
|
_stop = null;
|
||||||
|
_waiting = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
stop.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stops the loop and waits for it, at most <see cref="AutoExportEnvironment.StopWait"/> in real time. A job already
|
||||||
|
/// started is not stopped here (the composition interrupts it next).
|
||||||
|
/// </summary>
|
||||||
|
public async Task StopAsync()
|
||||||
|
{
|
||||||
|
Task loop;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_stop?.Cancel();
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException)
|
||||||
|
{
|
||||||
|
// Already over.
|
||||||
|
}
|
||||||
|
|
||||||
|
loop = _loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await loop.WaitAsync(_env.StopWait).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OperationCanceledException or TimeoutException)
|
||||||
|
{
|
||||||
|
// Stopped, or a pass stuck on a share that went away: it ends by itself.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One pass, in order (D8): orphan automatic runs cancelled (round); the hold; an engine session, Alberto's work,
|
||||||
|
/// «Cerca i video fermi», a job at work; paused destinations tried again (round); unfinished automatic runs resumed
|
||||||
|
/// (those stopped with an error only at the round); else a job over every automatic destination not paused.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="round">A recovery round: «Non riuscito» copies are tried again too (answer 50).</param>
|
||||||
|
public async Task<AutoExportPass> RunOnceAsync(bool round, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await _pass.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await PassAsync(round, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref _passes);
|
||||||
|
_pass.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AutoExportPass> PassAsync(bool round, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||||
|
var exports = _env.Storage.Exports;
|
||||||
|
if (round)
|
||||||
|
{
|
||||||
|
// Ghost runs: of a destination retired, switched off, or of an account removed (engineering A10).
|
||||||
|
await service.CancelOrphanAutomaticRunsAsync(ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (service.AutomaticHeldUntil is not null)
|
||||||
|
{
|
||||||
|
return Outcome(AutoExportPass.Held, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (WaitingReason(service) is { } reason)
|
||||||
|
{
|
||||||
|
return Outcome(AutoExportPass.Waiting, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (service.AutomaticRunning)
|
||||||
|
{
|
||||||
|
return Outcome(AutoExportPass.Running, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (service.IsBusy)
|
||||||
|
{
|
||||||
|
return Outcome(AutoExportPass.Waiting, AutoExportText.ManualJob);
|
||||||
|
}
|
||||||
|
|
||||||
|
var destinations = await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||||
|
if (round && destinations.Any(d => d.PausedAt is not null))
|
||||||
|
{
|
||||||
|
foreach (var paused in destinations.Where(d => d.PausedAt is not null))
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Answers again: the pause goes (no event); still not: it stays, with no new event (D10, D11).
|
||||||
|
await service.ProbeDestinationAsync(paused.Id, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is KeyNotFoundException or InvalidOperationException)
|
||||||
|
{
|
||||||
|
// Retired meanwhile.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
destinations = await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var usable = destinations.Where(d => d is { Automatic: true, PausedAt: null, IsOrphan: false }).ToDictionary(d => d.Id);
|
||||||
|
var unfinished = (await exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false))
|
||||||
|
.Where(r => r.Origin == ExportRunOrigin.Automatic)
|
||||||
|
.ToList();
|
||||||
|
var resumable = unfinished
|
||||||
|
.Where(r => r.Kind == ExportRunKind.Copy && usable.ContainsKey(r.DestinationId) && (round || r.LastError is null))
|
||||||
|
.Select(r => r.Id)
|
||||||
|
.ToList();
|
||||||
|
if (resumable.Count > 0)
|
||||||
|
{
|
||||||
|
var resume = await service.TryResumeAutomaticAsync(resumable, ct).ConfigureAwait(false);
|
||||||
|
if (resume.Outcome != AutoExportStartOutcome.NothingToDo)
|
||||||
|
{
|
||||||
|
_resumed = resume.Outcome == AutoExportStartOutcome.Started;
|
||||||
|
return Answer(service, resume);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One run per destination at a time: a destination with an unfinished automatic run waits for it.
|
||||||
|
var withRun = unfinished.Select(r => r.DestinationId).ToHashSet();
|
||||||
|
var scopes = usable.Values
|
||||||
|
.Where(d => !withRun.Contains(d.Id))
|
||||||
|
.OrderBy(d => d.Id)
|
||||||
|
.Select(d => new ExportSelection.AutomaticScope(d.Id, d.AutomaticSince))
|
||||||
|
.ToList();
|
||||||
|
if (scopes.Count == 0)
|
||||||
|
{
|
||||||
|
return Outcome(AutoExportPass.NothingToDo, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var held = await LibraryIngest.PendingJournalEntriesAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var start = await service.TryStartAutomaticAsync(new ExportSelection.Automatic(scopes, held, round), ct).ConfigureAwait(false);
|
||||||
|
_resumed = false;
|
||||||
|
return Answer(service, start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Why no automatic copy can start now, or null: a session, Alberto's long work, «Cerca i video fermi».</summary>
|
||||||
|
private string? WaitingReason(ExportService service)
|
||||||
|
{
|
||||||
|
if (_env.Session.InSession)
|
||||||
|
{
|
||||||
|
return AutoExportText.InSession;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_env.Gate?.BusyFirm is { } busy)
|
||||||
|
{
|
||||||
|
return AutoExportText.LongWork(busy);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_env.OtherWorkRunning())
|
||||||
|
{
|
||||||
|
return AutoExportText.StillVideos;
|
||||||
|
}
|
||||||
|
|
||||||
|
return service.IsBusy && !service.AutomaticRunning ? AutoExportText.ManualJob : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AutoExportPass Answer(ExportService service, AutoExportStart start) => start.Outcome switch
|
||||||
|
{
|
||||||
|
AutoExportStartOutcome.Started => Outcome(AutoExportPass.Started, null),
|
||||||
|
AutoExportStartOutcome.Held => Outcome(AutoExportPass.Held, null),
|
||||||
|
AutoExportStartOutcome.Busy => Outcome(
|
||||||
|
AutoExportPass.Waiting,
|
||||||
|
start.BusyWith is { } kind ? AutoExportText.LongWork(kind) : WaitingReason(service)),
|
||||||
|
_ => Outcome(AutoExportPass.NothingToDo, null),
|
||||||
|
};
|
||||||
|
|
||||||
|
private AutoExportPass Outcome(AutoExportPass pass, string? waiting)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_waiting = waiting;
|
||||||
|
}
|
||||||
|
|
||||||
|
return pass;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ExportService> ServiceAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_service is { } ready)
|
||||||
|
{
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var service = await _env.Service(ct).ConfigureAwait(false);
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
return _service ??= service;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task LoopAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var clock = _env.Clock;
|
||||||
|
var signal = _env.Signal.Next();
|
||||||
|
var nextRound = clock.Now; // the start-up round
|
||||||
|
SetNextRound(nextRound);
|
||||||
|
var signalled = false;
|
||||||
|
var followUp = false;
|
||||||
|
var followUpRound = false;
|
||||||
|
Task? watching = null;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
if (signal.IsCompleted)
|
||||||
|
{
|
||||||
|
// A file saved (or a rebuild, a job of Alberto's ended…): a pass a little after the last one, at once when
|
||||||
|
// urgent (a destination turned on, «Riprendi ora»).
|
||||||
|
if (!await signal.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await SettleAsync(ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
signal = _env.Signal.Next();
|
||||||
|
signalled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watching is { IsCompleted: true })
|
||||||
|
{
|
||||||
|
// The automatic job ended: a pass follows when it was stopped (Alberto's work came first) or when it
|
||||||
|
// resumed runs and new files were not looked for.
|
||||||
|
watching = null;
|
||||||
|
followUp = await NeedsFollowUpAsync(ct).ConfigureAwait(false);
|
||||||
|
followUpRound &= followUp;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.Now;
|
||||||
|
var isRound = now >= nextRound;
|
||||||
|
var wake = nextRound - now;
|
||||||
|
if (isRound || signalled || followUp)
|
||||||
|
{
|
||||||
|
// The signal in hand was taken before the pass (above, or before the last sleep): one that arrives during
|
||||||
|
// the pass completes it and is not lost. Taking a new one here could drop one given since the check above.
|
||||||
|
var pass = AutoExportPass.Idle;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
pass = await RunOnceAsync(isRound || followUpRound, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_env.Log?.Invoke(AutoExportText.Error(ex));
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (pass)
|
||||||
|
{
|
||||||
|
case AutoExportPass.Waiting:
|
||||||
|
// Pending: looked at again soon (the round too, once Alberto's work or the session is over).
|
||||||
|
await SleepAsync(signal, null, _env.Poll, ct).ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
case AutoExportPass.Held:
|
||||||
|
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||||
|
var until = service.AutomaticHeldUntil ?? clock.Now;
|
||||||
|
await SleepAsync(signal, null, Min(until - clock.Now, _env.MaxSleep), ct).ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
case AutoExportPass.Running:
|
||||||
|
// Our own job: the pass is due again once it ends.
|
||||||
|
watching = (await ServiceAsync(ct).ConfigureAwait(false)).AutomaticWork;
|
||||||
|
await SleepAsync(signal, watching, _env.MaxSleep, ct).ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRound)
|
||||||
|
{
|
||||||
|
nextRound = now + _env.Round;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_lastRound = now;
|
||||||
|
_nextRound = nextRound;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
followUpRound = pass == AutoExportPass.Started && _resumed && (isRound || followUpRound);
|
||||||
|
signalled = false;
|
||||||
|
followUp = false;
|
||||||
|
if (pass == AutoExportPass.Started)
|
||||||
|
{
|
||||||
|
watching = (await ServiceAsync(ct).ConfigureAwait(false)).AutomaticWork;
|
||||||
|
}
|
||||||
|
|
||||||
|
wake = nextRound - clock.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
await SleepAsync(signal, watching, Min(wake, _env.MaxSleep), ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// After an automatic job: true when a pass must follow, because the job resumed runs (new files were not looked
|
||||||
|
/// for) or because it was stopped (Alberto's work, a change of destination, «Interrompi»: its runs are «interrotto»
|
||||||
|
/// with no error and resume by themselves). A job that simply ended needs nothing: a file that keeps giving nothing
|
||||||
|
/// to copy must not start a job after every job.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> NeedsFollowUpAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (_resumed)
|
||||||
|
{
|
||||||
|
_resumed = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||||
|
return unfinished.Any(r => r is { Origin: ExportRunOrigin.Automatic, Kind: ExportRunKind.Copy, LastError: null });
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_env.Log?.Invoke(AutoExportText.Error(ex));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Waits until a signal is given (from the first one, <see cref="AutoExportEnvironment.Settle"/> after the last one,
|
||||||
|
/// at most <see cref="AutoExportEnvironment.SettleLimit"/>), or an urgent one comes.
|
||||||
|
/// </summary>
|
||||||
|
private async Task SettleAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var clock = _env.Clock;
|
||||||
|
var limit = clock.Now + _env.SettleLimit;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var left = limit - clock.Now;
|
||||||
|
if (left <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var next = _env.Signal.Next();
|
||||||
|
using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
var delay = clock.Delay(Min(_env.Settle, left), wait.Token);
|
||||||
|
var first = await Task.WhenAny(next, delay).ConfigureAwait(false);
|
||||||
|
await wait.CancelAsync().ConfigureAwait(false);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
if (first != next || await next.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return; // settled, or urgent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sleeps until <paramref name="time"/> passes, a signal comes, or <paramref name="job"/> ends.</summary>
|
||||||
|
private async Task SleepAsync(Task<bool> signal, Task? job, TimeSpan time, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
var delay = _env.Clock.Delay(time > TimeSpan.Zero ? time : TimeSpan.Zero, wait.Token);
|
||||||
|
await (job is null ? Task.WhenAny(signal, delay) : Task.WhenAny(signal, delay, job)).ConfigureAwait(false);
|
||||||
|
await wait.CancelAsync().ConfigureAwait(false);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetNextRound(DateTimeOffset at)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_nextRound = at;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
||||||
|
}
|
||||||
@@ -112,6 +112,26 @@ public sealed partial class ExportService : IAsyncDisposable
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The automatic job running now (or the automatic start being planned) as a task that completes when it is over,
|
||||||
|
/// however it ends; a completed task when there is none. The worker waits on it instead of polling (tappa E5, D8).
|
||||||
|
/// </summary>
|
||||||
|
public Task AutomaticWork
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_job is { Automatic: true, Task.IsCompleted: false } job)
|
||||||
|
{
|
||||||
|
return job.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
return _startingAutomatic ? _automaticStartDone.Task : Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Until when «Interrompi» stopped the automatic copies (answer 53 of 4 December 2026); null when they are not held.
|
/// Until when «Interrompi» stopped the automatic copies (answer 53 of 4 December 2026); null when they are not held.
|
||||||
/// In memory only: after a restart the start-up round copies again.
|
/// In memory only: after a restart the start-up round copies again.
|
||||||
|
|||||||
@@ -101,6 +101,10 @@ public sealed record MediaSaveResult(MediaSaveOutcome Outcome, StoredFile? File,
|
|||||||
/// database update, probable duplicates (§9.5) and the <c>_febe.jsonl</c> line (§8.5).
|
/// database update, probable duplicates (§9.5) and the <c>_febe.jsonl</c> line (§8.5).
|
||||||
/// It never replaces or deletes a library file (rule 12): identical content is discarded, similar content is kept and
|
/// It never replaces or deletes a library file (rule 12): identical content is discarded, similar content is kept and
|
||||||
/// paired for Alberto's decision.
|
/// paired for Alberto's decision.
|
||||||
|
/// <para>
|
||||||
|
/// <c>autoExport</c>: the signal of the automatic export (tappa E5, D4), raised after each journal line;
|
||||||
|
/// null gives <see cref="AutoExportSignal.Default"/>, the application's.
|
||||||
|
/// </para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class LibraryIngest(
|
public sealed class LibraryIngest(
|
||||||
IFebeStorage storage,
|
IFebeStorage storage,
|
||||||
@@ -111,7 +115,8 @@ public sealed class LibraryIngest(
|
|||||||
ThumbnailStore? thumbnails = null,
|
ThumbnailStore? thumbnails = null,
|
||||||
PerceptualHashIndex? hashIndex = null,
|
PerceptualHashIndex? hashIndex = null,
|
||||||
bool setFileTimeToPublication = true,
|
bool setFileTimeToPublication = true,
|
||||||
SafeFileWriter? writer = null)
|
SafeFileWriter? writer = null,
|
||||||
|
AutoExportSignal? autoExport = null)
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// One gate per account folder, for every writer of the process: the §9.5 check «identical to a file of the
|
/// One gate per account folder, for every writer of the process: the §9.5 check «identical to a file of the
|
||||||
@@ -130,6 +135,7 @@ public sealed class LibraryIngest(
|
|||||||
private static readonly SemaphoreSlim PendingJournalGate = new(1, 1);
|
private static readonly SemaphoreSlim PendingJournalGate = new(1, 1);
|
||||||
|
|
||||||
private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength);
|
private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength);
|
||||||
|
private readonly AutoExportSignal _autoExport = autoExport ?? AutoExportSignal.Default;
|
||||||
private volatile LibraryNaming _naming = naming;
|
private volatile LibraryNaming _naming = naming;
|
||||||
private volatile bool _setFileTimeToPublication = setFileTimeToPublication;
|
private volatile bool _setFileTimeToPublication = setFileTimeToPublication;
|
||||||
private volatile LibraryLayout _layout = layout;
|
private volatile LibraryLayout _layout = layout;
|
||||||
@@ -376,6 +382,20 @@ public sealed class LibraryIngest(
|
|||||||
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
|
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
|
||||||
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
|
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
|
||||||
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// The automatic export (tappa E5, D4): the entry is settled once its line is written; the worker looks at the
|
||||||
|
// database a little later (a line kept for later signals when AppendPendingJournalAsync writes it).
|
||||||
|
_autoExport.Signal();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The entries whose <c>_febe.jsonl</c> line is still to write (<see cref="TryAppendJournalAsync"/>): the automatic
|
||||||
|
/// export leaves them out until their line is written (tappa E5, D4).
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<IReadOnlyList<long>> PendingJournalEntriesAsync(ISettingsStore settings, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
return ParsePendingJournal(await settings.GetAsync(PendingJournalKey, ct).ConfigureAwait(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -485,9 +505,11 @@ public sealed class LibraryIngest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<List<long>> ReadPendingJournalAsync()
|
private async Task<List<long>> ReadPendingJournalAsync() =>
|
||||||
|
ParsePendingJournal(await storage.Settings.GetAsync(PendingJournalKey, CancellationToken.None).ConfigureAwait(false));
|
||||||
|
|
||||||
|
private static List<long> ParsePendingJournal(string? text)
|
||||||
{
|
{
|
||||||
var text = await storage.Settings.GetAsync(PendingJournalKey, CancellationToken.None).ConfigureAwait(false);
|
|
||||||
var ids = new List<long>();
|
var ids = new List<long>();
|
||||||
foreach (var part in (text ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
foreach (var part in (text ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -129,6 +129,22 @@ public static class FebeWeb
|
|||||||
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
|
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
// The automatic export (tappa E5): registered always, started only by the composition's normal start (never in
|
||||||
|
// the demo, as the library conversion), stopped first at the end.
|
||||||
|
services.TryAddSingleton(sp =>
|
||||||
|
{
|
||||||
|
var logger = sp.GetService<ILoggerFactory>()?.CreateLogger("Febe.CopieAutomatiche");
|
||||||
|
return new AutoExportWorker(new AutoExportEnvironment
|
||||||
|
{
|
||||||
|
Storage = sp.GetRequiredService<IFebeStorage>(),
|
||||||
|
Clock = sp.GetRequiredService<IClock>(),
|
||||||
|
Service = ct => sp.GetRequiredService<ExportHub>().GetAsync(ct),
|
||||||
|
Session = sp.GetRequiredService<IEngineSessionState>(),
|
||||||
|
Gate = sp.GetRequiredService<LongWorkGate>(),
|
||||||
|
OtherWorkRunning = () => sp.GetRequiredService<StillVideoService>().Progress.Running,
|
||||||
|
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
|
||||||
|
});
|
||||||
|
});
|
||||||
services.AddHttpContextAccessor();
|
services.AddHttpContextAccessor();
|
||||||
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Tests.Desktop.Support;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Desktop;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The automatic export in the composition (tappa E5, D8): the worker runs only in a normal start (never with a
|
||||||
|
/// configuration problem; the demo never starts it), runs its start-up round at once, and the stop ends it first.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class AutoExportCompositionTests
|
||||||
|
{
|
||||||
|
public TestContext TestContext { get; set; } = null!;
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[Timeout(60_000, CooperativeCancellation = true)]
|
||||||
|
public async Task TheWorkerRunsInANormalStartAndTheStopEndsIt()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
AutoExportWorker worker;
|
||||||
|
await using (var bed = await DesktopTestBed.StartAsync())
|
||||||
|
{
|
||||||
|
Assert.IsEmpty(bed.App.Problems);
|
||||||
|
worker = bed.App.Web.Services.GetRequiredService<AutoExportWorker>();
|
||||||
|
var watch = Stopwatch.StartNew();
|
||||||
|
while ((await worker.StatusAsync(ct)).LastRound is null)
|
||||||
|
{
|
||||||
|
Assert.IsLessThan(TimeSpan.FromSeconds(30), watch.Elapsed, "the start-up round did not run");
|
||||||
|
await Task.Delay(20, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
var status = await worker.StatusAsync(ct);
|
||||||
|
Assert.IsTrue(status.Running);
|
||||||
|
Assert.IsFalse(status.AnyAutomatic, "«Automatica» is off by default");
|
||||||
|
Assert.AreEqual(status.LastRound + TimeSpan.FromHours(1), status.NextRound);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsFalse(worker.Running, "the stop ends the worker");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[Timeout(60_000, CooperativeCancellation = true)]
|
||||||
|
public async Task WithAStartupProblemTheWorkerDoesNotRun()
|
||||||
|
{
|
||||||
|
await using var bed = await DesktopTestBed.StartAsync(shell: new FakeDesktopShell { RuntimeVersion = null });
|
||||||
|
Assert.IsNotEmpty(bed.App.Problems);
|
||||||
|
var worker = bed.App.Web.Services.GetRequiredService<AutoExportWorker>();
|
||||||
|
await Task.Delay(200, TestContext.CancellationToken);
|
||||||
|
Assert.IsFalse(worker.Running);
|
||||||
|
Assert.IsNull((await worker.StatusAsync(TestContext.CancellationToken)).LastRound);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,880 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Library;
|
||||||
|
using Febe.Tests.Export.Support;
|
||||||
|
using Febe.Tests.Support;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The automatic export's worker (tappa E5, WP5, design §4.4), with the acceptance tests of §15: «Tolto» and «Superato»
|
||||||
|
/// are never copied again by themselves; an unreachable destination is paused and a later round resumes it; nothing is
|
||||||
|
/// copied during an engine session. Passes are driven one by one (<see cref="AutoExportWorker.RunOnceAsync"/>) or
|
||||||
|
/// through the loop with a <see cref="GatedClock"/>. Only the library and folders of the temporary bed are touched;
|
||||||
|
/// nothing contacts Instagram.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class AutoExportWorkerTests
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
public TestContext TestContext { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §15: a «Tolto» (A, found missing by «Controlla le copie»), a «Superato» (B, replaced the real way, its new file
|
||||||
|
/// signalled by its journal line) and a copy deleted without «Controlla le copie» (C) are never written again by
|
||||||
|
/// rounds or signal passes; «Copia di nuovo» by hand still writes A.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task RemovedAndSupersededAreNeverCopiedAgainByTheAutomaticExport()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
var a = await bed.PostAsync(bed.Luca, "a01", 1);
|
||||||
|
var b = await bed.PostAsync(bed.Luca, "b01", 2);
|
||||||
|
var c = await bed.PostAsync(bed.Luca, "c01", 3);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
foreach (var post in new[] { a, b, c })
|
||||||
|
{
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||||
|
}
|
||||||
|
|
||||||
|
await MakeRemovedAsync(bed, usb, a, ct);
|
||||||
|
var signals = bed.Signal.Count;
|
||||||
|
var newB = await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct);
|
||||||
|
Assert.IsGreaterThan(signals, bed.Signal.Count, "the new file's journal line signals the automatic export");
|
||||||
|
File.Delete(bed.GeneralCopy(bed.Luca, c.Media[0]));
|
||||||
|
var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||||
|
var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count;
|
||||||
|
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
{
|
||||||
|
bed.Clock.Now += TimeSpan.FromHours(1);
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.HasCount(copies.Count, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct), "no new copy row");
|
||||||
|
Assert.HasCount(runs, await bed.Db.Exports.ListRunsAsync(ct), "no new run");
|
||||||
|
Assert.IsEmpty((await bed.Db.Exports.ListCopiesBySha256Async(newB, ct)).Where(c => c.SourceSha256 == newB), "the replacement of a «Superato» is not copied");
|
||||||
|
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0])));
|
||||||
|
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, c.Media[0])));
|
||||||
|
|
||||||
|
// Control: «Copia di nuovo» by hand writes A.
|
||||||
|
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([a.Media[0].Id]), CopyAgain: true), ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The same through the loop: the start-up round copies, then hours of rounds and a signal write nothing.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task RemovedAndSupersededStayAsTheyAreThroughTheLoop()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
var a = await bed.PostAsync(bed.Luca, "a01", 1);
|
||||||
|
var b = await bed.PostAsync(bed.Luca, "b01", 2);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, b.Media[0]))), ct);
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
await MakeRemovedAsync(bed, usb, a, ct);
|
||||||
|
await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct);
|
||||||
|
var copies = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Count;
|
||||||
|
var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count;
|
||||||
|
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
var passes = worker.Passes;
|
||||||
|
clock!.Advance(TimeSpan.FromMinutes(2)); // the settle of the signal
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
for (var i = 0; i < 2; i++)
|
||||||
|
{
|
||||||
|
passes = worker.Passes;
|
||||||
|
clock.Advance(TimeSpan.FromHours(1));
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(copies, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Count);
|
||||||
|
Assert.AreEqual(runs, (await bed.Db.Exports.ListRunsAsync(ct)).Count);
|
||||||
|
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0])));
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Solo i nuovi» from before the replacement: the new file of B is new and due, and only its old copy's
|
||||||
|
/// «Superato» keeps it from being copied; a new post saved after the switch is copied.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task SupersededReplacementIsNotCopiedEvenWhenItIsNew()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
var b = await bed.PostAsync(bed.Luca, "b01", 2);
|
||||||
|
var usb = await bed.GeneralAsync(ct: ct);
|
||||||
|
await bed.CopyAccountAsync(bed.Luca, ct: ct);
|
||||||
|
bed.Clock.Now += TimeSpan.FromMinutes(1);
|
||||||
|
usb = await TurnOnAsync(bed, usb, onlyNew: true, ct);
|
||||||
|
Assert.IsNotNull(usb.AutomaticSince);
|
||||||
|
bed.Clock.Now += TimeSpan.FromMinutes(1);
|
||||||
|
var newB = await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct);
|
||||||
|
var fresh = await bed.PostAsync(bed.Luca, "n01", 5);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, fresh.Media[0])), "a new post is copied");
|
||||||
|
Assert.IsEmpty((await bed.Db.Exports.ListCopiesBySha256Async(newB, ct)).Where(c => c.SourceSha256 == newB), "the replacement of a «Superato» is never copied by itself");
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §15: an unreachable folder pauses the automatic run (one event, nothing created at the root); a round an hour
|
||||||
|
/// later finds it still away (no new event, no new run); once it is back the next round clears the pause and resumes
|
||||||
|
/// the same run, which completes with no <c>.part</c> left.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AnUnreachableDestinationPausesAndTheRoundResumesIt()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "u01", 1, 2);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
Directory.Move(bed.Usb, bed.Usb + "-staccata");
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single();
|
||||||
|
Assert.AreEqual((ExportRunOrigin.Automatic, ExportRunState.Paused), (run.Origin, run.State));
|
||||||
|
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||||
|
Assert.AreEqual(1, await PauseEventsAsync(bed, ct));
|
||||||
|
Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created");
|
||||||
|
|
||||||
|
bed.Clock.Now += TimeSpan.FromHours(1);
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
Assert.AreEqual(1, await PauseEventsAsync(bed, ct), "still away: no new event");
|
||||||
|
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct), "no new run while paused");
|
||||||
|
Assert.IsFalse(Directory.Exists(bed.Usb));
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct), "a signal pass leaves a paused folder alone");
|
||||||
|
|
||||||
|
Directory.Move(bed.Usb + "-staccata", bed.Usb);
|
||||||
|
bed.Clock.Now += TimeSpan.FromHours(1);
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
|
||||||
|
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State, "the same run resumed");
|
||||||
|
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])));
|
||||||
|
Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
|
||||||
|
Assert.AreEqual(1, await PauseEventsAsync(bed, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The same through the loop: the start-up round pauses, an hour later still away, then back: resumed.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AnUnreachableDestinationIsResumedByALaterRoundOfTheLoop()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "u01", 1);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
Directory.Move(bed.Usb, bed.Usb + "-staccata");
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
|
||||||
|
await WaitUntilAsync(async () => (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt is not null, ct);
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
var passes = worker.Passes;
|
||||||
|
clock!.Advance(TimeSpan.FromHours(1));
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||||
|
Assert.AreEqual(1, await PauseEventsAsync(bed, ct));
|
||||||
|
|
||||||
|
Directory.Move(bed.Usb + "-staccata", bed.Usb);
|
||||||
|
clock.Advance(TimeSpan.FromHours(1));
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.Db.Exports.ListRunsAsync(ct)).Single().State);
|
||||||
|
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||||
|
var status = await worker.StatusAsync(ct);
|
||||||
|
Assert.AreEqual((true, true, clock.Now, clock.Now + TimeSpan.FromHours(1)), (status.Running, status.AnyAutomatic, status.LastRound, status.NextRound));
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §15: (a) a signal during a session starts nothing and the status says why; (b) at its end a pass copies;
|
||||||
|
/// (c) a job that meets a session waits between files, an import displaces it, and once both are over a pass resumes
|
||||||
|
/// it. No library file is opened during a session.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task NoCopyDuringAnEngineSession()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
HeldExportFileSystem? held = null;
|
||||||
|
SessionRecordingFileSystem? files = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env =>
|
||||||
|
{
|
||||||
|
var library = env.Layout().Root;
|
||||||
|
held = new HeldExportFileSystem(p => p.EndsWith("_3.jpg", StringComparison.Ordinal));
|
||||||
|
files = new SessionRecordingFileSystem(env.Session, held, p => p.StartsWith(library, StringComparison.Ordinal));
|
||||||
|
return env with { FileSystem = files, Clock = new WaitingClock(env.Clock) };
|
||||||
|
});
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
// (a) A signal during a session.
|
||||||
|
bed.Session.InSession = true;
|
||||||
|
var first = await bed.PostAsync(bed.Luca, "s01", 1);
|
||||||
|
Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
Assert.AreEqual(AutoExportText.InSession, (await worker.StatusAsync(ct)).Waiting);
|
||||||
|
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct), "no run while the engine is in session");
|
||||||
|
|
||||||
|
// (b) The session ends: one pass copies.
|
||||||
|
bed.Session.InSession = false;
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, first.Media[0])));
|
||||||
|
|
||||||
|
// (c) A job of six files; the session starts while the third is read.
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "s02", 2, 3, 4, 5, 6, 7);
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await held!.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
bed.Session.InSession = true;
|
||||||
|
held.Release();
|
||||||
|
await WaitUntilAsync(async () => (await bed.Service.GetProgressAsync(ct)).Phase == ExportPhase.WaitingForSession, ct);
|
||||||
|
var run = (await bed.Db.Exports.ListRunsAsync(ct)).OrderBy(r => r.Id).Last();
|
||||||
|
|
||||||
|
var import = await bed.Gate.EnterAsync(LongWorkKind.Import, ct);
|
||||||
|
Assert.IsNotNull(import.Lease, "Alberto's import displaces the automatic copy waiting for the session");
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
var displaced = await bed.RunAsync(run.Id, ct);
|
||||||
|
Assert.AreEqual(ExportRunState.Interrupted, displaced.State);
|
||||||
|
Assert.IsNull(displaced.LastError, "displaced, not failed: any pass resumes it");
|
||||||
|
Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
import.Lease!.Dispose();
|
||||||
|
Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct), "still in session");
|
||||||
|
|
||||||
|
bed.Session.InSession = false;
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State, "the same run resumed");
|
||||||
|
foreach (var media in post.Media)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, media)), media.RelativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(0, files!.Violations, "no library file opened during a session");
|
||||||
|
Assert.IsNull(bed.Gate.Busy);
|
||||||
|
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An entry whose journal line is still to write is not copied; once the line is written (which signals) it is.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ANewFileIsCopiedOnlyAfterItsJournalLine()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
var entry = Make.Entry(bed.Luca.Id, "j01", Make.T0.AddDays(-1));
|
||||||
|
var file = ExportTestBed.Photo(1, 4);
|
||||||
|
var added = await bed.Db.Entries.AddAsync(entry, [file.Media], ct);
|
||||||
|
var media = added.Stored.Media.Single();
|
||||||
|
await bed.Library.Ingest.SaveMediaAsync(bed.Luca, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }, null, ct);
|
||||||
|
var journal = AccountJournal.PathFor(bed.Library.Layout.AccountFolder(bed.Luca));
|
||||||
|
var signals = bed.Signal.Count;
|
||||||
|
await using (new FileStream(journal, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(await bed.Library.Ingest.TryAppendJournalAsync(added.Stored.Entry.Id, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(signals, bed.Signal.Count, "no line, no signal");
|
||||||
|
CollectionAssert.AreEqual(new[] { added.Stored.Entry.Id }, (await LibraryIngest.PendingJournalEntriesAsync(bed.Db.Settings, ct)).ToArray());
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct), "held until its line is written");
|
||||||
|
|
||||||
|
Assert.AreEqual(0, await bed.Library.Ingest.AppendPendingJournalAsync(ct));
|
||||||
|
Assert.IsGreaterThan(signals, bed.Signal.Count, "the delayed line signals when it is written");
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
var stored = (await bed.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id, ct))!.Media.Single();
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, stored)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Solo i nuovi» leaves the files saved before the switch; «Copia anche quelli già in libreria» copies them.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task OnlyNewSkipsFilesSavedBeforeTheSwitch_AlsoAnswerCopiesThem()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
var old = await bed.PostAsync(bed.Luca, "o01", 1);
|
||||||
|
var usb = await bed.GeneralAsync(ct: ct);
|
||||||
|
bed.Clock.Now += TimeSpan.FromMinutes(1);
|
||||||
|
usb = await TurnOnAsync(bed, usb, onlyNew: true, ct);
|
||||||
|
bed.Clock.Now += TimeSpan.FromMinutes(1);
|
||||||
|
var fresh = await bed.PostAsync(bed.Luca, "o02", 2);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, fresh.Media[0])));
|
||||||
|
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, old.Media[0])), "saved before the switch");
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
|
||||||
|
// Off, then on with «Copia anche quelli già in libreria».
|
||||||
|
usb = (await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(usb) with { Automatic = false }, ct)).Destination;
|
||||||
|
await TurnOnAsync(bed, usb, onlyNew: false, ct);
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, old.Media[0])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Answer 50: every round tries every «Non riuscito» again, whatever the error; a signal pass leaves it.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task EveryRoundRetriesTheFailedCopies_ASignalPassDoesNot()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync();
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "f01", 1);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
await bed.Db.Exports.AddCopyAsync(
|
||||||
|
new ExportCopy
|
||||||
|
{
|
||||||
|
DestinationId = usb.Id,
|
||||||
|
AccountId = bed.Luca.Id,
|
||||||
|
MediaId = post.Media[0].Id,
|
||||||
|
SourceSha256 = post.Media[0].Sha256!,
|
||||||
|
Variant = ExportVariant.Whole,
|
||||||
|
State = ExportCopyState.Failed,
|
||||||
|
CopiedAt = Make.T0,
|
||||||
|
LastError = ExportText.Note(ExportText.Notes.PathTooLong),
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct), "even a «percorso troppo lungo»");
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One unfinished automatic run per destination: one stopped by an error is resumed only by the round, and meanwhile
|
||||||
|
/// the destination gets no other automatic run.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AnErroredAutomaticRunIsResumedOnlyByTheRound_AtMostOneUnfinishedRunPerDestination()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||||
|
await bed.PostAsync(bed.Luca, "e01", 1);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var run = await UnfinishedAutomaticRunAsync(bed, held, usb, "Errore di lettura o scrittura", ct);
|
||||||
|
var later = await bed.PostAsync(bed.Luca, "e02", 2);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct), "no second automatic run for the destination");
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||||
|
|
||||||
|
// The round resumed the run only: the next pass looks for the new files.
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, later.Media[0])));
|
||||||
|
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The start-up round resumes the automatic runs the last stop left «interrotto» (RecoverAsync), never a run of
|
||||||
|
/// Alberto's; and a manual «In pausa» stays paused when the round finds its folder back (answer 48).
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheStartupRoundResumesInterruptedAutomaticRunsButNotManualOnes()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "r01", 1);
|
||||||
|
await bed.PostAsync(bed.Marta, "r02", 2);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
|
||||||
|
var automatic = await UnfinishedAutomaticRunAsync(bed, held, usb, null, ct, ExportRunState.Running);
|
||||||
|
|
||||||
|
// A manual copy into Marta's folder paused because the folder went away.
|
||||||
|
Directory.Move(bed.Temp.Combine("marta-nas"), bed.Temp.Combine("marta-nas-via"));
|
||||||
|
var manual = (await bed.CopyAccountAsync(bed.Marta, ct: ct)).Runs.Single();
|
||||||
|
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State);
|
||||||
|
Directory.Move(bed.Temp.Combine("marta-nas-via"), bed.Temp.Combine("marta-nas"));
|
||||||
|
|
||||||
|
Assert.AreEqual(1, await bed.Service.RecoverAsync(ct), "the stop left the automatic run «in corso»");
|
||||||
|
var worker = Worker(bed);
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(automatic.Id, ct)).State);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||||
|
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(own.Id, ct))!.PausedAt, "the round found the folder back");
|
||||||
|
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State, "a manual «In pausa» stays Alberto's");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Interrompi» on an automatic copy holds the copies (at least an hour, answer 53); «Riprendi ora» releases them.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task InterruptHoldsUntilAtLeastAnHour_ResumeNowReleases()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "h01", 1, 2);
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
var until = await bed.Service.InterruptAsync(ct);
|
||||||
|
Assert.IsNotNull(until);
|
||||||
|
Assert.IsGreaterThanOrEqualTo(bed.Clock.Now + TimeSpan.FromHours(1), until.Value);
|
||||||
|
held.Release();
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.Held, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
Assert.AreEqual(until, (await worker.StatusAsync(ct)).HeldUntil);
|
||||||
|
bed.Clock.Now += TimeSpan.FromMinutes(59);
|
||||||
|
Assert.AreEqual(AutoExportPass.Held, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
|
||||||
|
var signals = bed.Signal.Count;
|
||||||
|
await worker.ResumeNowAsync(ct);
|
||||||
|
Assert.IsTrue(bed.Signal.Count > signals, "«Riprendi ora» wakes the worker at once");
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])));
|
||||||
|
Assert.AreEqual(ExportRunState.Completed, (await bed.Db.Exports.ListRunsAsync(ct)).Single().State, "the interrupted run resumed");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An import, a rebuild, a job of Alberto's and «Cerca i video fermi» come first: the worker waits and says why.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheWorkerWaitsForAnImportAManualJobAndTheStillVideoSearch()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "w01", 1);
|
||||||
|
await bed.PostAsync(bed.Marta, "w02", 2);
|
||||||
|
var usb = await bed.GeneralAsync(ct: ct);
|
||||||
|
var stills = false;
|
||||||
|
var worker = Worker(bed, other: () => stills);
|
||||||
|
await TurnOnAsync(bed, usb, onlyNew: false, ct);
|
||||||
|
|
||||||
|
Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Import, out var import, out _));
|
||||||
|
await AssertWaitingAsync(worker, AutoExportText.LongWork(LongWorkKind.Import), ct);
|
||||||
|
import.Dispose();
|
||||||
|
Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _));
|
||||||
|
await AssertWaitingAsync(worker, "Copie automatiche: aspettano la fine della ricostruzione.", ct);
|
||||||
|
rebuild.Dispose();
|
||||||
|
|
||||||
|
stills = true;
|
||||||
|
await AssertWaitingAsync(worker, AutoExportText.StillVideos, ct);
|
||||||
|
stills = false;
|
||||||
|
|
||||||
|
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
|
||||||
|
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
await AssertWaitingAsync(worker, AutoExportText.ManualJob, ct);
|
||||||
|
held.Release();
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
|
||||||
|
Assert.IsEmpty((await bed.Db.Exports.ListRunsAsync(ct)).Where(r => r.Origin == ExportRunOrigin.Automatic), "nothing started while waiting");
|
||||||
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
|
||||||
|
Assert.IsNull((await worker.StatusAsync(ct)).Waiting);
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A destination retired, or switched off, is never copied into, and its automatic runs are cancelled at the round.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task RetiredAndSwitchedOffDestinationsAreNeverAutomatic()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||||
|
await bed.PostAsync(bed.Marta, "x01", 1);
|
||||||
|
await bed.PostAsync(bed.Luca, "x02", 2);
|
||||||
|
var own = await TurnOnAsync(bed, await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct), onlyNew: false, ct);
|
||||||
|
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var run = await UnfinishedAutomaticRunAsync(bed, held, usb, null, ct);
|
||||||
|
await bed.Db.Exports.UpdateDestinationAsync(usb with { Automatic = false, AutomaticSince = null }, ct);
|
||||||
|
await bed.Service.Destinations.RetireAsync(own.Id, ct);
|
||||||
|
var worker = Worker(bed);
|
||||||
|
|
||||||
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
|
||||||
|
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State, "a ghost automatic run is cancelled by the round");
|
||||||
|
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
Assert.IsEmpty(Directory.GetFiles(bed.Usb, "*.jpg", SearchOption.AllDirectories));
|
||||||
|
Assert.IsEmpty(Directory.GetFiles(bed.Temp.Combine("marta-nas"), "*.jpg", SearchOption.AllDirectories));
|
||||||
|
Assert.IsFalse((await worker.StatusAsync(ct)).AnyAutomatic);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// After a non-urgent signal the pass waits for the settle (two minutes after the last file); an urgent one («Riprendi
|
||||||
|
/// ora», a destination turned on) needs no wait.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AnUrgentSignalSkipsTheSettle()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
|
||||||
|
var asked = clock!.Asked;
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "g01", 1);
|
||||||
|
var due = await clock.WaitForDelayAsync(asked, ct);
|
||||||
|
Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), due, "the settle");
|
||||||
|
var second = await bed.PostAsync(bed.Luca, "g02", 2);
|
||||||
|
await clock.WaitForDelayAsync(asked + 1, ct);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(1));
|
||||||
|
await Task.Delay(50, ct);
|
||||||
|
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])), "two minutes after the last file, not the first");
|
||||||
|
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
|
||||||
|
bed.Signal.Signal(urgent: true);
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, second.Media[0]))), ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A file saved while a pass's job is at work is copied by a pass after it: the signal is not lost.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ASignalDuringAPassIsNotLost()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal) && p.Contains("p01", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = held });
|
||||||
|
await bed.PostAsync(bed.Luca, "p01", 1);
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var started = clock!.Now;
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
await SleepingAsync(clock, ct);
|
||||||
|
|
||||||
|
var asked = clock.Asked;
|
||||||
|
var during = await bed.PostAsync(bed.Luca, "p02", 2);
|
||||||
|
Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), await clock.WaitForDelayAsync(asked, ct), "the settle");
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(2));
|
||||||
|
held.Release();
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, during.Media[0]))), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
Assert.AreEqual(started, (await worker.StatusAsync(ct)).LastRound, "copied by a signal pass, not by a round");
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A job displaced by Alberto's work is resumed by the loop once that work is over, without waiting for the round
|
||||||
|
/// (answer 49: «riparte da sola dopo»).
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AJobDisplacedByAnImportResumesWhenTheImportEnds()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = held });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "i01", 1, 2);
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var started = clock!.Now;
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
|
||||||
|
var import = await bed.Gate.EnterAsync(LongWorkKind.Import, ct);
|
||||||
|
Assert.IsNotNull(import.Lease);
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
held.Release();
|
||||||
|
var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single();
|
||||||
|
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State);
|
||||||
|
await WaitUntilAsync(async () => (await worker.StatusAsync(ct)).Waiting == AutoExportText.LongWork(LongWorkKind.Import), ct);
|
||||||
|
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
import.Lease!.Dispose();
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(5)); // the poll
|
||||||
|
await WaitUntilAsync(async () => (await bed.RunAsync(run.Id, ct)).State == ExportRunState.Completed, ct);
|
||||||
|
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])));
|
||||||
|
Assert.AreEqual(started, (await worker.StatusAsync(ct)).LastRound, "resumed when the import ended, not by a round");
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A job that ends normally starts no other by itself: a file that is in the database but no longer on disk gives a
|
||||||
|
/// run at the round, not a run after every run.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AFinishedJobStartsNoOtherByItself()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
var post = await bed.PostAsync(bed.Luca, "m01", 1);
|
||||||
|
File.Delete(bed.LibraryFile(bed.Luca, post.Media[0]));
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
|
||||||
|
await WaitUntilAsync(async () => (await bed.Db.Exports.ListRunsAsync(ct)).Count == 1, ct);
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
var passes = worker.Passes;
|
||||||
|
clock!.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
Assert.AreEqual(passes, worker.Passes, "no pass between rounds");
|
||||||
|
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>After a sleep of the PC the clock jumps: the round runs once, and the next is an hour after it.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ALateWakeAfterSleepRunsTheRound()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
|
||||||
|
var worker = Worker(bed, clock);
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
await IdleAsync(bed, worker, clock!, ct);
|
||||||
|
Assert.AreEqual(clock!.Now + TimeSpan.FromMinutes(5), clock.Pending.Single(), "never sleeps longer than five minutes");
|
||||||
|
|
||||||
|
var passes = worker.Passes;
|
||||||
|
clock.Advance(TimeSpan.FromHours(3));
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct);
|
||||||
|
await IdleAsync(bed, worker, clock, ct);
|
||||||
|
Assert.AreEqual(passes + 1, worker.Passes, "one round, not three");
|
||||||
|
var status = await worker.StatusAsync(ct);
|
||||||
|
Assert.AreEqual((clock.Now, clock.Now + TimeSpan.FromHours(1)), (status.LastRound, status.NextRound));
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An error of a pass is logged by type and the loop goes on; StopAsync ends it, and RunAsync does not throw.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheWorkerNeverThrowsOutOfRunAsync_StopAsyncEndsTheLoop()
|
||||||
|
{
|
||||||
|
var ct = TestContext.CancellationToken;
|
||||||
|
GatedClock? clock = null;
|
||||||
|
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
|
||||||
|
var logged = new List<string>();
|
||||||
|
var worker = new AutoExportWorker(Environment(bed, clock) with
|
||||||
|
{
|
||||||
|
Service = _ => throw new IOException("percorso segreto"),
|
||||||
|
Log = message =>
|
||||||
|
{
|
||||||
|
lock (logged)
|
||||||
|
{
|
||||||
|
logged.Add(message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
var loop = worker.RunAsync(ct);
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(Count(logged) == 1), ct);
|
||||||
|
await clock!.WaitForDelayAsync(0, ct);
|
||||||
|
clock.Advance(TimeSpan.FromHours(1));
|
||||||
|
await WaitUntilAsync(() => Task.FromResult(Count(logged) == 2), ct);
|
||||||
|
Assert.IsTrue(logged.All(m => m.Contains(nameof(IOException), StringComparison.Ordinal) && !m.Contains("segreto", StringComparison.Ordinal)), string.Join(" | ", logged));
|
||||||
|
Assert.IsTrue(worker.Running);
|
||||||
|
|
||||||
|
await worker.StopAsync();
|
||||||
|
await loop.WaitAsync(Patience, ct);
|
||||||
|
Assert.IsFalse(worker.Running);
|
||||||
|
Assert.IsFalse((await worker.StatusAsync(ct)).Running);
|
||||||
|
await Assert.ThrowsExactlyAsync<InvalidOperationException>(async () =>
|
||||||
|
{
|
||||||
|
var again = worker.RunAsync(ct);
|
||||||
|
var twice = worker.RunAsync(ct);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await twice;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await worker.StopAsync();
|
||||||
|
await again;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helpers -------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static AutoExportEnvironment Environment(ExportTestBed bed, IClock? clock = null, Func<bool>? other = null) => new()
|
||||||
|
{
|
||||||
|
Storage = bed.Db,
|
||||||
|
Clock = clock ?? bed.Environment.Clock,
|
||||||
|
Service = _ => Task.FromResult(bed.Service),
|
||||||
|
Signal = bed.Signal,
|
||||||
|
Session = bed.Session,
|
||||||
|
Gate = bed.Gate,
|
||||||
|
OtherWorkRunning = other ?? (() => false),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static AutoExportWorker Worker(ExportTestBed bed, IClock? clock = null, Func<bool>? other = null) => new(Environment(bed, clock, other));
|
||||||
|
|
||||||
|
/// <summary>«Automatica» on through the destinations (the dialog's answer: «Solo i nuovi» or «Copia anche quelli…»).</summary>
|
||||||
|
private static async Task<ExportDestination> TurnOnAsync(ExportTestBed bed, ExportDestination destination, bool onlyNew, CancellationToken ct) =>
|
||||||
|
(await bed.Service.Destinations.UpdateAsync(destination.Id, Spec(destination) with { Automatic = true, OnlyNew = onlyNew }, ct)).Destination;
|
||||||
|
|
||||||
|
private static DestinationSpec Spec(ExportDestination d) =>
|
||||||
|
new(d.Scope, d.AccountId, d.RootPath, d.Label, d.ContentTypes, d.NamingScheme, d.HighlightNamingScheme, d.ProfileNamingScheme, d.Automatic, d.AutomaticSince is not null, d.PhotoFormat, d.VideoFormat);
|
||||||
|
|
||||||
|
/// <summary>Deletes the copy of a post's first file and runs «Controlla le copie»: it becomes «Tolto».</summary>
|
||||||
|
private static async Task MakeRemovedAsync(ExportTestBed bed, ExportDestination usb, EntryWithMedia post, CancellationToken ct)
|
||||||
|
{
|
||||||
|
File.Delete(bed.GeneralCopy(bed.Luca, post.Media[0]));
|
||||||
|
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
var copy = (await bed.Db.Exports.ListCopiesBySha256Async(post.Media[0].Sha256!, ct)).Single();
|
||||||
|
Assert.AreEqual(ExportCopyState.Removed, copy.State);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Replaces a post's first library file the real way (ImportCopier's order): new bytes, the record, the supersession of
|
||||||
|
/// the old copies, the journal line (which signals). Returns the new SHA-256.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<string> ReplaceAsync(ExportTestBed bed, Account account, EntryWithMedia post, int scene, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var media = post.Media[0];
|
||||||
|
var bytes = ExportTestBed.Photo(1, scene).Bytes;
|
||||||
|
await File.WriteAllBytesAsync(bed.LibraryFile(account, media), bytes, ct);
|
||||||
|
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||||
|
await bed.Db.Media.MarkStoredAsync(media.Id, new StoredFile(media.RelativePath!, bytes.Length, sha, null, 96, 120, null, false), MediaState.Downloaded, bed.Clock.Now, ct);
|
||||||
|
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(bed.Db, account.Id, media.Sha256, sha, bed.Clock.Now, ct));
|
||||||
|
Assert.IsTrue(await bed.Library.Ingest.TryAppendJournalAsync(post.Entry.Id, ct));
|
||||||
|
return sha;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An automatic run of the destination left unfinished: started, stopped while it reads its first file (held), then
|
||||||
|
/// recorded with <paramref name="state"/> and <paramref name="error"/>; nothing was copied.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<ExportRun> UnfinishedAutomaticRunAsync(ExportTestBed bed, HeldExportFileSystem held, ExportDestination destination, string? error, CancellationToken ct, ExportRunState state = ExportRunState.Interrupted)
|
||||||
|
{
|
||||||
|
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([new(destination.Id, destination.AutomaticSince)], [], Round: true), ct);
|
||||||
|
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||||
|
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||||
|
Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct));
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
held.Release();
|
||||||
|
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||||
|
Assert.AreEqual(ExportRunState.Interrupted, run.State);
|
||||||
|
run = run with { State = state, LastError = error };
|
||||||
|
await bed.Db.Exports.UpdateRunAsync(run, ct);
|
||||||
|
Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(destination.Id, ct: ct));
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<int> PauseEventsAsync(ExportTestBed bed, CancellationToken ct) =>
|
||||||
|
(await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode);
|
||||||
|
|
||||||
|
private static async Task AssertWaitingAsync(AutoExportWorker worker, string because, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: true, ct), because);
|
||||||
|
Assert.AreEqual(because, (await worker.StatusAsync(ct)).Waiting);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Waits until no job runs and the worker sleeps on the clock after its last pass.</summary>
|
||||||
|
private static async Task IdleAsync(ExportTestBed bed, AutoExportWorker worker, GatedClock clock, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var watch = Stopwatch.StartNew();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
await bed.Service.WaitAsync(ct);
|
||||||
|
var passes = worker.Passes;
|
||||||
|
var asked = clock.Asked;
|
||||||
|
if (!bed.Service.IsBusy && clock.Pending.Count > 0)
|
||||||
|
{
|
||||||
|
await Task.Delay(50, ct);
|
||||||
|
if (worker.Passes == passes && clock.Asked == asked && !bed.Service.IsBusy && clock.Pending.Count > 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watch.Elapsed > Patience)
|
||||||
|
{
|
||||||
|
Assert.Fail("il lavoratore non si è fermato ad aspettare");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(10, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Waits until a delay waits on the clock and nothing more is asked for a moment (the worker sleeps).</summary>
|
||||||
|
private static async Task SleepingAsync(GatedClock clock, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var watch = Stopwatch.StartNew();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var asked = clock.Asked;
|
||||||
|
if (clock.Pending.Count > 0)
|
||||||
|
{
|
||||||
|
await Task.Delay(50, ct);
|
||||||
|
if (clock.Asked == asked && clock.Pending.Count > 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watch.Elapsed > Patience)
|
||||||
|
{
|
||||||
|
Assert.Fail("il lavoratore non dorme");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(10, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Count(List<string> list)
|
||||||
|
{
|
||||||
|
lock (list)
|
||||||
|
{
|
||||||
|
return list.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task WaitUntilAsync(Func<Task<bool>> done, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var watch = Stopwatch.StartNew();
|
||||||
|
while (!await done())
|
||||||
|
{
|
||||||
|
if (watch.Elapsed > Patience)
|
||||||
|
{
|
||||||
|
Assert.Fail("non è arrivato");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(10, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,9 @@ internal sealed class ExportTestBed : IAsyncDisposable
|
|||||||
|
|
||||||
public LongWorkGate Gate { get; }
|
public LongWorkGate Gate { get; }
|
||||||
|
|
||||||
|
/// <summary>The automatic export's signal of this bed: its journal lines and its destinations raise it.</summary>
|
||||||
|
public AutoExportSignal Signal => Library.AutoExport;
|
||||||
|
|
||||||
/// <summary>The folder of the general destination (created, empty).</summary>
|
/// <summary>The folder of the general destination (created, empty).</summary>
|
||||||
public string Usb => Temp.Combine("usb");
|
public string Usb => Temp.Combine("usb");
|
||||||
|
|
||||||
@@ -78,6 +81,7 @@ internal sealed class ExportTestBed : IAsyncDisposable
|
|||||||
Disk = disk,
|
Disk = disk,
|
||||||
Session = session,
|
Session = session,
|
||||||
Gate = gate,
|
Gate = gate,
|
||||||
|
AutoSignal = library.AutoExport,
|
||||||
};
|
};
|
||||||
return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate);
|
return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate);
|
||||||
}
|
}
|
||||||
@@ -178,6 +182,144 @@ internal sealed class WaitingClock(IClock inner) : IClock
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A clock whose delays end only when the test moves the time past them (<see cref="Advance"/>), shared by the worker
|
||||||
|
/// and the service in the loop tests of the automatic export (tappa E5). The time is the library's manual clock.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class GatedClock(ManualClock inner) : IClock
|
||||||
|
{
|
||||||
|
private readonly Lock _gate = new();
|
||||||
|
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _pending = [];
|
||||||
|
private long _asked;
|
||||||
|
|
||||||
|
public DateTimeOffset Now => inner.Now;
|
||||||
|
|
||||||
|
public TimeZoneInfo LocalZone => inner.LocalZone;
|
||||||
|
|
||||||
|
/// <summary>How many delays were asked so far.</summary>
|
||||||
|
public long Asked => Interlocked.Read(ref _asked);
|
||||||
|
|
||||||
|
/// <summary>When the delays waiting now end, earliest first.</summary>
|
||||||
|
public IReadOnlyList<DateTimeOffset> Pending
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
return [.. _pending.Select(p => p.Due).Order()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref _asked);
|
||||||
|
if (time <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var entry = (Now + time, done);
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_pending.Add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
ct.Register(() =>
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_pending.Remove(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
done.TrySetCanceled(ct);
|
||||||
|
});
|
||||||
|
return done.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Moves the time on and ends every delay that is due.</summary>
|
||||||
|
public void Advance(TimeSpan time)
|
||||||
|
{
|
||||||
|
List<TaskCompletionSource> due;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
inner.Now += time;
|
||||||
|
due = [.. _pending.Where(p => p.Due <= inner.Now).Select(p => p.Done)];
|
||||||
|
_pending.RemoveAll(p => p.Due <= inner.Now);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var done in due)
|
||||||
|
{
|
||||||
|
done.TrySetResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Waits (real time, at most 30 s) until more than <paramref name="asked"/> delays were asked and one waits.</summary>
|
||||||
|
public async Task<DateTimeOffset> WaitForDelayAsync(long asked, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (Asked > asked && Pending is [var first, ..])
|
||||||
|
{
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watch.Elapsed > TimeSpan.FromSeconds(30))
|
||||||
|
{
|
||||||
|
Assert.Fail("nessuna attesa sull'orologio");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(5, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file system of the copies, recording every file opened or hashed while an engine session is under way: the
|
||||||
|
/// automatic export never reads during a session (tappa E5, §15). Wraps another file system (the real one by default);
|
||||||
|
/// <c>watched</c> chooses the files that count (the library's, say).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class SessionRecordingFileSystem(IEngineSessionState session, IExportFileSystem? inner = null, Func<string, bool>? watched = null) : IExportFileSystem
|
||||||
|
{
|
||||||
|
private readonly IExportFileSystem _inner = inner ?? ExportFileSystem.Instance;
|
||||||
|
private int _violations;
|
||||||
|
|
||||||
|
/// <summary>Files opened or hashed during a session.</summary>
|
||||||
|
public int Violations => Volatile.Read(ref _violations);
|
||||||
|
|
||||||
|
public Stream OpenRead(string path)
|
||||||
|
{
|
||||||
|
Check(path);
|
||||||
|
return _inner.OpenRead(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream OpenRandomAccess(string path)
|
||||||
|
{
|
||||||
|
Check(path);
|
||||||
|
return _inner.OpenRandomAccess(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Check(path);
|
||||||
|
return _inner.ComputeSha256Async(path, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool FileExists(string path) => _inner.FileExists(path);
|
||||||
|
|
||||||
|
public long? FileLength(string path) => _inner.FileLength(path);
|
||||||
|
|
||||||
|
private void Check(string path)
|
||||||
|
{
|
||||||
|
if (session.InSession && (watched is null || watched(path)))
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref _violations);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>A mount table given by the test, on any platform (the longest mount point that holds the path wins).</summary>
|
/// <summary>A mount table given by the test, on any platform (the longest mount point that holds the path wins).</summary>
|
||||||
internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts
|
internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using Febe.Tests.Support;
|
using Febe.Tests.Support;
|
||||||
|
|
||||||
@@ -126,4 +127,52 @@ public sealed class LibraryIngestTests
|
|||||||
account, video.Stored.Entry, video.Stored.Media[0], new MediaContent { Content = new MemoryStream(new byte[10_000]), Extension = ".mp4", MaxBytes = 1000 }));
|
account, video.Stored.Entry, video.Stored.Media[0], new MediaContent { Content = new MemoryStream(new byte[10_000]), Extension = ".mp4", MaxBytes = 1000 }));
|
||||||
Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.mp4", SearchOption.AllDirectories));
|
Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.mp4", SearchOption.AllDirectories));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Tappa E5 (D4): each journal line wakes the automatic export; by default the application's signal.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AppendingTheJournalLineSignalsTheAutomaticExport()
|
||||||
|
{
|
||||||
|
using var temp = new TempFolder();
|
||||||
|
await using var library = await TestLibrary.CreateAsync(temp);
|
||||||
|
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||||
|
var before = library.AutoExport.Count;
|
||||||
|
|
||||||
|
var saved = await library.SaveAsync(account, Make.Entry(account.Id, "a1", Make.T0), [TestFile.Photo(1, 11, 64, 80)]);
|
||||||
|
Assert.AreEqual(before + 1, library.AutoExport.Count, "one line, one signal");
|
||||||
|
await library.Ingest.AppendJournalAsync(saved.Entry.Id);
|
||||||
|
Assert.AreEqual(before + 2, library.AutoExport.Count);
|
||||||
|
|
||||||
|
// Without a signal of its own, an ingest raises the application's.
|
||||||
|
var plain = new LibraryIngest(library.Db, library.Layout, LibraryNaming.Default, library.Journal, library.Clock);
|
||||||
|
var application = AutoExportSignal.Default.Count;
|
||||||
|
await plain.AppendJournalAsync(saved.Entry.Id);
|
||||||
|
Assert.IsGreaterThan(application, AutoExportSignal.Default.Count);
|
||||||
|
Assert.AreEqual(before + 2, library.AutoExport.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A line that cannot be written now signals nothing; it signals when it is written later.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ADelayedLineSignalsWhenItIsWritten()
|
||||||
|
{
|
||||||
|
using var temp = new TempFolder();
|
||||||
|
await using var library = await TestLibrary.CreateAsync(temp);
|
||||||
|
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||||
|
await library.SaveAsync(account, Make.Entry(account.Id, "a1", Make.T0), [TestFile.Photo(1, 11, 64, 80)]);
|
||||||
|
var file = TestFile.Photo(1, 12, 64, 80);
|
||||||
|
var added = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "a2", Make.T0), [file.Media]);
|
||||||
|
await library.Ingest.SaveMediaAsync(account, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension });
|
||||||
|
var before = library.AutoExport.Count;
|
||||||
|
|
||||||
|
await using (new FileStream(AccountJournal.PathFor(library.Layout.AccountFolder(account)), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(await library.Ingest.TryAppendJournalAsync(added.Stored.Entry.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(before, library.AutoExport.Count, "no line, no signal");
|
||||||
|
CollectionAssert.AreEqual(new[] { added.Stored.Entry.Id }, (await LibraryIngest.PendingJournalEntriesAsync(library.Db.Settings)).ToArray());
|
||||||
|
|
||||||
|
Assert.AreEqual(0, await library.Ingest.AppendPendingJournalAsync());
|
||||||
|
Assert.AreEqual(before + 1, library.AutoExport.Count);
|
||||||
|
Assert.IsEmpty(await LibraryIngest.PendingJournalEntriesAsync(library.Db.Settings));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using Febe.Data;
|
using Febe.Data;
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ internal sealed class TestLibrary : IAsyncDisposable
|
|||||||
Thumbnails = new ThumbnailStore(Data.Thumbnails);
|
Thumbnails = new ThumbnailStore(Data.Thumbnails);
|
||||||
Index = new PerceptualHashIndex();
|
Index = new PerceptualHashIndex();
|
||||||
Journal = new AccountJournal(clock);
|
Journal = new AccountJournal(clock);
|
||||||
Ingest = new LibraryIngest(db, Layout, LibraryNaming.Default, Journal, clock, Thumbnails, Index);
|
Ingest = new LibraryIngest(db, Layout, LibraryNaming.Default, Journal, clock, Thumbnails, Index, autoExport: AutoExport);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TempFolder Temp { get; }
|
public TempFolder Temp { get; }
|
||||||
@@ -38,6 +39,9 @@ internal sealed class TestLibrary : IAsyncDisposable
|
|||||||
|
|
||||||
public LibraryIngest Ingest { get; private set; }
|
public LibraryIngest Ingest { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The signal of the automatic export that this library's journal lines raise (its own: tests never wake each other).</summary>
|
||||||
|
public AutoExportSignal AutoExport { get; } = new();
|
||||||
|
|
||||||
public static async Task<TestLibrary> CreateAsync(TempFolder temp)
|
public static async Task<TestLibrary> CreateAsync(TempFolder temp)
|
||||||
{
|
{
|
||||||
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
|
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
|
||||||
@@ -67,7 +71,7 @@ internal sealed class TestLibrary : IAsyncDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
Db = await FebeDatabase.OpenAsync(Data.Root);
|
Db = await FebeDatabase.OpenAsync(Data.Root);
|
||||||
Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index);
|
Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index, autoExport: AutoExport);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
Reference in new issue
Block a user