diff --git a/docs/decisioni.md b/docs/decisioni.md
index 09e49d3..642459d 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -679,3 +679,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-12-01 | Tappa E4, **eventi `libreria`**: in attesa uno per motivo (`PendingLibraryChanges`, riempito direttamente, non dal canale che scarta), e a ogni giro un evento per ognuno: Dashboard e Account saltano `fermi`, che non cambia nulla lì. **Visualizzatore**: un evento `fermi` conta se l'elemento ha un video (l'esito è del file, non dell'account); conta solo l'ultima rilettura; si chiude quando cambia la pagina sotto (`febe:pagina`). **Copie**: `ExportCopyRequest.Still` dal nome `_fotogramma` (anche « (2)»); un lavoro «Fermo» il cui file è cambiato prende l'istante dell'analisi nuova o salta con la nota `NotStill` (l'istante dell'elemento del lavoro non cambia: è la sua identità) | Un evento solo, l'ultimo, faceva perdere la fine di una copia durante «Cerca i video fermi»; un fotogramma qualunque di un file nuovo non è quello che Alberto ha scelto |
| 2026-12-01 | Tappa E4, **seconda revisione dell'analisi** (sempre algoritmo 1: non è ancora uscito) e di ciò che le sta intorno. (a) `Offsets` = 0,54, 0,865, 0,417, 0,253, 0,432, 0,45, 0,46, trovati con una ricerca: di un filmato ripetuto da 1,9 a 40 volte, anche non un numero intero, i sette istanti abbracciano almeno il 49 % del giro (la prova chiede il 48 %); con quelli di prima il 28 %, e a quasi sette ripetizioni cadevano tutti insieme. Fra fotogrammi veri (18.054 coppie di numero di fotogrammi e periodo) i sette stanno entro mezzo giro in 5 casi (prima 820) ed entro il 40 % in nessuno (prima 338); il tratto più lungo non guardato è di 1,32 parti, il primo e l'ultimo istante restano lontani dalle estremità. Limite dichiarato: un'immagine mostrata per meno di metà giro può sfuggire. (b) Guadagno di una dissolvenza: per blocco il canale più forte non bruciato (non la luma: un blu puro ne ha poca), da 8 in su (`GainFloor`, era 16), almeno 10 blocchi (`GainBlocks`); mediana dei rapporti pesata sulla luce, e concordano se almeno metà della luce sta entro ±5 % (`GainAgreement` 0,1 in tutto) o 1,5 livelli, se sono di più (`GainNoise`); poi il rapporto fra le somme dei blocchi concordi; campo da 1/16 a 16 (`GainRange`, era 8). Prima con i soli blocchi non bruciati, poi con tutti, poi nessun guadagno. (c) Un fotogramma scuro fra due che non lo sono si confronta con l'ultimo chiaro (movimento con la media oltre 3 o l'area oltre il 15 %) e poi con la mediana, e non si sceglie mai. (d) Stesso colore: il canale più forte non bruciato del fotogramma più chiaro, guadagno entro 1/16–16, sul fotogramma come un blocco solo. (e) Un elemento «Fermo» di un lavoro tiene sempre lo SHA-256 sul quale il suo istante è stato scelto: registrarvi quello del file nuovo prima di scriverlo faceva credere, alla ripresa, che il file non fosse cambiato. (f) Anche ogni dialogo si chiude quando cambia la pagina sotto (`febe:pagina`), come se fosse annullato. Misure: 26 immagini × 11 dissolvenze × 2 grane, tutte «Fermo» (prima circa 150 no); scritta, marchio e banda sul nero, foto scure al 10, 14 e 18 %, cartello blu, dissolvenze da 0,5 a 2 s, sempre «Fermo» con D ≤ 0,59 e A 0; sfumature e scritte intorno alla soglia del nero con grana fino a ±10, mai «In movimento»; due immagini in un giro ripetuto circa 7 volte, sempre «In movimento». Resta «In movimento» ciò che ricomprime ogni fotogramma a blocchi 8 × 8 con passo da 8 in su, come prima | Un'immagine ferma su nero, un cartello blu o una foto scura che si dissolvono, o scure quanto la soglia, risultavano «In movimento», e un filmato di due immagini ripetuto circa 7 volte «Fermo»; «Salva il fotogramma» ripreso dopo una pausa salvava l'istante vecchio; una finestra aperta dal visualizzatore o dalla selezione restava sopra la pagina nuova, con i bottoni di ciò che non si vede più |
| 2026-12-04 | Tappa E5, **risposte di Alberto del 4 dicembre 2026 alle domande 48–55 di §16**, date prima del codice. 48: una copia fatta a mano rimasta «In pausa» resta di Alberto anche quando il giro di recupero trova di nuovo la cartella: la Dashboard dice «la cartella risponde di nuovo, riprendi quando vuoi» e riparte solo con «Riprendi» o «Riprova». 49: la copia automatica cede sempre il passo a importazione, ricostruzione, «Copia in…», «Riprendi», «Riconosci le copie già presenti», zip di fotogrammi e «Cerca i video fermi», e riparte da sola dopo; mai durante una sessione del motore, e se era già partita aspetta senza bloccare nulla. 50 (**non la proposta**): ogni giro di recupero, all'avvio e ogni ora, riprova tutti i «Non riuscito» delle copie automatiche, anche quelli che non possono cambiare (oltre 4 GB su FAT32, percorso troppo lungo): niente classe di errori permanenti, niente ritmo giornaliero; fra un giro e l'altro, i passaggi che partono dopo un salvataggio in libreria non li riprovano. 51 (**non la proposta**): «Riconosci le copie già presenti» come proposto (file dovuti non «Copiato», percorso dello schema e «nome (2)»…«(50)», forma di adesso e originale, lunghezza e poi SHA-256, nessun file scritto o tolto, fotogrammi solo se già registrati), ma un «Tolto» resta «Tolto» anche se il file è tornato identico: non adotta mai un file, o un fotogramma, la cui ultima copia in quella cartella è «Tolto»; «Superato» e «Non riuscito» sì. 52: spegnere «Automatica» ferma subito la copia automatica di quella cartella; i file già copiati restano, le copie a mano non si toccano. 53: «Interrompi» su una copia automatica ferma le copie automatiche fino al giro di recupero dopo (almeno un'ora), con «Riprendi ora»; dopo un riavvio ripartono all'avvio. 54: un lavoro per cartella due minuti dopo l'ultimo file salvato, e comunque al giro; «Copia automatica in … finita» in cronologia solo se ha copiato qualcosa o qualcosa non è riuscito. 55: allargare ciò che spetta a una cartella automatica non chiede di nuovo: vale la scelta dell'accensione, e la finestra, la conferma o l'avviso dice quanti file in più partiranno. **Letture** che il progetto della tappa ha fatto di tre punti che sembravano in contrasto: (a) la riga del 27/11 sulle copie rimaste «In corso» («si riprendono dalla Dashboard, mai da sole») vale per le copie fatte a mano; i lavori automatici riprendono da soli (§4.10, «il giro orario riprova»); (b) «alla prima accensione» della risposta 6 del 18/11 vuol dire a ogni passaggio da spenta ad accesa, come dicono già la riga del 26/11 («la prossima accensione chiede di nuovo»), §4.10 e §8.3; (c) nella riga del 26/11 su «Solo i nuovi», `media.downloaded_at` non è «l'ora della riga di `_febe.jsonl`» ma l'ora in cui Febe ha salvato il file in libreria, scaricato o importato (`MediaStore`, `ImportCopier`), che la ricostruzione rimette dalla riga: «nuovo» vuol dire salvato in libreria dopo l'accensione, anche un file arrivato in ritardo (righe del 28/11) | Le domande 48–55 sono le scelte che la tappa E5 non poteva prendere da sola (§16); le tre letture tolgono contraddizioni solo apparenti fra specifica, decisioni e schema, senza cambiare nulla di deciso. 50: Alberto preferisce il lavoro ripetuto e i resoconti con gli stessi errori a una classe di errori da tenere aggiornata; fuori dal giro i «Non riuscito» aspettano perché ogni lavoro finito risveglia la copia automatica, e un file che non riesce mai farebbe un lavoro ogni due minuti invece che ogni ora. 51: un «Tolto» è una scelta di Alberto, che un file rimesso nella cartella non deve annullare |
+| 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 |
diff --git a/src/Febe.Core/Abstractions/LongWorkGate.cs b/src/Febe.Core/Abstractions/LongWorkGate.cs
index 7609544..47bc5c3 100644
--- a/src/Febe.Core/Abstractions/LongWorkGate.cs
+++ b/src/Febe.Core/Abstractions/LongWorkGate.cs
@@ -24,6 +24,14 @@ public enum LongWorkKind
FrameDownload,
}
+///
+/// The answer of : the lease taken, or
+/// (with null) the kind of work that keeps the gate.
+///
+/// The lease, to dispose when the work ends; null when refused.
+/// Who refused the start; null when is set.
+public sealed record LongWorkEntry(IDisposable? Lease, LongWorkKind? BusyWith);
+
///
/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is
/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when
@@ -34,6 +42,13 @@ public enum LongWorkKind
/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one
/// transaction) is waited for, at most .
///
+///
+/// The automatic export (tappa E5, D6) takes a yielding lease with : it excludes the
+/// others like any lease, but a foreground displaces
+/// it (Alberto's work always comes first, §16 answer 49). The new lease becomes the holder at once, under the lock, so
+/// nothing can take the gate in between; then the yielding work is asked to stop and its release is awaited, in real
+/// time, at most a bounded wait. The synchronous refuses a yielding holder like any other.
+///
///
public sealed class LongWorkGate
{
@@ -44,7 +59,16 @@ public sealed class LongWorkGate
/// How long a foreground waits for a commit of the background work to end.
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
- /// Who holds the gate in the foreground, or null when it is free. The background lease does not count.
+ ///
+ /// The usual wait of for a yielding holder to let
+ /// go (15 s). Real time: a hand-over bound, not engine timing (like ).
+ ///
+ public TimeSpan YieldWait { get; init; } = TimeSpan.FromSeconds(15);
+
+ ///
+ /// Who holds the gate in the foreground, or null when it is free. The background lease does not count; a yielding
+ /// holder does (as , say), so work that waits for the gate keeps waiting.
+ ///
public LongWorkKind? Busy
{
get
@@ -56,6 +80,33 @@ public sealed class LongWorkGate
}
}
+ ///
+ /// The holder unless it is yielding work: what refuses a foreground start now. Null when the gate is free or held
+ /// by work that would give way ().
+ ///
+ public LongWorkKind? BusyFirm
+ {
+ get
+ {
+ lock (_lock)
+ {
+ return _holder is { Yielding: false } holder ? holder.Kind : null;
+ }
+ }
+ }
+
+ /// True while the gate is held by yielding work (the automatic export).
+ public bool HeldByYielding
+ {
+ get
+ {
+ lock (_lock)
+ {
+ return _holder is { Yielding: true };
+ }
+ }
+ }
+
/// True while the background lease (the conversion for the library) is held and not pre-empted.
public bool BackgroundRunning
{
@@ -76,24 +127,69 @@ public sealed class LongWorkGate
///
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
{
- if (kind == LongWorkKind.LibraryConversion)
+ if (TryTake(kind, yielding: false, out var taken, out busyWith))
{
- throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
+ lease = taken;
+ return true;
}
+ lease = null;
+ return false;
+ }
+
+ ///
+ /// Takes the gate for as work that yields (the automatic export, tappa E5). Fails, with
+ /// set, while any lease is held, a yielding one included. Pre-empts the background lease
+ /// as does. is cancelled when
+ /// or asks the work to
+ /// stop: it must then stop soon and dispose the lease.
+ ///
+ public bool TryEnterYielding(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out CancellationToken yield, out LongWorkKind? busyWith)
+ {
+ if (TryTake(kind, yielding: true, out var taken, out busyWith))
+ {
+ lease = taken;
+ yield = taken.YieldToken;
+ return true;
+ }
+
+ lease = null;
+ yield = CancellationToken.None;
+ return false;
+ }
+
+ ///
+ /// Takes the gate for in the foreground, waiting at most for a
+ /// yielding holder. See .
+ ///
+ public Task EnterAsync(LongWorkKind kind, CancellationToken ct = default) => EnterAsync(kind, YieldWait, ct);
+
+ ///
+ /// Takes the gate for in the foreground. A firm holder refuses at once, as
+ /// does. A yielding holder is displaced: under the lock the new lease becomes the holder at
+ /// once (so nothing else can take the gate in between), then, outside it, the yielding work is cancelled and its
+ /// release awaited, in real time, at most . Past the wait the new lease is given up, the
+ /// yielding work stays the holder until it lets go, and the entry says (its kind).
+ /// A background lease is pre-empted as with . Callers await this before taking their own lock.
+ ///
+ /// was cancelled during the wait (nothing is held).
+ public async Task EnterAsync(LongWorkKind kind, TimeSpan wait, CancellationToken ct = default)
+ {
+ ThrowIfBackground(kind);
+ ct.ThrowIfCancellationRequested();
Lease taken;
+ Lease? displaced;
BackgroundLease? preempted;
bool committing;
lock (_lock)
{
- if (_holder is { } holder)
+ if (_holder is { Yielding: false } firm)
{
- lease = null;
- busyWith = holder.Kind;
- return false;
+ return new LongWorkEntry(null, firm.Kind);
}
- taken = new Lease(this, kind);
+ displaced = _holder;
+ taken = new Lease(this, kind, yielding: false);
_holder = taken;
preempted = _background;
_background = null;
@@ -104,18 +200,67 @@ public sealed class LongWorkGate
{
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
preempted.CancelPreempted();
- if (committing && !preempted.WaitForCommit(CommitWait))
+ if (committing && !await Task.Run(() => preempted.WaitForCommit(CommitWait), CancellationToken.None).ConfigureAwait(false))
{
+ // A yielding holder pre-empts the background lease itself, so there is none to give back here.
taken.Dispose();
- lease = null;
- busyWith = LongWorkKind.LibraryConversion;
- return false;
+ return new LongWorkEntry(null, LongWorkKind.LibraryConversion);
}
}
- lease = taken;
- busyWith = null;
- return true;
+ if (displaced is null)
+ {
+ return new LongWorkEntry(taken, null);
+ }
+
+ displaced.CancelYield();
+ try
+ {
+ await displaced.Released.WaitAsync(wait, ct).ConfigureAwait(false);
+ return new LongWorkEntry(taken, null);
+ }
+ catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
+ {
+ lock (_lock)
+ {
+ if (displaced.IsReleased)
+ {
+ if (ex is TimeoutException)
+ {
+ return new LongWorkEntry(taken, null); // it let go just now: the gate is ours after all
+ }
+ }
+ else if (ReferenceEquals(_holder, taken))
+ {
+ // Still unwinding (a read stuck on a share that went away): it stays the holder, so nothing else
+ // starts over a copy that may still write; it was asked to stop and lets go by itself.
+ _holder = displaced;
+ }
+ }
+
+ taken.Dispose(); // no longer the holder: releases nothing
+ if (ex is OperationCanceledException)
+ {
+ throw;
+ }
+
+ return new LongWorkEntry(null, displaced.Kind);
+ }
+ }
+
+ ///
+ /// Asks the yielding holder, if any, to stop, without taking the gate («Cerca i video fermi», which takes no lease,
+ /// §16 answer 49). The gate stays held until that work disposes its lease.
+ ///
+ public void CancelYielding()
+ {
+ Lease? holder;
+ lock (_lock)
+ {
+ holder = _holder is { Yielding: true } yielding ? yielding : null;
+ }
+
+ holder?.CancelYield(); // outside the lock: the token's callbacks run synchronously
}
///
@@ -162,15 +307,67 @@ public sealed class LongWorkGate
_ => "riprova",
};
+ private static void ThrowIfBackground(LongWorkKind kind)
+ {
+ if (kind == LongWorkKind.LibraryConversion)
+ {
+ throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
+ }
+ }
+
+ /// The shared body of and : any holder refuses.
+ private bool TryTake(LongWorkKind kind, bool yielding, [NotNullWhen(true)] out Lease? lease, out LongWorkKind? busyWith)
+ {
+ ThrowIfBackground(kind);
+ Lease taken;
+ BackgroundLease? preempted;
+ bool committing;
+ lock (_lock)
+ {
+ if (_holder is { } holder)
+ {
+ lease = null;
+ busyWith = holder.Kind;
+ return false;
+ }
+
+ taken = new Lease(this, kind, yielding);
+ _holder = taken;
+ preempted = _background;
+ _background = null;
+ committing = preempted?.MarkPreempted() ?? false;
+ }
+
+ if (preempted is not null)
+ {
+ // Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
+ preempted.CancelPreempted();
+ if (committing && !preempted.WaitForCommit(CommitWait))
+ {
+ taken.Dispose();
+ lease = null;
+ busyWith = LongWorkKind.LibraryConversion;
+ return false;
+ }
+ }
+
+ lease = taken;
+ busyWith = null;
+ return true;
+ }
+
private void Release(Lease lease)
{
lock (_lock)
{
+ lease.IsReleased = true;
if (ReferenceEquals(_holder, lease))
{
_holder = null;
}
}
+
+ lease.MarkReleased(); // outside the lock: awaiting EnterAsync calls continue elsewhere anyway
}
private void Release(BackgroundLease lease)
@@ -184,12 +381,34 @@ public sealed class LongWorkGate
}
}
- private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
+ ///
+ /// A foreground lease. A yielding one carries the token that asks its work to stop; every lease completes
+ /// when disposed, which a displacing awaits.
+ ///
+ private sealed class Lease(LongWorkGate gate, LongWorkKind kind, bool yielding) : IDisposable
{
+ // Not disposed, as in BackgroundLease: a displacing caller may cancel it after the lease ended, and without a
+ // timer it holds nothing but memory.
+ private readonly CancellationTokenSource? _yield = yielding ? new CancellationTokenSource() : null;
+ private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _disposed;
public LongWorkKind Kind { get; } = kind;
+ public bool Yielding { get; } = yielding;
+
+ public CancellationToken YieldToken => _yield?.Token ?? CancellationToken.None;
+
+ /// Completed once the lease is disposed.
+ public Task Released => _released.Task;
+
+ /// Under the gate's lock: set when the lease was disposed.
+ public bool IsReleased { get; set; }
+
+ public void CancelYield() => _yield?.Cancel();
+
+ public void MarkReleased() => _released.TrySetResult();
+
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
diff --git a/src/Febe.Core/Export/ExportFolderCheck.cs b/src/Febe.Core/Export/ExportFolderCheck.cs
index 04a6433..7a4cd55 100644
--- a/src/Febe.Core/Export/ExportFolderCheck.cs
+++ b/src/Febe.Core/Export/ExportFolderCheck.cs
@@ -350,6 +350,10 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
{
var name = NewProbeName();
var probe = Path.Combine(full, name);
+
+ // Reserved like the safe writer's own temporary files (tappa E5, D7.12): the clean-up of leftovers in this folder,
+ // run by a copy or a discard meanwhile, leaves a live probe alone.
+ using var reservation = SafeFileWriter.ReserveTemporaryFile(probe);
try
{
try
diff --git a/src/Febe.Core/Import/ImportService.cs b/src/Febe.Core/Import/ImportService.cs
index 44d543d..cf3e63c 100644
--- a/src/Febe.Core/Import/ImportService.cs
+++ b/src/Febe.Core/Import/ImportService.cs
@@ -114,9 +114,17 @@ public sealed class ImportService : IAsyncDisposable
{
EnsureIdle();
var source = Sources.Inspect(sourcePath);
- var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false);
- StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token));
- return run;
+ var lease = await EnterGateAsync(ct).ConfigureAwait(false);
+ try
+ {
+ var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false);
+ StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token), ref lease);
+ return run;
+ }
+ finally
+ {
+ lease?.Dispose(); // not handed to a job: the start failed
+ }
}
/// Continues an interrupted analysis or copy in the background.
@@ -124,19 +132,30 @@ public sealed class ImportService : IAsyncDisposable
{
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
- switch (run.State)
+ if (run.State is not (ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted or ImportRunState.Copying or ImportRunState.CopyInterrupted))
{
- case ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted:
- StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token));
- break;
- case ImportRunState.Copying or ImportRunState.CopyInterrupted:
- StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token));
- break;
- default:
- throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
+ throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
}
- return run;
+ EnsureIdle();
+ var lease = await EnterGateAsync(ct).ConfigureAwait(false);
+ try
+ {
+ if (run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted)
+ {
+ StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token), ref lease);
+ }
+ else
+ {
+ StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token), ref lease);
+ }
+
+ return run;
+ }
+ finally
+ {
+ lease?.Dispose();
+ }
}
///
@@ -146,16 +165,24 @@ public sealed class ImportService : IAsyncDisposable
public async Task StartCopyAsync(long runId, ImportMode? mode = null, CancellationToken ct = default)
{
EnsureIdle();
- var run = mode is { } m
- ? await Review.SetModeAsync(runId, m, ct).ConfigureAwait(false)
- : await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
- if (run.State is not (ImportRunState.Reviewing or ImportRunState.CopyInterrupted or ImportRunState.Completed))
+ var lease = await EnterGateAsync(ct).ConfigureAwait(false);
+ try
{
- throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare.");
- }
+ var run = mode is { } m
+ ? await Review.SetModeAsync(runId, m, ct).ConfigureAwait(false)
+ : await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
+ if (run.State is not (ImportRunState.Reviewing or ImportRunState.CopyInterrupted or ImportRunState.Completed))
+ {
+ throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare.");
+ }
- StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token));
- return run;
+ StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token), ref lease);
+ return run;
+ }
+ finally
+ {
+ lease?.Dispose();
+ }
}
/// «Interrompi»: stops the running job of this import and waits until its state is saved.
@@ -278,6 +305,10 @@ public sealed class ImportService : IAsyncDisposable
}
}
+ ///
+ /// The quick refusals, before anything is read or recorded: an import job runs, or a long work that does not give way
+ /// holds the gate (an automatic copy does give way: displaces it).
+ ///
private void EnsureIdle()
{
if (ActiveRunId is not null)
@@ -285,14 +316,32 @@ public sealed class ImportService : IAsyncDisposable
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
- // Checked up front too, so a refused start records nothing; StartJob takes the gate for real.
- if (_env.Gate?.Busy is { } busy)
+ if (_env.Gate?.BusyFirm is { } busy)
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy));
}
}
- private void StartJob(long runId, ImportPhase phase, Func, CancellationToken, Task> work)
+ ///
+ /// Takes the long-work gate before anything is recorded and outside (tappa E5, D6): a yielding
+ /// automatic copy is stopped and awaited (at most , real time), and meanwhile a
+ /// second start is refused at once. Null without a gate (tests).
+ ///
+ private async Task EnterGateAsync(CancellationToken ct)
+ {
+ if (_env.Gate is not { } gate)
+ {
+ return null;
+ }
+
+ var entry = await gate.EnterAsync(LongWorkKind.Import, ct).ConfigureAwait(false);
+ return entry.BusyWith is { } busy
+ ? throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy))
+ : entry.Lease;
+ }
+
+ /// Starts the job; on success it owns (set to null here) and releases it when it ends.
+ private void StartJob(long runId, ImportPhase phase, Func, CancellationToken, Task> work, ref IDisposable? held)
{
lock (_gate)
{
@@ -301,12 +350,8 @@ public sealed class ImportService : IAsyncDisposable
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
- IDisposable? lease = null;
- if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy))
- {
- throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value));
- }
-
+ var lease = held;
+ held = null;
_job?.Cancellation.Dispose();
var cancellation = new CancellationTokenSource();
var reporter = new Reporter(this);
diff --git a/src/Febe.Core/Library/StillVideos/StillVideoService.cs b/src/Febe.Core/Library/StillVideos/StillVideoService.cs
index 6d1e683..c22e7ab 100644
--- a/src/Febe.Core/Library/StillVideos/StillVideoService.cs
+++ b/src/Febe.Core/Library/StillVideos/StillVideoService.cs
@@ -151,7 +151,8 @@ public sealed record StillVideoProgress(
/// - , «Cerca i video fermi» from a selection (answer 41): a job in memory, one video at a
/// time, never during an engine session and never while an import, a copy, a rebuild or a zip of frames holds the
/// (it takes no lease, so it never blocks them: a video being analysed when one starts is
-/// given up and analysed again after). Each video within , inside the
+/// given up and analysed again after). An automatic copy is the exception: a start asks it to stop
+/// (, tappa E5), and the job waits only until it has let go. Each video within , inside the
/// ; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current
/// algorithm are skipped, but for those whose analysis took too long (a start tries them again, once): so a job ended by
/// «Interrompi» or by closing Febe is not resumed by itself: started again, it goes on where it was.
@@ -360,6 +361,7 @@ public sealed class StillVideoService : IDisposable
{
ObjectDisposedException.ThrowIf(_disposed, this);
var (items, _, _, _) = await CollectAsync(selection, ct).ConfigureAwait(false);
+ StillVideoProgress started;
lock (_lock)
{
if (!_running || _jobStop.IsCancellationRequested)
@@ -393,8 +395,17 @@ public sealed class StillVideoService : IDisposable
_loop = Task.Run(LoopAsync);
}
- return Snapshot() with { Added = added };
+ started = Snapshot() with { Added = added };
}
+
+ if (started.Running)
+ {
+ // Alberto's search comes before an automatic copy (§16 answer 49): it is asked to stop, outside the lock (the
+ // token's callbacks run synchronously), and the job waits for the gate as for any long work.
+ _env.Gate?.CancelYielding();
+ }
+
+ return started;
}
/// «Interrompi»: the queue empties, the video being analysed is given up and nothing is stored for it.
diff --git a/src/Febe.Web/Api/FramesApi.cs b/src/Febe.Web/Api/FramesApi.cs
index 6ccfa50..d7c8f72 100644
--- a/src/Febe.Web/Api/FramesApi.cs
+++ b/src/Febe.Web/Api/FramesApi.cs
@@ -148,10 +148,14 @@ public static class FramesApi
throw new ApiStatusException(409, FrameService.SessionText);
}
- if (!gate.TryEnter(LongWorkKind.FrameDownload, out lease, out var busy))
+ // An automatic copy gives way and is awaited here, before anything is sent (tappa E5, D6).
+ var entry = await gate.EnterAsync(LongWorkKind.FrameDownload, ct).ConfigureAwait(false);
+ if (entry.BusyWith is { } busy)
{
- throw new ApiStatusException(409, LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy ?? LongWorkKind.FrameDownload));
+ throw new ApiStatusException(409, LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy));
}
+
+ lease = entry.Lease;
}
try
@@ -360,7 +364,8 @@ public static class FramesApi
return FrameService.SessionText;
}
- if (gate.Busy is { } busy)
+ // An automatic copy does not stop «Scarica»: it gives way when the zip starts.
+ if (gate.BusyFirm is { } busy)
{
return LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy);
}
diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs
index 14c621d..8a64e21 100644
--- a/src/Febe.Web/Api/SettingsApi.cs
+++ b/src/Febe.Web/Api/SettingsApi.cs
@@ -237,8 +237,10 @@ public static class SettingsApi
throw new BadRequestException(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import));
}
- // The gate covers import, copies to external folders and another rebuild (spec §4.10).
- if (!job.TryStart(out var busy))
+ // The gate covers import, copies to external folders and another rebuild (spec §4.10); an automatic copy gives
+ // way, and is awaited here, outside every lock (tappa E5, D6).
+ var (started, busy) = await job.TryStartAsync(ct).ConfigureAwait(false);
+ if (!started)
{
throw new BadRequestException(busy ?? LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild));
}
diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs
index c53ad7e..81b3780 100644
--- a/src/Febe.Web/Library/DataFolderServices.cs
+++ b/src/Febe.Web/Library/DataFolderServices.cs
@@ -177,12 +177,44 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
}
}
- /// Starts the rebuild; false when one is already running or another long job holds the gate.
+ ///
+ /// «Ricostruisci» from the page (tappa E5, D6): takes the long-work gate first, outside this job's lock, so an
+ /// automatic copy is stopped and awaited (at most , real time) without holding
+ /// anything; then starts. Not started, with the Italian reason, when a rebuild, an import, a copy started by Alberto
+ /// or a zip of frames is running, or the automatic copy does not let go in time.
+ ///
+ public async Task<(bool Started, string? Busy)> TryStartAsync(CancellationToken ct = default)
+ {
+ if (Running)
+ {
+ return (false, LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild));
+ }
+
+ var entry = await gate.EnterAsync(LongWorkKind.Rebuild, ct).ConfigureAwait(false);
+ if (entry.BusyWith is { } holder)
+ {
+ return (false, LongWorkGate.BusyMessage(LongWorkKind.Rebuild, holder));
+ }
+
+ lock (_gate)
+ {
+ if (_task is { IsCompleted: false })
+ {
+ entry.Lease!.Dispose();
+ return (false, LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild));
+ }
+
+ Begin(entry.Lease!);
+ return (true, null);
+ }
+ }
+
+ /// Starts the rebuild; false when one is already running or another long job holds the gate (tests).
public bool TryStart() => TryStart(out _);
///
/// Starts the rebuild; false, with the Italian reason in , when a rebuild, an import or a copy
- /// to external folders is running.
+ /// to external folders is running. It does not wait for a yielding holder ( does).
///
public bool TryStart(out string? busy)
{
@@ -201,12 +233,18 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
}
busy = null;
- State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
- _task = Task.Run(() => RunAsync(lease));
+ Begin(lease);
return true;
}
}
+ /// Under : the job starts and owns .
+ private void Begin(IDisposable lease)
+ {
+ State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
+ _task = Task.Run(() => RunAsync(lease));
+ }
+
/// Waits for the running rebuild (tests).
public Task WaitAsync() => _task ?? Task.CompletedTask;
@@ -221,6 +259,9 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
State = State with { Running = false, Report = report, FinishedAt = clock.Now };
changes.Publish(new LibraryChange(clock.Now, null, "rebuild"));
await RecheckExportsAsync().ConfigureAwait(false);
+
+ // The rebuild may have brought back files and accounts: the automatic export looks again (tappa E5, D4).
+ Febe.Core.Export.AutoExportSignal.Default.Signal();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{
diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs
index 73672f1..c67ee86 100644
--- a/tests/Febe.Tests/Export/ExportFoundationTests.cs
+++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs
@@ -3,6 +3,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
+using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
@@ -10,7 +11,8 @@ namespace Febe.Tests.Export;
///
/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder
-/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set.
+/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set. Tappa E5
+/// (WP1) adds the yielding leases of the automatic export and the starters that await them outside their locks.
///
[TestClass]
public sealed class ExportFoundationTests
@@ -129,6 +131,334 @@ public sealed class ExportFoundationTests
Assert.IsNull(gate.Busy); // the job's lease went with it
}
+ // ---------------------------------------------------------------- Yielding leases (tappa E5, D6; §16 answer 49)
+
+ [TestMethod]
+ public void AYieldingLeaseExcludesOthersLikeAnyLease()
+ {
+ var gate = new LongWorkGate();
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out var none));
+ Assert.IsNull(none);
+ Assert.IsTrue(yield.CanBeCanceled);
+ Assert.IsFalse(yield.IsCancellationRequested);
+
+ Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out var second, out var busy));
+ Assert.AreEqual(LongWorkKind.Export, busy);
+ Assert.IsFalse(second.CanBeCanceled);
+ Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out busy));
+ Assert.AreEqual(LongWorkKind.Export, busy);
+
+ automatic.Dispose();
+ Assert.IsNull(gate.Busy);
+ Assert.IsFalse(gate.HeldByYielding);
+ Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
+ automatic.Dispose(); // a second dispose of the old lease releases nothing
+ Assert.AreEqual(LongWorkKind.Import, gate.Busy);
+ import.Dispose();
+ Assert.ThrowsExactly(() => gate.TryEnterYielding(LongWorkKind.LibraryConversion, out _, out _, out _));
+ }
+
+ [TestMethod]
+ [Timeout(60_000, CooperativeCancellation = true)]
+ public async Task EnterAsyncDisplacesTheYieldingHolderAndTakesTheGateAtOnce()
+ {
+ var ct = TestContext.CancellationToken;
+ var gate = new LongWorkGate();
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+
+ var entering = gate.EnterAsync(LongWorkKind.Import, TimeSpan.FromSeconds(30), ct);
+
+ // The new holder is in place before the copy has let go: nothing can slip in between.
+ Assert.IsTrue(yield.IsCancellationRequested, "the copy is asked to stop");
+ Assert.IsFalse(entering.IsCompleted, "the import waits for the copy to let go");
+ Assert.AreEqual(LongWorkKind.Import, gate.Busy);
+ Assert.AreEqual(LongWorkKind.Import, gate.BusyFirm);
+ Assert.IsFalse(gate.HeldByYielding);
+ Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out var busy), "the worker cannot start again meanwhile");
+ Assert.AreEqual(LongWorkKind.Import, busy);
+ Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out busy));
+ Assert.AreEqual(LongWorkKind.Import, busy);
+ Assert.AreEqual(LongWorkKind.Import, (await gate.EnterAsync(LongWorkKind.Rebuild, TimeSpan.FromSeconds(30), ct)).BusyWith, "a firm holder refuses at once");
+
+ automatic.Dispose(); // the copy unwinds: its release does not clear the new holder
+ var entry = await entering.WaitAsync(TimeSpan.FromSeconds(30), ct);
+ Assert.IsNull(entry.BusyWith);
+ Assert.IsNotNull(entry.Lease);
+ Assert.AreEqual(LongWorkKind.Import, gate.Busy);
+
+ entry.Lease.Dispose();
+ Assert.IsNull(gate.Busy);
+
+ // A free gate is taken at once, and so is one whose yielding holder has already let go.
+ var free = await gate.EnterAsync(LongWorkKind.Rebuild, ct);
+ Assert.IsNotNull(free.Lease);
+ Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
+ free.Lease.Dispose();
+ }
+
+ [TestMethod]
+ [Timeout(60_000, CooperativeCancellation = true)]
+ public async Task EnterAsyncGivesExportWhenTheYieldingHolderDoesNotReleaseInTime()
+ {
+ var ct = TestContext.CancellationToken;
+ var gate = new LongWorkGate { YieldWait = TimeSpan.FromMilliseconds(100) };
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var stuck, out var yield, out _));
+
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var entry = await gate.EnterAsync(LongWorkKind.Import, ct);
+ watch.Stop();
+ Assert.IsNull(entry.Lease);
+ Assert.AreEqual(LongWorkKind.Export, entry.BusyWith);
+ Assert.IsTrue(yield.IsCancellationRequested);
+ Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the wait is bounded");
+
+ // The copy that has not let go yet keeps the gate: nothing starts over a copy that may still write.
+ Assert.AreEqual(LongWorkKind.Export, gate.Busy);
+ Assert.IsTrue(gate.HeldByYielding);
+ Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out var busy));
+ Assert.AreEqual(LongWorkKind.Export, busy);
+
+ // The same when the caller gives up (the page went away).
+ using var gone = new CancellationTokenSource();
+ var waiting = gate.EnterAsync(LongWorkKind.Rebuild, TimeSpan.FromSeconds(30), gone.Token);
+ Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
+ await gone.CancelAsync();
+ await Assert.ThrowsAsync(() => waiting);
+ Assert.AreEqual(LongWorkKind.Export, gate.Busy);
+ Assert.IsTrue(gate.HeldByYielding);
+
+ stuck.Dispose();
+ Assert.IsNull(gate.Busy);
+ var late = await gate.EnterAsync(LongWorkKind.Import, ct);
+ Assert.IsNotNull(late.Lease, "once it let go the gate is free");
+ late.Lease.Dispose();
+ }
+
+ [TestMethod]
+ public void TryEnterRefusesAYieldingHolderWithoutWaiting()
+ {
+ var gate = new LongWorkGate { YieldWait = TimeSpan.FromMinutes(5) };
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ Assert.IsFalse(gate.TryEnter(LongWorkKind.Import, out _, out var busy));
+ watch.Stop();
+ Assert.AreEqual(LongWorkKind.Export, busy);
+ Assert.IsLessThan(TimeSpan.FromSeconds(5), watch.Elapsed);
+ Assert.IsFalse(yield.IsCancellationRequested, "a caller left on TryEnter does not stop the copy");
+ Assert.IsTrue(gate.HeldByYielding);
+ automatic.Dispose();
+ }
+
+ [TestMethod]
+ public void TryEnterYieldingFailsWhileAnyLeaseIsHeldAndPreemptsTheLibraryConversion()
+ {
+ var gate = new LongWorkGate();
+ foreach (var kind in new[] { LongWorkKind.Import, LongWorkKind.Export, LongWorkKind.Rebuild, LongWorkKind.FrameDownload })
+ {
+ Assert.IsTrue(gate.TryEnter(kind, out var firm, out _));
+ Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out var busy), kind.ToString());
+ Assert.AreEqual(kind, busy);
+ firm.Dispose();
+ }
+
+ Assert.IsTrue(gate.TryEnterBackground(out var conversion));
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
+ Assert.IsTrue(conversion.Preempted.IsCancellationRequested, "the automatic copy pre-empts the library conversion");
+ Assert.IsTrue(conversion.IsPreempted);
+ Assert.IsFalse(gate.BackgroundRunning);
+ conversion.Dispose();
+ automatic.Dispose();
+
+ // A commit of the conversion is waited for, as with TryEnter.
+ var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) };
+ Assert.IsTrue(quick.TryEnterBackground(out var slow));
+ Assert.IsTrue(slow.TryBeginCommit(out var commit));
+ Assert.IsFalse(quick.TryEnterYielding(LongWorkKind.Export, out _, out _, out var committing));
+ Assert.AreEqual(LongWorkKind.LibraryConversion, committing);
+ Assert.IsNull(quick.Busy);
+ commit.Dispose();
+ slow.Dispose();
+ }
+
+ [TestMethod]
+ public void TryEnterBackgroundFailsWhileAYieldingLeaseIsHeld()
+ {
+ var gate = new LongWorkGate();
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
+ Assert.IsFalse(gate.TryEnterBackground(out _), "the library conversion waits for the automatic copy too");
+ automatic.Dispose();
+ Assert.IsTrue(gate.TryEnterBackground(out var conversion));
+ conversion.Dispose();
+ }
+
+ [TestMethod]
+ public void BusyReportsExportButBusyFirmIsNullForAYieldingHolder()
+ {
+ var gate = new LongWorkGate();
+ Assert.IsNull(gate.BusyFirm);
+ Assert.IsFalse(gate.HeldByYielding);
+
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
+ Assert.AreEqual(LongWorkKind.Export, gate.Busy, "the conversion and the still-video search keep waiting");
+ Assert.IsNull(gate.BusyFirm, "a start is not refused: the copy gives way");
+ Assert.IsTrue(gate.HeldByYielding);
+ automatic.Dispose();
+
+ Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var manual, out _));
+ Assert.AreEqual(LongWorkKind.Export, gate.Busy);
+ Assert.AreEqual(LongWorkKind.Export, gate.BusyFirm, "a copy started by Alberto does not give way");
+ Assert.IsFalse(gate.HeldByYielding);
+ manual.Dispose();
+ Assert.IsNull(gate.BusyFirm);
+ }
+
+ [TestMethod]
+ public void CancelYieldingStopsTheHolderWithoutTakingTheGate()
+ {
+ var gate = new LongWorkGate();
+ gate.CancelYielding(); // nothing held: nothing happens
+
+ Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
+ gate.CancelYielding(); // a firm holder is not touched
+ Assert.AreEqual(LongWorkKind.Import, gate.Busy);
+ import.Dispose();
+
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+ gate.CancelYielding();
+ Assert.IsTrue(yield.IsCancellationRequested);
+ Assert.AreEqual(LongWorkKind.Export, gate.Busy, "the gate stays held until the copy lets go");
+ Assert.IsTrue(gate.HeldByYielding);
+ Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out _));
+ automatic.Dispose();
+ Assert.IsNull(gate.Busy);
+ }
+
+ [TestMethod]
+ [Timeout(120_000, CooperativeCancellation = true)]
+ public async Task AnImportStartRecordsNothingWhenRefused_AndWaitsOutsideItsLock()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var bed = await ImportTestBed.CreateAsync(temp);
+ bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(330, 200, 150));
+ var gate = new LongWorkGate();
+ await using var service = new ImportService(bed.Environment with { Gate = gate });
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+
+ var first = service.StartAsync(bed.Source, ct: ct);
+ Assert.IsTrue(yield.IsCancellationRequested, "the automatic copy is asked to give way");
+ Assert.IsFalse(first.IsCompleted, "the import waits for the copy to let go");
+ Assert.AreEqual(LongWorkKind.Import, gate.BusyFirm, "the import holds the gate already");
+ var active = await Task.Run(() => service.ActiveRunId, ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
+ Assert.IsNull(active, "the service's own lock is free while it waits");
+ Assert.IsEmpty(await service.ListRunsAsync(ct), "nothing is recorded before the gate is taken");
+
+ // A second start meanwhile is answered at once, and records nothing.
+ var second = await Assert.ThrowsExactlyAsync(() => service.StartAsync(bed.Source, ct: ct));
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Import), second.Message);
+ Assert.IsFalse(first.IsCompleted);
+ Assert.IsEmpty(await service.ListRunsAsync(ct));
+
+ automatic.Dispose();
+ var run = await first.WaitAsync(TimeSpan.FromSeconds(30), ct);
+ await service.WaitAsync(run.Id, ct);
+ Assert.HasCount(1, await service.ListRunsAsync(ct));
+ Assert.IsNull(gate.Busy, "the job's lease went with it");
+
+ // A copy that does not let go in time: refused with the copy's message, nothing recorded, the copy keeps the gate.
+ var slow = new LongWorkGate { YieldWait = TimeSpan.FromMilliseconds(100) };
+ await using var other = new ImportService(bed.Environment with { Gate = slow });
+ Assert.IsTrue(slow.TryEnterYielding(LongWorkKind.Export, out var stuck, out _, out _));
+ var refused = await Assert.ThrowsExactlyAsync(() => other.StartAsync(bed.Source, ct: ct));
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), refused.Message);
+ Assert.HasCount(1, await other.ListRunsAsync(ct), "a refused import records nothing");
+ Assert.IsTrue(slow.HeldByYielding);
+ stuck.Dispose();
+
+ // A copy started by Alberto refuses at once, before anything is read or recorded.
+ Assert.IsTrue(slow.TryEnter(LongWorkKind.Export, out var manual, out _));
+ var firm = await Assert.ThrowsExactlyAsync(() => other.StartCopyAsync(run.Id, ImportMode.Copy, ct));
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), firm.Message);
+ manual.Dispose();
+ }
+
+ [TestMethod]
+ [Timeout(120_000, CooperativeCancellation = true)]
+ public async Task TheRebuildStartAwaitsTheYieldOutsideItsLock()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var library = await TestLibrary.CreateAsync(temp);
+ var gate = new LongWorkGate();
+ var job = new Febe.Web.Library.RebuildJob(
+ library.Db,
+ new Febe.Web.Library.FebeLibrary(library.Db, library.Data, library.Layout, library.Clock),
+ library.Clock,
+ new Febe.Web.Library.LibraryChanges(),
+ gate);
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+
+ var starting = job.TryStartAsync(ct);
+ Assert.IsTrue(yield.IsCancellationRequested, "the automatic copy is asked to give way");
+ Assert.IsFalse(starting.IsCompleted, "the rebuild waits for the copy to let go");
+ var running = await Task.Run(() => job.Running, ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
+ Assert.IsFalse(running, "the job's own lock is free while it waits");
+
+ // Meanwhile another «Ricostruisci» is answered at once.
+ var again = await job.TryStartAsync(ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
+ Assert.IsFalse(again.Started);
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild), again.Busy);
+ Assert.IsFalse(job.TryStart(out var busy));
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild), busy);
+
+ var signals = AutoExportSignal.Default.Count;
+ automatic.Dispose();
+ var started = await starting.WaitAsync(TimeSpan.FromSeconds(30), ct);
+ Assert.IsTrue(started.Started);
+ Assert.IsNull(started.Busy);
+ await job.WaitAsync();
+ Assert.IsNull(job.State.Error);
+ Assert.IsNotNull(job.State.Report);
+ Assert.IsNull(gate.Busy, "the rebuild's lease went with it");
+ Assert.IsGreaterThan(signals, AutoExportSignal.Default.Count, "a finished rebuild wakes the automatic export");
+
+ // A long work that does not give way refuses the rebuild with its message.
+ Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
+ var refused = await job.TryStartAsync(ct);
+ Assert.IsFalse(refused.Started);
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import), refused.Busy);
+ import.Dispose();
+ }
+
+ [TestMethod]
+ public async Task TheProbeIsReservedWhileItIsChecked()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var usb = temp.Combine("usb");
+ Directory.CreateDirectory(usb);
+ var survived = new List();
+ var check = new ExportFolderCheck(new FixedMounts(), writeProbe: path =>
+ {
+ File.WriteAllText(path, "Febe");
+
+ // The clean-up of leftovers of another job runs in the same folder meanwhile (tappa E5, D7.12).
+ SafeFileWriter.CleanupTemporaryFiles(usb);
+ survived.Add(File.Exists(path));
+ });
+ var context = new ExportFolderContext([], ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() });
+
+ Assert.IsTrue((await check.CheckAsync(usb, context, ct)).Accepted);
+ CollectionAssert.AreEqual(new[] { true }, survived, "a live probe is left alone");
+ Assert.IsEmpty(Directory.GetFileSystemEntries(usb), "the probe is removed after the check");
+
+ // Once the check is over, a probe left behind is an ordinary leftover.
+ var left = Path.Combine(usb, ExportFolderCheck.NewProbeName());
+ File.WriteAllText(left, "Febe");
+ Assert.AreEqual(1, SafeFileWriter.CleanupTemporaryFiles(usb));
+ }
+
[TestMethod]
public void MountInfoGivesRootMountPointAndType()
{
diff --git a/tests/Febe.Tests/Library/StillVideoServiceTests.cs b/tests/Febe.Tests/Library/StillVideoServiceTests.cs
index 115d168..60fe022 100644
--- a/tests/Febe.Tests/Library/StillVideoServiceTests.cs
+++ b/tests/Febe.Tests/Library/StillVideoServiceTests.cs
@@ -294,6 +294,35 @@ public sealed class StillVideoServiceTests
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
+ [TestMethod]
+ public async Task AStartAsksAnAutomaticCopyToStopAndWaitsUntilItLetsGo()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var library = await TestLibrary.CreateAsync(temp);
+ var (account, video) = await SaveVideoAsync(library, "1", StillVideo(12));
+ var empty = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
+ var gate = new LongWorkGate();
+ var calls = new ConcurrentQueue();
+ using var service = new StillVideoService(Environment(library, gate) with { Analyser = Counting(calls) });
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+
+ // Nothing to search: the copy goes on.
+ Assert.IsFalse((await service.StartAsync(new ExportSelection.Account(empty.Id), ct)).Running);
+ Assert.IsFalse(yield.IsCancellationRequested);
+
+ // «Cerca i video fermi» comes first (§16 answer 49): the copy is asked to stop, and the job waits for the gate.
+ await service.StartAsync(new ExportSelection.Account(account.Id), ct);
+ Assert.IsTrue(yield.IsCancellationRequested);
+ await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork, ct);
+ Assert.IsEmpty(calls);
+
+ automatic.Dispose();
+ await service.Job.WaitAsync(Patience, ct);
+ Assert.HasCount(1, calls);
+ Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
+ }
+
[TestMethod]
public async Task ASessionThatStartsDuringAnAnalysisMakesTheJobGiveWay()
{
diff --git a/tests/Febe.Tests/Web/ExportFramesApiTests.cs b/tests/Febe.Tests/Web/ExportFramesApiTests.cs
index 4e76c57..0cf7d9e 100644
--- a/tests/Febe.Tests/Web/ExportFramesApiTests.cs
+++ b/tests/Febe.Tests/Web/ExportFramesApiTests.cs
@@ -222,6 +222,18 @@ public sealed class ExportFramesApiTests
}
Assert.IsNull(gate.Busy, "no lease is left behind");
+
+ // An automatic copy (tappa E5) does not stop «Scarica»: the zip asks it to give way and starts once it has.
+ Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
+ using (yield.Register(automatic.Dispose))
+ {
+ Assert.AreEqual(JsonValueKind.Null, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.GetProperty("problem").ValueKind);
+ Assert.IsFalse(yield.IsCancellationRequested, "the plan alone does not stop the copy");
+ Assert.IsNotEmpty((await ZipAsync(server, Selection(21))).Entries);
+ Assert.IsTrue(yield.IsCancellationRequested);
+ }
+
+ Assert.IsNull(gate.Busy, "no lease is left behind");
}
[TestMethod]