E5: archivio delle copie automatiche, segnale e domande 48–55

La tappa E5 copia da sola i file nuovi nelle cartelle con «Automatica».
Questo pacchetto (WP2) dà al motore che verrà ciò che gli serve dal
database, senza migrazioni:

- ExportSelection.Automatic: i file dovuti, non copiati («Tolto» e
  «Superato» mai), nuovi dal «Solo i nuovi», di elementi assestati (niente
  file da scaricare, riga del giornale scritta); i «Non riuscito» solo al
  giro di recupero, tutti e ogni giro (risposta 50 di Alberto), così un
  file che non riesce mai non fa un lavoro ogni due minuti.
- HasAutomaticCandidatesAsync, CountAutomaticBacklogAsync (la domanda
  «Copia anche gli N», i file in più, una cartella nuova), i candidati di
  «Riconosci le copie già presenti» (un «Tolto» resta «Tolto», risposta
  51) e i byte del primo file in attesa di un lavoro in pausa.
- La pausa di una destinazione si scrive solo con metodi suoi, così un
  salvataggio dall'interfaccia non la annulla; l'evento resta uno per
  passaggio.
- AutoExportSignal, un'istanza per le prove, Default per l'applicazione.

Prove nuove su un database vero, confrontate con il piano di «Copia in…»,
e misure su 200.000 elementi entro 2 s senza indici nuovi.

Documenti: in §16 le righe 48–55 con le risposte del 4 dicembre 2026 e in
decisioni.md la riga con le risposte e le tre letture del progetto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 13:21:56 +01:00
1 parent df50c32e22
commit f2568b5d88
12 files changed
+1212 -63

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
namespace Febe.Core.Export;
/// <summary>
/// Wakes the automatic export (tappa E5, decision D4): a line of <c>_febe.jsonl</c> was written, a rebuild ended, a
/// destination was turned on, a job ended. The signal only makes the next pass sooner: what to copy always comes from
/// the database. An instance, not a static, so parallel tests give their worker one of their own and cannot wake each
/// other; production code uses <see cref="Default"/>.
/// </summary>
public sealed class AutoExportSignal
{
private readonly Lock _gate = new();
private TaskCompletionSource<bool> _next = NewSignal();
private long _count;
/// <summary>The signal of the application (the journal hook, the rebuild, the API).</summary>
public static AutoExportSignal Default { get; } = new();
/// <summary>How many times <see cref="Signal"/> was called (monotonic, for tests).</summary>
public long Count => Interlocked.Read(ref _count);
/// <summary>
/// Completes the task of <see cref="Next"/> with <paramref name="urgent"/> and arms a new one. Urgent (a destination
/// turned on, «Riprendi ora») means the worker skips its settle wait.
/// </summary>
public void Signal(bool urgent = false)
{
TaskCompletionSource<bool> fired;
lock (_gate)
{
fired = _next;
_next = NewSignal();
_count++;
}
fired.TrySetResult(urgent);
}
/// <summary>
/// A task that completes at the next <see cref="Signal"/>, with whether that signal was urgent. Take it before a pass,
/// so a signal that arrives during the pass is not lost; a second signal before the task is awaited arms a new task
/// (take <see cref="Next"/> again to see it, for example during the settle wait).
/// </summary>
public Task<bool> Next()
{
lock (_gate)
{
return _next.Task;
}
}
private static TaskCompletionSource<bool> NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}
+18
View File
@@ -21,6 +21,24 @@ public abstract record ExportSelection
/// <summary>Every file of an account (the account card).</summary>
public sealed record Account(long AccountId) : ExportSelection;
/// <summary>
/// The automatic export (tappa E5, D4 and D5): per automatic destination, the files it is the effective destination
/// of, not copied («Tolto» and «Superato» never), new since its «Solo i nuovi» instant, and settled (no file of the
/// entry still to download, the entry not in <paramref name="HeldEntryIds"/>).
/// </summary>
/// <param name="Destinations">The automatic destinations of the pass; one not in use (retired, unknown) gives nothing.</param>
/// <param name="HeldEntryIds">Entries whose line of <c>_febe.jsonl</c> is still to be written (<c>libreria.giornale-da-scrivere</c>).</param>
/// <param name="Round">
/// A recovery round (start-up and every hour): files whose last copy in the destination is «Non riuscito» are
/// candidates too, every round, whatever the error (answer 50 of 4 December 2026). Outside a round they wait for it,
/// so a file that keeps failing does not make a job at every signal.
/// </param>
public sealed record Automatic(IReadOnlyList<AutomaticScope> Destinations, IReadOnlyList<long> HeldEntryIds, bool Round) : ExportSelection;
/// <summary>One automatic destination and its «Solo i nuovi» instant (null: everything due, saved before or after).</summary>
/// <param name="Since">Files saved in the library at or after it (<c>media.downloaded_at</c>); a file without that time is not new.</param>
public sealed record AutomaticScope(long DestinationId, DateTimeOffset? Since);
}
/// <summary>How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»).</summary>
+15 -30
View File
@@ -13,29 +13,20 @@ public static class ExportPause
public const string PausedEventCode = "esportazione-in-pausa";
/// <summary>
/// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it
/// is). The event is written only on the transition from running to paused. Returns the stored row.
/// Pauses a destination with an Italian reason. Only the pause and its reason are written, in one statement (tappa
/// E5, D10), so a save of the destination from the interface and a copy or a round never undo each other's writes; a
/// retired row is left as it is. The event is written only on the transition from running to paused. Returns the
/// stored row.
/// </summary>
public static async Task<ExportDestination> PauseAsync(ExportEnvironment env, ExportDestination destination, string message)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(destination);
ArgumentException.ThrowIfNullOrWhiteSpace(message);
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
if (stored.IsRetired)
{
return stored;
}
var wasPaused = stored.PausedAt is not null;
if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal))
{
return stored;
}
var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message };
await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false);
if (!wasPaused)
var exports = env.Storage.Exports;
var paused = await exports.SetDestinationPausedAsync(destination.Id, env.Clock.Now, message, CancellationToken.None).ConfigureAwait(false);
var stored = await exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
if (paused)
{
await env.Storage.Events.AppendAsync(
new EventRecord
@@ -43,28 +34,22 @@ public static class ExportPause
At = env.Clock.Now,
Code = PausedEventCode,
Severity = EventSeverity.Warning,
Message = $"{ExportDestinations.Label(paused)} in pausa: {message}",
AccountId = paused.AccountId,
Message = $"{ExportDestinations.Label(stored)} in pausa: {message}",
AccountId = stored.AccountId,
},
CancellationToken.None).ConfigureAwait(false);
}
return paused;
return stored;
}
/// <summary>Clears the pause of a destination after a check succeeded. Returns the stored row.</summary>
/// <summary>Clears the pause of a destination after a check succeeded (only the pause and its reason). Returns the stored row.</summary>
public static async Task<ExportDestination> ClearAsync(ExportEnvironment env, ExportDestination destination)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(destination);
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null))
{
return stored;
}
var cleared = stored with { PausedAt = null, LastError = null };
await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false);
return cleared;
var exports = env.Storage.Exports;
await exports.ClearDestinationPauseAsync(destination.Id, CancellationToken.None).ConfigureAwait(false);
return await exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
}
}
+11
View File
@@ -46,6 +46,14 @@ public static class ExportText
public const string CopiedInAnotherFormat = "CopiedInAnotherFormat";
public const string LostTracks = Mp4Remuxer.LostTracks;
public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata;
// Tappa E5. A path too long for the destination: «Non riuscito» like any other, retried by every recovery round
// (answer 50 of 4 December 2026: no class of failures that never retry by themselves).
public const string PathTooLong = "PathTooLong";
// «Riconosci le copie già presenti» (tappa E5, D13): nothing at the paths looked at, or another file there.
public const string NotFound = "NotFound";
public const string Different = "Different";
}
/// <summary>Name of the state of a file of a job.</summary>
@@ -148,6 +156,9 @@ public static class ExportText
Notes.NotStill => "Il video è cambiato: il file di adesso non è un video fermo, o non è stato analizzato",
Notes.TransparencyWhite => "La trasparenza è diventata bianco",
Notes.CopiedInAnotherFormat => "Già copiato in un altro formato",
Notes.PathTooLong => "Percorso troppo lungo per la cartella",
Notes.NotFound => "Non c'è nella cartella",
Notes.Different => "Nel percorso c'è un altro file",
ImageConversionLosses.LostTexts => "Non tenuti: testi",
ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore",
ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC",
+84 -2
View File
@@ -21,7 +21,9 @@ public interface IExportStore
Task<ExportDestination> AddDestinationAsync(ExportDestination destination, CancellationToken ct = default);
/// <summary>
/// Writes label, content types, formats, naming schemes, «Automatica» and its answer, pause and error.
/// Writes label, content types, formats, naming schemes, «Automatica» and its answer. Never the pause and its error
/// (tappa E5, D10): those change only with <see cref="SetDestinationPausedAsync"/> and
/// <see cref="ClearDestinationPauseAsync"/>, so a save from the interface cannot undo a pause written meanwhile.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="ArgumentException"/> if scope, account or root
/// differ from the stored row, the row is retired, or «Automatica» is turned on for an own folder whose account was
/// removed (it is attached to an account first).
@@ -39,6 +41,16 @@ public interface IExportStore
/// <summary>The general folder first, then by id; retired rows only when asked.</summary>
Task<IReadOnlyList<ExportDestination>> ListDestinationsAsync(bool includeRetired = false, CancellationToken ct = default);
/// <summary>
/// Pauses a destination in use (tappa E5, D10): keeps the instant of a pause already there, writes the problem.
/// True only on the transition from not paused to paused (the caller writes the event then); false for a retired or
/// missing row and for one already paused.
/// </summary>
Task<bool> SetDestinationPausedAsync(long id, DateTimeOffset at, string problem, CancellationToken ct = default);
/// <summary>Clears the pause and its problem of a destination in use; true when there was one to clear.</summary>
Task<bool> ClearDestinationPauseAsync(long id, CancellationToken ct = default);
/// <summary>
/// Retires a destination (removed by Alberto, or replaced by another folder): sets the removal time and turns
/// «Automatica» off. No row and no file is deleted. <see cref="KeyNotFoundException"/> for a missing id.
@@ -238,10 +250,46 @@ public interface IExportStore
/// <summary>
/// The library files of a «Copia in…», by media id, a page at a time (after <paramref name="afterMediaId"/>), present
/// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter
/// the files of its entries (with «Tutte le foto», only the files it shows).
/// the files of its entries (with «Tutte le foto», only the files it shows). The automatic export
/// (<see cref="ExportSelection.Automatic"/>, tappa E5) gives only due files to copy: see that record.
/// </summary>
Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default);
// Tappa E5: the automatic export and «Riconosci le copie già presenti» -------------------------------------------
/// <summary>
/// Whether <see cref="ListCandidatesAsync"/> would give any file for this automatic selection (one EXISTS): a pass
/// with nothing to copy takes no lease and never stops the conversion of the library.
/// </summary>
Task<bool> HasAutomaticCandidatesAsync(ExportSelection.Automatic selection, CancellationToken ct = default);
/// <summary>
/// What an automatic destination would copy by itself (the question «Solo i nuovi / Copia anche gli N», the files
/// in more when it takes more, the files waiting for a paused folder): due files not copied, «Tolto» and «Superato»
/// left out, «Non riuscito» in, each file once as the plan counts it (per account, or once with «Una copia sola»),
/// with their bytes. The destination may be one not stored yet (see <see cref="ExportBacklogQuery"/>).
/// <see cref="ArgumentException"/> for an own folder without account, or a history destination that is not the
/// one in use for that scope and account.
/// </summary>
Task<ExportBacklog> CountAutomaticBacklogAsync(ExportBacklogQuery query, CancellationToken ct = default);
/// <summary>
/// «Riconosci le copie già presenti» (tappa E5, D13 and answer 51), a page of at most <paramref name="limit"/> library
/// files after <paramref name="afterMediaId"/>, by media id. For each due file of the destination (its effective
/// destination in use): the file itself, when it is not «Copiato» (with «Una copia sola», copied for another account
/// counts) and its newest row there in any form but a frame is not «Tolto»; then its frames already recorded there
/// whose newest row is «Non riuscito» or «Superato», or an orphan's (account removed) that is not «Tolto» when the
/// account has no row of that frame. A «Tolto» stays «Tolto»: only «Copia di nuovo» copies it again. Empty for a
/// destination not in use.
/// </summary>
Task<IReadOnlyList<ExportRecognizeCandidate>> ListRecognizeCandidatesAsync(long destinationId, long afterMediaId, int limit, CancellationToken ct = default);
/// <summary>
/// The bytes of the library file of the first item still «In attesa» of the oldest paused job of a destination (D11:
/// a pause for space is cleared only when it fits); null without such an item or without its size.
/// </summary>
Task<long?> GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default);
/// <summary>Jobs for the Dashboard: newest first, at most <paramref name="limit"/>.</summary>
Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default);
@@ -280,6 +328,40 @@ public sealed record ExportCandidate(
bool InHighlight,
TimeSpan? Duration = null);
/// <summary>
/// A file «Riconosci le copie già presenti» looks for (tappa E5, D13): the file in the form the destination asks now
/// (<paramref name="Frame"/> null), or one of its frames already recorded in the destination.
/// </summary>
/// <param name="File">The library file.</param>
/// <param name="Frame">The newest row of that frame in the destination (format and instant), or null for the file itself.</param>
public sealed record ExportRecognizeCandidate(ExportCandidate File, ExportCopy? Frame = null);
/// <summary>
/// What <see cref="IExportStore.CountAutomaticBacklogAsync"/> counts: one destination as it is, or as it would be.
/// </summary>
/// <param name="Scope">The general folder, or the own folder of <paramref name="AccountId"/>.</param>
/// <param name="AccountId">
/// For an own folder, its account (required). For the general folder, only that account's files (null: every account
/// the general folder is the effective destination of).
/// </param>
/// <param name="Types">The content types the destination takes (as it would be saved).</param>
/// <param name="HistoryDestinationId">
/// The destination in use whose copies count (the folder is the same); null for a new destination or a new folder,
/// whose copies are none: then nothing is «Copiato», «Tolto» or «Superato» there.
/// </param>
/// <param name="Since">«Solo i nuovi»: only files saved in the library at or after it; null: every due file.</param>
/// <param name="IgnoreOwnFolderOfAccount">The own folder of this account is counted as gone (its files go to the general folder).</param>
public sealed record ExportBacklogQuery(
ExportScope Scope,
long? AccountId,
ContentTypes Types,
long? HistoryDestinationId,
DateTimeOffset? Since,
long? IgnoreOwnFolderOfAccount = null);
/// <summary>Files an automatic destination would copy by itself, and their bytes.</summary>
public sealed record ExportBacklog(int Files, long Bytes);
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
public enum ExportMark
{