E3: conversione della libreria in sottofondo con righe sempre vere

La libreria può ora tenere accanto a ogni originale una copia nel
formato scelto, preparata in sottofondo senza mai sostituire o
cancellare l'originale.

- LongWorkGate ha un permesso di sottofondo che il lavoro in primo
  piano (importazione, copie, ricostruzione) interrompe; il
  salvataggio in corso si aspetta al più CommitWait.
- La coda e il lavoratore: nuovi file accodati all'arrivo, quelli già
  in libreria solo su richiesta, pausa, nuovo tentativo, attesa
  durante una sessione del motore o con poco spazio, nomi liberi e
  adozione di un file identico già presente.
- Le righe di media_conversion restano vere in ogni via: eliminazione
  (Ricorda e Consenti il ritorno, con RemoveWithConversionsAsync per
  il vincolo RESTRICT), perdente del ripasso dei doppioni, file
  cambiato (superate e riaccodate), ricostruzione (conta e riconosce
  i convertiti, accoda solo Pending), importazione (una copia
  convertita o un fotogramma non rientra come file nuovo).
- FebeApp avvia il lavoratore con InBackground; la demo mai.
  _febe.jsonl non cambia.

La prova RecordsCannotBeDeletedFromUnderTheirCopies usa ora una riga
Converted: RemoveAsync toglie da sé le righe senza file, e il vincolo
si verifica sia in SQL sia attraverso il magazzino.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 23:57:48 +01:00
1 parent b746aff45d
commit 724c5bda6f
25 files changed
+2621 -38

No files matched your search

+213 -10
View File
@@ -13,19 +13,38 @@ public enum LongWorkKind
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
Rebuild,
/// <summary>
/// The conversion for the library (tappa E3, spec §4.10): held only as a <see cref="LongWorkGate.BackgroundLease"/>,
/// which any of the others pre-empts.
/// </summary>
LibraryConversion,
/// <summary>A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14).</summary>
FrameDownload,
}
/// <summary>
/// Lets only one of import, export and rebuild 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 it ends; disposing
/// it twice releases nothing more.
/// 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
/// it ends; disposing it twice releases nothing more.
/// <para>
/// The conversion for the library takes a <see cref="BackgroundLease"/> instead (tappa E3, WP2.1): it runs only while
/// no foreground lease is held, and a foreground <see cref="TryEnter"/> pre-empts it. Outside a commit the conversion
/// 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 <see cref="CommitWait"/>.
/// </para>
/// </summary>
public sealed class LongWorkGate
{
private readonly Lock _lock = new();
private Lease? _holder;
private BackgroundLease? _background;
/// <summary>Who holds the gate, or null when it is free.</summary>
/// <summary>How long a foreground <see cref="TryEnter"/> waits for a commit of the background work to end.</summary>
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>Who holds the gate in the foreground, or null when it is free. The background lease does not count.</summary>
public LongWorkKind? Busy
{
get
@@ -37,12 +56,34 @@ public sealed class LongWorkGate
}
}
/// <summary>True while the background lease (the conversion for the library) is held and not pre-empted.</summary>
public bool BackgroundRunning
{
get
{
lock (_lock)
{
return _background is not null;
}
}
}
/// <summary>
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
/// kind, the same one included) holds it.
/// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is
/// cancelled and, if it is committing a file, the commit is waited for (at most <see cref="CommitWait"/>; past it,
/// false with <see cref="LongWorkKind.LibraryConversion"/>).
/// </summary>
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
{
if (kind == LongWorkKind.LibraryConversion)
{
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
}
Lease taken;
BackgroundLease? preempted;
bool committing;
lock (_lock)
{
if (_holder is { } holder)
@@ -52,10 +93,47 @@ public sealed class LongWorkGate
return false;
}
var taken = new Lease(this, kind);
taken = new Lease(this, kind);
_holder = taken;
lease = taken;
busyWith = null;
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;
}
/// <summary>
/// Takes the gate in the background for the conversion for the library. False while any foreground lease, or
/// another background lease, is held.
/// </summary>
public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease)
{
lock (_lock)
{
if (_holder is not null || _background is not null)
{
lease = null;
return false;
}
lease = new BackgroundLease(this);
_background = lease;
return true;
}
}
@@ -68,14 +146,20 @@ public sealed class LongWorkGate
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
(_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.",
(_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.",
(_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.",
_ => "Un altro lavoro lungo è in corso: aspetta che finisca.",
};
private static string Verb(LongWorkKind kind) => kind switch
{
LongWorkKind.Import => "importa",
LongWorkKind.Export => "copia",
_ => "ricostruisci",
LongWorkKind.Rebuild => "ricostruisci",
LongWorkKind.FrameDownload => "scarica i fotogrammi",
LongWorkKind.LibraryConversion => "converti",
_ => "riprova",
};
private void Release(Lease lease)
@@ -89,6 +173,17 @@ public sealed class LongWorkGate
}
}
private void Release(BackgroundLease lease)
{
lock (_lock)
{
if (ReferenceEquals(_background, lease))
{
_background = null;
}
}
}
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
{
private int _disposed;
@@ -103,4 +198,112 @@ public sealed class LongWorkGate
}
}
}
/// <summary>
/// The background lease of the conversion for the library. <see cref="Preempted"/> is cancelled when a foreground
/// job wants the gate; a commit (<see cref="TryBeginCommit"/>) is waited for by that job, and none begins once
/// pre-empted or disposed.
/// </summary>
public sealed class BackgroundLease : IDisposable
{
private readonly LongWorkGate _gate;
// Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a
// timer or a wait handle asked for they hold nothing but memory.
private readonly CancellationTokenSource _preempted = new();
private readonly ManualResetEventSlim _noCommit = new(initialState: true);
private bool _isPreempted;
private bool _committing;
private int _disposed;
internal BackgroundLease(LongWorkGate gate)
{
_gate = gate;
Preempted = _preempted.Token;
}
/// <summary>Cancelled when a foreground job takes the gate.</summary>
public CancellationToken Preempted { get; }
/// <summary>True once a foreground job asked for the gate (or the lease ended).</summary>
public bool IsPreempted
{
get
{
lock (_gate._lock)
{
return _isPreempted;
}
}
}
/// <summary>
/// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed,
/// or while another commit of this lease runs: then nothing may be renamed or recorded.
/// </summary>
public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit)
{
lock (_gate._lock)
{
if (_isPreempted || _disposed != 0 || _committing)
{
commit = null;
return false;
}
_committing = true;
_noCommit.Reset();
commit = new Commit(this);
return true;
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
EndCommit();
_gate.Release(this);
lock (_gate._lock)
{
_isPreempted = true;
}
}
/// <summary>Under the gate's lock: marks the lease pre-empted and tells whether a commit is running.</summary>
internal bool MarkPreempted()
{
_isPreempted = true;
return _committing;
}
internal void CancelPreempted() => _preempted.Cancel();
internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout);
private void EndCommit()
{
lock (_gate._lock)
{
_committing = false;
_noCommit.Set();
}
}
private sealed class Commit(BackgroundLease lease) : IDisposable
{
private int _disposed;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
lease.EndCommit();
}
}
}
}
}