E5: il lavoratore delle copie automatiche, all'avvio e ogni ora
AutoExportWorker copia da solo nelle cartelle con «Automatica» accesa: il giro di recupero all'avvio e ogni ora (IClock), una passata due minuti dopo l'ultima riga di _febe.jsonl (il segnale parte da LibraryIngest, anche per le righe scritte in ritardo), subito con un segnale urgente. Mai durante una sessione del motore: aspetta e dice perché; i lavori di Alberto vengono prima e, finiti, il lavoro automatico spostato riprende da solo (risposta 49). Al giro riprova le cartelle in pausa (una copia manuale «In pausa» resta di Alberto, risposta 48) e tutti i «Non riuscito» (risposta 50b); «Interrompi» lo ferma fino alla fine della sosta (risposta 53). Un lavoro finito non ne fa partire un altro da solo, così un file che non cambia torna solo al giro. La composizione lo avvia solo nell'avvio normale (mai nella dimostrazione) e lo ferma per primo alla chiusura. Prove: AutoExportWorkerTests (le prove di accettazione di §15: «Tolto» e «Superato» non si ricopiano, una cartella irraggiungibile va in pausa e un giro dopo riprende, nessuna copia durante una sessione), il segnale del giornale, la composizione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0ff4a0d632
commit
e66e322d35
12 files changed
+1821
-5
No files matched your search
@@ -0,0 +1,36 @@
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Why the automatic export waits (tappa E5, D8), as the Dashboard shows it: one line, Italian, never a path. The
|
||||
/// interface never says a bare «giro» here, which names the engine's «Giro dei seguiti».
|
||||
/// </summary>
|
||||
public static class AutoExportText
|
||||
{
|
||||
/// <summary>An engine session is under way: nothing is copied during it.</summary>
|
||||
public const string InSession = "Copie automatiche: riprendono alla fine della sessione del motore.";
|
||||
|
||||
/// <summary>«Cerca i video fermi» is at work: it never runs together with copies.</summary>
|
||||
public const string StillVideos = "Copie automatiche: aspettano la fine di «Cerca i video fermi».";
|
||||
|
||||
/// <summary>A copy started by Alberto («Copia in…», «Riprendi», «Controlla le copie», «Riconosci») is at work.</summary>
|
||||
public const string ManualJob = "Copie automatiche: aspettano la fine della copia in corso.";
|
||||
|
||||
/// <summary>Alberto's long work holds the gate (import, rebuild, a zip of frames).</summary>
|
||||
public static string LongWork(LongWorkKind kind) => kind switch
|
||||
{
|
||||
LongWorkKind.Import => "Copie automatiche: aspettano la fine di un'importazione.",
|
||||
LongWorkKind.Rebuild => "Copie automatiche: aspettano la fine della ricostruzione.",
|
||||
LongWorkKind.FrameDownload => "Copie automatiche: aspettano la fine di uno zip di fotogrammi.",
|
||||
LongWorkKind.Export => ManualJob,
|
||||
_ => "Copie automatiche: aspettano la fine di un lavoro lungo.",
|
||||
};
|
||||
|
||||
/// <summary>The worker's loop met an unexpected error (the log gets the type only, rule 10).</summary>
|
||||
public static string Error(Exception ex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
return $"Le copie automatiche si sono fermate per un errore ({ex.GetType().Name}): riprovano al prossimo giro di recupero.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>What the automatic export needs from the rest of Febe (tappa E5, D8).</summary>
|
||||
public sealed record AutoExportEnvironment
|
||||
{
|
||||
public required IFebeStorage Storage { get; init; }
|
||||
|
||||
/// <summary>Engine timing: rounds, settle, polls and sleeps (never DateTime.Now or Task.Delay).</summary>
|
||||
public required IClock Clock { get; init; }
|
||||
|
||||
/// <summary>The export service of the application (the web host's ExportHub builds it at the first use).</summary>
|
||||
public required Func<CancellationToken, Task<ExportService>> Service { get; init; }
|
||||
|
||||
/// <summary>What wakes the worker: journal lines, a rebuild, a destination turned on, «Riprendi ora».</summary>
|
||||
public AutoExportSignal Signal { get; init; } = AutoExportSignal.Default;
|
||||
|
||||
/// <summary>No copy starts during an engine session.</summary>
|
||||
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
|
||||
|
||||
/// <summary>The gate of long work: Alberto's import, rebuild and zip of frames come first. Null: none (tests).</summary>
|
||||
public LongWorkGate? Gate { get; init; }
|
||||
|
||||
/// <summary>Other work the copies never run with: «Cerca i video fermi» (its progress says it runs).</summary>
|
||||
public Func<bool> OtherWorkRunning { get; init; } = () => false;
|
||||
|
||||
/// <summary>The recovery round: at start-up and then every this long (answer 54: «e comunque al giro»).</summary>
|
||||
public TimeSpan Round { get; init; } = TimeSpan.FromHours(1);
|
||||
|
||||
/// <summary>A pass starts this long after the last file saved in the library (answer 54).</summary>
|
||||
public TimeSpan Settle { get; init; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>The longest the settle can be pushed on by files that keep arriving.</summary>
|
||||
public TimeSpan SettleLimit { get; init; } = TimeSpan.FromMinutes(15);
|
||||
|
||||
/// <summary>How often the worker looks again while it waits for a session or Alberto's work to end.</summary>
|
||||
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// The longest sleep without looking at the clock: after a sleep or hibernation of the PC the round runs at most this
|
||||
/// late (engineering B10).
|
||||
/// </summary>
|
||||
public TimeSpan MaxSleep { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>The longest wait for the loop to end at the stop, in real time (a safety bound, not engine timing).</summary>
|
||||
public TimeSpan StopWait { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>One line for the log: Italian text and exception type names only, never paths (rule 10).</summary>
|
||||
public Action<string>? Log { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What one pass of the automatic export did.</summary>
|
||||
public enum AutoExportPass
|
||||
{
|
||||
/// <summary>Nothing looked at (an error, logged).</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>«Interrompi» holds the automatic copies (answer 53): the pass is due again when the hold ends.</summary>
|
||||
Held,
|
||||
|
||||
/// <summary>An engine session or Alberto's work: the pass is due again after <see cref="AutoExportEnvironment.Poll"/>.</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>An automatic job is already at work: the pass is due again when it ends.</summary>
|
||||
Running,
|
||||
|
||||
/// <summary>An automatic job started (new files, or unfinished automatic runs resumed).</summary>
|
||||
Started,
|
||||
|
||||
/// <summary>Nothing to copy.</summary>
|
||||
NothingToDo,
|
||||
}
|
||||
|
||||
/// <summary>The automatic export as the Dashboard shows it.</summary>
|
||||
/// <param name="Running">The worker's loop runs (never in the demo, nor in a start with problems).</param>
|
||||
/// <param name="AnyAutomatic">At least one destination in use has «Automatica» on.</param>
|
||||
/// <param name="Waiting">Why the copies wait now (<see cref="AutoExportText"/>), or null.</param>
|
||||
/// <param name="LastRound">When the last recovery round ran.</param>
|
||||
/// <param name="NextRound">When the next recovery round is due.</param>
|
||||
/// <param name="HeldUntil">Until when «Interrompi» holds the automatic copies.</param>
|
||||
public sealed record AutoExportStatus(bool Running, bool AnyAutomatic, string? Waiting, DateTimeOffset? LastRound, DateTimeOffset? NextRound, DateTimeOffset? HeldUntil);
|
||||
|
||||
/// <summary>
|
||||
/// The automatic export (tappa E5, spec §4.10, D8): copies by itself, into each destination with «Automatica» on, the
|
||||
/// files due there and not copied yet (from the database, <see cref="ExportSelection.Automatic"/>). A pass runs a little
|
||||
/// after a file is saved in the library (<see cref="AutoExportEnvironment.Settle"/> after its <c>_febe.jsonl</c> line,
|
||||
/// answer 54), at start-up and at every recovery round (every hour). One job per destination per pass; never during an
|
||||
/// engine session; Alberto's work comes first (answer 49: the job's lease yields and the worker waits, then resumes
|
||||
/// the interrupted runs); «Tolto» and «Superato» are never copied again. The round also tries every paused destination
|
||||
/// again: one that answers is no longer paused, and its automatic runs resume (a manual «In pausa» stays Alberto's,
|
||||
/// answer 48); every «Non riuscito» is tried again by each round (answer 50). Started by the composition, never in the
|
||||
/// demo (as decision r.644 for the library conversion). Touches nothing but the disk: no Instagram, no Governatore.
|
||||
/// </summary>
|
||||
public sealed class AutoExportWorker
|
||||
{
|
||||
private readonly AutoExportEnvironment _env;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _pass = new(1, 1);
|
||||
private ExportService? _service;
|
||||
private CancellationTokenSource? _stop;
|
||||
private Task _loop = Task.CompletedTask;
|
||||
private bool _running;
|
||||
private string? _waiting;
|
||||
private DateTimeOffset? _lastRound;
|
||||
private DateTimeOffset? _nextRound;
|
||||
private long _passes;
|
||||
|
||||
// The last Started pass resumed runs instead of looking for new files: a pass follows once that job ends.
|
||||
private bool _resumed;
|
||||
|
||||
public AutoExportWorker(AutoExportEnvironment env)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
_env = env;
|
||||
}
|
||||
|
||||
/// <summary>True while <see cref="RunAsync"/> runs.</summary>
|
||||
public bool Running
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _running;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tests only: how many passes ended (however they ended).</summary>
|
||||
internal long Passes => Interlocked.Read(ref _passes);
|
||||
|
||||
/// <summary>The automatic export now: whether any destination is automatic is read from the database.</summary>
|
||||
public async Task<AutoExportStatus> StatusAsync(CancellationToken ct = default)
|
||||
{
|
||||
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||
var any = destinations.Any(d => d is { Automatic: true, IsOrphan: false });
|
||||
DateTimeOffset? held;
|
||||
lock (_gate)
|
||||
{
|
||||
held = _service?.AutomaticHeldUntil;
|
||||
return new AutoExportStatus(_running, any, _waiting, _lastRound, _nextRound, held);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Riprendi ora» (answer 53): the automatic copies are no longer held, and a pass runs at once (no settle).
|
||||
/// </summary>
|
||||
public async Task ResumeNowAsync(CancellationToken ct = default)
|
||||
{
|
||||
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||
service.ReleaseAutomaticHold();
|
||||
_env.Signal.Signal(urgent: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The loop: the start-up round at once, then a pass at each signal (after the settle) and at each recovery round.
|
||||
/// An error of a pass is logged by type and the loop goes on. Ends, without throwing, when <paramref name="ct"/> is
|
||||
/// cancelled or <see cref="StopAsync"/> is called.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The loop already runs.</exception>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
CancellationTokenSource stop;
|
||||
Task loop;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_running)
|
||||
{
|
||||
throw new InvalidOperationException("Le copie automatiche sono già al lavoro.");
|
||||
}
|
||||
|
||||
_running = true;
|
||||
stop = _stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
loop = _loop = Task.Run(() => LoopAsync(stop.Token), CancellationToken.None);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await loop.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (stop.IsCancellationRequested)
|
||||
{
|
||||
// Stopped.
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_running = false;
|
||||
_stop = null;
|
||||
_waiting = null;
|
||||
}
|
||||
|
||||
stop.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the loop and waits for it, at most <see cref="AutoExportEnvironment.StopWait"/> in real time. A job already
|
||||
/// started is not stopped here (the composition interrupts it next).
|
||||
/// </summary>
|
||||
public async Task StopAsync()
|
||||
{
|
||||
Task loop;
|
||||
lock (_gate)
|
||||
{
|
||||
try
|
||||
{
|
||||
_stop?.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// Already over.
|
||||
}
|
||||
|
||||
loop = _loop;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await loop.WaitAsync(_env.StopWait).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or TimeoutException)
|
||||
{
|
||||
// Stopped, or a pass stuck on a share that went away: it ends by itself.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One pass, in order (D8): orphan automatic runs cancelled (round); the hold; an engine session, Alberto's work,
|
||||
/// «Cerca i video fermi», a job at work; paused destinations tried again (round); unfinished automatic runs resumed
|
||||
/// (those stopped with an error only at the round); else a job over every automatic destination not paused.
|
||||
/// </summary>
|
||||
/// <param name="round">A recovery round: «Non riuscito» copies are tried again too (answer 50).</param>
|
||||
public async Task<AutoExportPass> RunOnceAsync(bool round, CancellationToken ct = default)
|
||||
{
|
||||
await _pass.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await PassAsync(round, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Increment(ref _passes);
|
||||
_pass.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AutoExportPass> PassAsync(bool round, CancellationToken ct)
|
||||
{
|
||||
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||
var exports = _env.Storage.Exports;
|
||||
if (round)
|
||||
{
|
||||
// Ghost runs: of a destination retired, switched off, or of an account removed (engineering A10).
|
||||
await service.CancelOrphanAutomaticRunsAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (service.AutomaticHeldUntil is not null)
|
||||
{
|
||||
return Outcome(AutoExportPass.Held, null);
|
||||
}
|
||||
|
||||
if (WaitingReason(service) is { } reason)
|
||||
{
|
||||
return Outcome(AutoExportPass.Waiting, reason);
|
||||
}
|
||||
|
||||
if (service.AutomaticRunning)
|
||||
{
|
||||
return Outcome(AutoExportPass.Running, null);
|
||||
}
|
||||
|
||||
if (service.IsBusy)
|
||||
{
|
||||
return Outcome(AutoExportPass.Waiting, AutoExportText.ManualJob);
|
||||
}
|
||||
|
||||
var destinations = await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||
if (round && destinations.Any(d => d.PausedAt is not null))
|
||||
{
|
||||
foreach (var paused in destinations.Where(d => d.PausedAt is not null))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
// Answers again: the pause goes (no event); still not: it stays, with no new event (D10, D11).
|
||||
await service.ProbeDestinationAsync(paused.Id, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is KeyNotFoundException or InvalidOperationException)
|
||||
{
|
||||
// Retired meanwhile.
|
||||
}
|
||||
}
|
||||
|
||||
destinations = await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var usable = destinations.Where(d => d is { Automatic: true, PausedAt: null, IsOrphan: false }).ToDictionary(d => d.Id);
|
||||
var unfinished = (await exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false))
|
||||
.Where(r => r.Origin == ExportRunOrigin.Automatic)
|
||||
.ToList();
|
||||
var resumable = unfinished
|
||||
.Where(r => r.Kind == ExportRunKind.Copy && usable.ContainsKey(r.DestinationId) && (round || r.LastError is null))
|
||||
.Select(r => r.Id)
|
||||
.ToList();
|
||||
if (resumable.Count > 0)
|
||||
{
|
||||
var resume = await service.TryResumeAutomaticAsync(resumable, ct).ConfigureAwait(false);
|
||||
if (resume.Outcome != AutoExportStartOutcome.NothingToDo)
|
||||
{
|
||||
_resumed = resume.Outcome == AutoExportStartOutcome.Started;
|
||||
return Answer(service, resume);
|
||||
}
|
||||
}
|
||||
|
||||
// One run per destination at a time: a destination with an unfinished automatic run waits for it.
|
||||
var withRun = unfinished.Select(r => r.DestinationId).ToHashSet();
|
||||
var scopes = usable.Values
|
||||
.Where(d => !withRun.Contains(d.Id))
|
||||
.OrderBy(d => d.Id)
|
||||
.Select(d => new ExportSelection.AutomaticScope(d.Id, d.AutomaticSince))
|
||||
.ToList();
|
||||
if (scopes.Count == 0)
|
||||
{
|
||||
return Outcome(AutoExportPass.NothingToDo, null);
|
||||
}
|
||||
|
||||
var held = await LibraryIngest.PendingJournalEntriesAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
var start = await service.TryStartAutomaticAsync(new ExportSelection.Automatic(scopes, held, round), ct).ConfigureAwait(false);
|
||||
_resumed = false;
|
||||
return Answer(service, start);
|
||||
}
|
||||
|
||||
/// <summary>Why no automatic copy can start now, or null: a session, Alberto's long work, «Cerca i video fermi».</summary>
|
||||
private string? WaitingReason(ExportService service)
|
||||
{
|
||||
if (_env.Session.InSession)
|
||||
{
|
||||
return AutoExportText.InSession;
|
||||
}
|
||||
|
||||
if (_env.Gate?.BusyFirm is { } busy)
|
||||
{
|
||||
return AutoExportText.LongWork(busy);
|
||||
}
|
||||
|
||||
if (_env.OtherWorkRunning())
|
||||
{
|
||||
return AutoExportText.StillVideos;
|
||||
}
|
||||
|
||||
return service.IsBusy && !service.AutomaticRunning ? AutoExportText.ManualJob : null;
|
||||
}
|
||||
|
||||
private AutoExportPass Answer(ExportService service, AutoExportStart start) => start.Outcome switch
|
||||
{
|
||||
AutoExportStartOutcome.Started => Outcome(AutoExportPass.Started, null),
|
||||
AutoExportStartOutcome.Held => Outcome(AutoExportPass.Held, null),
|
||||
AutoExportStartOutcome.Busy => Outcome(
|
||||
AutoExportPass.Waiting,
|
||||
start.BusyWith is { } kind ? AutoExportText.LongWork(kind) : WaitingReason(service)),
|
||||
_ => Outcome(AutoExportPass.NothingToDo, null),
|
||||
};
|
||||
|
||||
private AutoExportPass Outcome(AutoExportPass pass, string? waiting)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_waiting = waiting;
|
||||
}
|
||||
|
||||
return pass;
|
||||
}
|
||||
|
||||
private async Task<ExportService> ServiceAsync(CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_service is { } ready)
|
||||
{
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
|
||||
var service = await _env.Service(ct).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
return _service ??= service;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoopAsync(CancellationToken ct)
|
||||
{
|
||||
var clock = _env.Clock;
|
||||
var signal = _env.Signal.Next();
|
||||
var nextRound = clock.Now; // the start-up round
|
||||
SetNextRound(nextRound);
|
||||
var signalled = false;
|
||||
var followUp = false;
|
||||
var followUpRound = false;
|
||||
Task? watching = null;
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (signal.IsCompleted)
|
||||
{
|
||||
// A file saved (or a rebuild, a job of Alberto's ended…): a pass a little after the last one, at once when
|
||||
// urgent (a destination turned on, «Riprendi ora»).
|
||||
if (!await signal.ConfigureAwait(false))
|
||||
{
|
||||
await SettleAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
signal = _env.Signal.Next();
|
||||
signalled = true;
|
||||
}
|
||||
|
||||
if (watching is { IsCompleted: true })
|
||||
{
|
||||
// The automatic job ended: a pass follows when it was stopped (Alberto's work came first) or when it
|
||||
// resumed runs and new files were not looked for.
|
||||
watching = null;
|
||||
followUp = await NeedsFollowUpAsync(ct).ConfigureAwait(false);
|
||||
followUpRound &= followUp;
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
var isRound = now >= nextRound;
|
||||
var wake = nextRound - now;
|
||||
if (isRound || signalled || followUp)
|
||||
{
|
||||
// The signal in hand was taken before the pass (above, or before the last sleep): one that arrives during
|
||||
// the pass completes it and is not lost. Taking a new one here could drop one given since the check above.
|
||||
var pass = AutoExportPass.Idle;
|
||||
try
|
||||
{
|
||||
pass = await RunOnceAsync(isRound || followUpRound, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_env.Log?.Invoke(AutoExportText.Error(ex));
|
||||
}
|
||||
|
||||
switch (pass)
|
||||
{
|
||||
case AutoExportPass.Waiting:
|
||||
// Pending: looked at again soon (the round too, once Alberto's work or the session is over).
|
||||
await SleepAsync(signal, null, _env.Poll, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
case AutoExportPass.Held:
|
||||
var service = await ServiceAsync(ct).ConfigureAwait(false);
|
||||
var until = service.AutomaticHeldUntil ?? clock.Now;
|
||||
await SleepAsync(signal, null, Min(until - clock.Now, _env.MaxSleep), ct).ConfigureAwait(false);
|
||||
continue;
|
||||
case AutoExportPass.Running:
|
||||
// Our own job: the pass is due again once it ends.
|
||||
watching = (await ServiceAsync(ct).ConfigureAwait(false)).AutomaticWork;
|
||||
await SleepAsync(signal, watching, _env.MaxSleep, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRound)
|
||||
{
|
||||
nextRound = now + _env.Round;
|
||||
lock (_gate)
|
||||
{
|
||||
_lastRound = now;
|
||||
_nextRound = nextRound;
|
||||
}
|
||||
}
|
||||
|
||||
followUpRound = pass == AutoExportPass.Started && _resumed && (isRound || followUpRound);
|
||||
signalled = false;
|
||||
followUp = false;
|
||||
if (pass == AutoExportPass.Started)
|
||||
{
|
||||
watching = (await ServiceAsync(ct).ConfigureAwait(false)).AutomaticWork;
|
||||
}
|
||||
|
||||
wake = nextRound - clock.Now;
|
||||
}
|
||||
|
||||
await SleepAsync(signal, watching, Min(wake, _env.MaxSleep), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After an automatic job: true when a pass must follow, because the job resumed runs (new files were not looked
|
||||
/// for) or because it was stopped (Alberto's work, a change of destination, «Interrompi»: its runs are «interrotto»
|
||||
/// with no error and resume by themselves). A job that simply ended needs nothing: a file that keeps giving nothing
|
||||
/// to copy must not start a job after every job.
|
||||
/// </summary>
|
||||
private async Task<bool> NeedsFollowUpAsync(CancellationToken ct)
|
||||
{
|
||||
if (_resumed)
|
||||
{
|
||||
_resumed = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||
return unfinished.Any(r => r is { Origin: ExportRunOrigin.Automatic, Kind: ExportRunKind.Copy, LastError: null });
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_env.Log?.Invoke(AutoExportText.Error(ex));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a signal is given (from the first one, <see cref="AutoExportEnvironment.Settle"/> after the last one,
|
||||
/// at most <see cref="AutoExportEnvironment.SettleLimit"/>), or an urgent one comes.
|
||||
/// </summary>
|
||||
private async Task SettleAsync(CancellationToken ct)
|
||||
{
|
||||
var clock = _env.Clock;
|
||||
var limit = clock.Now + _env.SettleLimit;
|
||||
while (true)
|
||||
{
|
||||
var left = limit - clock.Now;
|
||||
if (left <= TimeSpan.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var next = _env.Signal.Next();
|
||||
using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var delay = clock.Delay(Min(_env.Settle, left), wait.Token);
|
||||
var first = await Task.WhenAny(next, delay).ConfigureAwait(false);
|
||||
await wait.CancelAsync().ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (first != next || await next.ConfigureAwait(false))
|
||||
{
|
||||
return; // settled, or urgent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sleeps until <paramref name="time"/> passes, a signal comes, or <paramref name="job"/> ends.</summary>
|
||||
private async Task SleepAsync(Task<bool> signal, Task? job, TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var delay = _env.Clock.Delay(time > TimeSpan.Zero ? time : TimeSpan.Zero, wait.Token);
|
||||
await (job is null ? Task.WhenAny(signal, delay) : Task.WhenAny(signal, delay, job)).ConfigureAwait(false);
|
||||
await wait.CancelAsync().ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
}
|
||||
|
||||
private void SetNextRound(DateTimeOffset at)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_nextRound = at;
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
||||
}
|
||||
@@ -112,6 +112,26 @@ public sealed partial class ExportService : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The automatic job running now (or the automatic start being planned) as a task that completes when it is over,
|
||||
/// however it ends; a completed task when there is none. The worker waits on it instead of polling (tappa E5, D8).
|
||||
/// </summary>
|
||||
public Task AutomaticWork
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_job is { Automatic: true, Task.IsCompleted: false } job)
|
||||
{
|
||||
return job.Task;
|
||||
}
|
||||
|
||||
return _startingAutomatic ? _automaticStartDone.Task : Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
|
||||
Reference in new issue
Block a user