diff --git a/docs/decisioni.md b/docs/decisioni.md index 642459d..8830afe 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -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 | diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs index 08f275f..a4dea58 100644 --- a/src/Febe.Core/Export/ExportCopier.cs +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -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(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; } - /// Before a file: the probe at the start of each group, then the wait for the end of an engine session. + /// + /// 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» (). + /// private async Task 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; } + /// A run that cannot go on (its destination was retired, or is no longer automatic) becomes «annullato». + private async Task 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; + } + + /// The destination of an automatic run was switched off (or retired) while the run worked on it. + private sealed class AutomaticTurnedOffException : Exception + { + public AutomaticTurnedOffException() + : base(ExportText.AutomaticTurnedOff) + { + } + } + /// The counts of one finished item: progress, states, and the group of the probe. 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(ByState), - env.Clock.Now)); + env.Clock.Now) + { + Kind = Run.Kind, + Origin = Run.Origin, + }); } } diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs index bc33dd6..d8e2b85 100644 --- a/src/Febe.Core/Export/ExportDestinations.cs +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -13,7 +13,7 @@ namespace Febe.Core.Export; /// General scheme; null: «Come la libreria». /// Scheme of highlight collections; null: «Come la libreria». /// Scheme of profile pictures; null: «Come la libreria». -/// «Automatica»: stored only in tappa E2 (tappa E5 acts on it). +/// «Automatica»: the files due here are copied by themselves (tappa E5, the automatic export). /// «Solo i nuovi» when «Automatica» is turned on. /// Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1). /// Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali». @@ -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); } /// «Togli la cartella»: only the configuration goes; copies and files stay (). @@ -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); } /// «Esporta questo account». @@ -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); } /// Checks a folder for the dialog, before saving (WP1.3). @@ -388,15 +399,29 @@ public sealed class ExportDestinations(ExportEnvironment env) return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath; } + /// + /// 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): ExportService.ChangeDestinationAsync stops them before the change + /// and cancels them after it, and the copier cancels one whose destination is no longer automatic. + /// 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); } } + /// Wakes the automatic export at once (no settle wait): what goes by itself may have grown. + 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, diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs index 91bd374..32f67cc 100644 --- a/src/Febe.Core/Export/ExportEnvironment.cs +++ b/src/Febe.Core/Export/ExportEnvironment.cs @@ -65,6 +65,12 @@ public sealed record ExportEnvironment /// One conversion at a time in the process (tappa E3, D16): shared with the library conversion. public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; + /// + /// 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 (). Tests give their own instance. + /// + public AutoExportSignal AutoSignal { get; init; } = AutoExportSignal.Default; + /// The checker of destination folders of this environment. public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe); diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index 4c11ec5..fc0fcfc 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -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; + + /// + /// The kind of '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. + /// + public ExportRunKind? Kind { get; init; } + + /// Who started 's run: an automatic run resumed with «Riprendi» stays automatic here. + public ExportRunOrigin? Origin { get; init; } } +/// What an automatic start did (tappa E5, D7): never an exception because Febe is busy. +public enum AutoExportStartOutcome +{ + /// A job started: are its runs. + Started, + + /// Nothing to copy (or to resume): no lease was taken, no run recorded. + NothingToDo, + + /// + /// Something else comes first: a job, an engine session, a change of destination, other long work + /// (), or Alberto's work displaced the start while it planned. + /// + Busy, + + /// «Interrompi» stopped the automatic copies until ExportService.AutomaticHeldUntil (answer 53). + Held, +} + +/// The answer of ExportService.TryStartAutomaticAsync and TryResumeAutomaticAsync. +/// The long work that holds the gate, when that is why the start is . +public sealed record AutoExportStart(AutoExportStartOutcome Outcome, IReadOnlyList Runs, LongWorkKind? BusyWith = null); + /// What ExportService.StartAsync did: one run per destination (D6), and the plan it followed. public sealed record ExportStart(IReadOnlyList Runs, ExportPlan Plan); diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs index 0846416..7860c78 100644 --- a/src/Febe.Core/Export/ExportPlanner.cs +++ b/src/Febe.Core/Export/ExportPlanner.cs @@ -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)); diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index 1309938..8f7dcf1 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -10,9 +10,15 @@ namespace Febe.Core.Export; /// The copies to external folders for the interface (spec §4.10): one background job at a time, never together with /// an import or a rebuild (), never during an engine session. A «Copia in…» makes one job /// record per destination (decision D6 of tappa E2) and the job works on them in order. Every state lives in the -/// database: after a restart call once; «Riprendi» is always Alberto's. +/// database: after a restart call once. +/// +/// Tappa E5: the automatic export starts its jobs here too (, +/// ), with a yielding lease of the gate: Alberto's work always comes first (answer +/// 49), and a manual start displaces an automatic job instead of being refused. Automatic runs resume by themselves +/// (the worker's passes); «Riprendi» of a run Alberto started stays his (decision of 27 November 2026, answer 48). +/// /// -public sealed class ExportService : IAsyncDisposable +public sealed partial class ExportService : IAsyncDisposable { private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; @@ -23,12 +29,26 @@ public sealed class ExportService : IAsyncDisposable private readonly ExportEnvironment _env; private readonly Lock _gate = new(); + + // Held by an automatic start while it plans, and by a change of destination (D7.4): never both. + private readonly SemaphoreSlim _destinationChange = new(1, 1); private Job? _job; private ExportProgress? _current; private long _lastPublished; private Task _cleanup = Task.CompletedTask; private bool _starting; + // Tappa E5: an automatic start between its lease and its job, how to stop it, and when it is over. + private bool _startingAutomatic; + private CancellationTokenSource? _automaticPlanning; + private TaskCompletionSource _automaticStartDone = Done(); + + // Changes of destination waiting or running: automatic starts stay away meanwhile. + private int _changeRequests; + + // «Interrompi» of an automatic copy (answer 53): in memory only, a restart forgets it. + private DateTimeOffset? _heldUntil; + public ExportService(ExportEnvironment env) { ArgumentNullException.ThrowIfNull(env); @@ -65,25 +85,71 @@ public sealed class ExportService : IAsyncDisposable } } - /// A job is running. + /// A job is running (or being started), automatic ones included. public bool IsBusy { get { lock (_gate) { - return _starting || _job is { Task.IsCompleted: false }; + return _starting || _startingAutomatic || _job is { Task.IsCompleted: false }; } } } + /// + /// True while the running job (or the start being planned) is automatic: it holds a yielding lease, and a manual + /// start displaces it instead of being refused (tappa E5, D7). + /// + public bool AutomaticRunning + { + get + { + lock (_gate) + { + return _startingAutomatic || _job is { Automatic: true, Task.IsCompleted: false }; + } + } + } + + /// + /// 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. + /// + public DateTimeOffset? AutomaticHeldUntil + { + get + { + lock (_gate) + { + return _heldUntil is { } until && until > _env.Clock.Now ? until : null; + } + } + } + + /// + /// How long «Interrompi» holds the automatic copies: until the next recovery round, at least an hour (answer 53). + /// The worker can hold longer with . + /// + public TimeSpan AutomaticHoldTime { get; init; } = TimeSpan.FromHours(1); + + /// + /// The longest wait, in real time, for a job to stop: at the end of Febe, and for a displaced automatic job to unwind + /// before a manual start or a change of destination goes on (D7.1, D7.10). A safety bound, not engine timing. + /// + public TimeSpan StopWait { get; init; } = TimeSpan.FromSeconds(10); + /// The last error of a background job that could not be stored with its run (normally null). public string? LastJobError { get; private set; } + /// Tests only: awaited after each run an automatic plan records, to act in the middle of a plan. + internal Func? AutomaticRunRecorded { get; set; } + /// /// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the /// .part files of unfinished jobs are removed in the background, only in their items' folders. Never resumes - /// by itself. Returns how many jobs became interrupted. + /// by itself: «Riprendi» of a run Alberto started is his; automatic runs are resumed by the automatic export's + /// passes (tappa E5). Returns how many jobs became interrupted. /// public async Task RecoverAsync(CancellationToken ct = default) { @@ -124,43 +190,25 @@ public sealed class ExportService : IAsyncDisposable { ArgumentNullException.ThrowIfNull(request); ExportPlanner.Validate(request); - var held = new LeaseHolder(); - lock (_gate) + if (request.Origin == ExportRunOrigin.Automatic) { - EnsureIdle(); - - // The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano - // insieme»): a rebuild or an import cannot start while the runs and their items are being recorded. - if (_env.Gate is { } gate) - { - if (!gate.TryEnter(LongWorkKind.Export, out var lease, out var busy)) - { - throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); - } - - held.Lease = lease; - } - - _starting = true; // a second «Copia in…» meanwhile records nothing + throw new ArgumentException("Le copie automatiche partono solo dalla copia automatica.", nameof(request)); } - try - { - return await StartReservedAsync(request, held, ct).ConfigureAwait(false); - } - finally - { - lock (_gate) - { - _starting = false; - } - - held.Lease?.Dispose(); // not handed to a job: nothing to copy, or the start failed - } + // The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano + // insieme»): a rebuild or an import cannot start while the runs and their items are being recorded. A second + // «Copia in…» meanwhile records nothing. + return await RunManualAsync(held => StartReservedAsync(request, held, ct, automatic: null), ct).ConfigureAwait(false); } - private async Task StartReservedAsync(ExportJobRequest request, LeaseHolder held, CancellationToken ct) + /// + /// Records the runs and items of and starts their job. : the + /// job is the automatic export's (its yield token stops it; only files to write are recorded, D5). + /// + private async Task StartReservedAsync(ExportJobRequest request, LeaseHolder held, CancellationToken ct, AutomaticJob? automatic) { + // Tappa E5 (D5): the destinations an automatic start may write to, checked again under its lease. + var scopes = request.Selection is ExportSelection.Automatic auto ? auto.Destinations.Select(s => s.DestinationId).ToHashSet() : null; var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false); var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); var tally = new PlanTally(); @@ -213,6 +261,13 @@ public sealed class ExportService : IAsyncDisposable continue; } + // The safety net of an automatic run (D5): only files to write, only in its destinations. «Già copiato», + // «Tolto» and «Superato» are not even recorded, so its report and its event tell only what it did. + if (scopes is not null && (file.Action != PlannedCopy.Write || file.Again || !scopes.Contains(destination))) + { + continue; + } + if (!runs.TryGetValue(destination, out var run)) { run = await exports.CreateRunAsync( @@ -220,6 +275,10 @@ public sealed class ExportService : IAsyncDisposable CancellationToken.None).ConfigureAwait(false); runs[destination] = run; await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false); + if (automatic is not null && AutomaticRunRecorded is { } recorded) + { + await recorded(ct).ConfigureAwait(false); + } } // Frame items of one video are added together, in instant order (the copy takes them as one batch). @@ -270,8 +329,22 @@ public sealed class ExportService : IAsyncDisposable { lock (_gate) { - _starting = false; - StartCopyJob(ordered.Select(r => r.Id).ToList(), held.Lease); + if (automatic is not null) + { + // A change of destination began, or Alberto's work displaced the start, after the plan: nothing runs. + if (_changeRequests > 0 || ct.IsCancellationRequested) + { + throw new OperationCanceledException(ct); + } + + _startingAutomatic = false; + } + else + { + _starting = false; + } + + StartCopyJob(ordered.Select(r => r.Id).ToList(), held.Lease, automatic is null ? null : automatic with { Destinations = ordered.Select(r => r.DestinationId).ToHashSet() }); held.Lease = null; // the job owns it now } } @@ -347,9 +420,38 @@ public sealed class ExportService : IAsyncDisposable /// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a /// paused one checks its destination first and pauses again if it still does not answer). /// + /// + /// Automatic runs too (D7.7): resumed by hand they run as Alberto's job, which an automatic job gives way to. + /// public async Task> ResumeAsync(IReadOnlyList? runIds = null, CancellationToken ct = default) { - EnsureIdle(); + ThrowIfManualJob(); + var chosen = await ChooseUnfinishedAsync(runIds, ct).ConfigureAwait(false); + if (chosen.Count == 0) + { + return chosen; // nothing to resume: an automatic job is not stopped for nothing + } + + return await RunManualAsync( + async held => + { + // An automatic job just displaced left its runs «interrotto»: the choice is read again. + var again = await ChooseUnfinishedAsync(chosen.Select(r => r.Id).ToList(), ct).ConfigureAwait(false); + lock (_gate) + { + _starting = false; + StartCopyJob(again.Select(r => r.Id).ToList(), held.Lease); + held.Lease = null; + } + + return again; + }, + ct).ConfigureAwait(false); + } + + /// The unfinished runs asked, oldest first (null: every one). + private async Task> ChooseUnfinishedAsync(IReadOnlyList? runIds, CancellationToken ct) + { var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); List chosen; if (runIds is null) @@ -372,31 +474,106 @@ public sealed class ExportService : IAsyncDisposable } } - chosen = chosen.OrderBy(r => r.Id).ToList(); - if (chosen.Count > 0) - { - StartCopyJob(chosen.Select(r => r.Id).ToList()); - } - - return chosen; + return chosen.OrderBy(r => r.Id).ToList(); } - /// «Interrompi»: stops the running job and waits until its states are saved. - public async Task InterruptAsync(CancellationToken ct = default) + /// + /// «Interrompi»: stops the running job and waits until its states are saved. When the job was automatic, the + /// automatic copies are also held for (answer 53): returns until when; null otherwise. + /// + public async Task InterruptAsync(CancellationToken ct = default) + { + DateTimeOffset? held = null; + if (AutomaticRunning) + { + // Held first, so the worker cannot start again in between. + held = HoldAutomatic(_env.Clock.Now + AutomaticHoldTime); + } + + await StopAsync(automaticOnly: false, destinationId: null, ct).ConfigureAwait(false); + return held; + } + + /// + /// Stops the running job (or the start being planned) when it is automatic, without holding the automatic copies; + /// true when one was stopped. Its runs stay «interrotto» and the next pass resumes them. + /// + public Task InterruptAutomaticAsync(CancellationToken ct = default) => StopAsync(automaticOnly: true, destinationId: null, ct); + + /// + /// Holds the automatic copies until (or later, when already held longer): the automatic + /// starts answer meanwhile. Returns the end of the hold. + /// + public DateTimeOffset HoldAutomatic(DateTimeOffset until) { - Job? job; lock (_gate) { - job = _job is { Task.IsCompleted: false } j ? j : null; + _heldUntil = _heldUntil is { } now && now > until ? now : until; + return _heldUntil.Value; } + } - if (job is null) + /// «Riprendi ora»: the automatic copies are no longer held. + public void ReleaseAutomaticHold() + { + lock (_gate) { - return; + _heldUntil = null; + } + } + + /// + /// Stops the running job (only an automatic one with ; only one that works on + /// when given) and any automatic start being planned, and waits until their states + /// are saved, at most in real time when given. True when something was stopped. + /// + private async Task StopAsync(bool automaticOnly, long? destinationId, CancellationToken ct, TimeSpan? bound = null) + { + Job? job; + CancellationTokenSource? planning; + Task planned; + lock (_gate) + { + job = _job is { Task.IsCompleted: false } j + && (!automaticOnly || j.Automatic) + && (destinationId is not { } id || j.Destinations.Contains(id)) + ? j + : null; + planning = _startingAutomatic ? _automaticPlanning : null; + planned = _automaticStartDone.Task; } - await job.Cancellation.CancelAsync().ConfigureAwait(false); - await job.Task.WaitAsync(ct).ConfigureAwait(false); + Cancel(planning); + if (job is not null) + { + Cancel(job.Cancellation); + } + + var stopping = Task.WhenAll(job?.Task ?? Task.CompletedTask, planning is null ? Task.CompletedTask : planned); + try + { + await (bound is { } wait ? stopping.WaitAsync(wait, ct) : stopping.WaitAsync(ct)).ConfigureAwait(false); + } + catch (TimeoutException) + { + // A copy stuck in a read on a share that went away: it was asked to stop and stops by itself; the copier + // also cancels an automatic run whose destination is no longer automatic at its next group. + } + + return job is not null || planning is not null; + } + + /// Cancels a token source that may have been disposed meanwhile (its job ended). + private static void Cancel(CancellationTokenSource? source) + { + try + { + source?.Cancel(); + } + catch (ObjectDisposedException) + { + // Already over. + } } /// @@ -407,7 +584,7 @@ public sealed class ExportService : IAsyncDisposable { if (ActiveRunIds.Contains(runId)) { - await InterruptAsync(ct).ConfigureAwait(false); + await StopAsync(automaticOnly: false, destinationId: null, ct).ConfigureAwait(false); // not «Interrompi»: nothing is held } var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); @@ -430,7 +607,7 @@ public sealed class ExportService : IAsyncDisposable /// public async Task CheckCopiesAsync(long destinationId, CancellationToken ct = default) { - EnsureIdle(); + ThrowIfManualJob(); var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); if (destination.IsRetired) @@ -438,42 +615,106 @@ public sealed class ExportService : IAsyncDisposable throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da controllare."); } - StartJob([], (progress, token) => CheckJobAsync(destination, progress, token)); + await RunManualAsync( + held => + { + lock (_gate) + { + _starting = false; + StartJob([], (progress, token) => CheckJobAsync(destination, progress, token), held.Lease); + held.Lease = null; + } + + return Task.FromResult(true); + }, + ct).ConfigureAwait(false); } /// - /// «Riprova» of a paused destination: checks it with its probe (WP1.3). Still not writable: it stays paused with the - /// new reason, returned. Writable: the pause goes and, when no other long work runs, its paused jobs resume (oldest - /// first); otherwise they wait for «Riprendi». + /// «Riprova» of a paused destination: checks it with its probe (WP1.3) and, with a paused job, whether the disk has + /// room for its next file (). Still not writable: it stays paused with the reason, + /// returned. Writable: the pause goes and, unless a job of Alberto's or other long work runs, its paused jobs resume + /// (oldest first, automatic ones too, as Alberto's job: an automatic copy gives way); otherwise they wait for + /// «Riprendi». /// /// No such destination. /// The destination was retired. public async Task RetryDestinationAsync(long destinationId, CancellationToken ct = default) { - var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) + if (await ProbeDestinationAsync(destinationId, ct).ConfigureAwait(false) is { } problem) + { + return new ExportRetry(problem, []); + } + + var paused = (await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) + .Where(r => r.DestinationId == destinationId && r.State == ExportRunState.Paused) + .Select(r => r.Id) + .ToList(); + if (paused.Count == 0 || (IsBusy && !AutomaticRunning) || _env.Gate?.BusyFirm is not null) + { + return new ExportRetry(null, []); + } + + try + { + return new ExportRetry(null, await ResumeAsync(paused, ct).ConfigureAwait(false)); + } + catch (InvalidOperationException) + { + // Something else started meanwhile, or the runs ended: they wait for «Riprendi», as when busy. + return new ExportRetry(null, []); + } + } + + /// + /// The probe of «Riprova», without resuming anything (tappa E5, D11; the recovery rounds use it): null when the + /// destination is writable and, if a job of it is paused, the disk has room for that job's next file plus + /// ; the pause is then cleared. Otherwise the problem, and the destination stays (or + /// goes) in pause with it; the pause event is written only when it was not paused already (D10). + /// + /// No such destination. + /// The destination was retired. + public async Task ProbeDestinationAsync(long destinationId, CancellationToken ct = default) + { + var exports = _env.Storage.Exports; + var destination = await exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); if (destination.IsRetired) { throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da riprovare."); } - if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem) + var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false); + if (problem is null + && await exports.GetFirstPendingBytesAsync(destinationId, ct).ConfigureAwait(false) is { } bytes + && await FreeBytesAsync(destination, ct).ConfigureAwait(false) is { } free + && free < bytes + ExportSpace.Margin) + { + // Still too full: resuming would only pause again (engineering B1). Unmeasurable space clears, as before. + problem = ExportText.NoSpaceForNext(destination, free, bytes); + } + + if (problem is not null) { await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); - return new ExportRetry(problem, []); + return problem; } await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false); - var paused = (await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) - .Where(r => r.DestinationId == destinationId && r.State == ExportRunState.Paused) - .Select(r => r.Id) - .ToList(); - if (paused.Count == 0 || IsBusy || _env.Gate?.Busy is not null) - { - return new ExportRetry(null, []); - } + return null; + } - return new ExportRetry(null, await ResumeAsync(paused, ct).ConfigureAwait(false)); + /// The free space of a destination's disk, asked within the folder-check time; null when not measurable. + private async Task FreeBytesAsync(ExportDestination destination, CancellationToken ct) + { + try + { + return await Task.Run(() => _env.Disk.FreeBytes(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return null; + } } /// The progress of the running job, or a snapshot of the newest job. @@ -512,24 +753,47 @@ public sealed class ExportService : IAsyncDisposable await cleanup.WaitAsync(ct).ConfigureAwait(false); } + /// + /// Stops the job and waits for it, at most in real time (D7.10): a copy stuck in a read on a + /// share that went away must not keep Febe from closing. A run left «in corso» becomes «interrotto» at the next start + /// (), as after a crash. + /// public async ValueTask DisposeAsync() { Job? job; Task cleanup; + CancellationTokenSource? planning; lock (_gate) { job = _job; cleanup = _cleanup; + planning = _automaticPlanning; } + Cancel(planning); if (job is not null) { - await job.Cancellation.CancelAsync().ConfigureAwait(false); - await job.Task.ConfigureAwait(false); - job.Cancellation.Dispose(); + Cancel(job.Cancellation); + await WithinStopWaitAsync(job.Task).ConfigureAwait(false); + if (job.Task.IsCompleted) + { + job.Cancellation.Dispose(); // only once nothing uses it any more (engineering A9) + } } - await cleanup.ConfigureAwait(false); + await WithinStopWaitAsync(cleanup).ConfigureAwait(false); + } + + private async Task WithinStopWaitAsync(Task task) + { + try + { + await task.WaitAsync(StopWait).ConfigureAwait(false); + } + catch (TimeoutException) + { + // Left behind: see DisposeAsync. + } } private async Task SnapshotAsync(ExportRun run, CancellationToken ct) @@ -547,7 +811,11 @@ public sealed class ExportService : IAsyncDisposable null, destination is null ? null : ExportDestinations.Label(destination), summary.ByState, - _env.Clock.Now); + _env.Clock.Now) + { + Kind = run.Kind, + Origin = run.Origin, + }; } private async Task CheckJobAsync(ExportDestination destination, IProgress progress, CancellationToken ct) @@ -704,20 +972,372 @@ public sealed class ExportService : IAsyncDisposable } } - private void EnsureIdle() + /// A job of Alberto's runs, or one is being started: a second manual start is refused at once. + private void ThrowIfManualJob() { - if (IsBusy) + lock (_gate) { - throw new InvalidOperationException(BusyText); - } - - if (_env.Gate?.Busy is { } busy) - { - throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy)); + if (_starting || _job is { Automatic: false, Task.IsCompleted: false }) + { + throw new InvalidOperationException(BusyText); + } } } - private void StartCopyJob(IReadOnlyList runIds, IDisposable? lease = null) => + /// + /// A start of Alberto's («Copia in…», «Riprendi», «Controlla le copie», «Riprova», «Riconosci»; D7.1): the lease of + /// the gate is taken first, outside the service's lock, displacing an automatic job or start (answer 49); then the + /// displaced automatic work is awaited until it has saved its states (at most ), and + /// runs with _starting set. hands the lease to its job and + /// clears _starting under the lock; a lease it does not hand over is released here. + /// + /// A job of Alberto's or other long work runs (Italian message). + private async Task RunManualAsync(Func> start, CancellationToken ct) + { + var held = await AcquireManualLeaseAsync(ct).ConfigureAwait(false); + try + { + return await start(held).ConfigureAwait(false); + } + finally + { + lock (_gate) + { + _starting = false; + } + + held.Lease?.Dispose(); // not handed to a job: nothing to do, or the start failed + } + } + + private async Task AcquireManualLeaseAsync(CancellationToken ct) + { + ThrowIfManualJob(); + var held = new LeaseHolder(); + if (_env.Gate is { } gate) + { + var entry = await gate.EnterAsync(LongWorkKind.Export, gate.YieldWait, ct).ConfigureAwait(false); + if (entry.Lease is null) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, entry.BusyWith ?? LongWorkKind.Export)); + } + + held.Lease = entry.Lease; + } + + try + { + // The yielding lease is released in the job's finally, before its runs are all saved and its task ends + // (engineering A4): the displaced job and start are awaited too. Without a gate (tests) they are stopped here. + await StopAsync(automaticOnly: true, destinationId: null, ct, StopWait).ConfigureAwait(false); + lock (_gate) + { + if (_starting || _startingAutomatic || _job is { Task.IsCompleted: false }) + { + throw new InvalidOperationException(BusyText); + } + + _starting = true; + } + + return held; + } + catch + { + held.Lease?.Dispose(); + throw; + } + } + + /// + /// Plans and starts an automatic job (tappa E5, D7.2) with a yielding lease of the gate, over the destinations of + /// that are still automatic, not paused, with the same «da quando», and without an + /// unfinished automatic run (that run is resumed instead, ). Only files to write + /// are recorded, one run per destination (answer 54). Never throws because Febe is busy: a job, an engine session, a + /// change of destination, Alberto's long work, or a hold give or + /// without side effects; nothing to copy gives + /// without taking the lease, so the library conversion is not + /// pre-empted for nothing. Alberto's work arriving during the plan displaces it: the runs recorded so far become + /// «annullato» (nothing was copied) and the answer is Busy. + /// + public async Task TryStartAutomaticAsync(ExportSelection.Automatic selection, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(selection); + if (Refusal() is { } refused) + { + return refused; + } + + if (selection.Destinations.Count == 0 || !await _env.Storage.Exports.HasAutomaticCandidatesAsync(selection, ct).ConfigureAwait(false)) + { + return new AutoExportStart(AutoExportStartOutcome.NothingToDo, []); + } + + return await StartAutomaticAsync( + async (held, automatic, token) => + { + var scopes = await UsableScopesAsync(selection.Destinations, token).ConfigureAwait(false); + if (scopes.Count == 0) + { + return new AutoExportStart(AutoExportStartOutcome.NothingToDo, []); + } + + var request = new ExportJobRequest(selection with { Destinations = scopes }, Origin: ExportRunOrigin.Automatic); + ExportPlanner.Validate(request); + var start = await StartReservedAsync(request, held, token, automatic).ConfigureAwait(false); + return start.Runs.Count == 0 + ? new AutoExportStart(AutoExportStartOutcome.NothingToDo, []) + : new AutoExportStart(AutoExportStartOutcome.Started, start.Runs); + }, + ct).ConfigureAwait(false); + } + + /// + /// Resumes unfinished automatic runs (tappa E5, D7.3) as an automatic job, with a yielding lease. Only runs of + /// whose destination is still automatic and not paused are taken; the others + /// are left as they are (a manual «In pausa» stays Alberto's, answer 48). Busy, Held and NothingToDo as + /// . + /// + public async Task TryResumeAutomaticAsync(IReadOnlyList runIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(runIds); + if (Refusal() is { } refused) + { + return refused; + } + + if (runIds.Count == 0) + { + return new AutoExportStart(AutoExportStartOutcome.NothingToDo, []); + } + + return await StartAutomaticAsync( + async (held, automatic, token) => + { + var exports = _env.Storage.Exports; + var destinations = (await exports.ListDestinationsAsync(includeRetired: false, token).ConfigureAwait(false)).ToDictionary(d => d.Id); + var unfinished = await exports.ListUnfinishedRunsAsync(token).ConfigureAwait(false); + var chosen = unfinished + .Where(r => runIds.Contains(r.Id) && r.Origin == ExportRunOrigin.Automatic && r.Kind == ExportRunKind.Copy) + .Where(r => destinations.TryGetValue(r.DestinationId, out var d) && d is { Automatic: true, PausedAt: null }) + .OrderBy(r => r.Id) + .ToList(); + if (chosen.Count == 0) + { + return new AutoExportStart(AutoExportStartOutcome.NothingToDo, []); + } + + lock (_gate) + { + if (_changeRequests > 0 || token.IsCancellationRequested) + { + throw new OperationCanceledException(token); + } + + _startingAutomatic = false; + StartCopyJob(chosen.Select(r => r.Id).ToList(), held.Lease, automatic with { Destinations = chosen.Select(r => r.DestinationId).ToHashSet() }); + held.Lease = null; + } + + return new AutoExportStart(AutoExportStartOutcome.Started, chosen); + }, + ct).ConfigureAwait(false); + } + + /// Why an automatic start cannot even try now, or null; no side effects. + private AutoExportStart? Refusal() + { + if (AutomaticHeldUntil is not null) + { + return new AutoExportStart(AutoExportStartOutcome.Held, []); + } + + if (_env.Session.InSession) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, []); + } + + lock (_gate) + { + if (_starting || _startingAutomatic || _changeRequests > 0 || _job is { Task.IsCompleted: false }) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, []); + } + } + + return _env.Gate?.BusyFirm is { } firm ? new AutoExportStart(AutoExportStartOutcome.Busy, [], firm) : null; + } + + /// + /// The frame of an automatic start: the change-of-destination semaphore (not waited for), the yielding lease, the + /// state checked again under the service's lock, then with a token that the lease's yield, + /// a change of destination and cancel. A cancellation that is not 's + /// gives Busy. + /// + private async Task StartAutomaticAsync(Func> start, CancellationToken ct) + { + if (!await _destinationChange.WaitAsync(0, ct).ConfigureAwait(false)) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, []); + } + + var held = new LeaseHolder(); + TaskCompletionSource? done = null; + CancellationTokenSource? planning = null; + try + { + var yield = CancellationToken.None; + if (_env.Gate is { } gate) + { + if (!gate.TryEnterYielding(LongWorkKind.Export, out var lease, out yield, out var busy)) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, [], busy); + } + + held.Lease = lease; + } + + lock (_gate) + { + if (_starting || _startingAutomatic || _changeRequests > 0 || _job is { Task.IsCompleted: false }) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, []); + } + + _startingAutomatic = true; + planning = _automaticPlanning = CancellationTokenSource.CreateLinkedTokenSource(ct, yield); + done = _automaticStartDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + + try + { + return await start(held, new AutomaticJob(yield, new HashSet()), planning.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return new AutoExportStart(AutoExportStartOutcome.Busy, []); // Alberto's work or a change came first + } + } + finally + { + lock (_gate) + { + if (done is not null) + { + _startingAutomatic = false; + _automaticPlanning = null; + } + } + + held.Lease?.Dispose(); + _destinationChange.Release(); + planning?.Dispose(); + done?.TrySetResult(); + } + } + + /// + /// The scopes still good under the lease (D7.2): the destination in use, automatic, not paused, with the «da quando» + /// the selection was made with, and without an unfinished automatic run. + /// + private async Task> UsableScopesAsync(IReadOnlyList scopes, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var destinations = (await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).ToDictionary(d => d.Id); + var busy = (await exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) + .Where(r => r.Origin == ExportRunOrigin.Automatic) + .Select(r => r.DestinationId) + .ToHashSet(); + return scopes + .Where(s => destinations.TryGetValue(s.DestinationId, out var d) + && d is { Automatic: true, PausedAt: null } + && d.AutomaticSince == s.Since + && !busy.Contains(s.DestinationId)) + .DistinctBy(s => s.DestinationId) + .ToList(); + } + + /// + /// Every change of a destination from the interface (create, update, retire, D7.4), serialised with the automatic + /// starts: automatic starts stay away from the first moment; a start being planned is stopped, and so is the + /// automatic job when it works on (any automatic job when null: a new destination); + /// then runs, and the unfinished automatic runs whose destination is no longer automatic, or + /// retired, become «annullato» (answer 52: the copies made stay, manual runs are not touched). When + /// throws, the stopped runs stay «interrotto» and the next pass resumes them. + /// + public async Task ChangeDestinationAsync(long? destinationId, Func> change, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(change); + lock (_gate) + { + _changeRequests++; + } + + try + { + await StopAsync(automaticOnly: true, destinationId, ct, StopWait).ConfigureAwait(false); + await _destinationChange.WaitAsync(ct).ConfigureAwait(false); + try + { + var result = await change(ct).ConfigureAwait(false); + await CancelOrphanAutomaticRunsAsync(CancellationToken.None).ConfigureAwait(false); + return result; + } + finally + { + _destinationChange.Release(); + } + } + finally + { + lock (_gate) + { + _changeRequests--; + } + } + } + + /// + /// The unfinished automatic runs whose destination is retired, gone, or no longer automatic (switched off, its + /// account removed) become «annullato» with the reason (D7, engineering A10): nothing would ever resume them. The + /// runs of the running job are left to the copier, which cancels them at its next group. Returns how many. + /// + public async Task CancelOrphanAutomaticRunsAsync(CancellationToken ct = default) + { + var exports = _env.Storage.Exports; + var active = ActiveRunIds; + var destinations = (await exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id); + var cancelled = 0; + foreach (var run in await exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) + { + if (run.Origin != ExportRunOrigin.Automatic || active.Contains(run.Id) + || (destinations.TryGetValue(run.DestinationId, out var destination) && destination.Automatic)) + { + continue; + } + + var reason = destination is null || destination.IsRetired ? ExportText.RetiredDestination : ExportText.AutomaticTurnedOff; + await exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = reason }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false); + cancelled++; + if (destination is { IsRetired: false }) + { + try + { + // Our .part files of the run, as «Annulla» does (bounded: a folder that does not answer is skipped). + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort. + } + } + } + + return cancelled; + } + + private void StartCopyJob(IReadOnlyList runIds, IDisposable? lease = null, AutomaticJob? automatic = null) => StartJob( runIds, async (progress, token) => @@ -747,7 +1367,8 @@ public sealed class ExportService : IAsyncDisposable await InterruptQueuedAsync(runIds.Skip(next)).ConfigureAwait(false); } }, - lease); + lease, + automatic); /// Runs of a stopped job that were never reached and are still recorded as running become «interrotto». private async Task InterruptQueuedAsync(IEnumerable runIds) @@ -768,8 +1389,11 @@ public sealed class ExportService : IAsyncDisposable } } - /// Starts a job; is a lease of the gate already taken (the job owns it once started). - private void StartJob(IReadOnlyList runIds, Func, CancellationToken, Task> work, IDisposable? held = null) + /// + /// Starts a job; is a lease of the gate already taken (the job owns it once started). + /// : the automatic export's job, which its lease's yield stops (tappa E5). + /// + private void StartJob(IReadOnlyList runIds, Func, CancellationToken, Task> work, IDisposable? held = null, AutomaticJob? automatic = null) { lock (_gate) { @@ -785,7 +1409,7 @@ public sealed class ExportService : IAsyncDisposable } _job?.Cancellation.Dispose(); - var cancellation = new CancellationTokenSource(); + var cancellation = automatic is null ? new CancellationTokenSource() : CancellationTokenSource.CreateLinkedTokenSource(automatic.Yield); var reporter = new Reporter(this); LastJobError = null; _current = new ExportProgress(runIds.Count > 0 ? runIds[0] : null, runIds.Count > 0 ? ExportPhase.Preparing : ExportPhase.Checking, 0, 0, 0, 0, null, null, new Dictionary(), _env.Clock.Now); @@ -828,7 +1452,7 @@ public sealed class ExportService : IAsyncDisposable } } }); - _job = new Job(runIds, cancellation, task); + _job = new Job(runIds, cancellation, task, automatic is not null, automatic?.Destinations ?? new HashSet()); } } @@ -850,7 +1474,19 @@ public sealed class ExportService : IAsyncDisposable ProgressChanged?.Invoke(this, progress); } - private sealed record Job(IReadOnlyList RunIds, CancellationTokenSource Cancellation, Task Task); + /// The automatic export's job (a yielding lease). + /// The destinations of an automatic job's runs (a change of one of them stops it). + private sealed record Job(IReadOnlyList RunIds, CancellationTokenSource Cancellation, Task Task, bool Automatic, IReadOnlySet Destinations); + + /// What makes a job automatic: the yield token of its lease, and the destinations of its runs. + private sealed record AutomaticJob(CancellationToken Yield, IReadOnlySet Destinations); + + private static TaskCompletionSource Done() + { + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + done.SetResult(); + return done; + } /// A lease of the long-work gate on its way from to the job. private sealed class LeaseHolder diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index 0d3c1f9..e75d585 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -177,8 +177,11 @@ public static class ExportText /// «1 file copiato», «1.204 file copiati». public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many; - /// The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.» - public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination) + /// + /// 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: …». + /// + 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)}."; } + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + public const string AutomaticTurnedOff = "«Automatica» è stata spenta: i file rimasti non si copiano da soli."; + + /// + /// The answer to «Interrompi» of an automatic copy (answer 53): what was copied stays, and the automatic copies wait + /// until («Riprendi ora» before). + /// + public static string AutomaticInterrupted(DateTimeOffset until, TimeZoneInfo zone) => + $"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle {ItalianText.Clock(until, zone)}."; + + /// + /// A paused destination still without room for the next file of its paused job (tappa E5, D11): the pause stays. + /// + 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."; + /// The event of «Controlla le copie». public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination) { diff --git a/tests/Febe.Tests/Export/ExportDestinationsTests.cs b/tests/Febe.Tests/Export/ExportDestinationsTests.cs index 8e6583a..bb9936c 100644 --- a/tests/Febe.Tests/Export/ExportDestinationsTests.cs +++ b/tests/Febe.Tests/Export/ExportDestinationsTests.cs @@ -213,34 +213,61 @@ public sealed class ExportDestinationsTests Assert.AreEqual(ContentTypes.Tagged, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes); } + /// + /// 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. + /// [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)); } diff --git a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs new file mode 100644 index 0000000..e2bd715 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs @@ -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; + +/// +/// 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. +/// +[TestClass] +public sealed class ExportServiceAutomaticTests +{ + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30); + + public TestContext TestContext { get; set; } = null!; + + /// An automatic job records only the files it writes: no «già copiato», no «Tolto», one run per destination. + [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"); + } + + /// + /// 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). + /// + [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); + } + + /// + /// «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. + /// + [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); + } + + /// A «Non riuscito» waits for the recovery round, and every round retries it whatever the error (answer 50). + [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]))); + } + + /// A busy Febe gives Busy, never an exception, and records nothing; Held while «Interrompi» holds. + [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(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); + } + + /// + /// 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. + /// + [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(); + } + + /// + /// 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. + /// + [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)); + } + + /// + /// «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. + /// + [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)))); + } + + /// Alberto's work that arrives while an automatic start plans: the runs recorded so far become «annullato». + [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); + } + + /// An import takes the gate from an automatic job; while it runs the automatic export only gets Busy. + [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); + } + + /// + /// 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. + /// + [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(); + } + + /// A change that fails (here a type list left empty) leaves the stopped automatic run «interrotto», to be resumed. + [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(() => 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); + } + + /// + /// 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». + /// + [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); + } + + /// + /// 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. + /// + [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); + } + + /// An account removed: its own folder is no longer automatic, and its automatic runs are cancelled by the round. + [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)); + } + + /// + /// 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. + /// + [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(); + 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)); + } + } + + /// + /// «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. + /// + [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); + } + + /// + /// 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. + /// + [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); + } + + /// + /// 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. + /// + [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)); + } + + /// The end of Febe stops the job and waits until its states are saved. + [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); + } + + /// A copy stuck in a read that ignores cancellation (a dead share) does not keep Febe from closing (D7.10). + [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); + } + + /// + /// An automatic run that copied, adopted and failed nothing leaves no event (answer 54); one that copied writes + /// «Copia automatica in … finita». + /// + [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")); + } + + /// The planner refuses an automatic selection outside the automatic export, and «Copia in…» cannot claim to be automatic. + [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(() => ExportPlanner.Validate(new ExportJobRequest(selection))); + Assert.ThrowsExactly(() => ExportPlanner.Validate(new ExportJobRequest(selection, CopyAgain: true, Origin: ExportRunOrigin.Automatic))); + Assert.ThrowsExactly(() => ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id), Origin: ExportRunOrigin.Automatic))); + ExportPlanner.Validate(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic)); + await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic), ct)); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + } + + // Helpers ------------------------------------------------------------------------------------------------------- + + /// «Automatica» on with «Copia anche quelli già in libreria» (no «da quando»), through the destinations. + private static async Task 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); + } + + /// The planner's «da scrivere» of «Copia in…» of the whole library, per destination: (account, SHA-256). + private static async Task>> 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>(); + 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 WaitUntilAsync(Func> read, Func 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); + } + } + + /// The real file system, but reading a chosen file never ends, whatever the token says, until . + private sealed class StuckExportFileSystem(Func 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 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 ReadAsync(Memory 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(); + } + } +}