E5: il servizio avvia, cede e ferma le copie automatiche
Il servizio delle copie impara le partenze automatiche: TryStartAutomaticAsync e TryResumeAutomaticAsync non lanciano mai eccezioni perché Febe è occupata (occupato, niente da fare senza prendere il cancello, ferme), registrano solo i file da scrivere, un lavoro per cartella, e prendono il cancello con il permesso che cede: «Copia in…», «Riprendi», «Controlla le copie» e «Riprova» lo spostano con EnterAsync e aspettano che abbia salvato i suoi stati. I cambi di cartella passano da ChangeDestinationAsync, serializzati con le partenze automatiche: spegnere «Automatica» ferma subito la copia automatica di quella cartella e annulla i suoi lavori (risposta 52); un lavoro automatico non finito non blocca più il cambio di cartella. La copia annulla da sé un lavoro automatico la cui cartella non è più automatica. «Interrompi» di una copia automatica la ferma per un'ora, in memoria, con «Riprendi ora» (risposta 53). La prova di «Riprova» guarda anche lo spazio per il prossimo file prima di togliere una pausa. «Copia automatica in … finita» solo se il lavoro ha fatto qualcosa (risposta 54). I «Non riuscito» restano candidati di ogni giro (risposta 50); il percorso troppo lungo ha la sua nota. La chiusura aspetta il lavoro al più 10 secondi. Il segnale parte dal nucleo quando una cartella si accende o prende più file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cfd0ef88d7
commit
0f69a01f88
10 files changed
+1872
-123
No files matched your search
@@ -680,3 +680,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-12-01 | Tappa E4, **seconda revisione dell'analisi** (sempre algoritmo 1: non è ancora uscito) e di ciò che le sta intorno. (a) `Offsets` = 0,54, 0,865, 0,417, 0,253, 0,432, 0,45, 0,46, trovati con una ricerca: di un filmato ripetuto da 1,9 a 40 volte, anche non un numero intero, i sette istanti abbracciano almeno il 49 % del giro (la prova chiede il 48 %); con quelli di prima il 28 %, e a quasi sette ripetizioni cadevano tutti insieme. Fra fotogrammi veri (18.054 coppie di numero di fotogrammi e periodo) i sette stanno entro mezzo giro in 5 casi (prima 820) ed entro il 40 % in nessuno (prima 338); il tratto più lungo non guardato è di 1,32 parti, il primo e l'ultimo istante restano lontani dalle estremità. Limite dichiarato: un'immagine mostrata per meno di metà giro può sfuggire. (b) Guadagno di una dissolvenza: per blocco il canale più forte non bruciato (non la luma: un blu puro ne ha poca), da 8 in su (`GainFloor`, era 16), almeno 10 blocchi (`GainBlocks`); mediana dei rapporti pesata sulla luce, e concordano se almeno metà della luce sta entro ±5 % (`GainAgreement` 0,1 in tutto) o 1,5 livelli, se sono di più (`GainNoise`); poi il rapporto fra le somme dei blocchi concordi; campo da 1/16 a 16 (`GainRange`, era 8). Prima con i soli blocchi non bruciati, poi con tutti, poi nessun guadagno. (c) Un fotogramma scuro fra due che non lo sono si confronta con l'ultimo chiaro (movimento con la media oltre 3 o l'area oltre il 15 %) e poi con la mediana, e non si sceglie mai. (d) Stesso colore: il canale più forte non bruciato del fotogramma più chiaro, guadagno entro 1/16–16, sul fotogramma come un blocco solo. (e) Un elemento «Fermo» di un lavoro tiene sempre lo SHA-256 sul quale il suo istante è stato scelto: registrarvi quello del file nuovo prima di scriverlo faceva credere, alla ripresa, che il file non fosse cambiato. (f) Anche ogni dialogo si chiude quando cambia la pagina sotto (`febe:pagina`), come se fosse annullato. Misure: 26 immagini × 11 dissolvenze × 2 grane, tutte «Fermo» (prima circa 150 no); scritta, marchio e banda sul nero, foto scure al 10, 14 e 18 %, cartello blu, dissolvenze da 0,5 a 2 s, sempre «Fermo» con D ≤ 0,59 e A 0; sfumature e scritte intorno alla soglia del nero con grana fino a ±10, mai «In movimento»; due immagini in un giro ripetuto circa 7 volte, sempre «In movimento». Resta «In movimento» ciò che ricomprime ogni fotogramma a blocchi 8 × 8 con passo da 8 in su, come prima | Un'immagine ferma su nero, un cartello blu o una foto scura che si dissolvono, o scure quanto la soglia, risultavano «In movimento», e un filmato di due immagini ripetuto circa 7 volte «Fermo»; «Salva il fotogramma» ripreso dopo una pausa salvava l'istante vecchio; una finestra aperta dal visualizzatore o dalla selezione restava sopra la pagina nuova, con i bottoni di ciò che non si vede più |
|
||||
| 2026-12-04 | Tappa E5, **risposte di Alberto del 4 dicembre 2026 alle domande 48–55 di §16**, date prima del codice. 48: una copia fatta a mano rimasta «In pausa» resta di Alberto anche quando il giro di recupero trova di nuovo la cartella: la Dashboard dice «la cartella risponde di nuovo, riprendi quando vuoi» e riparte solo con «Riprendi» o «Riprova». 49: la copia automatica cede sempre il passo a importazione, ricostruzione, «Copia in…», «Riprendi», «Riconosci le copie già presenti», zip di fotogrammi e «Cerca i video fermi», e riparte da sola dopo; mai durante una sessione del motore, e se era già partita aspetta senza bloccare nulla. 50 (**non la proposta**): ogni giro di recupero, all'avvio e ogni ora, riprova tutti i «Non riuscito» delle copie automatiche, anche quelli che non possono cambiare (oltre 4 GB su FAT32, percorso troppo lungo): niente classe di errori permanenti, niente ritmo giornaliero; fra un giro e l'altro, i passaggi che partono dopo un salvataggio in libreria non li riprovano. 51 (**non la proposta**): «Riconosci le copie già presenti» come proposto (file dovuti non «Copiato», percorso dello schema e «nome (2)»…«(50)», forma di adesso e originale, lunghezza e poi SHA-256, nessun file scritto o tolto, fotogrammi solo se già registrati), ma un «Tolto» resta «Tolto» anche se il file è tornato identico: non adotta mai un file, o un fotogramma, la cui ultima copia in quella cartella è «Tolto»; «Superato» e «Non riuscito» sì. 52: spegnere «Automatica» ferma subito la copia automatica di quella cartella; i file già copiati restano, le copie a mano non si toccano. 53: «Interrompi» su una copia automatica ferma le copie automatiche fino al giro di recupero dopo (almeno un'ora), con «Riprendi ora»; dopo un riavvio ripartono all'avvio. 54: un lavoro per cartella due minuti dopo l'ultimo file salvato, e comunque al giro; «Copia automatica in … finita» in cronologia solo se ha copiato qualcosa o qualcosa non è riuscito. 55: allargare ciò che spetta a una cartella automatica non chiede di nuovo: vale la scelta dell'accensione, e la finestra, la conferma o l'avviso dice quanti file in più partiranno. **Letture** che il progetto della tappa ha fatto di tre punti che sembravano in contrasto: (a) la riga del 27/11 sulle copie rimaste «In corso» («si riprendono dalla Dashboard, mai da sole») vale per le copie fatte a mano; i lavori automatici riprendono da soli (§4.10, «il giro orario riprova»); (b) «alla prima accensione» della risposta 6 del 18/11 vuol dire a ogni passaggio da spenta ad accesa, come dicono già la riga del 26/11 («la prossima accensione chiede di nuovo»), §4.10 e §8.3; (c) nella riga del 26/11 su «Solo i nuovi», `media.downloaded_at` non è «l'ora della riga di `_febe.jsonl`» ma l'ora in cui Febe ha salvato il file in libreria, scaricato o importato (`MediaStore`, `ImportCopier`), che la ricostruzione rimette dalla riga: «nuovo» vuol dire salvato in libreria dopo l'accensione, anche un file arrivato in ritardo (righe del 28/11) | Le domande 48–55 sono le scelte che la tappa E5 non poteva prendere da sola (§16); le tre letture tolgono contraddizioni solo apparenti fra specifica, decisioni e schema, senza cambiare nulla di deciso. 50: Alberto preferisce il lavoro ripetuto e i resoconti con gli stessi errori a una classe di errori da tenere aggiornata; fuori dal giro i «Non riuscito» aspettano perché ogni lavoro finito risveglia la copia automatica, e un file che non riesce mai farebbe un lavoro ogni due minuti invece che ogni ora. 51: un «Tolto» è una scelta di Alberto, che un file rimesso nella cartella non deve annullare |
|
||||
| 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 |
|
||||
@@ -52,10 +52,14 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
var destination = await store.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false);
|
||||
if (destination is null || destination.IsRetired)
|
||||
{
|
||||
run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = ExportText.RetiredDestination };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
|
||||
return run;
|
||||
return await CancelAsync(run, ExportText.RetiredDestination).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Tappa E5 (D7.5, answer 52): an automatic run goes on only while its destination is automatic. Retired and
|
||||
// orphan destinations are never automatic (CHECK of 0003), so this also covers them.
|
||||
if (run.Origin == ExportRunOrigin.Automatic && !destination.Automatic)
|
||||
{
|
||||
return await CancelAsync(run, ExportText.AutomaticTurnedOff).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
run = run with { State = ExportRunState.Running, LastError = null };
|
||||
@@ -121,21 +125,33 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false);
|
||||
run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = _env.Clock.Now,
|
||||
Code = "esportazione-completata",
|
||||
Message = ExportText.CompletionMessage(final, x.Destination),
|
||||
Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success,
|
||||
AccountId = x.Destination.AccountId,
|
||||
},
|
||||
none).ConfigureAwait(false);
|
||||
var automatic = run.Origin == ExportRunOrigin.Automatic;
|
||||
if (!automatic || ExportText.AutomaticRunIsWorthAnEvent(final))
|
||||
{
|
||||
// Answer 54: an automatic run that copied, adopted and failed nothing leaves no trace in the history.
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = _env.Clock.Now,
|
||||
Code = "esportazione-completata",
|
||||
Message = ExportText.CompletionMessage(final, x.Destination, automatic),
|
||||
Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success,
|
||||
AccountId = x.Destination.AccountId,
|
||||
},
|
||||
none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
|
||||
x.ByState = new Dictionary<ExportItemState, int>(final.ByState);
|
||||
x.Report(_env, ExportPhase.Finished, null);
|
||||
return run;
|
||||
}
|
||||
catch (AutomaticTurnedOffException)
|
||||
{
|
||||
// Between two files: nothing is half written. The files done stay copied (answer 52).
|
||||
x.Report(_env, ExportPhase.Finished, null);
|
||||
return await CancelAsync(run, ExportText.AutomaticTurnedOff).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested;
|
||||
@@ -178,18 +194,49 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
return problem;
|
||||
}
|
||||
|
||||
/// <summary>Before a file: the probe at the start of each group, then the wait for the end of an engine session.</summary>
|
||||
/// <summary>
|
||||
/// Before a file: the probe at the start of each group, then the wait for the end of an engine session. At the start
|
||||
/// of each group an automatic run also looks whether its destination is still automatic (tappa E5, D7.5): if not it
|
||||
/// ends «annullato» (<see cref="AutomaticTurnedOffException"/>).
|
||||
/// </summary>
|
||||
private async Task<string?> BeforeItemAsync(RunContext x, CancellationToken ct)
|
||||
{
|
||||
if (x.GroupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
|
||||
if (x.GroupFiles == 0)
|
||||
{
|
||||
return problem;
|
||||
if (x.Run.Origin == ExportRunOrigin.Automatic
|
||||
&& await _env.Storage.Exports.GetDestinationAsync(x.Destination.Id, ct).ConfigureAwait(false) is not { Automatic: true })
|
||||
{
|
||||
throw new AutomaticTurnedOffException();
|
||||
}
|
||||
|
||||
if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
|
||||
{
|
||||
return problem;
|
||||
}
|
||||
}
|
||||
|
||||
await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A run that cannot go on (its destination was retired, or is no longer automatic) becomes «annullato».</summary>
|
||||
private async Task<ExportRun> CancelAsync(ExportRun run, string reason)
|
||||
{
|
||||
run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = reason };
|
||||
await _env.Storage.Exports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>The destination of an automatic run was switched off (or retired) while the run worked on it.</summary>
|
||||
private sealed class AutomaticTurnedOffException : Exception
|
||||
{
|
||||
public AutomaticTurnedOffException()
|
||||
: base(ExportText.AutomaticTurnedOff)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The counts of one finished item: progress, states, and the group of the probe.</summary>
|
||||
private void Account(RunContext x, ItemResult result)
|
||||
{
|
||||
@@ -816,7 +863,8 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
}
|
||||
catch (PathTooLongException ex)
|
||||
{
|
||||
return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false);
|
||||
// «Non riuscito» like any other failure: the next recovery round retries it (answer 50 of 4 December 2026).
|
||||
return await FailAsync(item, file, failed, ex.Message, ExportText.Notes.PathTooLong).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_env.Disk.MaxFileBytes(root) is { } max && output.Length > max)
|
||||
@@ -1369,6 +1417,10 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
current,
|
||||
ExportDestinations.Label(Destination),
|
||||
new Dictionary<ExportItemState, int>(ByState),
|
||||
env.Clock.Now));
|
||||
env.Clock.Now)
|
||||
{
|
||||
Kind = Run.Kind,
|
||||
Origin = Run.Origin,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ namespace Febe.Core.Export;
|
||||
/// <param name="NamingScheme">General scheme; null: «Come la libreria».</param>
|
||||
/// <param name="HighlightNamingScheme">Scheme of highlight collections; null: «Come la libreria».</param>
|
||||
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
|
||||
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
|
||||
/// <param name="Automatic">«Automatica»: the files due here are copied by themselves (tappa E5, the automatic export).</param>
|
||||
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
|
||||
/// <param name="PhotoFormat">Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).</param>
|
||||
/// <param name="VideoFormat">Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».</param>
|
||||
@@ -129,7 +129,9 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
var row = Build(spec, full, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
|
||||
try
|
||||
{
|
||||
return new DestinationSaveResult(await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false), warnings);
|
||||
var added = await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false);
|
||||
SignalIf(added.Automatic);
|
||||
return new DestinationSaveResult(added, warnings);
|
||||
}
|
||||
catch (DuplicateRecordException)
|
||||
{
|
||||
@@ -187,6 +189,9 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
LastError = stored.LastError,
|
||||
};
|
||||
await exports.UpdateDestinationAsync(updated, ct).ConfigureAwait(false);
|
||||
|
||||
// Turned on, or more types while on (answer 55: no new question, the same «da quando»).
|
||||
SignalIf(updated.Automatic && (!stored.Automatic || (updated.ContentTypes & ~stored.ContentTypes) != ContentTypes.None));
|
||||
return new DestinationSaveResult(updated, warnings);
|
||||
}
|
||||
|
||||
@@ -201,7 +206,9 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
// Two transactions, as the store wants: the old folder is retired with its copies, then the new one is added.
|
||||
await exports.RetireDestinationAsync(id, now, CancellationToken.None).ConfigureAwait(false);
|
||||
var row = Build(spec, newFolder, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
|
||||
return new DestinationSaveResult(await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false), warnings);
|
||||
var moved = await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false);
|
||||
SignalIf(moved.Automatic);
|
||||
return new DestinationSaveResult(moved, warnings);
|
||||
}
|
||||
|
||||
/// <summary>«Togli la cartella»: only the configuration goes; copies and files stay (<see cref="RetiredText"/>).</summary>
|
||||
@@ -217,6 +224,9 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
|
||||
await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false);
|
||||
await _env.Storage.Exports.RetireDestinationAsync(id, _env.Clock.Now, ct).ConfigureAwait(false);
|
||||
|
||||
// Without its own folder an account's files go to the general folder, which may be automatic.
|
||||
SignalIf(stored.Scope == ExportScope.Account);
|
||||
}
|
||||
|
||||
/// <summary>«Esporta questo account».</summary>
|
||||
@@ -225,6 +235,7 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
{
|
||||
_ = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Account {accountId} non trovato.");
|
||||
await _env.Storage.Exports.SetAccountExportEnabledAsync(accountId, enabled, ct).ConfigureAwait(false);
|
||||
SignalIf(enabled);
|
||||
}
|
||||
|
||||
/// <summary>Checks a folder for the dialog, before saving (WP1.3).</summary>
|
||||
@@ -388,15 +399,29 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job Alberto started (or resumed) towards the destination blocks a change of folder and «Togli la cartella».
|
||||
/// Automatic runs do not (tappa E5, D7.4): <c>ExportService.ChangeDestinationAsync</c> stops them before the change
|
||||
/// and cancels them after it, and the copier cancels one whose destination is no longer automatic.
|
||||
/// </summary>
|
||||
private async Task EnsureNoUnfinishedRunAsync(long destinationId, CancellationToken ct)
|
||||
{
|
||||
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||
if (unfinished.Any(r => r.DestinationId == destinationId))
|
||||
if (unfinished.Any(r => r.DestinationId == destinationId && r.Origin != ExportRunOrigin.Automatic))
|
||||
{
|
||||
throw new InvalidOperationException(UnfinishedRunText);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wakes the automatic export at once (no settle wait): what goes by itself may have grown.</summary>
|
||||
private void SignalIf(bool grew)
|
||||
{
|
||||
if (grew)
|
||||
{
|
||||
_env.AutoSignal.Signal(urgent: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static ExportDestination Build(DestinationSpec spec, string root, DateTimeOffset createdAt) => new()
|
||||
{
|
||||
Scope = spec.Scope,
|
||||
|
||||
@@ -65,6 +65,12 @@ public sealed record ExportEnvironment
|
||||
/// <summary>One conversion at a time in the process (tappa E3, D16): shared with the library conversion.</summary>
|
||||
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Woken when what goes by itself may have grown (tappa E5, D3/D4): «Automatica» turned on, types added, a folder
|
||||
/// changed or removed, «Esporta questo account» turned on (<see cref="ExportDestinations"/>). Tests give their own instance.
|
||||
/// </summary>
|
||||
public AutoExportSignal AutoSignal { get; init; } = AutoExportSignal.Default;
|
||||
|
||||
/// <summary>The checker of destination folders of this environment.</summary>
|
||||
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
@@ -204,8 +205,40 @@ public sealed record ExportProgress(
|
||||
public double Fraction => BytesTotal > 0
|
||||
? Math.Clamp((double)BytesDone / BytesTotal, 0, 1)
|
||||
: FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0;
|
||||
|
||||
/// <summary>
|
||||
/// The kind of <see cref="RunId"/>'s run (tappa E5, D7.8): taken from the run being worked on, not from the job; null
|
||||
/// for «Controlla le copie» and before a run is reached.
|
||||
/// </summary>
|
||||
public ExportRunKind? Kind { get; init; }
|
||||
|
||||
/// <summary>Who started <see cref="RunId"/>'s run: an automatic run resumed with «Riprendi» stays automatic here.</summary>
|
||||
public ExportRunOrigin? Origin { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What an automatic start did (tappa E5, D7): never an exception because Febe is busy.</summary>
|
||||
public enum AutoExportStartOutcome
|
||||
{
|
||||
/// <summary>A job started: <see cref="AutoExportStart.Runs"/> are its runs.</summary>
|
||||
Started,
|
||||
|
||||
/// <summary>Nothing to copy (or to resume): no lease was taken, no run recorded.</summary>
|
||||
NothingToDo,
|
||||
|
||||
/// <summary>
|
||||
/// Something else comes first: a job, an engine session, a change of destination, other long work
|
||||
/// (<see cref="AutoExportStart.BusyWith"/>), or Alberto's work displaced the start while it planned.
|
||||
/// </summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>«Interrompi» stopped the automatic copies until <c>ExportService.AutomaticHeldUntil</c> (answer 53).</summary>
|
||||
Held,
|
||||
}
|
||||
|
||||
/// <summary>The answer of <c>ExportService.TryStartAutomaticAsync</c> and <c>TryResumeAutomaticAsync</c>.</summary>
|
||||
/// <param name="BusyWith">The long work that holds the gate, when that is why the start is <see cref="AutoExportStartOutcome.Busy"/>.</param>
|
||||
public sealed record AutoExportStart(AutoExportStartOutcome Outcome, IReadOnlyList<ExportRun> Runs, LongWorkKind? BusyWith = null);
|
||||
|
||||
/// <summary>What <c>ExportService.StartAsync</c> did: one run per destination (D6), and the plan it followed.</summary>
|
||||
public sealed record ExportStart(IReadOnlyList<ExportRun> Runs, ExportPlan Plan);
|
||||
|
||||
|
||||
@@ -41,6 +41,19 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(request.Selection, nameof(request));
|
||||
|
||||
// Tappa E5 (D5): the automatic selection is the automatic export's alone, in the destinations' own forms, never
|
||||
// «Copia di nuovo»; and an automatic run plans only the automatic selection.
|
||||
if (request.Selection is ExportSelection.Automatic != (request.Origin == ExportRunOrigin.Automatic))
|
||||
{
|
||||
throw new ArgumentException("Le copie automatiche si chiedono solo dalla copia automatica.", nameof(request));
|
||||
}
|
||||
|
||||
if (request.Selection is ExportSelection.Automatic && (request.CopyAgain || request.Formats is not null || request.Frames is not null || request.Exact is not null))
|
||||
{
|
||||
throw new ArgumentException("Una copia automatica non ricopia «Tolti» e «Superati» e usa i formati della cartella.", nameof(request));
|
||||
}
|
||||
|
||||
if (request.Frames is not null && request.Formats is not null)
|
||||
{
|
||||
throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request));
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -177,8 +177,11 @@ public static class ExportText
|
||||
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
|
||||
public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many;
|
||||
|
||||
/// <summary>The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.»</summary>
|
||||
public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination)
|
||||
/// <summary>
|
||||
/// The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.»; for an automatic
|
||||
/// run (tappa E5) «Copia automatica in Disco USB finita: …».
|
||||
/// </summary>
|
||||
public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination, bool automatic = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
@@ -204,9 +207,41 @@ public static class ExportText
|
||||
parts.Add(Count(Of(ExportItemState.Failed), "non riuscito", "non riusciti"));
|
||||
}
|
||||
|
||||
return $"Copia in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}.";
|
||||
return $"{(automatic ? "Copia automatica" : "Copia")} in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the end of an automatic run is worth an event (answer 54 of 4 December 2026): only when it copied or
|
||||
/// adopted something, or something did not succeed. A run that only found files already copied leaves no trace.
|
||||
/// </summary>
|
||||
public static bool AutomaticRunIsWorthAnEvent(ExportRunSummary summary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
return summary.ByState.GetValueOrDefault(ExportItemState.Copied)
|
||||
+ summary.ByState.GetValueOrDefault(ExportItemState.Adopted)
|
||||
+ summary.ByState.GetValueOrDefault(ExportItemState.Failed) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why an automatic run was cancelled (tappa E5, answer 52): its destination was switched off, retired, or lost its
|
||||
/// account meanwhile. The copies made stay.
|
||||
/// </summary>
|
||||
public const string AutomaticTurnedOff = "«Automatica» è stata spenta: i file rimasti non si copiano da soli.";
|
||||
|
||||
/// <summary>
|
||||
/// The answer to «Interrompi» of an automatic copy (answer 53): what was copied stays, and the automatic copies wait
|
||||
/// until <paramref name="until"/> («Riprendi ora» before).
|
||||
/// </summary>
|
||||
public static string AutomaticInterrupted(DateTimeOffset until, TimeZoneInfo zone) =>
|
||||
$"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle {ItalianText.Clock(until, zone)}.";
|
||||
|
||||
/// <summary>
|
||||
/// A paused destination still without room for the next file of its paused job (tappa E5, D11): the pause stays.
|
||||
/// </summary>
|
||||
public static string NoSpaceForNext(ExportDestination destination, long free, long bytes) =>
|
||||
$"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per il prossimo file ({ItalianText.Bytes(bytes)}) serve più spazio, "
|
||||
+ $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi.";
|
||||
|
||||
/// <summary>The event of «Controlla le copie».</summary>
|
||||
public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination)
|
||||
{
|
||||
|
||||
@@ -213,34 +213,61 @@ public sealed class ExportDestinationsTests
|
||||
Assert.AreEqual(ContentTypes.Tagged, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tappa E5 (D3, D4): turning «Automatica» on, adding types while on, removing an own folder and turning
|
||||
/// «Esporta questo account» on wake the automatic export at once (an urgent signal); the save itself copies nothing
|
||||
/// and records no job (the worker's pass does). «Da quando» is kept while on, forgotten when off.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AutomaticIsStoredButNothingIsQueued()
|
||||
public async Task TurningAutomaticOnSignalsTheAutomaticExport()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var signal = new AutoExportSignal();
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { AutoSignal = signal });
|
||||
await bed.PostAsync(bed.Marta, "920", 1);
|
||||
var spec = new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.All, null, null, null, Automatic: true, OnlyNew: true);
|
||||
var spec = new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.PostPhotos, null, null, null, Automatic: true, OnlyNew: true);
|
||||
var next = signal.Next();
|
||||
var saved = (await bed.Service.Destinations.CreateAsync(spec, ct)).Destination;
|
||||
var stored = (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!;
|
||||
Assert.IsTrue(stored.Automatic);
|
||||
Assert.AreEqual(Make.T0, stored.AutomaticSince);
|
||||
Assert.AreEqual(1, signal.Count);
|
||||
Assert.IsTrue(await next, "turned on: urgent, no settle wait");
|
||||
|
||||
// Tappa E2 does not act on it: no job, nothing written, nothing running.
|
||||
// The save copies nothing by itself: no job, nothing written, nothing running.
|
||||
Assert.IsFalse(bed.Service.IsBusy);
|
||||
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||
Assert.IsEmpty(Directory.GetFileSystemEntries(bed.Usb));
|
||||
|
||||
// Still on: «da quando» is kept; off: it goes; on with «tutti»: no date.
|
||||
// Still on: «da quando» is kept, and a new label wakes nothing; off: it goes; on with «tutti»: no date.
|
||||
bed.Clock.Now = Make.T0.AddDays(3);
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Label = "Disco" }, ct);
|
||||
Assert.AreEqual(Make.T0, (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince);
|
||||
Assert.AreEqual(1, signal.Count);
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct);
|
||||
Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: false, AutomaticSince: null });
|
||||
Assert.AreEqual(1, signal.Count, "turned off: nothing to wake");
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { OnlyNew = false }, ct);
|
||||
Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: true, AutomaticSince: null });
|
||||
Assert.AreEqual(2, signal.Count);
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct);
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec, ct);
|
||||
Assert.AreEqual(Make.T0.AddDays(3), (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince);
|
||||
Assert.AreEqual(3, signal.Count);
|
||||
|
||||
// A type added while on (answer 55: no new question), an own folder removed, an account switched on again.
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { ContentTypes = ContentTypes.PostPhotos | ContentTypes.Stories }, ct);
|
||||
Assert.AreEqual(4, signal.Count);
|
||||
await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { ContentTypes = ContentTypes.Stories }, ct);
|
||||
Assert.AreEqual(4, signal.Count, "fewer types: nothing new goes");
|
||||
var own = await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct);
|
||||
Assert.AreEqual(4, signal.Count, "an own folder without «Automatica»");
|
||||
await bed.Service.Destinations.RetireAsync(own.Id, ct);
|
||||
Assert.AreEqual(5, signal.Count);
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Luca.Id, false, ct);
|
||||
Assert.AreEqual(5, signal.Count);
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Luca.Id, true, ct);
|
||||
Assert.AreEqual(6, signal.Count);
|
||||
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,921 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Export.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The service side of the automatic export (tappa E5, WP3, design §4.3): automatic starts that never throw because Febe
|
||||
/// is busy and record only files to write; Alberto's work that displaces them; changes of destination serialised with
|
||||
/// them; the copier's safety net; «Interrompi» and its hold (answer 53); the probe of a space pause; the bounded stop.
|
||||
/// Only the library and folders of the temporary bed are touched; nothing contacts Instagram.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ExportServiceAutomaticTests
|
||||
{
|
||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
/// <summary>An automatic job records only the files it writes: no «già copiato», no «Tolto», one run per destination.</summary>
|
||||
[TestMethod]
|
||||
public async Task TryStartAutomaticRecordsOnlyFilesToCopy_NoAlreadyCopiedItems()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Luca, "a01", 1, 2, 3);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id, post.Media[1].Id])), ct);
|
||||
File.Delete(bed.GeneralCopy(bed.Luca, post.Media[1]));
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: false), ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||
var run = start.Runs.Single();
|
||||
Assert.AreEqual((ExportRunOrigin.Automatic, ExportRunKind.Copy, ExportRunState.Completed), (run.Origin, run.Kind, (await bed.RunAsync(run.Id, ct)).State));
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.AreEqual(post.Media[2].Id, items.Single().MediaId, "only the file not copied: not the copied one, not the «Tolto» one");
|
||||
Assert.AreEqual(ExportItemState.Copied, items.Single().State);
|
||||
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])), "«Tolto» is never copied again by itself");
|
||||
|
||||
// Nothing left: no lease, no run.
|
||||
var again = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, again.Outcome);
|
||||
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct), "«Controlla le copie» has no run");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// With «Copia anche quelli già in libreria» an automatic round copies exactly what «Copia in…» of the whole library
|
||||
/// would write, folder by folder (two folders, a type not taken, an account switched off, copied, «Tolto», «Non
|
||||
/// riuscito», the same bytes twice).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AutomaticAllCopiesExactlyWhatCopyInWouldWrite()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var anna = await bed.Db.Accounts.AddAsync(Make.Account("anna.demo", "300"), ct);
|
||||
var a = await bed.PostAsync(bed.Luca, "m01", 1, 2);
|
||||
var b = await bed.PostAsync(bed.Luca, "m02", 3);
|
||||
var c = await bed.PostAsync(bed.Luca, "m03", 4);
|
||||
var d = await bed.PostAsync(bed.Luca, "m04", 5);
|
||||
await bed.PostAsync(bed.Luca, "m05", 1);
|
||||
await bed.PostAsync(bed.Marta, "m06", 6, 7);
|
||||
await bed.PostAsync(anna, "m07", 8);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ContentTypes.PostPhotos, ct);
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(anna.Id, false, ct);
|
||||
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([b.Media[0].Id, c.Media[0].Id])), ct);
|
||||
File.Delete(bed.GeneralCopy(bed.Luca, c.Media[0]));
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
await bed.Db.Exports.AddCopyAsync(
|
||||
new ExportCopy
|
||||
{
|
||||
DestinationId = usb.Id,
|
||||
AccountId = bed.Luca.Id,
|
||||
MediaId = d.Media[0].Id,
|
||||
SourceSha256 = d.Media[0].Sha256!,
|
||||
Variant = ExportVariant.Whole,
|
||||
State = ExportCopyState.Failed,
|
||||
CopiedAt = Make.T0,
|
||||
LastError = "Errore di lettura o scrittura: prova",
|
||||
},
|
||||
ct);
|
||||
var general = await TurnOnAsync(bed, usb, ct);
|
||||
var marta = await TurnOnAsync(bed, own, ct);
|
||||
var planned = await PlannedWritesAsync(bed, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true), ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||
CollectionAssert.AreEquivalent(new[] { usb.Id, own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
|
||||
foreach (var run in start.Runs)
|
||||
{
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.IsTrue(items.All(i => i.State == ExportItemState.Copied), string.Join(", ", items.Select(i => i.State)));
|
||||
var written = items.Select(i => (i.AccountId!.Value, i.SourceSha256!)).ToHashSet();
|
||||
Assert.IsTrue(planned[run.DestinationId].SetEquals(written), $"{run.DestinationId}: {string.Join(", ", written)}");
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[1])));
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, d.Media[0])), "«Non riuscito» is retried by the round");
|
||||
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, c.Media[0])), "«Tolto» stays «Tolto»");
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "anna.demo")), "«Esporta questo account» off");
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true), ct)).Outcome);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Una copia sola»: the same bytes of two accounts, both new, are one file to write; the second is not even recorded
|
||||
/// as «già copiato» (the skip list of D5), and the next pass finds nothing.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task WithOneCopyOnlyTheSameBytesOfTwoAccountsAreOneItem()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
|
||||
var luca = await bed.PostAsync(bed.Luca, "o01", 1);
|
||||
await bed.PostAsync(bed.Marta, "o02", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
|
||||
Assert.AreEqual((luca.Media[0].Id, ExportItemState.Copied), (item.MediaId!.Value, item.State));
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
}
|
||||
|
||||
/// <summary>A «Non riuscito» waits for the recovery round, and every round retries it whatever the error (answer 50).</summary>
|
||||
[TestMethod]
|
||||
public async Task AFailedCopyIsRetriedByTheRoundNotByASignalPass()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Luca, "f01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: 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 = "Più grande di 4 GB",
|
||||
},
|
||||
ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: false), ct)).Outcome);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||
}
|
||||
|
||||
/// <summary>A busy Febe gives Busy, never an exception, and records nothing; Held while «Interrompi» holds.</summary>
|
||||
[TestMethod]
|
||||
public async Task TryStartAutomaticReturnsBusyInsteadOfThrowing()
|
||||
{
|
||||
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, "b01", 1, 2);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var selection = Selection(auto, round: true);
|
||||
|
||||
// A job of Alberto's.
|
||||
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
await AssertBusyAsync(bed, selection, null, ct);
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count;
|
||||
|
||||
// An import holding the gate.
|
||||
Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Import, out var import, out _));
|
||||
await AssertBusyAsync(bed, selection, LongWorkKind.Import, ct);
|
||||
import.Dispose();
|
||||
|
||||
// An engine session.
|
||||
bed.Session.InSession = true;
|
||||
await AssertBusyAsync(bed, selection, null, ct);
|
||||
bed.Session.InSession = false;
|
||||
|
||||
// A change of destination in progress.
|
||||
var changing = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inside = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var change = bed.Service.ChangeDestinationAsync<bool>(usb.Id, async token =>
|
||||
{
|
||||
inside.TrySetResult();
|
||||
await changing.Task.WaitAsync(token);
|
||||
return true;
|
||||
}, ct);
|
||||
await inside.Task.WaitAsync(Patience, ct);
|
||||
await AssertBusyAsync(bed, selection, null, ct);
|
||||
changing.SetResult();
|
||||
await change;
|
||||
|
||||
// «Interrompi» holds.
|
||||
bed.Service.HoldAutomatic(bed.Clock.Now.AddMinutes(30));
|
||||
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryResumeAutomaticAsync([1], ct)).Outcome);
|
||||
bed.Service.ReleaseAutomaticHold();
|
||||
|
||||
Assert.HasCount(runs, await bed.Db.Exports.ListRunsAsync(ct), "nothing was recorded while busy");
|
||||
Assert.IsNull(bed.Gate.Busy, "no lease left behind");
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nothing to copy takes no lease, so the library conversion is not pre-empted for nothing; something to copy takes
|
||||
/// a yielding lease, which pre-empts it like any lease.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task NothingToDoTakesNoLease_TheLibraryConversionIsNotPreempted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
Assert.IsTrue(bed.Gate.TryEnterBackground(out var conversion));
|
||||
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
Assert.IsFalse(conversion.IsPreempted);
|
||||
Assert.IsTrue(bed.Gate.BackgroundRunning);
|
||||
|
||||
await bed.PostAsync(bed.Luca, "n01", 1);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
Assert.IsTrue(conversion.IsPreempted);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
conversion.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Under its lease the start reads the destinations again: one switched off, paused, with another «da quando», or
|
||||
/// with an unfinished automatic run is left out.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task TryStartAutomaticDropsADestinationTurnedOffMeanwhile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Luca, "d01", 1);
|
||||
await bed.PostAsync(bed.Marta, "d02", 2);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
|
||||
var general = await TurnOnAsync(bed, usb, ct);
|
||||
var marta = await TurnOnAsync(bed, own, ct);
|
||||
var selection = new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true);
|
||||
|
||||
// Switched off after the worker read it (directly in the store: the service is not told).
|
||||
await bed.Db.Exports.UpdateDestinationAsync(general with { Automatic = false }, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(selection, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
CollectionAssert.AreEqual(new[] { own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
|
||||
|
||||
// Another «da quando», or a pause: left out too.
|
||||
await bed.PostAsync(bed.Luca, "d03", 3);
|
||||
await bed.PostAsync(bed.Marta, "d04", 4);
|
||||
await bed.Db.Exports.UpdateDestinationAsync(general with { AutomaticSince = Make.T0.AddDays(-30) }, ct);
|
||||
await bed.Db.Exports.SetDestinationPausedAsync(own.Id, bed.Clock.Now, "Non risponde.", ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
|
||||
|
||||
// An unfinished automatic run of the destination: it is resumed, not planned again.
|
||||
await bed.Db.Exports.ClearDestinationPauseAsync(own.Id, ct);
|
||||
await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
|
||||
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Copia in…» while an automatic job copies is not refused: it displaces the automatic job (answer 49), whose run
|
||||
/// becomes «interrotto» without an error and resumes by itself afterwards.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AManualStartPreemptsTheAutomaticJob()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
var post = await bed.PostAsync(bed.Luca, "p01", 1, 2, 3);
|
||||
var other = await bed.PostAsync(bed.Marta, "p02", 4);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
Assert.IsTrue(bed.Service.AutomaticRunning);
|
||||
Assert.IsTrue(bed.Gate.HeldByYielding);
|
||||
Assert.IsNull(bed.Gate.BusyFirm);
|
||||
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
|
||||
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([other.Media[0].Id])), ct);
|
||||
var automaticRun = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Interrupted, null), (automaticRun.State, automaticRun.LastError), "displaced, not failed");
|
||||
Assert.IsFalse(bed.Service.AutomaticRunning);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
|
||||
|
||||
// The next pass resumes it where it was.
|
||||
held.Release();
|
||||
var resumed = await bed.Service.TryResumeAutomaticAsync([automaticRun.Id], ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, resumed.Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(automaticRun.Id, ct)).State);
|
||||
Assert.IsTrue(post.Media.All(m => File.Exists(bed.GeneralCopy(bed.Luca, m))));
|
||||
}
|
||||
|
||||
/// <summary>Alberto's work that arrives while an automatic start plans: the runs recorded so far become «annullato».</summary>
|
||||
[TestMethod]
|
||||
public async Task AManualStartDuringAnAutomaticPlanCancelsThePartialRuns()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Luca, "q01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var planning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
bed.Service.AutomaticRunRecorded = async token =>
|
||||
{
|
||||
planning.TrySetResult();
|
||||
await Task.Delay(Timeout.Infinite, token);
|
||||
};
|
||||
|
||||
var automatic = bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await planning.Task.WaitAsync(Patience, ct);
|
||||
Assert.IsTrue(bed.Service.AutomaticRunning);
|
||||
var partial = (await bed.Db.Exports.ListUnfinishedRunsAsync(ct)).Single();
|
||||
|
||||
bed.Service.AutomaticRunRecorded = null;
|
||||
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Busy, (await automatic).Outcome);
|
||||
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(partial.Id, ct)).State);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunOrigin.Manual, (await bed.RunAsync(manual.Runs.Single().Id, ct)).Origin);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>An import takes the gate from an automatic job; while it runs the automatic export only gets Busy.</summary>
|
||||
[TestMethod]
|
||||
public async Task AnImportPreemptsTheAutomaticJobThroughTheGate()
|
||||
{
|
||||
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, "i01", 1, 2);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
var entry = await bed.Gate.EnterAsync(LongWorkKind.Import, ct);
|
||||
Assert.IsNotNull(entry.Lease);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
|
||||
var busy = await bed.Service.TryResumeAutomaticAsync([run.Id], ct);
|
||||
Assert.AreEqual((AutoExportStartOutcome.Busy, LongWorkKind.Import), (busy.Outcome, busy.BusyWith));
|
||||
|
||||
entry.Lease.Dispose();
|
||||
held.Release();
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switching «Automatica» off stops its automatic job at once and cancels its automatic runs (answer 52): the files
|
||||
/// copied stay, a run Alberto started is not touched.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ChangeDestinationStopsAndCancelsItsAutomaticRuns_ManualRunsStay()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
var post = await bed.PostAsync(bed.Luca, "c01", 1, 2, 3);
|
||||
var manualPost = await bed.PostAsync(bed.Marta, "c02", 4, 5);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
|
||||
// A run of Alberto's, interrupted on its second file.
|
||||
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. manualPost.Media.Select(m => m.Id)])), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
Assert.IsNull(await bed.Service.InterruptAsync(ct), "a manual job holds nothing");
|
||||
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome, "the manual run is on Marta's files, the automatic one on Luca's");
|
||||
await WaitForCopyAsync(bed.GeneralCopy(bed.Luca, post.Media[0]), ct);
|
||||
|
||||
var spec = Spec(bed, auto) with { Automatic = false };
|
||||
await bed.Service.ChangeDestinationAsync(usb.Id, token => bed.Service.Destinations.UpdateAsync(usb.Id, spec, token), ct);
|
||||
|
||||
Assert.IsFalse(bed.Service.IsBusy);
|
||||
var automaticRun = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (automaticRun.State, automaticRun.LastError));
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])), "what was copied stays");
|
||||
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[2])));
|
||||
Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
|
||||
held.Release();
|
||||
}
|
||||
|
||||
/// <summary>A change that fails (here a type list left empty) leaves the stopped automatic run «interrotto», to be resumed.</summary>
|
||||
[TestMethod]
|
||||
public async Task AFailedUpdateLeavesAutomaticRunsInterruptedNotCancelled()
|
||||
{
|
||||
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, "u01", 1, 2);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
var bad = Spec(bed, auto) with { ContentTypes = ContentTypes.None };
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.ChangeDestinationAsync(usb.Id, token => bed.Service.Destinations.UpdateAsync(usb.Id, bad, token), ct));
|
||||
|
||||
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
|
||||
Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.Automatic);
|
||||
held.Release();
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No automatic job starts between the stop and the update of a change (engineering A5); a change of folder and
|
||||
/// «Togli la cartella» are not refused because of automatic runs, which become «annullato».
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task NoAutomaticJobStartsDuringADestinationChange()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Luca, "x01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var interrupted = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inside = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var other = bed.Temp.Combine("nuovo-disco");
|
||||
Directory.CreateDirectory(other);
|
||||
var change = bed.Service.ChangeDestinationAsync(usb.Id, async token =>
|
||||
{
|
||||
inside.TrySetResult();
|
||||
await release.Task.WaitAsync(token);
|
||||
return await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed, auto) with { Path = other }, token);
|
||||
}, ct);
|
||||
await inside.Task.WaitAsync(Patience, ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryResumeAutomaticAsync([interrupted.Id], ct)).Outcome);
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
|
||||
release.SetResult();
|
||||
var moved = (await change).Destination;
|
||||
|
||||
// The folder changed although an automatic run was unfinished there: that run is cancelled, the new folder is new.
|
||||
Assert.AreEqual((ExportRunState.Cancelled, ExportText.RetiredDestination), ((await bed.RunAsync(interrupted.Id, ct)).State, (await bed.RunAsync(interrupted.Id, ct)).LastError));
|
||||
Assert.IsTrue(moved.Automatic);
|
||||
var started = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(moved)], [], Round: true), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, started.Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
// «Togli la cartella» with an unfinished automatic run.
|
||||
var again = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = moved.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Service.ChangeDestinationAsync(moved.Id, async token =>
|
||||
{
|
||||
await bed.Service.Destinations.RetireAsync(moved.Id, token);
|
||||
return true;
|
||||
}, ct);
|
||||
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(again.Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The copier's safety net (D7.5): an automatic run whose destination is no longer automatic stops at its next group
|
||||
/// (or at its start), «annullato»; the files done stay.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnAutomaticRunWhoseDestinationIsNoLongerAutomaticIsCancelledAtTheNextGroup()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held, GroupFiles = 1 });
|
||||
var post = await bed.PostAsync(bed.Luca, "g01", 1, 2, 3);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
// Switched off without telling the service (the store directly): the copy in progress finishes, the next does not start.
|
||||
await bed.Db.Exports.UpdateDestinationAsync(auto with { Automatic = false, AutomaticSince = null }, ct);
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (run.State, run.LastError));
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
|
||||
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])), "the file being written finishes");
|
||||
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[2])));
|
||||
Assert.AreEqual(1, (await bed.ItemsAsync(run.Id, ct)).Count(i => i.State == ExportItemState.Pending));
|
||||
|
||||
// At the start of a run: «Riprendi» of an automatic run whose folder is off cancels it.
|
||||
var later = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Service.ResumeAsync([later.Id], ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(later.Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>An account removed: its own folder is no longer automatic, and its automatic runs are cancelled by the round.</summary>
|
||||
[TestMethod]
|
||||
public async Task CancelOrphanAutomaticRunsAfterAccountRemoval()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
|
||||
var general = await bed.GeneralAsync(ct: ct);
|
||||
await TurnOnAsync(bed, own, ct);
|
||||
await TurnOnAsync(bed, general, ct);
|
||||
var orphan = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = bed.Clock.Now }, ct);
|
||||
var kept = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = general.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
var manual = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Assert.AreEqual(1, await bed.Service.CancelOrphanAutomaticRunsAsync(ct));
|
||||
|
||||
var cancelled = await bed.RunAsync(orphan.Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (cancelled.State, cancelled.LastError));
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(kept.Id, ct)).State);
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(manual.Id, ct)).State, "a run of Alberto's stays his");
|
||||
Assert.AreEqual(0, await bed.Service.CancelOrphanAutomaticRunsAsync(ct));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The progress tells the kind and origin of the run being worked on: an automatic run resumed by hand stays
|
||||
/// «automatica» (but runs as Alberto's job), a manual run is «manuale», «Controlla le copie» has none.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ProgressKindAndOriginComeFromTheRun()
|
||||
{
|
||||
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, "k01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
var now = await WaitUntilAsync(() => bed.Service.GetProgressAsync(ct), p => p.Origin is not null, ct);
|
||||
Assert.AreEqual((ExportRunKind.Copy, ExportRunOrigin.Automatic), (now.Kind!.Value, now.Origin!.Value));
|
||||
Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct));
|
||||
Assert.IsNull(bed.Service.AutomaticHeldUntil, "stopped without «Interrompi»: nothing held");
|
||||
|
||||
await bed.Service.ResumeAsync([start.Runs[0].Id], ct);
|
||||
Assert.IsFalse(bed.Service.AutomaticRunning, "resumed by hand: Alberto's job");
|
||||
now = await WaitUntilAsync(() => bed.Service.GetProgressAsync(ct), p => p.Origin is not null, ct);
|
||||
Assert.AreEqual(ExportRunOrigin.Automatic, now.Origin);
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunOrigin.Automatic, (await bed.Service.GetProgressAsync(ct)).Origin, "the snapshot of the newest run");
|
||||
|
||||
var second = await bed.PostAsync(bed.Luca, "k02", 2);
|
||||
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([second.Media[0].Id])), ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var manual = await bed.Service.GetProgressAsync(ct);
|
||||
Assert.AreEqual((ExportRunKind.Copy, ExportRunOrigin.Manual), (manual.Kind!.Value, manual.Origin!.Value));
|
||||
|
||||
var check = new List<ExportProgress>();
|
||||
bed.Service.ProgressChanged += (_, p) => { lock (check) { check.Add(p); } };
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
lock (check)
|
||||
{
|
||||
Assert.IsTrue(check.Count > 0 && check.All(p => p.Kind is null && p.Origin is null && p.RunId is null));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Interrompi» of an automatic copy holds the automatic copies at least an hour (answer 53); «Riprendi ora»
|
||||
/// releases them; «Interrompi» of a job of Alberto's holds nothing.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task InterruptOfAnAutomaticJobHoldsTheAutomaticCopies_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 });
|
||||
await bed.PostAsync(bed.Luca, "h01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
var until = await bed.Service.InterruptAsync(ct);
|
||||
Assert.AreEqual(bed.Clock.Now.AddHours(1), until);
|
||||
Assert.AreEqual(until, bed.Service.AutomaticHeldUntil);
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryResumeAutomaticAsync([start.Runs[0].Id], ct)).Outcome);
|
||||
Assert.AreEqual(
|
||||
$"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle {Core.Engine.ItalianText.Clock(until!.Value, bed.Clock.LocalZone)}.",
|
||||
ExportText.AutomaticInterrupted(until.Value, bed.Clock.LocalZone));
|
||||
|
||||
// A longer hold wins; the hour passes; «Riprendi ora».
|
||||
Assert.AreEqual(until.Value.AddHours(1), bed.Service.HoldAutomatic(until.Value.AddHours(1)));
|
||||
Assert.AreEqual(until.Value.AddHours(1), bed.Service.HoldAutomatic(until.Value));
|
||||
bed.Clock.Now = until.Value.AddHours(1);
|
||||
Assert.IsNull(bed.Service.AutomaticHeldUntil);
|
||||
bed.Service.HoldAutomatic(bed.Clock.Now.AddHours(1));
|
||||
bed.Service.ReleaseAutomaticHold();
|
||||
Assert.IsNull(bed.Service.AutomaticHeldUntil);
|
||||
|
||||
held.Release();
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([start.Runs[0].Id], ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The automatic export resumes only automatic runs: a manual «In pausa» stays Alberto's even when its folder
|
||||
/// answers again (answer 48); «Riprova» resumes it.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AManualPausedRunIsNotResumedByTheAutomaticExport()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Luca, "w01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
await TurnOnAsync(bed, usb, ct);
|
||||
Directory.Move(bed.Usb, bed.Usb + "-via");
|
||||
var start = await bed.CopyAccountAsync(bed.Luca, ct: ct);
|
||||
var run = start.Runs.Single();
|
||||
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
|
||||
Directory.Move(bed.Usb + "-via", bed.Usb);
|
||||
|
||||
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
|
||||
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
|
||||
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
|
||||
|
||||
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(run.Id, retry.Resumed.Single().Id);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A destination paused because its disk is full stays paused at each probe until the next file of its paused job
|
||||
/// fits with the margin (D11): one pause event, no resume meanwhile; unmeasurable space clears as before.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ProbeKeepsASpacePauseUntilTheNextFileFits()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Luca, "s01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
bed.Disk.Free = ExportSpace.Margin / 2;
|
||||
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||
|
||||
var bytes = post.Media[0].Bytes!.Value;
|
||||
bed.Disk.Free = ExportSpace.Margin + bytes - 1;
|
||||
var problem = await bed.Service.ProbeDestinationAsync(usb.Id, ct);
|
||||
Assert.IsNotNull(problem);
|
||||
StringAssert.StartsWith(problem, "Su Disco USB restano");
|
||||
StringAssert.Contains(problem, "per il prossimo file");
|
||||
var stored = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
|
||||
Assert.AreEqual(problem, stored.LastError);
|
||||
Assert.IsNotNull(stored.PausedAt);
|
||||
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode));
|
||||
|
||||
bed.Disk.Free = ExportSpace.Margin + bytes;
|
||||
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
|
||||
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||
|
||||
// Unmeasurable space: cleared, as before E5.
|
||||
await bed.Db.Exports.SetDestinationPausedAsync(usb.Id, bed.Clock.Now, "Pieno.", ct);
|
||||
bed.Disk.Free = null;
|
||||
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
|
||||
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode));
|
||||
}
|
||||
|
||||
/// <summary>The end of Febe stops the job and waits until its states are saved.</summary>
|
||||
[TestMethod]
|
||||
public async Task DisposeAwaitsARunningJob()
|
||||
{
|
||||
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, "z01", 1);
|
||||
await bed.GeneralAsync(ct: ct);
|
||||
var service = new ExportService(bed.Environment);
|
||||
var start = await service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
await service.DisposeAsync();
|
||||
Assert.IsFalse(service.IsBusy);
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>A copy stuck in a read that ignores cancellation (a dead share) does not keep Febe from closing (D7.10).</summary>
|
||||
[TestMethod]
|
||||
public async Task DisposeDoesNotWaitForeverForAStuckCopy()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var stuck = new StuckExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = stuck });
|
||||
await bed.PostAsync(bed.Luca, "z02", 1);
|
||||
await bed.GeneralAsync(ct: ct);
|
||||
var service = new ExportService(bed.Environment) { StopWait = TimeSpan.FromMilliseconds(300) };
|
||||
var start = await service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct);
|
||||
await stuck.Reached.Task.WaitAsync(Patience, ct);
|
||||
|
||||
var watch = Stopwatch.StartNew();
|
||||
await service.DisposeAsync();
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed);
|
||||
Assert.IsTrue(service.IsBusy, "the job is still stuck");
|
||||
Assert.AreEqual(ExportRunState.Running, (await bed.RunAsync(start.Runs[0].Id, ct)).State, "RecoverAsync makes it «interrotto» at the next start");
|
||||
|
||||
stuck.Release();
|
||||
await service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An automatic run that copied, adopted and failed nothing leaves no event (answer 54); one that copied writes
|
||||
/// «Copia automatica in … finita».
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnAutomaticRunThatDidNothingWritesNoEvent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var gone = await bed.PostAsync(bed.Luca, "e01", 1);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var auto = await TurnOnAsync(bed, usb, ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var completed = (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Single(e => e.Code == "esportazione-completata");
|
||||
Assert.AreEqual("Copia automatica in Disco USB finita: 1 file copiato.", completed.Message);
|
||||
Assert.AreEqual(EventSeverity.Success, completed.Severity);
|
||||
|
||||
// A run whose only file left the library meanwhile: «non presente», nothing copied, no second event.
|
||||
var empty = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Db.Exports.AddItemsAsync(
|
||||
[new ExportItem { RunId = empty.Id, MediaId = gone.Media[0].Id, AccountId = bed.Luca.Id, SourceSha256 = gone.Media[0].Sha256, State = ExportItemState.Pending }],
|
||||
ct);
|
||||
File.Delete(bed.LibraryFile(bed.Luca, gone.Media[0]));
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([empty.Id], ct)).Outcome);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(empty.Id, ct)).State);
|
||||
Assert.AreEqual(ExportItemState.Missing, (await bed.ItemsAsync(empty.Id, ct)).Single().State);
|
||||
Assert.HasCount(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Where(e => e.Code == "esportazione-completata"));
|
||||
}
|
||||
|
||||
/// <summary>The planner refuses an automatic selection outside the automatic export, and «Copia in…» cannot claim to be automatic.</summary>
|
||||
[TestMethod]
|
||||
public async Task TheAutomaticSelectionIsTheAutomaticExportsAlone()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var selection = new ExportSelection.Automatic([new(usb.Id, null)], [], Round: true);
|
||||
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(selection)));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(selection, CopyAgain: true, Origin: ExportRunOrigin.Automatic)));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id), Origin: ExportRunOrigin.Automatic)));
|
||||
ExportPlanner.Validate(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic), ct));
|
||||
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||
}
|
||||
|
||||
// Helpers -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>«Automatica» on with «Copia anche quelli già in libreria» (no «da quando»), through the destinations.</summary>
|
||||
private static async Task<ExportDestination> TurnOnAsync(ExportTestBed bed, ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
var spec = Spec(bed, destination) with { Automatic = true, OnlyNew = false };
|
||||
return (await bed.Service.Destinations.UpdateAsync(destination.Id, spec, ct)).Destination;
|
||||
}
|
||||
|
||||
private static DestinationSpec Spec(ExportTestBed bed, 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);
|
||||
|
||||
private static ExportSelection.AutomaticScope Scope(ExportDestination d) => new(d.Id, d.AutomaticSince);
|
||||
|
||||
private static ExportSelection.Automatic Selection(ExportDestination d, bool round) => new([Scope(d)], [], round);
|
||||
|
||||
private static async Task AssertBusyAsync(ExportTestBed bed, ExportSelection.Automatic selection, LongWorkKind? with, CancellationToken ct)
|
||||
{
|
||||
var start = await bed.Service.TryStartAutomaticAsync(selection, ct);
|
||||
Assert.AreEqual((AutoExportStartOutcome.Busy, with), (start.Outcome, start.BusyWith));
|
||||
Assert.IsEmpty(start.Runs);
|
||||
var resume = await bed.Service.TryResumeAutomaticAsync([1, 2, 3], ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Busy, resume.Outcome);
|
||||
}
|
||||
|
||||
/// <summary>The planner's «da scrivere» of «Copia in…» of the whole library, per destination: (account, SHA-256).</summary>
|
||||
private static async Task<Dictionary<long, HashSet<(long, string)>>> PlannedWritesAsync(ExportTestBed bed, CancellationToken ct)
|
||||
{
|
||||
var effective = await bed.Service.Destinations.ResolveAllAsync(ct);
|
||||
var settings = await ExportSettings.LoadAsync(bed.Db.Settings, ct);
|
||||
var writes = new Dictionary<long, HashSet<(long, string)>>();
|
||||
var request = new ExportJobRequest(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped));
|
||||
await foreach (var file in bed.Service.Planner.EnumerateAsync(request, effective, settings, ct))
|
||||
{
|
||||
if (file.Action == PlannedCopy.Write)
|
||||
{
|
||||
if (!writes.TryGetValue(file.DestinationId!.Value, out var set))
|
||||
{
|
||||
writes[file.DestinationId.Value] = set = [];
|
||||
}
|
||||
|
||||
set.Add((file.Candidate.AccountId, file.Candidate.Sha256!));
|
||||
}
|
||||
}
|
||||
|
||||
return writes;
|
||||
}
|
||||
|
||||
private static async Task WaitForCopyAsync(string path, CancellationToken ct)
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
while (!File.Exists(path))
|
||||
{
|
||||
if (watch.Elapsed > Patience)
|
||||
{
|
||||
Assert.Fail($"{Path.GetFileName(path)} non copiato");
|
||||
}
|
||||
|
||||
await Task.Delay(10, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<T> WaitUntilAsync<T>(Func<Task<T>> read, Func<T, bool> done, CancellationToken ct)
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
while (true)
|
||||
{
|
||||
var value = await read();
|
||||
if (done(value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
if (watch.Elapsed > Patience)
|
||||
{
|
||||
Assert.Fail($"non è arrivato: {value}");
|
||||
}
|
||||
|
||||
await Task.Delay(10, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The real file system, but reading a chosen file never ends, whatever the token says, until <see cref="Release"/>.</summary>
|
||||
private sealed class StuckExportFileSystem(Func<string, bool> sticks) : IExportFileSystem
|
||||
{
|
||||
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
|
||||
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public void Release() => _release.TrySetResult();
|
||||
|
||||
public Stream OpenRead(string path)
|
||||
{
|
||||
var stream = _inner.OpenRead(path);
|
||||
if (!sticks(path))
|
||||
{
|
||||
return stream;
|
||||
}
|
||||
|
||||
Reached.TrySetResult();
|
||||
return new StuckStream(stream, _release.Task);
|
||||
}
|
||||
|
||||
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
|
||||
|
||||
public bool FileExists(string path) => _inner.FileExists(path);
|
||||
|
||||
public long? FileLength(string path) => _inner.FileLength(path);
|
||||
|
||||
private sealed class StuckStream(Stream inner, Task release) : ReadOnlyStream(inner)
|
||||
{
|
||||
private readonly Stream _inner = inner;
|
||||
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await release; // ignores the token, as a read on a share that went away
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return await _inner.ReadAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user