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,
}
///
/// 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.
///
public sealed class LongWorkGate
{
private readonly Lock _lock = new();
private Lease? _holder;
/// Who holds the gate, or null when it is free.
public LongWorkKind? Busy
{
get
{
lock (_lock)
{
return _holder?.Kind;
}
}
}
///
/// Takes the gate for . False, with set, when another job (of any
/// kind, the same one included) holds it.
///
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
{
lock (_lock)
{
if (_holder is { } holder)
{
lease = null;
busyWith = holder.Kind;
return false;
}
var taken = new Lease(this, kind);
_holder = taken;
lease = taken;
busyWith = null;
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)}.",
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
};
private static string Verb(LongWorkKind kind) => kind switch
{
LongWorkKind.Import => "importa",
LongWorkKind.Export => "copia",
_ => "ricostruisci",
};
private void Release(Lease lease)
{
lock (_lock)
{
if (ReferenceEquals(_holder, lease))
{
_holder = 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);
}
}
}
}