using System.Diagnostics.CodeAnalysis;
namespace Febe.Core.Abstractions;
/// The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»).
public enum LongWorkKind
{
/// An import job: analysis or copy (spec §9).
Import,
/// A job of copies to external folders (spec §4.10).
Export,
/// «Ricostruisci il database dalla libreria» (spec §8.5).
Rebuild,
///
/// The conversion for the library (tappa E3, spec §4.10): held only as a ,
/// which any of the others pre-empts.
///
LibraryConversion,
/// A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14).
FrameDownload,
}
///
/// 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.
///
/// The conversion for the library takes a instead (tappa E3, WP2.1): it runs only while
/// no foreground lease is held, and a foreground 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 .
///
///
public sealed class LongWorkGate
{
private readonly Lock _lock = new();
private Lease? _holder;
private BackgroundLease? _background;
/// 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.
public LongWorkKind? Busy
{
get
{
lock (_lock)
{
return _holder?.Kind;
}
}
}
/// True while the background lease (the conversion for the library) is held and not pre-empted.
public bool BackgroundRunning
{
get
{
lock (_lock)
{
return _background is not null;
}
}
}
///
/// Takes the gate for . False, with set, when another job (of any
/// 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 ; past it,
/// false with ).
///
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)
{
lease = null;
busyWith = holder.Kind;
return false;
}
taken = new Lease(this, kind);
_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;
}
///
/// Takes the gate in the background for the conversion for the library. False while any foreground lease, or
/// another background lease, is held.
///
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;
}
}
/// The Italian answer when cannot start because is running.
public static string BusyMessage(LongWorkKind wanted, LongWorkKind busy) => (wanted, busy) switch
{
(LongWorkKind.Import, LongWorkKind.Import) => "C'è già un'importazione al lavoro: aspetta che finisca o interrompila.",
(LongWorkKind.Export, LongWorkKind.Export) => "C'è già una copia al lavoro: aspetta che finisca o interrompila.",
(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)}.",
(_, 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",
LongWorkKind.Rebuild => "ricostruisci",
LongWorkKind.FrameDownload => "scarica i fotogrammi",
LongWorkKind.LibraryConversion => "converti",
_ => "riprova",
};
private void Release(Lease lease)
{
lock (_lock)
{
if (ReferenceEquals(_holder, lease))
{
_holder = null;
}
}
}
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;
public LongWorkKind Kind { get; } = kind;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
gate.Release(this);
}
}
}
///
/// The background lease of the conversion for the library. is cancelled when a foreground
/// job wants the gate; a commit () is waited for by that job, and none begins once
/// pre-empted or disposed.
///
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;
}
/// Cancelled when a foreground job takes the gate.
public CancellationToken Preempted { get; }
/// True once a foreground job asked for the gate (or the lease ended).
public bool IsPreempted
{
get
{
lock (_gate._lock)
{
return _isPreempted;
}
}
}
///
/// 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.
///
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;
}
}
/// Under the gate's lock: marks the lease pre-empted and tells whether a commit is running.
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();
}
}
}
}
}