E3: seconda revisione di rimuxaggio, spazio, impostazioni e zip
verifica / controlli (push) Canceled after 0s
verifica / prove (push) Canceled after 0s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s

Le quattro osservazioni confermate della seconda revisione, ognuna con
la sua prova (ciascuna cade sul codice di prima):

- Rimuxaggio con fotogrammi B: l'MP4 misura la fine della presentazione
  in tempo di composizione, non con la somma delle durate di decodifica.
  Prima nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone) e
  durava altrettanto meno in elst, tkhd e mvhd. Per le tracce senza
  scarti di composizione i byte restano gli stessi.
- Conversione della libreria: il lavoro ricorda il file che l'ha messo
  in pausa per spazio e quanto serve al suo convertito. Finché il disco
  non ha posto anche per quello, non rilegge l'originale a ogni
  risveglio (anche quando lo spazio libero sta appena sopra la soglia).
- Impostazioni dell'esportazione: formati, chiavi «dal» e coda del
  formato sostituito si salvano in una transazione sola; «Anche i N»
  dopo il salvataggio non dipende più dalla richiesta. Il gancio della
  libreria legge formati e chiavi «dal» in una lettura. Una scheda
  chiusa o un arresto non lasciano più un formato senza la sua chiave
  né «Non riuscito» che «Riprova» non tocca.
- Zip dei fotogrammi: i tempi del blocco passano da un TimeProvider
  della BCL, e la prova del lettore lento non dipende più dal carico
  della macchina.

Decisioni in docs/decisioni.md (28/11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 14:29:00 +01:00
1 parent 958cb71cd6
commit 2efb408957
13 files changed
+459 -49

No files matched your search

+4
View File
@@ -653,3 +653,7 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro | | 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro |
| 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate | | 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate |
| 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola | | 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola |
| 2026-11-28 | Seconda revisione della tappa E3, video: `Mp4Writer` misura la fine della presentazione in tempo di composizione (il massimo di decodifica + scarto di composizione + durata di ogni campione), non la somma delle durate di decodifica. Con i fotogrammi B l'edit comincia al primo scarto di composizione e con la somma l'MP4 nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone), e durava altrettanto meno in `mvhd`, `tkhd` ed `elst`; il segmento della sorgente resta il limite. Vale per ogni scrittura, non solo per le sorgenti con un segmento: per una traccia senza scarti la fine è la stessa di prima e i byte non cambiano, con gli scarti il risultato di prima era sbagliato anche senza segmento (Matroska, ISO senza `elst`). | Una MOV con fotogrammi B rimuxata in MP4 (conversione della libreria o copia) deve mostrare quello che mostrava la sorgente; i fotogrammi presi dal convertito ora leggono il segmento giusto. |
| 2026-11-28 | Seconda revisione della tappa E3, conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito (riga, SHA-256 dell'originale, byte), e finché il disco non ha posto anche per quello la pausa vale prima di rileggere l'originale (hash, decodifica, rimuxaggio). Non si sottraggono i byte dell'originale in anticipo: un PNG grande che diventa un JPG piccolo resterebbe fermo senza motivo. Il ricordo è del processo: dopo un riavvio l'originale si rilegge una volta. | La pausa per spazio (D17) non deve rileggere lo stesso video di 2 GB a ogni risveglio quando lo spazio libero sta fra la soglia e la soglia più il file. |
| 2026-11-28 | Seconda revisione della tappa E3: un cambio dei formati della libreria si salva in una transazione sola con le chiavi «dal» e la coda svuotata del formato sostituito (`LibraryConversionQueue.SaveSettingsAsync`, `IMediaConversionStore.SaveSettingsAndDeleteQueuesAsync`); «Anche i N» dopo il salvataggio non dipende più dalla richiesta (`CancellationToken.None`). Il gancio della libreria legge formati e chiavi «dal» con una lettura sola. | Una scheda chiusa, un arresto o un file salvato in quel momento non devono vedere il formato nuovo senza la sua chiave «dal» (che metterebbe in coda tutto l'elemento) né lasciare «Non riuscito» del formato vecchio che «Riprova» non tocca più. |
| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. |
+15 -6
View File
@@ -271,13 +271,14 @@ public static class Mp4Writer
} }
/// <summary> /// <summary>
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/> and <paramref name="Shown"/> (the media /// Times of a track as the boxes need them; <paramref name="EmptyEdit"/>, <paramref name="Shown"/> (the media
/// the edit shows, from <paramref name="EditMediaTime"/>) are in track units. /// the edit shows, from <paramref name="EditMediaTime"/>) and <paramref name="PresentationEnd"/> (where the last
/// sample stops being shown, in composition time) are in track units.
/// </summary> /// </summary>
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown) private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown, long PresentationEnd)
{ {
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary> /// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
public bool TrimsEnd => Shown < MediaDuration - EditMediaTime; public bool TrimsEnd => Shown < PresentationEnd - EditMediaTime;
internal static Timing Of(Mp4OutputTrack track) internal static Timing Of(Mp4OutputTrack track)
{ {
@@ -315,6 +316,14 @@ public static class Mp4Writer
total += d; total += d;
} }
// The presentation ends where the sample shown last stops, in composition time: with B frames that is later
// than the decoding durations add up to (by the first composition offset), and the edit starts there too.
long presentationEnd = 0;
for (var i = 0; i < n; i++)
{
presentationEnd = Math.Max(presentationEnd, samples[i].DecodeTime - first + offsets[i] + durations[i]);
}
// The edit list starts the presentation at the first shown sample, or where the track says; a start before // The edit list starts the presentation at the first shown sample, or where the track says; a start before
// the first sample becomes an empty edit. // the first sample becomes an empty edit.
var editTime = (track.EditMediaTime ?? minPts) - first + shift; var editTime = (track.EditMediaTime ?? minPts) - first + shift;
@@ -325,13 +334,13 @@ public static class Mp4Writer
editTime = 0; editTime = 0;
} }
var shown = Math.Max(0, total - editTime); var shown = Math.Max(0, presentationEnd - editTime);
if (track.EditSegmentDuration is { } segment && segment > 0) if (track.EditSegmentDuration is { } segment && segment > 0)
{ {
shown = Math.Min(shown, segment); shown = Math.Min(shown, segment);
} }
return new Timing(durations, offsets, total, editTime, allKey, empty, shown); return new Timing(durations, offsets, total, editTime, allKey, empty, shown, presentationEnd);
} }
} }
+11 -10
View File
@@ -68,18 +68,19 @@ public sealed record ExportSettings(
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default) public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(store); ArgumentNullException.ThrowIfNull(store);
return store.SetManyAsync( return store.SetManyAsync(Values(), ct);
new Dictionary<string, string?>
{
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
[ExportSettingKeys.SamePost] = SamePost.ToString(),
},
ct);
} }
/// <summary>The five keys with their stored values (for a write that stores more with them).</summary>
public Dictionary<string, string?> Values() => new(StringComparer.Ordinal)
{
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
[ExportSettingKeys.SamePost] = SamePost.ToString(),
};
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary> /// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
internal static ExportSettings From(IReadOnlyDictionary<string, string> values) internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
{ {
@@ -72,15 +72,48 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
} }
/// <summary> /// <summary>
/// The settings changed: a library format turned off or changed loses its queue and its failures that «Riprova» /// Saves the settings <paramref name="after"/> (they were <paramref name="before"/>) with what a change of a library
/// would put back (its converted files and rows stay). /// format brings, in one transaction: the format, since when it is set (<see cref="PhotoSinceKey"/>) and the
/// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees
/// the new format without its «dal» key, nor the old failures left behind (D17, Q29).
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for /// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
/// «Anche i N già in libreria». /// «Anche i N già in libreria».
/// </summary> /// </summary>
public async Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default) public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(before); ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after); ArgumentNullException.ThrowIfNull(after);
var values = after.Values();
var (since, formats) = Changes(before, after);
foreach (var (key, value) in since)
{
values[key] = value;
}
return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct);
}
/// <summary>
/// The settings were saved by another way: a library format turned off or changed loses its queue and its failures
/// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction.
/// <see cref="SaveSettingsAsync"/> stores the settings with them.
/// </summary>
public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var (since, formats) = Changes(before, after);
return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct);
}
/// <summary>
/// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and
/// the format replaced, whose queue goes.
/// </summary>
private (Dictionary<string, string?> Since, List<ExportFormat> Formats) Changes(ExportSettings before, ExportSettings after)
{
var since = new Dictionary<string, string?>(StringComparer.Ordinal);
var formats = new List<ExportFormat>();
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video }) foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{ {
var old = LibraryConversionRules.FormatFor(kind, before); var old = LibraryConversionRules.FormatFor(kind, before);
@@ -92,13 +125,14 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
if (old is { } format) if (old is { } format)
{ {
await storage.Conversions.DeleteQueueAsync(format, ct).ConfigureAwait(false); formats.Add(format);
} }
// The files of the library before now are «già in libreria»: only «Anche i N» queues them. // The files of the library before now are «già in libreria»: only «Anche i N» queues them.
var since = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
await storage.Settings.SetAsync(SinceKey(kind), since, ct).ConfigureAwait(false);
} }
return (since, formats);
} }
/// <summary> /// <summary>
@@ -148,14 +182,16 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
{ {
ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(media); ArgumentNullException.ThrowIfNull(media);
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); // One read: the formats and their «dal» keys as one change stored them, never a format with an older key.
var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false);
var settings = ExportSettings.From(values);
if (!settings.ConvertsLibrary) if (!settings.ConvertsLibrary)
{ {
return 0; return 0;
} }
var photoSince = await SinceAsync(storage.Settings, MediaKind.Photo, ct).ConfigureAwait(false); var photoSince = Since(values, MediaKind.Photo);
var videoSince = await SinceAsync(storage.Settings, MediaKind.Video, ct).ConfigureAwait(false); var videoSince = Since(values, MediaKind.Video);
var requests = LibraryConversionRules.RequestsFor( var requests = LibraryConversionRules.RequestsFor(
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)), || (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
@@ -177,8 +213,8 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey; private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
/// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary> /// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary>
private static async Task<long?> SinceAsync(ISettingsStore settings, MediaKind kind, CancellationToken ct) => private static long? Since(IReadOnlyDictionary<string, string> values, MediaKind kind) =>
long.TryParse(await settings.GetAsync(SinceKey(kind), ct).ConfigureAwait(false), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null; long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary> /// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
public static void Signal() public static void Signal()
@@ -78,6 +78,14 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
private volatile string? _waiting; private volatile string? _waiting;
private long _current; private long _current;
/// <summary>
/// The file that last paused the conversion for space, with the length its converted file needs: until the disk
/// has room for that too, the original is not read (hashed, decoded or remuxed) again at every wake-up (D17).
/// </summary>
private volatile LowSpaceMark? _lowSpace;
private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed);
/// <summary>The counts of the store with what the worker is doing now.</summary> /// <summary>The counts of the store with what the worker is doing now.</summary>
public async Task<LibraryConversionStatus> StatusAsync(CancellationToken ct = default) public async Task<LibraryConversionStatus> StatusAsync(CancellationToken ct = default)
{ {
@@ -278,14 +286,16 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
return Outcome.Settled; return Outcome.Settled;
} }
// A disk already below the threshold stays below it with the file: the pause starts before the original is read // A disk already below the threshold stays below it with the file, and the file that paused the conversion last
// (hashed, decoded or remuxed) again at every wake-up (D17). The exact check with the file's length follows. // needs as much again: the pause holds before the original is read (hashed, decoded or remuxed) again at every
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before)) // wake-up (D17). The exact check with the file's length follows.
var source = media.Sha256.ToLowerInvariant();
var needed = _lowSpace is { } mark && mark.RowId == row.Id && string.Equals(mark.SourceSha256, source, StringComparison.Ordinal) ? mark.Needed : 0;
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before with { AvailableBytes = before.AvailableBytes - needed }))
{ {
return Outcome.LowSpace; return Outcome.LowSpace;
} }
var source = media.Sha256.ToLowerInvariant();
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal)) if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
{ {
row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now }; row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now };
@@ -332,9 +342,11 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
if (_env.FreeSpace.Measure(folder) is { } space if (_env.FreeSpace.Measure(folder) is { } space
&& _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length })) && _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length }))
{ {
_lowSpace = new LowSpaceMark(row.Id, source, result.Length);
return Outcome.LowSpace; return Outcome.LowSpace;
} }
_lowSpace = null;
return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false); return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false);
} }
} }
@@ -71,6 +71,13 @@ public interface IMediaConversionStore
/// </summary> /// </summary>
Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default); Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default);
/// <summary>
/// A change of the library formats: stores <paramref name="settings"/> (null values remove their key) and empties
/// the queues of <paramref name="formats"/> as <see cref="DeleteQueueAsync"/> does, in one transaction, so that the
/// formats, the keys that go with them and the queues are stored whole or not at all. Returns how many rows went.
/// </summary>
Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default);
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary> /// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default); Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
+2 -1
View File
@@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore
}, },
ct); ct);
private static void Set(WriteContext w, string key, string? value) /// <summary>Stores one value inside a write (null removes the key): also for stores that save settings with their rows.</summary>
internal static void Set(WriteContext w, string key, string? value)
{ {
if (value is null) if (value is null)
{ {
@@ -188,12 +188,41 @@ internal sealed partial class MediaConversionStore
} }
public Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) => public Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) =>
db.WriteAsync( db.WriteAsync(w => DeleteQueue(w, format), ct);
w => w.Command($"""
DELETE FROM media_conversion public Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default)
WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})))) {
""").With("@f", Sql.Enum(format)).ExecuteNonQuery(), ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(formats);
foreach (var key in settings.Keys)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
}
return db.WriteAsync(
w =>
{
foreach (var (key, value) in settings)
{
SettingsStore.Set(w, key, value);
}
var deleted = 0;
foreach (var format in formats.Distinct())
{
deleted += DeleteQueue(w, format);
}
return deleted;
},
ct); ct);
}
private static int DeleteQueue(WriteContext w, ExportFormat format) =>
w.Command($"""
DELETE FROM media_conversion
WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition}))))
""").With("@f", Sql.Enum(format)).ExecuteNonQuery();
public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) => public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
db.WriteAsync( db.WriteAsync(
+4 -3
View File
@@ -689,8 +689,9 @@ public static class ExportApi
throw new BadRequestException("Niente da salvare: scegli un'impostazione."); throw new BadRequestException("Niente da salvare: scegli un'impostazione.");
} }
await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false); // The formats, their «dal» keys and the queue of a format replaced in one transaction; once it is stored, what
await queue.OnSettingsChangedAsync(before, after, ct).ConfigureAwait(false); // follows no longer depends on the request (a closed tab must not leave half of it).
await queue.SaveSettingsAsync(before, after, ct).ConfigureAwait(false);
if (body.ConvertExisting == true) if (body.ConvertExisting == true)
{ {
// «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps // «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps
@@ -699,7 +700,7 @@ public static class ExportApi
var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after); var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after);
if (photo is not null || video is not null) if (photo is not null || video is not null)
{ {
queued = await queue.EnqueueExistingAsync(photo, video, ct).ConfigureAwait(false); queued = await queue.EnqueueExistingAsync(photo, video, CancellationToken.None).ConfigureAwait(false);
} }
} }
+7 -4
View File
@@ -77,6 +77,9 @@ public sealed class FrameService(IClock clock)
/// </summary> /// </summary>
public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60); public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>The timers of <see cref="WriteStall"/> (a seam: a test moves their time only as its link sends).</summary>
public TimeProvider StallTime { get; init; } = TimeProvider.System;
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary> /// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
public async Task<VideoFrameInfo> InfoAsync(string path, string? sha256, CancellationToken ct) public async Task<VideoFrameInfo> InfoAsync(string path, string? sha256, CancellationToken ct)
{ {
@@ -203,7 +206,7 @@ public sealed class FrameService(IClock clock)
ArgumentNullException.ThrowIfNull(output); ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(plan);
var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan)); var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan));
var guarded = new StallGuardStream(output, WriteStall); var guarded = new StallGuardStream(output, WriteStall, StallTime);
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false); var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false);
await using (zip.ConfigureAwait(false)) await using (zip.ConfigureAwait(false))
@@ -369,7 +372,7 @@ public sealed class FrameService(IClock clock)
/// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those /// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those
/// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write. /// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write.
/// </summary> /// </summary>
private sealed class StallGuardStream(Stream inner, TimeSpan stall) : Stream private sealed class StallGuardStream(Stream inner, TimeSpan stall, TimeProvider time) : Stream
{ {
// A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL. // A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL.
private const int MaxPending = 64 * 1024; private const int MaxPending = 64 * 1024;
@@ -459,8 +462,8 @@ public sealed class FrameService(IClock clock)
{ {
for (var offset = 0; offset < buffer.Length; offset += Piece) for (var offset = 0; offset < buffer.Length; offset += Piece)
{ {
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct); using var timer = new CancellationTokenSource(stall, time);
guard.CancelAfter(stall); using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct, timer.Token);
await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false); await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false);
} }
} }
@@ -1,9 +1,11 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export; using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Library.Conversion; using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
using Febe.Tests.Alerts.Support; using Febe.Tests.Alerts.Support;
using Febe.Tests.Export.Support; using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support; using Febe.Tests.Import.Support;
@@ -343,6 +345,55 @@ public sealed class LibraryConversionTests
Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts"); Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts");
} }
[TestMethod]
public async Task AFileThatWouldTakeTheDiskBelowTheThresholdIsNotReadAgainAtEveryWakeUp()
{
// Free space above the threshold, but not by the converted file's length: the first pass reads the original and
// pauses; the next ones pause before reading it again, until the disk has room for that file too.
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
await TurnOnAsync(library, ExportFormat.Jpg);
var (account, entry) = await SavePngAsync(library, "1", 25);
var folder = library.Layout.AccountFolder(account);
const long Threshold = 10 * FakeFreeSpaceProbe.GB;
var space = new FakeFreeSpaceProbe();
space.Set(folder, Threshold + 1, 1000 * FakeFreeSpaceProbe.GB);
var throttle = new ConversionThrottle();
var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with
{
FreeSpace = space,
Thresholds = new DiskThresholds(Threshold, 0),
});
var first = await worker.RunOnceAsync(ct);
Assert.AreEqual((0, false), (first.Done, first.Again));
Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting, "the converted file does not fit");
// Another conversion holds the throttle: a pass that decoded the photo again would wait for it.
using var release = new ManualResetEventSlim();
var other = throttle.RunAsync(_ => release.Wait(TimeSpan.FromMinutes(1)), ct);
try
{
for (var wakeUp = 0; wakeUp < 3; wakeUp++)
{
space.Set(folder, Threshold + 1 + wakeUp, 1000 * FakeFreeSpaceProbe.GB); // a little more, never enough
var pass = await worker.RunOnceAsync(ct).WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.AreEqual((0, false), (pass.Done, pass.Again));
Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting);
}
}
finally
{
release.Set();
await other;
}
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State);
space.Set(folder, Threshold + FakeFreeSpaceProbe.GB, 1000 * FakeFreeSpaceProbe.GB);
Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "room for the file: it converts");
}
[TestMethod] [TestMethod]
public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted() public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted()
{ {
@@ -386,6 +437,43 @@ public sealed class LibraryConversionTests
Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal)), "only the original"); Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal)), "only the original");
} }
[TestMethod]
public async Task AChangeOfFormatIsStoredWithItsDalKeyAndQueueWholeOrNotAtAll()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var jpg = await TurnOnAsync(library, ExportFormat.Jpg);
var (account, failed) = await SavePngAsync(library, "1", 26);
File.Delete(library.Layout.FullPath(account, failed.Media[0].RelativePath!));
await Worker(library).RunOnceAsync(ct);
await SavePngAsync(library, "2", 27);
Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed));
var png = jpg with { LibraryPhotoFormat = ExportFormat.Png };
// A request aborted before its write stores nothing of the change.
using var aborted = new CancellationTokenSource();
await aborted.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => new LibraryConversionQueue(library.Db, library.Clock).SaveSettingsAsync(jpg, png, aborted.Token));
Assert.AreEqual(ExportFormat.Jpg, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat);
Assert.IsNull(await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct));
Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed));
// A request aborted once the format is written (the tab closed): the change is already whole, never a format
// without its «dal» key or with the old failures left behind.
using var request = new CancellationTokenSource();
var storage = new AbortAfterSettingsWrite(library.Db, request);
library.Clock.Now += TimeSpan.FromMinutes(1);
await new LibraryConversionQueue(storage, library.Clock).SaveSettingsAsync(jpg, png, request.Token);
Assert.AreEqual(0, storage.SettingsWrites, "nothing of the change is written on its own");
Assert.AreEqual(ExportFormat.Png, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat);
Assert.AreEqual(library.Clock.Now.ToUnixTimeMilliseconds().ToString(System.Globalization.CultureInfo.InvariantCulture), await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct));
var counts = await library.Db.Conversions.CountByStateAsync(ct);
Assert.AreEqual((0, 0), (counts.Pending, counts.Failed), "the queue and the failures of JPG went with it");
Assert.AreEqual(0, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct));
}
[TestMethod] [TestMethod]
public async Task AConversionRecordedWhileTheEntryIsDeletedGoesWithIt() public async Task AConversionRecordedWhileTheEntryIsDeletedGoesWithIt()
{ {
@@ -699,6 +787,73 @@ public sealed class LibraryConversionTests
private static LibraryConversionWorker Worker(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => private static LibraryConversionWorker Worker(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) =>
new(Environment(library, gate, throttle)); new(Environment(library, gate, throttle));
/// <summary>
/// The storage of a request whose client goes away as soon as a setting is written on its own (outside the
/// transaction of the conversion store): every later write that honours the request's token fails.
/// </summary>
private sealed class AbortAfterSettingsWrite(IFebeStorage inner, CancellationTokenSource request) : IFebeStorage, ISettingsStore
{
public int SettingsWrites { get; private set; }
public IAccountStore Accounts => inner.Accounts;
public IEntryStore Entries => inner.Entries;
public IMediaStore Media => inner.Media;
public IHighlightStore Highlights => inner.Highlights;
public IDuplicateStore Duplicates => inner.Duplicates;
public ITaskStore Tasks => inner.Tasks;
public IActionLogStore ActionLog => inner.ActionLog;
public ISessionStore Sessions => inner.Sessions;
public IIncidentStore Incidents => inner.Incidents;
public IEventStore Events => inner.Events;
public IFollowingStore Following => inner.Following;
public IImportStore Imports => inner.Imports;
public IExportStore Exports => inner.Exports;
public IVideoAnalysisStore VideoAnalyses => inner.VideoAnalyses;
public IMediaConversionStore Conversions => inner.Conversions;
public ISettingsStore Settings => this;
public IDatabaseMaintenance Maintenance => inner.Maintenance;
public Task<string?> GetAsync(string key, CancellationToken ct = default) => inner.Settings.GetAsync(key, ct);
public Task<IReadOnlyDictionary<string, string>> GetAllAsync(CancellationToken ct = default) => inner.Settings.GetAllAsync(ct);
public async Task SetAsync(string key, string? value, CancellationToken ct = default)
{
await inner.Settings.SetAsync(key, value, ct);
Wrote();
}
public async Task SetManyAsync(IReadOnlyDictionary<string, string?> values, CancellationToken ct = default)
{
await inner.Settings.SetManyAsync(values, ct);
Wrote();
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // the library owns the database
private void Wrote()
{
SettingsWrites++;
request.Cancel();
}
}
private static async Task<ExportSettings> TurnOnAsync(TestLibrary library, ExportFormat photo) private static async Task<ExportSettings> TurnOnAsync(TestLibrary library, ExportFormat photo)
{ {
var settings = ExportSettings.Default with { LibraryPhotoFormat = photo }; var settings = ExportSettings.Default with { LibraryPhotoFormat = photo };
@@ -1,3 +1,4 @@
using System.Buffers.Binary;
using System.Security.Cryptography; using System.Security.Cryptography;
using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Containers;
@@ -97,6 +98,62 @@ public sealed class Mp4RemuxerTests
Assert.AreEqual(ShownFrames - 1, last.Sample); Assert.AreEqual(ShownFrames - 1, last.Sample);
} }
[TestMethod]
public void TheLastReorderedFramesStayShownInTheMp4()
{
// B frames, as iPhones and High profile encoders write them: the edit starts at the first composition offset
// and shows the whole presentation (N frames). The MP4 must show as much, never 2 frames less.
var es = ElementaryStream.Load("CABA3_SVA_B");
var n = es.Count;
Assert.IsTrue(Enumerable.Range(0, n).Any(i => es.Rank[i] < i), "the stream has reordered frames");
var presentation = (long)n * TestVideos.FrameTicks;
var mov = TestVideos.Mov(es, new MovOptions(VideoTrim: presentation));
using var source = new MemoryStream(mov);
var before = Read(source);
Assert.IsGreaterThan(0L, before.Video!.EditMediaTime ?? 0, "the edit starts at the first composition offset");
AssertAbout(presentation, before.Video.EditSegmentDuration, "the source shows all N frames");
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
var mp4 = Remux(plan!, source);
using var output = new MemoryStream(mp4);
var after = Read(output);
Assert.AreEqual(before.Video.EditMediaTime, after.Video!.EditMediaTime);
Assert.AreEqual(before.Video.EditSegmentDuration, after.Video.EditSegmentDuration, "the segment is the source's");
AssertAbout(presentation, after.Video.EditSegmentDuration, "the MP4 shows all N frames");
Assert.AreEqual(before.Duration, after.Duration);
var shownMs = (long)Math.Ceiling(n * 1000.0 / 30);
Assert.AreEqual((shownMs, shownMs), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)), "mvhd and tkhd last N frames");
Assert.AreEqual((HeaderDuration(mov, "mvhd"u8), HeaderDuration(mov, "tkhd"u8)), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)));
AssertSameSamples(before.Video, source, after.Video, output, "video");
// A frame «oltre la fine» is the one presented last, not one that decodes last.
var lastShown = Enumerable.Range(0, n).MaxBy(i => es.Rank[i]);
using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info);
Assert.IsTrue(info.Available);
Assert.AreEqual(lastShown, reader.Locate([TimeSpan.FromHours(1)]).Single().Sample);
}
/// <summary>A segment read back from the movie timescale (milliseconds, rounded up) is within a millisecond.</summary>
private static void AssertAbout(long expected, long? actual, string what)
{
Assert.IsNotNull(actual, what);
Assert.IsLessThanOrEqualTo(TestVideos.Timescale / 1000, Math.Abs(actual.Value - expected), $"{what}: {actual} for {expected}");
}
/// <summary>The duration of the first <c>mvhd</c> or <c>tkhd</c> of a file (movie units), of either version.</summary>
private static long HeaderDuration(byte[] file, ReadOnlySpan<byte> type)
{
var at = file.AsSpan().IndexOf(type);
Assert.IsGreaterThan(0, at);
var body = file.AsSpan(at + 4);
var wide = body[0] == 1;
var isTrack = type[0] == (byte)'t';
// version and flags, the dates, then the timescale (mvhd) or the track id and a reserved word (tkhd).
var offset = 4 + (wide ? 16 : 8) + (isTrack ? 8 : 4);
return wide ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[offset..]) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
}
[TestMethod] [TestMethod]
[DataRow(44100, 0x6B)] [DataRow(44100, 0x6B)]
[DataRow(32000, 0x6B)] [DataRow(32000, 0x6B)]
+100 -5
View File
@@ -54,14 +54,17 @@ public sealed class FrameServiceTests
using var temp = new TempFolder("fotogrammi-lento"); using var temp = new TempFolder("fotogrammi-lento");
var path = temp.Combine("rumore.mp4"); var path = temp.Combine("rumore.mp4");
await File.WriteAllBytesAsync(path, NoiseVideo(), ct); await File.WriteAllBytesAsync(path, NoiseVideo(), ct);
var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400) };
// The time of the stalls moves only as the link sends, never with the load of the machine.
var time = new LinkTime();
var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400), StallTime = time };
var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [
new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0), new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0),
]); ]);
// 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes. // 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes.
using var sent = new MemoryStream(); using var sent = new MemoryStream();
var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150)); var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150), time);
await service.WriteZipAsync(link, plan, publicationTime: false, ct); await service.WriteZipAsync(link, plan, publicationTime: false, ct);
using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
@@ -113,9 +116,10 @@ public sealed class FrameServiceTests
/// <summary> /// <summary>
/// A response body on a slow link: asynchronous writes only, each taking <c>perPiece</c> for every 64 KB it holds /// A response body on a slow link: asynchronous writes only, each taking <c>perPiece</c> for every 64 KB it holds
/// (a write completes once its bytes are sent); an infinite time is a reader that stopped. /// (a write completes once its bytes are sent); an infinite time is a reader that stopped. With a
/// <see cref="LinkTime"/> a write moves that time instead of waiting for the real one.
/// </summary> /// </summary>
private sealed class SlowStream(Stream inner, TimeSpan perPiece) : Stream private sealed class SlowStream(Stream inner, TimeSpan perPiece, LinkTime? time = null) : Stream
{ {
public TimeSpan Busy { get; private set; } public TimeSpan Busy { get; private set; }
@@ -149,7 +153,16 @@ public sealed class FrameServiceTests
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{ {
var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536); var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536);
await Task.Delay(wait, cancellationToken); if (time is not null && wait != Timeout.InfiniteTimeSpan)
{
time.Advance(wait); // the stall timers due before this write is sent fire now
cancellationToken.ThrowIfCancellationRequested();
}
else
{
await Task.Delay(wait, cancellationToken);
}
if (wait != Timeout.InfiniteTimeSpan) if (wait != Timeout.InfiniteTimeSpan)
{ {
Busy += wait; Busy += wait;
@@ -159,6 +172,88 @@ public sealed class FrameServiceTests
} }
} }
/// <summary>
/// A time that moves only when <see cref="Advance"/> is called: its timers fire then, in order, on the caller's
/// thread. Only one-shot timers (those of a <see cref="CancellationTokenSource"/>) are supported.
/// </summary>
private sealed class LinkTime : TimeProvider
{
private readonly Lock _gate = new();
private readonly List<LinkTimer> _timers = [];
private DateTimeOffset _now = Make.T0;
public override DateTimeOffset GetUtcNow()
{
lock (_gate)
{
return _now;
}
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
Assert.AreEqual(Timeout.InfiniteTimeSpan, period, "one-shot timers only");
var timer = new LinkTimer(this, callback, state);
timer.Change(dueTime, period);
return timer;
}
public void Advance(TimeSpan by)
{
List<LinkTimer> due;
lock (_gate)
{
_now += by;
due = [.. _timers.Where(t => t.Due <= _now).OrderBy(t => t.Due)];
foreach (var t in due)
{
_timers.Remove(t);
}
}
foreach (var t in due)
{
t.Fire();
}
}
private sealed class LinkTimer(LinkTime owner, TimerCallback callback, object? state) : ITimer
{
public DateTimeOffset Due { get; private set; }
public bool Change(TimeSpan dueTime, TimeSpan period)
{
lock (owner._gate)
{
owner._timers.Remove(this);
if (dueTime != Timeout.InfiniteTimeSpan)
{
Due = owner._now + dueTime;
owner._timers.Add(this);
}
}
return true;
}
public void Fire() => callback(state);
public void Dispose()
{
lock (owner._gate)
{
owner._timers.Remove(this);
}
}
public ValueTask DisposeAsync()
{
Dispose();
return ValueTask.CompletedTask;
}
}
}
/// <summary>A response body: asynchronous writes only.</summary> /// <summary>A response body: asynchronous writes only.</summary>
private sealed class AsyncOnlyStream(Stream inner) : Stream private sealed class AsyncOnlyStream(Stream inner) : Stream
{ {