E1: schema dell'esportazione, migrazione 0003, archivi ed ExportSettings (#58)
verifica / controlli (push) Successful in 19s
verifica / prove (push) Canceled after 10m59s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s

La tappa E1 della 0.3.0 prepara il database per le copie esterne senza cambiare
comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue.

- Migrazione 0003: export_destination, export_account, export_copy, export_run,
  export_item, video_analysis e media_conversion (risposta di Alberto del 26
  novembre: i convertiti per la libreria in una tabella a parte, media non cambia),
  con i vincoli e gli indici di §8.3.
- Archivi IExportStore, IVideoAnalysisStore e IMediaConversionStore in IFebeStorage;
  ExportSettings sulle cinque chiavi esportazione.*.
- AccountStore.DeleteAsync spegne «Automatica» delle cartelle dell'account e vi
  scrive il suo nome prima di cancellarlo (finché non ci sono destinazioni non fa nulla).
- Prove: aggiornamento dei database delle versioni 1 e 2 con foreign_key_check
  pulito, database più nuovo rifiutato e lasciato intatto, vincoli, archivi,
  piani delle ricerche, impostazioni e documenti.
- SPECIFICA §4.10, §8.3 e §15, decisioni.md e stato.md aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-26 19:29:14 +01:00
1 parent dc92cabe5c
commit ea4666d49b
23 files changed
+3756 -7

No files matched your search

+381
View File
@@ -0,0 +1,381 @@
namespace Febe.Core.Domain;
/// <summary>Scope of an export destination (spec §4.10 «Destinazioni»).</summary>
public enum ExportScope
{
/// <summary>«Cartella di esportazione generale»: every account, each under its own segment.</summary>
General,
/// <summary>«Cartella propria» of one account, which replaces the general folder for that account.</summary>
Account,
}
/// <summary>Format of an exported file or of a converted library file (spec §4.10 «Conversione del formato»).</summary>
public enum ExportFormat
{
/// <summary>«Originale»: the file as it is in the library, byte for byte.</summary>
Original,
/// <summary>JPG, quality 92: the only lossy choice («con perdita»).</summary>
Jpg,
/// <summary>PNG.</summary>
Png,
/// <summary>«WEBP senza perdita».</summary>
WebpLossless,
/// <summary>MP4, by remuxing only.</summary>
Mp4,
}
/// <summary>Which formats belong to photos and which to videos.</summary>
public static class ExportFormats
{
/// <summary>Originale, JPG, PNG, WEBP senza perdita.</summary>
public static bool IsPhotoFormat(ExportFormat format) =>
format is ExportFormat.Original or ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless;
/// <summary>Originale, MP4.</summary>
public static bool IsVideoFormat(ExportFormat format) => format is ExportFormat.Original or ExportFormat.Mp4;
}
/// <summary>What an export writes from a library file.</summary>
public enum ExportVariant
{
/// <summary>«Intero»: the whole file, byte for byte (format Original).</summary>
Whole,
/// <summary>«Convertito»: the file in another format.</summary>
Converted,
/// <summary>«Fotogramma»: a picture of a video at an instant.</summary>
Frame,
}
/// <summary>State of a copy in a destination (spec §4.10 «Già copiato»).</summary>
public enum ExportCopyState
{
/// <summary>«Copiato».</summary>
Copied,
/// <summary>«Tolto»: the file is no longer in the destination. Never copied again by itself.</summary>
Removed,
/// <summary>«Superato»: the library file changed after the copy. Never copied again by itself.</summary>
Superseded,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>How a copy came to be recorded.</summary>
public enum ExportCopyOrigin
{
/// <summary>Written by Febe.</summary>
Written,
/// <summary>An existing file recognised by path (spec §4.10 «Adozione per percorso»).</summary>
Adopted,
}
/// <summary>Kind of an export job.</summary>
public enum ExportRunKind
{
/// <summary>«Copia in…» or the automatic export.</summary>
Copy,
/// <summary>«Riconosci le copie già presenti».</summary>
Recognize,
}
/// <summary>Who started an export job.</summary>
public enum ExportRunOrigin
{
Manual,
Automatic,
}
/// <summary>State of an export job (on the model of <see cref="ImportRunState"/>).</summary>
public enum ExportRunState
{
Running,
/// <summary>Febe was closed: resumes from the pending items.</summary>
Interrupted,
/// <summary>The destination is not reachable: resumes when a later check succeeds.</summary>
Paused,
Completed,
Cancelled,
}
/// <summary>Progress of one file of an export job.</summary>
public enum ExportItemState
{
Pending,
/// <summary>Written to the destination.</summary>
Copied,
/// <summary>An existing file recognised by path.</summary>
Adopted,
/// <summary>«Già copiato»: nothing to do.</summary>
AlreadyCopied,
Skipped,
/// <summary>«File non presente in libreria».</summary>
Missing,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>Outcome of «È un video fermo?» (spec §4.10).</summary>
public enum VideoAnalysisOutcome
{
/// <summary>«Fermo».</summary>
Still,
/// <summary>«In movimento».</summary>
Moving,
/// <summary>«Non analizzabile».</summary>
NotAnalyzable,
}
/// <summary>State of a converted file added to an entry by the conversion for the library.</summary>
public enum MediaConversionState
{
/// <summary>«In attesa»: the queue of the conversion.</summary>
Pending,
/// <summary>«Convertito».</summary>
Converted,
/// <summary>«Superato»: the original changed after the conversion.</summary>
Superseded,
/// <summary>«Tolto»: the converted file was deleted with its remembered entry.</summary>
Removed,
/// <summary>«Non riuscito».</summary>
Failed,
}
/// <summary>
/// An export destination (spec §8.3 <c>export_destination</c>): the general folder or the own folder of an account.
/// One row is one root folder for ever: another folder is a new row, and the old one is retired with its copies.
/// </summary>
public sealed record ExportDestination
{
public long Id { get; init; }
public required ExportScope Scope { get; init; }
/// <summary>The account of an own folder; null for the general folder, and after the account was removed.</summary>
public long? AccountId { get; init; }
/// <summary>User name of the account when it was removed («era di @nome»). Written only by the account removal.</summary>
public string? RemovedAccountUsername { get; init; }
/// <summary>Name shown in the interface; null: the last segment of <see cref="RootPath"/>.</summary>
public string? Label { get; init; }
/// <summary>Root folder as chosen. Never created by Febe, never changed.</summary>
public required string RootPath { get; init; }
public required ContentTypes ContentTypes { get; init; }
/// <summary>Null: «Come le impostazioni generali».</summary>
public ExportFormat? PhotoFormat { get; init; }
/// <summary>Null: «Come le impostazioni generali».</summary>
public ExportFormat? VideoFormat { get; init; }
/// <summary>General naming scheme under the destination; null: «Come la libreria».</summary>
public string? NamingScheme { get; init; }
/// <summary>Naming scheme of highlight collections; null: «Come la libreria».</summary>
public string? HighlightNamingScheme { get; init; }
/// <summary>Naming scheme of profile pictures; null: «Come la libreria».</summary>
public string? ProfileNamingScheme { get; init; }
/// <summary>«Automatica» (off by default).</summary>
public bool Automatic { get; init; }
/// <summary>
/// «Solo i nuovi»: files downloaded at or after this instant; null with <see cref="Automatic"/>: everything. Must
/// be null when <see cref="Automatic"/> is off.
/// </summary>
public DateTimeOffset? AutomaticSince { get; init; }
/// <summary>The probe file could not be written: paused until a later check succeeds.</summary>
public DateTimeOffset? PausedAt { get; init; }
public string? LastError { get; init; }
public required DateTimeOffset CreatedAt { get; init; }
/// <summary>Retired: removed by Alberto, or replaced by a row with another folder.</summary>
public DateTimeOffset? RemovedAt { get; init; }
public bool IsRetired => RemovedAt is not null;
/// <summary>An own folder whose account was removed.</summary>
public bool IsOrphan => Scope == ExportScope.Account && AccountId is null;
}
/// <summary>
/// The identity of a copy: SHA-256 of the original, destination, effective account, variant, format and frame instant,
/// always the effective ones (a byte-for-byte result is <see cref="ExportVariant.Whole"/> and
/// <see cref="ExportFormat.Original"/> whatever was requested).
/// </summary>
public sealed record ExportCopyIdentity(long DestinationId, long AccountId, string SourceSha256, ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
/// <summary>A copy made in a destination (spec §8.3 <c>export_copy</c>). It outlives the library entry.</summary>
public sealed record ExportCopy
{
public long Id { get; init; }
public required long DestinationId { get; init; }
/// <summary>Effective account; null only after the account was removed («orphan»).</summary>
public long? AccountId { get; init; }
/// <summary>The library file; null after the entry or its files were deleted.</summary>
public long? MediaId { get; init; }
public required string SourceSha256 { get; init; }
public required ExportVariant Variant { get; init; }
public ExportFormat Format { get; init; } = ExportFormat.Original;
/// <summary>Instant of a frame; set only for <see cref="ExportVariant.Frame"/>.</summary>
public TimeSpan? FrameAt { get; init; }
public required ExportCopyState State { get; init; }
/// <summary>SHA-256 of the library file that took the place of the original: required for Superseded, allowed on Removed.</summary>
public string? SupersededBySha256 { get; init; }
public ExportCopyOrigin Origin { get; init; } = ExportCopyOrigin.Written;
/// <summary>Path relative to the destination root, '/' separated, NFC.</summary>
public string? RelativePath { get; init; }
public long? Bytes { get; init; }
public string? CopySha256 { get; init; }
public required DateTimeOffset CopiedAt { get; init; }
public DateTimeOffset? StateChangedAt { get; init; }
public string? LastError { get; init; }
/// <summary>The identity of the copy; null for an orphan row.</summary>
public ExportCopyIdentity? Identity =>
AccountId is { } account ? new ExportCopyIdentity(DestinationId, account, SourceSha256, Variant, Format, FrameAt) : null;
}
/// <summary>An export job (spec §8.3 <c>export_run</c>, on the model of <see cref="ImportRun"/>).</summary>
public sealed record ExportRun
{
public long Id { get; init; }
public required long DestinationId { get; init; }
public ExportRunKind Kind { get; init; } = ExportRunKind.Copy;
public ExportRunOrigin Origin { get; init; } = ExportRunOrigin.Manual;
public ExportRunState State { get; init; } = ExportRunState.Running;
public required DateTimeOffset StartedAt { get; init; }
public DateTimeOffset? CompletedAt { get; init; }
public string? LastError { get; init; }
}
/// <summary>
/// A file of an export job (spec §8.3 <c>export_item</c>, on the model of <see cref="ImportFile"/>): the request
/// (variant and format as asked) and how it went; the effective result goes to <see cref="ExportCopy"/>.
/// </summary>
public sealed record ExportItem
{
public long Id { get; init; }
public required long RunId { get; init; }
/// <summary>The library file; null when it was deleted meanwhile.</summary>
public long? MediaId { get; init; }
/// <summary>Effective account; required when the item is added.</summary>
public long? AccountId { get; init; }
/// <summary>SHA-256 of the original when queued; null when the file was not in the library.</summary>
public string? SourceSha256 { get; init; }
public ExportVariant Variant { get; init; } = ExportVariant.Whole;
public ExportFormat Format { get; init; } = ExportFormat.Original;
public TimeSpan? FrameAt { get; init; }
public ExportItemState State { get; init; } = ExportItemState.Pending;
/// <summary>English code of a note for the report.</summary>
public string? Note { get; init; }
/// <summary>Target path in the destination, written before the <c>.part</c> is created.</summary>
public string? RelativePath { get; init; }
public long? CopyId { get; init; }
public string? LastError { get; init; }
}
/// <summary>Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 <c>video_analysis</c>).</summary>
public sealed record VideoAnalysis(string Sha256, int Algorithm, VideoAnalysisOutcome Outcome, DateTimeOffset AnalyzedAt);
/// <summary>
/// A converted file added to an entry by the conversion for the library (spec §4.10, §8.3 <c>media_conversion</c>),
/// linked to the media row of its original, which does not change.
/// </summary>
public sealed record MediaConversion
{
public long Id { get; init; }
public required long MediaId { get; init; }
public required ExportFormat Format { get; init; }
public MediaConversionState State { get; init; } = MediaConversionState.Pending;
/// <summary>SHA-256 of the original it was made from.</summary>
public required string SourceSha256 { get; init; }
/// <summary>Path relative to the account folder, like <see cref="Media.RelativePath"/>.</summary>
public string? RelativePath { get; init; }
public long? Bytes { get; init; }
/// <summary>SHA-256 of the converted file.</summary>
public string? Sha256 { get; init; }
public required DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset? ConvertedAt { get; init; }
public DateTimeOffset? StateChangedAt { get; init; }
public string? LastError { get; init; }
}
+102
View File
@@ -0,0 +1,102 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>Setting keys of Impostazioni → Esportazione (spec §4.10). Values are the English names of the enumerations.</summary>
public static class ExportSettingKeys
{
/// <summary>Format of the copies of photos (Original, Jpg, Png, WebpLossless).</summary>
public const string PhotoFormat = "esportazione.formato-foto";
/// <summary>Format of the copies of videos (Original, Mp4).</summary>
public const string VideoFormat = "esportazione.formato-video";
/// <summary>Conversion of photos for the library; Original: off.</summary>
public const string LibraryPhotoFormat = "esportazione.libreria-formato-foto";
/// <summary>Conversion of videos for the library; Original: off.</summary>
public const string LibraryVideoFormat = "esportazione.libreria-formato-video";
/// <summary>The same post in two accounts: «Una copia per account» or «Una copia sola».</summary>
public const string SamePost = "esportazione.stesso-post";
public static IReadOnlyList<string> All { get; } = [PhotoFormat, VideoFormat, LibraryPhotoFormat, LibraryVideoFormat, SamePost];
}
/// <summary>How many copies the same post gets when it is in two accounts (spec §4.10).</summary>
public enum SamePostCopies
{
/// <summary>«Una copia per account» (default).</summary>
OnePerAccount,
/// <summary>«Una copia sola».</summary>
OneOnly,
}
/// <summary>
/// General settings of the export (spec §4.10, Impostazioni → Esportazione), in the <c>setting</c> table. Both
/// conversions are off by default. The general folder, its content types, naming schemes and «Automatica» are columns
/// of the general destination, not settings.
/// </summary>
public sealed record ExportSettings(
ExportFormat PhotoFormat = ExportFormat.Original,
ExportFormat VideoFormat = ExportFormat.Original,
ExportFormat LibraryPhotoFormat = ExportFormat.Original,
ExportFormat LibraryVideoFormat = ExportFormat.Original,
SamePostCopies SamePost = SamePostCopies.OnePerAccount)
{
/// <summary>Quality of the only lossy conversion, JPG (spec §4.10): fixed, not a setting.</summary>
public const int JpegQuality = 92;
public static ExportSettings Default { get; } = new();
/// <summary>The conversion for the copies is on for photos or videos.</summary>
public bool ConvertsCopies => PhotoFormat != ExportFormat.Original || VideoFormat != ExportFormat.Original;
/// <summary>The conversion for the library is on for photos or videos.</summary>
public bool ConvertsLibrary => LibraryPhotoFormat != ExportFormat.Original || LibraryVideoFormat != ExportFormat.Original;
/// <summary>Loads the settings in one read. A missing or invalid value gives that key's default; the others are not affected.</summary>
public static async Task<ExportSettings> LoadAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
return From(await store.GetAllAsync(ct).ConfigureAwait(false));
}
/// <summary>Stores the five keys in one transaction.</summary>
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
return store.SetManyAsync(
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 settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
{
ArgumentNullException.ThrowIfNull(values);
ExportFormat Format(string key, Func<ExportFormat, bool> fits) =>
Parse<ExportFormat>(values.GetValueOrDefault(key)) is { } format && fits(format) ? format : ExportFormat.Original;
return new ExportSettings(
Format(ExportSettingKeys.PhotoFormat, ExportFormats.IsPhotoFormat),
Format(ExportSettingKeys.VideoFormat, ExportFormats.IsVideoFormat),
Format(ExportSettingKeys.LibraryPhotoFormat, ExportFormats.IsPhotoFormat),
Format(ExportSettingKeys.LibraryVideoFormat, ExportFormats.IsVideoFormat),
Parse<SamePostCopies>(values.GetValueOrDefault(ExportSettingKeys.SamePost)) ?? SamePostCopies.OnePerAccount);
}
// Not Enum.TryParse: it accepts numbers («2») and lists («Jpg, Png») and returns values that are not names.
private static T? Parse<T>(string? text)
where T : struct, Enum =>
text is not null && Enum.GetNames<T>().Contains(text, StringComparer.Ordinal) ? Enum.Parse<T>(text, ignoreCase: false) : null;
}
+2 -1
View File
@@ -60,7 +60,8 @@ public interface IAccountStore
/// <summary>
/// Removes the account record and, by cascade, its entries, files records and highlights. Files on disk are not
/// touched: removing an account with its files is a library operation, and the default is to keep them and make
/// the account «Solo archivio» (spec §4.2).
/// the account «Solo archivio» (spec §4.2). Its export destinations stay, without account and with the user name;
/// its «Esporta questo account» choice goes with it (spec §4.10).
/// </summary>
Task DeleteAsync(long accountId, CancellationToken ct = default);
}
+173
View File
@@ -0,0 +1,173 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Export destinations, the switch «Esporta questo account», copies, jobs and their files (spec §4.10; §8.3
/// <c>export_destination</c>, <c>export_account</c>, <c>export_copy</c>, <c>export_run</c>, <c>export_item</c>).
/// Only records: no method touches a file.
/// </summary>
public interface IExportStore
{
// Destinations ---------------------------------------------------------------------------------------------------
/// <summary>
/// Adds a destination. General: <see cref="ExportDestination.AccountId"/> null; Account: set.
/// <see cref="ExportDestination.RemovedAt"/> and <see cref="ExportDestination.RemovedAccountUsername"/> must be null.
/// <see cref="DuplicateRecordException"/> when a general folder is already in use, or the account already has an own
/// folder in use (retire it first).
/// </summary>
Task<ExportDestination> AddDestinationAsync(ExportDestination destination, CancellationToken ct = default);
/// <summary>
/// Writes label, content types, formats, naming schemes, «Automatica» and its answer, pause and error.
/// <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).
/// </summary>
Task UpdateDestinationAsync(ExportDestination destination, CancellationToken ct = default);
Task<ExportDestination?> GetDestinationAsync(long id, CancellationToken ct = default);
/// <summary>The general folder in use, or null.</summary>
Task<ExportDestination?> GetGeneralDestinationAsync(CancellationToken ct = default);
/// <summary>The own folder in use of an account, or null.</summary>
Task<ExportDestination?> GetAccountDestinationAsync(long accountId, CancellationToken ct = default);
/// <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>
/// 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.
/// </summary>
Task RetireDestinationAsync(long id, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// Gives an orphan own folder in use back to a re-added account: sets the account, clears the user name and, in the
/// same transaction, sets the account on its orphan copies. «Automatica» stays off (the removal of the account turned
/// it off and forgot «Solo i nuovi»), so turning it on again asks. <see cref="InvalidOperationException"/> if it is not
/// an orphan in use, or the account already has an own folder in use; <see cref="DuplicateRecordException"/> if an
/// orphan copy would collide with a current copy of the account.
/// </summary>
Task AttachDestinationAsync(long id, long accountId, CancellationToken ct = default);
// «Esporta questo account» ---------------------------------------------------------------------------------------
/// <summary>The choice of the account; null when none is recorded (the default applies).</summary>
Task<bool?> GetAccountExportEnabledAsync(long accountId, CancellationToken ct = default);
Task SetAccountExportEnabledAsync(long accountId, bool enabled, CancellationToken ct = default);
// Copies ---------------------------------------------------------------------------------------------------------
/// <summary>
/// Records a copy. <see cref="ArgumentException"/> when the account is null (only the removal of an account clears it);
/// <see cref="DuplicateRecordException"/> when its identity already has a current (Copied or Failed) row, or its path
/// in the destination is held by a Copied or Superseded row.
/// </summary>
Task<ExportCopy> AddCopyAsync(ExportCopy copy, CancellationToken ct = default);
/// <summary>
/// Writes state, superseded-by, media, origin, path, bytes, copy SHA-256, state time and error.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="ArgumentException"/> if an identity column
/// (destination, account, source SHA-256, variant, format, frame) differs from the stored row;
/// <see cref="DuplicateRecordException"/> when the new state collides with another current row or path (as in
/// <see cref="AddCopyAsync"/>).
/// </summary>
Task UpdateCopyAsync(ExportCopy copy, CancellationToken ct = default);
Task<ExportCopy?> GetCopyAsync(long id, CancellationToken ct = default);
/// <summary>The current (Copied or Failed) copy of an identity.</summary>
Task<ExportCopy?> FindCurrentCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default);
/// <summary>The newest row of an identity in any state: Removed or Superseded means «never queued by itself».</summary>
Task<ExportCopy?> FindLatestCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default);
/// <summary>Every copy whose original has this SHA-256 or was replaced by it, any destination, account and state, newest first.</summary>
Task<IReadOnlyList<ExportCopy>> ListCopiesBySha256Async(string sha256, CancellationToken ct = default);
/// <summary>The Copied or Superseded copy recorded on this path of a destination (case-insensitive for ASCII).</summary>
Task<ExportCopy?> FindCopyByPathAsync(long destinationId, string relativePath, CancellationToken ct = default);
/// <summary>Copies of a destination by key, with an optional state.</summary>
Task<IReadOnlyList<ExportCopy>> ListCopiesAsync(long destinationId, ExportCopyState? state = null, long afterId = 0, int limit = 500, CancellationToken ct = default);
/// <summary>Counts per state of a destination; every state is present, zero included.</summary>
Task<IReadOnlyDictionary<ExportCopyState, int>> CountCopiesAsync(long destinationId, CancellationToken ct = default);
/// <summary>
/// Re-links an orphan row (account removed) to a re-added account, when its file is adopted again.
/// <see cref="KeyNotFoundException"/> for a missing id; <see cref="InvalidOperationException"/> if the row is not an orphan;
/// <see cref="DuplicateRecordException"/> if the account already has a current copy of that identity.
/// </summary>
Task<ExportCopy> RelinkOrphanCopyAsync(long copyId, long accountId, long? mediaId, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// The library file of an account changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/>: its
/// Copied rows of the old file become Superseded, its Removed rows of the old file get the new SHA-256, and its rows
/// superseded by the old file move to the new one. A row whose own original is the new file (the library went back to
/// it, A→B→A) is never superseded by itself: a Removed one loses the stamp, and the newest Superseded one of each
/// identity becomes Copied again, unless that identity already has a current row (then it stays Superseded by the old
/// file, as history). Returns the rows changed. The caller calls it only when no present file of that account still
/// has the old SHA-256.
/// </summary>
Task<int> SupersedeCopiesAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
// Jobs and their files -------------------------------------------------------------------------------------------
Task<ExportRun> CreateRunAsync(ExportRun run, CancellationToken ct = default);
Task UpdateRunAsync(ExportRun run, CancellationToken ct = default);
Task<ExportRun?> GetRunAsync(long runId, CancellationToken ct = default);
/// <summary>Jobs, newest first.</summary>
Task<IReadOnlyList<ExportRun>> ListRunsAsync(CancellationToken ct = default);
/// <summary>Running, Interrupted and Paused jobs, oldest first.</summary>
Task<IReadOnlyList<ExportRun>> ListUnfinishedRunsAsync(CancellationToken ct = default);
/// <summary>
/// Adds items in one transaction; an item already there for the same job, file, variant, format and frame is left
/// unchanged (so a resumed job adds nothing twice). <see cref="ArgumentException"/> when an item has no account or no
/// library file (only the deletion of the file clears it, and an item without one would not be recognised again).
/// </summary>
Task AddItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default);
/// <summary>
/// Writes account (never cleared), source SHA-256, state, note, path, copy and error of items. Job, file, variant,
/// format and frame are the identity of an item and are never rewritten: <see cref="ArgumentException"/> if they
/// differ from the stored row (a file deleted meanwhile stays cleared); <see cref="KeyNotFoundException"/> for a
/// missing item of the job.
/// </summary>
Task UpdateItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default);
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
/// <summary>Items of a job, by key, with an optional state.</summary>
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
/// <summary>Counts by state of a job's items; every state is present, zero included.</summary>
Task<ExportRunSummary> GetRunSummaryAsync(long runId, CancellationToken ct = default);
/// <summary>Removes a job with its items. Only records: copies stay.</summary>
Task DeleteRunAsync(long runId, CancellationToken ct = default);
}
/// <summary>A page of the items of an export job.</summary>
public sealed record ExportItemQuery
{
public required long RunId { get; init; }
public ExportItemState? State { get; init; }
public long AfterId { get; init; }
public int Limit { get; init; } = 500;
}
/// <summary>Counts of the items of an export job.</summary>
public sealed record ExportRunSummary(int Total, IReadOnlyDictionary<ExportItemState, int> ByState);
+6
View File
@@ -30,6 +30,12 @@ public interface IFebeStorage : IAsyncDisposable
IImportStore Imports { get; }
IExportStore Exports { get; }
IVideoAnalysisStore VideoAnalyses { get; }
IMediaConversionStore Conversions { get; }
ISettingsStore Settings { get; }
IDatabaseMaintenance Maintenance { get; }
@@ -0,0 +1,33 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Converted files added to entries by the conversion for the library (spec §4.10, §8.3 <c>media_conversion</c>).
/// Only records: no method touches a file.
/// </summary>
public interface IMediaConversionStore
{
/// <summary>
/// Records a conversion. <see cref="DuplicateRecordException"/> when the file already has a current (Pending,
/// Converted or Failed) conversion in that format.
/// </summary>
Task<MediaConversion> AddAsync(MediaConversion conversion, CancellationToken ct = default);
/// <summary>
/// Writes state, path, bytes, SHA-256, times and error. <see cref="KeyNotFoundException"/> for a missing id;
/// <see cref="DuplicateRecordException"/> when the new state collides with another current conversion (as in <see cref="AddAsync"/>).
/// </summary>
Task UpdateAsync(MediaConversion conversion, CancellationToken ct = default);
Task<MediaConversion?> GetAsync(long id, CancellationToken ct = default);
/// <summary>The conversions of one library file, in creation order.</summary>
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
/// <summary>The queue of the conversion, in order, by key.</summary>
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
}
@@ -0,0 +1,19 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// Outcomes of «È un video fermo?» by SHA-256 of the video and number of the algorithm (spec §4.10, §8.3
/// <c>video_analysis</c>). No link to the library: an outcome outlives deletion and re-import of the same file.
/// </summary>
public interface IVideoAnalysisStore
{
/// <summary>The analysis with the highest algorithm number for this SHA-256, or null.</summary>
Task<VideoAnalysis?> GetAsync(string sha256, CancellationToken ct = default);
/// <summary>The analysis with the highest algorithm number for each SHA-256 that has one, keyed by lower-case SHA-256.</summary>
Task<IReadOnlyDictionary<string, VideoAnalysis>> GetManyAsync(IReadOnlyCollection<string> sha256s, CancellationToken ct = default);
/// <summary>Stores (or replaces) the outcome of one algorithm for one SHA-256.</summary>
Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default);
}
+9
View File
@@ -40,6 +40,9 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
Events = new EventStore(this);
Following = new FollowingStore(this);
Imports = new ImportStore(this);
Exports = new ExportStore(this);
VideoAnalyses = new VideoAnalysisStore(this);
Conversions = new MediaConversionStore(this);
Settings = new SettingsStore(this);
}
@@ -67,6 +70,12 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
public IImportStore Imports { get; }
public IExportStore Exports { get; }
public IVideoAnalysisStore VideoAnalyses { get; }
public IMediaConversionStore Conversions { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
@@ -0,0 +1,246 @@
-- Febe, schema version 3: export (tappa E1 of 0.3.0, issue #58; spec §4.10, §8.3).
-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
-- Only new tables and indexes: no column or index of the existing tables changes. The only existing path that touches
-- the new tables is AccountStore.DeleteAsync, which disables the account's destinations and keeps its user name on them
-- before deleting the account (nothing to do while there are no destinations); nothing else reads or writes them yet
-- (tappa E1: no behaviour change). Times are UTC Unix milliseconds; enumerations are their English names,
-- checked here. Paths in a destination are relative to its root, '/' separated, NFC; paths of converted library files
-- are relative to the account folder, like media.relative_path. Every foreign key has an index on its child column.
-- A destination (spec §4.10 «Destinazioni»): the general export folder (scope General) or the own folder of an account
-- (scope Account), which replaces the general one for that account. One row is one root folder for ever: choosing
-- another folder retires the row (removed_at) and adds a new one, so «già copiato» never points at a folder the copies
-- were not written to. Retired rows stay with their copies (spec §4.10: removing a destination removes only the
-- configuration; §13.2: export_copy is all Febe knows of the copies). Removing an account never deletes its row, it
-- disables it: AccountStore.DeleteAsync turns «Automatica» off (forgetting «Solo i nuovi») and keeps the user name in the
-- same transaction, then ON DELETE SET NULL clears the link, and the row stays inactive until the account is attached
-- again, still with «Automatica» off; the last two CHECKs make any path that forgets either fail.
CREATE TABLE export_destination (
id INTEGER PRIMARY KEY,
scope TEXT NOT NULL CHECK (scope IN ('General', 'Account')),
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
-- User name of the account when it was removed, so the destination can still be named («era di @nome»).
removed_account_username TEXT CHECK (removed_account_username IS NULL OR length(removed_account_username) > 0),
-- Name shown in the interface («Disco USB»); NULL: the last segment of root_path.
label TEXT CHECK (label IS NULL OR length(label) > 0),
-- Root folder as chosen (Windows: full path, UNC included; Docker: a subfolder of /esporta). Never created by Febe,
-- never changed (see above).
root_path TEXT NOT NULL CHECK (length(root_path) > 0),
-- ContentTypes flags (PostPhotos 1, PostVideos 2, Stories 4, Highlights 8, Tagged 16, ProfilePicture 32).
content_types INTEGER NOT NULL CHECK (content_types >= 0),
-- Formats of the copies, as requested; NULL: «Come le impostazioni generali» (esportazione.formato-foto/-video).
photo_format TEXT CHECK (photo_format IS NULL OR photo_format IN ('Original', 'Jpg', 'Png', 'WebpLossless')),
video_format TEXT CHECK (video_format IS NULL OR video_format IN ('Original', 'Mp4')),
-- The three naming schemes of §4.7 (general, highlight collections, profile pictures) under the destination, checked
-- like the library's; each NULL: «Come la libreria» (libreria.schema, libreria.schema-evidenza, libreria.schema-profilo).
naming_scheme TEXT CHECK (naming_scheme IS NULL OR length(naming_scheme) > 0),
highlight_naming_scheme TEXT CHECK (highlight_naming_scheme IS NULL OR length(highlight_naming_scheme) > 0),
profile_naming_scheme TEXT CHECK (profile_naming_scheme IS NULL OR length(profile_naming_scheme) > 0),
-- «Automatica» (off by default). automatic_since is the answer «Solo i nuovi»: files whose media.downloaded_at (the
-- time of their _febe.jsonl line, kept by a rebuild) is at or after it; NULL with automatic = 1: everything. Turning
-- the switch off forgets the answer, so the next activation asks again.
automatic INTEGER NOT NULL DEFAULT 0 CHECK (automatic IN (0, 1)),
automatic_since INTEGER,
-- The probe file could not be written: the destination is paused until a later check succeeds (spec §4.10).
paused_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL,
-- Retired: removed by Alberto, or replaced by a row with another folder. Never automatic again.
removed_at INTEGER,
CHECK (automatic = 1 OR automatic_since IS NULL),
CHECK (removed_at IS NULL OR automatic = 0),
CHECK (scope = 'Account' OR (account_id IS NULL AND removed_account_username IS NULL)),
CHECK (scope = 'General' OR account_id IS NOT NULL OR removed_account_username IS NOT NULL),
-- An own folder without its account (orphan) is never automatic.
CHECK (scope = 'General' OR account_id IS NOT NULL OR automatic = 0)
);
-- At most one general folder in use.
CREATE UNIQUE INDEX ux_export_destination_general ON export_destination (scope) WHERE scope = 'General' AND removed_at IS NULL;
-- At most one own folder in use per account: with the general folder, at most one effective destination per account.
CREATE UNIQUE INDEX ux_export_destination_account ON export_destination (account_id) WHERE account_id IS NOT NULL AND removed_at IS NULL;
-- Foreign key of the account (SET NULL): the unique index above is partial on removed_at and cannot serve it.
CREATE INDEX ix_export_destination_account ON export_destination (account_id) WHERE account_id IS NOT NULL;
-- «Esporta questo account» (spec §4.10; scheda account → Impostazioni, «Copie esterne»): a switch of the account,
-- whatever its effective destination, not a destination. No row: the default, decided by tappa E2. A setting of the
-- account, so it goes with it (CASCADE); no column in account (spec §8.3).
CREATE TABLE export_account (
account_id INTEGER PRIMARY KEY REFERENCES account (id) ON DELETE CASCADE,
enabled INTEGER NOT NULL CHECK (enabled IN (0, 1))
);
-- A copy made (spec §4.10 «Già copiato»). Its identity is SHA-256 of the original, destination, effective account,
-- variant, format and frame instant, always the effective ones: a byte-for-byte result (same format as the source,
-- HEIC, animated images, a video that cannot be remuxed) is Whole/Original whatever was requested. Removed and
-- Superseded rows stay as history and are never copied again by themselves, only by «Copia di nuovo», which adds a new
-- row; so only the current row of an identity (Copied or Failed) is unique, and the latest row of an identity in any
-- state answers «may this be queued automatically?». The row outlives the library: deleting an entry or its files sets
-- media_id to NULL and keeps source_sha256, so an entry deleted with «Eliminalo e lascia che torni» finds its copies
-- again by SHA-256. A destination with copies cannot be deleted (RESTRICT): it is retired instead.
CREATE TABLE export_copy (
id INTEGER PRIMARY KEY,
destination_id INTEGER NOT NULL REFERENCES export_destination (id) ON DELETE RESTRICT,
-- Effective account: the account segment in the general folder, or the account of its own folder. NULL only after
-- the account was removed («orphan»): the store never writes NULL, and re-links an orphan row when its file is
-- adopted again or its destination is attached to the account again.
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
source_sha256 TEXT NOT NULL CHECK (length(source_sha256) = 64),
variant TEXT NOT NULL CHECK (variant IN ('Whole', 'Converted', 'Frame')),
format TEXT NOT NULL CHECK (format IN ('Original', 'Jpg', 'Png', 'WebpLossless', 'Mp4')),
frame_at_ms INTEGER CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0),
state TEXT NOT NULL CHECK (state IN ('Copied', 'Removed', 'Superseded', 'Failed')),
-- SHA-256 of the library file that took the place of the original («Tieni il più grande», a rebuild). Required for
-- Superseded, allowed on Removed, so the new file is not «Non ancora copiato» and is never queued by itself. Never
-- the original itself: when the library file goes back to it, the copy matches again (see SupersedeCopiesAsync).
superseded_by_sha256 TEXT CHECK (superseded_by_sha256 IS NULL OR length(superseded_by_sha256) = 64),
-- Written by Febe, or an existing file adopted by path (spec §4.10 «Adozione per percorso»).
origin TEXT NOT NULL DEFAULT 'Written' CHECK (origin IN ('Written', 'Adopted')),
-- NOCASE: destinations are Windows and SMB folders, where Mario/x.jpg and mario/X.jpg are one file (ASCII only).
relative_path TEXT COLLATE NOCASE CHECK (relative_path IS NULL OR length(relative_path) > 0),
bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0),
copy_sha256 TEXT CHECK (copy_sha256 IS NULL OR length(copy_sha256) = 64),
copied_at INTEGER NOT NULL,
state_changed_at INTEGER,
last_error TEXT,
-- A whole copy is byte for byte; a conversion changes the format; a frame is a picture at an instant.
CHECK ((variant = 'Whole' AND format = 'Original')
OR (variant = 'Converted' AND format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4'))
OR (variant = 'Frame' AND format IN ('Jpg', 'Png', 'WebpLossless'))),
CHECK ((variant = 'Frame') = (frame_at_ms IS NOT NULL)),
-- Every state but Failed had a file in the destination.
CHECK (state = 'Failed' OR (relative_path IS NOT NULL AND bytes IS NOT NULL AND copy_sha256 IS NOT NULL)),
-- Whole copies have the SHA-256 of their original, and only they: a converted file equal to its original is Whole.
CHECK (copy_sha256 IS NULL OR (variant = 'Whole') = (copy_sha256 = source_sha256)),
CHECK (state <> 'Superseded' OR superseded_by_sha256 IS NOT NULL),
CHECK (superseded_by_sha256 IS NULL OR state IN ('Superseded', 'Removed')),
CHECK (superseded_by_sha256 IS NULL OR superseded_by_sha256 <> source_sha256)
);
-- The copy identity: one current row (Copied or Failed) per identity. NULL account_id (orphan) is distinct.
CREATE UNIQUE INDEX ux_export_copy_identity ON export_copy
(destination_id, source_sha256, account_id, variant, format, ifnull(frame_at_ms, -1))
WHERE state IN ('Copied', 'Failed');
-- Never two rows on one file: a path holding a Copied or Superseded copy is taken (a Removed one is free again).
CREATE UNIQUE INDEX ux_export_copy_path ON export_copy (destination_id, relative_path)
WHERE state IN ('Copied', 'Superseded');
-- Foreign key of the destination (RESTRICT), counts per state (Dashboard «Esportazione»), the walk of a destination
-- («Riconosci», Tolto checks), and the set shape of the «Copie» filter over the whole library (E2), from the index alone.
CREATE INDEX ix_export_copy_destination ON export_copy (destination_id, state, source_sha256, account_id);
-- The copies of a destination by key (ListCopiesAsync, with or without a state): (destination_id, rowid), so a page
-- reads on from the last key instead of sorting every copy of the destination again.
CREATE INDEX ix_export_copy_destination_id ON export_copy (destination_id);
-- Lookups by SHA-256 (spec §4.10: «Si cerca per SHA-256»): viewer File panel, «Una copia sola», entries that come back,
-- the EXISTS of the «Copie» filter inside a window, and the latest row of an identity in any state (rowid order).
CREATE INDEX ix_export_copy_sha256 ON export_copy
(source_sha256, destination_id, account_id, variant, format, ifnull(frame_at_ms, -1));
-- Superseded and Removed copies of a library file that changed, by the SHA-256 of the file now in the library.
CREATE INDEX ix_export_copy_superseded_by ON export_copy (superseded_by_sha256, destination_id, account_id)
WHERE superseded_by_sha256 IS NOT NULL;
-- Foreign keys with SET NULL.
CREATE INDEX ix_export_copy_media ON export_copy (media_id) WHERE media_id IS NOT NULL;
CREATE INDEX ix_export_copy_account ON export_copy (account_id) WHERE account_id IS NOT NULL;
-- An export job (on the model of import_run): «Copia in…», the automatic export, «Riconosci le copie già presenti».
-- Interrupted (Febe closed) and Paused (destination not reachable) runs resume from their pending items.
CREATE TABLE export_run (
id INTEGER PRIMARY KEY,
destination_id INTEGER NOT NULL REFERENCES export_destination (id) ON DELETE RESTRICT,
kind TEXT NOT NULL CHECK (kind IN ('Copy', 'Recognize')),
origin TEXT NOT NULL CHECK (origin IN ('Manual', 'Automatic')),
state TEXT NOT NULL CHECK (state IN ('Running', 'Interrupted', 'Paused', 'Completed', 'Cancelled')),
started_at INTEGER NOT NULL,
completed_at INTEGER,
last_error TEXT
);
-- Foreign key of the destination.
CREATE INDEX ix_export_run_destination ON export_run (destination_id);
-- Runs to resume at start-up and in the hourly round, without reading the finished ones.
CREATE INDEX ix_export_run_unfinished ON export_run (state) WHERE state IN ('Running', 'Interrupted', 'Paused');
-- A file of an export job (on the model of import_file): what was requested (variant and format as asked: the effective
-- ones are known only on the file and go to export_copy), and how it went.
CREATE TABLE export_item (
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES export_run (id) ON DELETE CASCADE,
-- The library file; NULL when it was deleted meanwhile (the item then ends «File non presente in libreria»).
media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
-- Effective account; never written NULL, cleared only by the removal of the account.
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
-- SHA-256 of the original when queued; NULL when the file was not in the library.
source_sha256 TEXT CHECK (source_sha256 IS NULL OR length(source_sha256) = 64),
variant TEXT NOT NULL CHECK (variant IN ('Whole', 'Converted', 'Frame')),
format TEXT NOT NULL CHECK (format IN ('Original', 'Jpg', 'Png', 'WebpLossless', 'Mp4')),
frame_at_ms INTEGER CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0),
state TEXT NOT NULL CHECK (state IN ('Pending', 'Copied', 'Adopted', 'AlreadyCopied', 'Skipped', 'Missing', 'Failed')),
-- English code of a note for the report (an animated image copied as original, metadata the format cannot keep).
note TEXT,
-- Target path in the destination, written in its own transaction before the .part is created: the .part left by a
-- crash are removed only in the folders of the items of unfinished runs, never by a scan (spec §4.10).
relative_path TEXT CHECK (relative_path IS NULL OR length(relative_path) > 0),
copy_id INTEGER REFERENCES export_copy (id) ON DELETE SET NULL,
last_error TEXT,
CHECK ((variant = 'Whole' AND format = 'Original')
OR (variant = 'Converted' AND format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4'))
OR (variant = 'Frame' AND format IN ('Jpg', 'Png', 'WebpLossless'))),
CHECK ((variant = 'Frame') = (frame_at_ms IS NOT NULL))
);
-- One item per file and request in a job, so adding the items again on resume adds nothing (ON CONFLICT DO NOTHING).
-- The store never writes a NULL media_id (only the deletion of the file clears it), so NULLs, distinct here, never meet.
CREATE UNIQUE INDEX ux_export_item_file ON export_item (run_id, media_id, variant, format, ifnull(frame_at_ms, -1));
-- Resume, report and .part cleanup: the items of a run by state.
CREATE INDEX ix_export_item_run_state ON export_item (run_id, state);
-- The items of a run by key, whatever their state (report, resume): (run_id, rowid), without a sort at each page.
CREATE INDEX ix_export_item_run ON export_item (run_id);
-- Foreign keys with SET NULL.
CREATE INDEX ix_export_item_media ON export_item (media_id) WHERE media_id IS NOT NULL;
CREATE INDEX ix_export_item_account ON export_item (account_id) WHERE account_id IS NOT NULL;
CREATE INDEX ix_export_item_copy ON export_item (copy_id) WHERE copy_id IS NOT NULL;
-- «È un video fermo?» (spec §4.10, tappa E4): the outcome per SHA-256 of the video and number of the algorithm, so a
-- later algorithm can analyse again. No link to media: the answer outlives deletion and re-import of the same file.
CREATE TABLE video_analysis (
sha256 TEXT NOT NULL CHECK (length(sha256) = 64),
algorithm INTEGER NOT NULL CHECK (algorithm >= 1),
outcome TEXT NOT NULL CHECK (outcome IN ('Still', 'Moving', 'NotAnalyzable')),
analyzed_at INTEGER NOT NULL,
PRIMARY KEY (sha256, algorithm)
) WITHOUT ROWID;
-- A converted file added to an entry by the conversion for the library (spec §4.10, tappa E3; decision of Alberto of
-- 26 November 2026): one row per converted file, linked to the media row of its original, which does not change. SHA-256,
-- perceptual hash, thumbnail, duplicate check and _febe.jsonl stay those of the original; the converted file is never
-- downloaded again and never a duplicate. Pending rows are the queue of the conversion (it resumes from them).
-- RESTRICT: deleting the media row while a record exists fails, so the converted file can never be left on disk
-- unrecorded; tappa E3 deletes the converted files and their rows explicitly (Removed when the entry is remembered).
CREATE TABLE media_conversion (
id INTEGER PRIMARY KEY,
media_id INTEGER NOT NULL REFERENCES media (id) ON DELETE RESTRICT,
format TEXT NOT NULL CHECK (format IN ('Jpg', 'Png', 'WebpLossless', 'Mp4')),
state TEXT NOT NULL CHECK (state IN ('Pending', 'Converted', 'Superseded', 'Removed', 'Failed')),
-- SHA-256 of the original it was made from: when media.sha256 changes, the conversion is Superseded.
source_sha256 TEXT NOT NULL CHECK (length(source_sha256) = 64),
relative_path TEXT CHECK (relative_path IS NULL OR length(relative_path) > 0),
bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0),
sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64),
created_at INTEGER NOT NULL,
converted_at INTEGER,
state_changed_at INTEGER,
last_error TEXT,
-- Every state past Pending and Failed had a converted file.
CHECK (state IN ('Pending', 'Failed')
OR (relative_path IS NOT NULL AND bytes IS NOT NULL AND sha256 IS NOT NULL AND converted_at IS NOT NULL)),
CHECK (sha256 IS NULL OR sha256 <> source_sha256)
);
-- One current conversion per original and format (Superseded and Removed are history).
CREATE UNIQUE INDEX ux_media_conversion_current ON media_conversion (media_id, format) WHERE state IN ('Pending', 'Converted', 'Failed');
-- Foreign key (RESTRICT) and the conversions of an entry's files.
CREATE INDEX ix_media_conversion_media ON media_conversion (media_id, state);
-- A converted file met by download, import or rebuild is recognised by its own SHA-256 and never counted as a duplicate.
CREATE INDEX ix_media_conversion_sha256 ON media_conversion (sha256) WHERE sha256 IS NOT NULL;
-- The queue of the conversion, in order, without reading the finished rows.
CREATE INDEX ix_media_conversion_pending ON media_conversion (id) WHERE state = 'Pending';
+14 -1
View File
@@ -467,7 +467,20 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
ct);
public Task DeleteAsync(long accountId, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery(), ct);
db.WriteAsync(
w =>
{
// Its export destinations stay, disabled (spec §4.10): «Automatica» goes off and forgets «Solo i nuovi», so
// attaching the folder again never restarts it without asking; they keep the user name, then ON DELETE SET
// NULL clears the link. CHECKs of export_destination make the delete fail if either is not written first.
w.Command("""
UPDATE export_destination SET removed_account_username = (SELECT username FROM account WHERE id = @id),
automatic = 0, automatic_since = NULL
WHERE account_id = @id
""").With("@id", accountId).ExecuteNonQuery();
w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery();
},
ct);
private static Account? ReadOne(SqliteCommand command)
{
+789
View File
@@ -0,0 +1,789 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class ExportStore(FebeDatabase db) : IExportStore
{
private const string DestinationColumns =
"id, scope, account_id, removed_account_username, label, root_path, content_types, photo_format, video_format, naming_scheme, "
+ "highlight_naming_scheme, profile_naming_scheme, automatic, automatic_since, paused_at, last_error, created_at, removed_at";
private const string CopyColumns =
"id, destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state, superseded_by_sha256, origin, "
+ "relative_path, bytes, copy_sha256, copied_at, state_changed_at, last_error";
private const string RunColumns = "id, destination_id, kind, origin, state, started_at, completed_at, last_error";
private const string ItemColumns =
"id, run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state, note, relative_path, copy_id, last_error";
/// <summary>The frame instant as the identity indexes see it: <c>ifnull(frame_at_ms, -1)</c>.</summary>
private const string IdentityWhere =
"destination_id = @d AND source_sha256 = @h AND account_id = @a AND variant = @v AND format = @f AND ifnull(frame_at_ms, -1) = @fr";
// The lookups, also read by the plan tests (ExportConstraintTests.ExportLookupsUseTheirIndex).
internal const string CurrentCopySql = $"SELECT {CopyColumns} FROM export_copy WHERE {IdentityWhere} AND state IN ('Copied', 'Failed') LIMIT 1";
internal const string LatestCopySql = $"SELECT {CopyColumns} FROM export_copy WHERE {IdentityWhere} ORDER BY id DESC LIMIT 1";
internal const string CopiesBySha256Sql = $"SELECT {CopyColumns} FROM export_copy WHERE source_sha256 = @h OR superseded_by_sha256 = @h ORDER BY id DESC";
internal const string CopyByPathSql =
$"SELECT {CopyColumns} FROM export_copy WHERE destination_id = @d AND relative_path = @p AND state IN ('Copied', 'Superseded') LIMIT 1";
internal const string CountCopiesSql = "SELECT state, COUNT(*) FROM export_copy WHERE destination_id = @d GROUP BY state";
internal const string UnfinishedRunsSql = $"SELECT {RunColumns} FROM export_run WHERE state IN ('Running', 'Interrupted', 'Paused')";
/// <summary>
/// Copies of a destination by key (@d, @after, @limit; @s with a state). <c>+state</c> keeps the planner on
/// ix_export_copy_destination_id, which reads in key order, instead of sorting the copies of that state at each page.
/// </summary>
internal static string CopiesOfDestinationSql(bool withState) =>
$"SELECT {CopyColumns} FROM export_copy WHERE destination_id = @d{(withState ? " AND +state = @s" : string.Empty)} AND id > @after ORDER BY id LIMIT @limit";
/// <summary>Items of a job by key (@r, @after, @limit; @s with a state).</summary>
internal static string ItemsOfRunSql(bool withState) =>
$"SELECT {ItemColumns} FROM export_item WHERE run_id = @r{(withState ? " AND state = @s" : string.Empty)} AND id > @after ORDER BY id LIMIT @limit";
// Mapping --------------------------------------------------------------------------------------------------------
private static ExportDestination ReadDestination(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
Scope = r.GetEnum<ExportScope>(1),
AccountId = r.GetInt64OrNull(2),
RemovedAccountUsername = r.GetTextOrNull(3),
Label = r.GetTextOrNull(4),
RootPath = r.GetString(5),
ContentTypes = (ContentTypes)r.GetInt32(6),
PhotoFormat = r.GetEnumOrNull<ExportFormat>(7),
VideoFormat = r.GetEnumOrNull<ExportFormat>(8),
NamingScheme = r.GetTextOrNull(9),
HighlightNamingScheme = r.GetTextOrNull(10),
ProfileNamingScheme = r.GetTextOrNull(11),
Automatic = r.GetBool(12),
AutomaticSince = r.GetTimeOrNull(13),
PausedAt = r.GetTimeOrNull(14),
LastError = r.GetTextOrNull(15),
CreatedAt = r.GetTime(16),
RemovedAt = r.GetTimeOrNull(17),
};
private static ExportCopy ReadCopy(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
DestinationId = r.GetInt64(1),
AccountId = r.GetInt64OrNull(2),
MediaId = r.GetInt64OrNull(3),
SourceSha256 = r.GetString(4),
Variant = r.GetEnum<ExportVariant>(5),
Format = r.GetEnum<ExportFormat>(6),
FrameAt = r.GetDurationOrNull(7),
State = r.GetEnum<ExportCopyState>(8),
SupersededBySha256 = r.GetTextOrNull(9),
Origin = r.GetEnum<ExportCopyOrigin>(10),
RelativePath = r.GetTextOrNull(11),
Bytes = r.GetInt64OrNull(12),
CopySha256 = r.GetTextOrNull(13),
CopiedAt = r.GetTime(14),
StateChangedAt = r.GetTimeOrNull(15),
LastError = r.GetTextOrNull(16),
};
private static ExportRun ReadRun(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
DestinationId = r.GetInt64(1),
Kind = r.GetEnum<ExportRunKind>(2),
Origin = r.GetEnum<ExportRunOrigin>(3),
State = r.GetEnum<ExportRunState>(4),
StartedAt = r.GetTime(5),
CompletedAt = r.GetTimeOrNull(6),
LastError = r.GetTextOrNull(7),
};
private static ExportItem ReadItem(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
RunId = r.GetInt64(1),
MediaId = r.GetInt64OrNull(2),
AccountId = r.GetInt64OrNull(3),
SourceSha256 = r.GetTextOrNull(4),
Variant = r.GetEnum<ExportVariant>(5),
Format = r.GetEnum<ExportFormat>(6),
FrameAt = r.GetDurationOrNull(7),
State = r.GetEnum<ExportItemState>(8),
Note = r.GetTextOrNull(9),
RelativePath = r.GetTextOrNull(10),
CopyId = r.GetInt64OrNull(11),
LastError = r.GetTextOrNull(12),
};
private static List<T> ReadAll<T>(SqliteCommand command, Func<SqliteDataReader, T> read)
{
using var r = command.ExecuteReader();
var list = new List<T>();
while (r.Read())
{
list.Add(read(r));
}
return list;
}
private static T? ReadFirst<T>(SqliteCommand command, Func<SqliteDataReader, T> read)
where T : class
{
using var r = command.ExecuteReader();
return r.Read() ? read(r) : null;
}
private static void BindDestinationSettings(SqliteCommand c, ExportDestination d) =>
c.With("@label", Sql.Text(d.Label))
.With("@content_types", (long)d.ContentTypes)
.With("@photo_format", Sql.Enum(d.PhotoFormat))
.With("@video_format", Sql.Enum(d.VideoFormat))
.With("@naming_scheme", Sql.Text(d.NamingScheme))
.With("@highlight_naming_scheme", Sql.Text(d.HighlightNamingScheme))
.With("@profile_naming_scheme", Sql.Text(d.ProfileNamingScheme))
.With("@automatic", Sql.Bool(d.Automatic))
.With("@automatic_since", Sql.Time(d.AutomaticSince))
.With("@paused_at", Sql.Time(d.PausedAt))
.With("@last_error", Sql.Text(d.LastError));
private static void BindCopyState(SqliteCommand c, ExportCopy copy) =>
c.With("@media_id", Sql.Int(copy.MediaId))
.With("@state", Sql.Enum(copy.State))
.With("@superseded_by", Sql.Text(ExportValues.OptionalSha(copy.SupersededBySha256, nameof(copy.SupersededBySha256))))
.With("@origin", Sql.Enum(copy.Origin))
.With("@relative_path", Sql.Text(ExportValues.OptionalPath(copy.RelativePath)))
.With("@bytes", Sql.Int(copy.Bytes))
.With("@copy_sha256", Sql.Text(ExportValues.OptionalSha(copy.CopySha256, nameof(copy.CopySha256))))
.With("@copied_at", Sql.Time(copy.CopiedAt))
.With("@state_changed_at", Sql.Time(copy.StateChangedAt))
.With("@last_error", Sql.Text(copy.LastError));
private static SqliteCommand BindIdentity(SqliteCommand c, ExportCopyIdentity identity) =>
c.With("@d", identity.DestinationId)
.With("@h", ExportValues.Sha(identity.SourceSha256, nameof(identity.SourceSha256)))
.With("@a", identity.AccountId)
.With("@v", Sql.Enum(identity.Variant))
.With("@f", Sql.Enum(identity.Format))
.With("@fr", ExportValues.FrameKey(identity.FrameAt));
private static string CopyCollision(ExportCopy copy) =>
$"Nella destinazione {copy.DestinationId} c'è già una copia corrente dello stesso file per lo stesso account, variante e formato, "
+ "oppure una copia registrata sullo stesso percorso.";
private static void BindRun(SqliteCommand c, ExportRun run) =>
c.With("@destination_id", run.DestinationId)
.With("@kind", Sql.Enum(run.Kind))
.With("@origin", Sql.Enum(run.Origin))
.With("@state", Sql.Enum(run.State))
.With("@started_at", Sql.Time(run.StartedAt))
.With("@completed_at", Sql.Time(run.CompletedAt))
.With("@last_error", Sql.Text(run.LastError));
private static void BindItem(SqliteCommand c, ExportItem item) =>
c.With("@run_id", item.RunId)
.With("@media_id", Sql.Int(item.MediaId))
.With("@account_id", Sql.Int(item.AccountId))
.With("@source_sha256", Sql.Text(ExportValues.OptionalSha(item.SourceSha256, nameof(item.SourceSha256))))
.With("@variant", Sql.Enum(item.Variant))
.With("@format", Sql.Enum(item.Format))
.With("@frame_at_ms", Sql.Duration(item.FrameAt))
.With("@state", Sql.Enum(item.State))
.With("@note", Sql.Text(item.Note))
.With("@relative_path", Sql.Text(ExportValues.OptionalPath(item.RelativePath)))
.With("@copy_id", Sql.Int(item.CopyId))
.With("@last_error", Sql.Text(item.LastError));
/// <summary>
/// Runs a write guarded by a unique index of 0003 and reports a collision as <see cref="DuplicateRecordException"/>,
/// as the other stores do, so the callers in Febe.Core can catch it without knowing SQLite.
/// </summary>
private static T Unique<T>(Func<T> write, string message)
{
try
{
return write();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(message, ex);
}
}
private static void ValidateSettings(ExportDestination d)
{
if (d.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo))
{
throw new ArgumentException($"{photo} non è un formato per le foto.", nameof(d));
}
if (d.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video))
{
throw new ArgumentException($"{video} non è un formato per i video.", nameof(d));
}
if (!d.Automatic && d.AutomaticSince is not null)
{
throw new ArgumentException("«Solo i nuovi» vale solo con «Automatica» accesa.", nameof(d));
}
}
// Destinations ---------------------------------------------------------------------------------------------------
public Task<ExportDestination> AddDestinationAsync(ExportDestination destination, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentException.ThrowIfNullOrWhiteSpace(destination.RootPath);
if (destination.RemovedAt is not null || destination.RemovedAccountUsername is not null)
{
throw new ArgumentException("Una destinazione nuova non può essere già ritirata né senza account.", nameof(destination));
}
if ((destination.Scope == ExportScope.General) != (destination.AccountId is null))
{
throw new ArgumentException("La cartella generale non ha account; la cartella di un account sì.", nameof(destination));
}
ValidateSettings(destination);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_destination (scope, account_id, label, root_path, content_types, photo_format, video_format,
naming_scheme, highlight_naming_scheme, profile_naming_scheme, automatic, automatic_since, paused_at, last_error, created_at)
VALUES (@scope, @account_id, @label, @root_path, @content_types, @photo_format, @video_format,
@naming_scheme, @highlight_naming_scheme, @profile_naming_scheme, @automatic, @automatic_since, @paused_at, @last_error, @created_at)
""");
BindDestinationSettings(c, destination);
c.With("@scope", Sql.Enum(destination.Scope))
.With("@account_id", Sql.Int(destination.AccountId))
.With("@root_path", destination.RootPath)
.With("@created_at", Sql.Time(destination.CreatedAt));
Unique(
c.ExecuteNonQuery,
destination.Scope == ExportScope.General
? "C'è già una cartella generale in uso: va tolta prima di sceglierne un'altra."
: $"L'account {destination.AccountId} ha già una cartella propria in uso: va tolta prima di sceglierne un'altra.");
return destination with { Id = w.LastInsertRowId() };
},
ct);
}
public Task UpdateDestinationAsync(ExportDestination destination, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(destination);
ValidateSettings(destination);
return db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", destination.Id), ReadDestination)
?? throw new KeyNotFoundException($"Destinazione di esportazione {destination.Id} non trovata.");
if (stored.IsRetired)
{
throw new ArgumentException($"La destinazione {destination.Id} è ritirata: non si modifica più.", nameof(destination));
}
if (stored.IsOrphan && destination.Automatic)
{
throw new ArgumentException(
$"La destinazione {destination.Id} è di un account rimosso: «Automatica» si accende solo dopo averla ridata a un account.",
nameof(destination));
}
if (stored.Scope != destination.Scope || stored.AccountId != destination.AccountId
|| !string.Equals(stored.RootPath, destination.RootPath, StringComparison.Ordinal))
{
throw new ArgumentException(
$"Ambito, account e cartella della destinazione {destination.Id} non cambiano: un'altra cartella è una destinazione nuova.",
nameof(destination));
}
var c = w.Command("""
UPDATE export_destination SET label = @label, content_types = @content_types, photo_format = @photo_format,
video_format = @video_format, naming_scheme = @naming_scheme, highlight_naming_scheme = @highlight_naming_scheme,
profile_naming_scheme = @profile_naming_scheme, automatic = @automatic, automatic_since = @automatic_since,
paused_at = @paused_at, last_error = @last_error
WHERE id = @id
""");
BindDestinationSettings(c, destination);
c.With("@id", destination.Id).ExecuteNonQuery();
},
ct);
}
public Task<ExportDestination?> GetDestinationAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", id), ReadDestination), ct);
public Task<ExportDestination?> GetGeneralDestinationAsync(CancellationToken ct = default) =>
db.ReadAsync(
c => ReadFirst(c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE scope = 'General' AND removed_at IS NULL"), ReadDestination),
ct);
public Task<ExportDestination?> GetAccountDestinationAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c => ReadFirst(
c.Command($"SELECT {DestinationColumns} FROM export_destination WHERE account_id = @a AND removed_at IS NULL").With("@a", accountId),
ReadDestination),
ct);
public Task<IReadOnlyList<ExportDestination>> ListDestinationsAsync(bool includeRetired = false, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportDestination>>(
c => ReadAll(
c.Command($"""
SELECT {DestinationColumns} FROM export_destination WHERE @all = 1 OR removed_at IS NULL
ORDER BY CASE scope WHEN 'General' THEN 0 ELSE 1 END, id
""").With("@all", Sql.Bool(includeRetired)),
ReadDestination),
ct);
public Task RetireDestinationAsync(long id, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var changed = w.Command("""
UPDATE export_destination SET removed_at = @at, automatic = 0, automatic_since = NULL
WHERE id = @id AND removed_at IS NULL
""").With("@at", Sql.Time(at)).With("@id", id).ExecuteNonQuery();
if (changed == 0 && w.Command("SELECT COUNT(*) FROM export_destination WHERE id = @id").With("@id", id).ScalarInt64() == 0)
{
throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
}
},
ct);
public Task AttachDestinationAsync(long id, long accountId, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {DestinationColumns} FROM export_destination WHERE id = @id").With("@id", id), ReadDestination)
?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
if (!stored.IsOrphan || stored.IsRetired)
{
throw new InvalidOperationException($"La destinazione {id} non è la cartella in uso di un account rimosso.");
}
if (w.Command("SELECT COUNT(*) FROM export_destination WHERE account_id = @a AND removed_at IS NULL").With("@a", accountId).ScalarInt64() > 0)
{
throw new InvalidOperationException($"L'account {accountId} ha già una cartella propria in uso.");
}
w.Command("UPDATE export_destination SET account_id = @a, removed_account_username = NULL WHERE id = @id")
.With("@a", accountId).With("@id", id).ExecuteNonQuery();
// «Automatica» stays off (the removal of the account turned it off): turning it on again asks «Solo i nuovi».
Unique(
w.Command("UPDATE export_copy SET account_id = @a WHERE destination_id = @id AND account_id IS NULL")
.With("@a", accountId).With("@id", id).ExecuteNonQuery,
$"L'account {accountId} ha già una copia corrente uguale a una copia della destinazione {id}.");
},
ct);
// «Esporta questo account» ---------------------------------------------------------------------------------------
public Task<bool?> GetAccountExportEnabledAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
using var r = c.Command("SELECT enabled FROM export_account WHERE account_id = @a").With("@a", accountId).ExecuteReader();
return r.Read() ? r.GetBool(0) : (bool?)null;
},
ct);
public Task SetAccountExportEnabledAsync(long accountId, bool enabled, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("""
INSERT INTO export_account (account_id, enabled) VALUES (@a, @e)
ON CONFLICT (account_id) DO UPDATE SET enabled = excluded.enabled
""").With("@a", accountId).With("@e", Sql.Bool(enabled)).ExecuteNonQuery(),
ct);
// Copies ---------------------------------------------------------------------------------------------------------
public Task<ExportCopy> AddCopyAsync(ExportCopy copy, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copy);
if (copy.AccountId is null)
{
throw new ArgumentException("Una copia si registra sempre con il suo account effettivo.", nameof(copy));
}
ExportValues.ValidateShape(copy.Variant, copy.Format, copy.FrameAt);
var source = ExportValues.Sha(copy.SourceSha256, nameof(copy.SourceSha256));
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state,
superseded_by_sha256, origin, relative_path, bytes, copy_sha256, copied_at, state_changed_at, last_error)
VALUES (@destination_id, @account_id, @media_id, @source_sha256, @variant, @format, @frame_at_ms, @state,
@superseded_by, @origin, @relative_path, @bytes, @copy_sha256, @copied_at, @state_changed_at, @last_error)
""");
BindCopyState(c, copy);
c.With("@destination_id", copy.DestinationId)
.With("@account_id", copy.AccountId.Value)
.With("@source_sha256", source)
.With("@variant", Sql.Enum(copy.Variant))
.With("@format", Sql.Enum(copy.Format))
.With("@frame_at_ms", Sql.Duration(copy.FrameAt));
Unique(c.ExecuteNonQuery, CopyCollision(copy));
var id = w.LastInsertRowId();
return ReadFirst(w.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", id), ReadCopy)!;
},
ct);
}
public Task UpdateCopyAsync(ExportCopy copy, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copy);
var source = ExportValues.Sha(copy.SourceSha256, nameof(copy.SourceSha256));
return db.WriteAsync(
w =>
{
var stored = ReadFirst(w.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", copy.Id), ReadCopy)
?? throw new KeyNotFoundException($"Copia {copy.Id} non trovata.");
if (stored.DestinationId != copy.DestinationId || stored.AccountId != copy.AccountId
|| !string.Equals(stored.SourceSha256, source, StringComparison.Ordinal) || stored.Variant != copy.Variant
|| stored.Format != copy.Format || ExportValues.FrameKey(stored.FrameAt) != ExportValues.FrameKey(copy.FrameAt))
{
throw new ArgumentException(
$"L'identità della copia {copy.Id} non cambia: «Copia di nuovo» aggiunge una riga.", nameof(copy));
}
var c = w.Command("""
UPDATE export_copy SET media_id = @media_id, state = @state, superseded_by_sha256 = @superseded_by, origin = @origin,
relative_path = @relative_path, bytes = @bytes, copy_sha256 = @copy_sha256, copied_at = @copied_at,
state_changed_at = @state_changed_at, last_error = @last_error
WHERE id = @id
""");
BindCopyState(c, copy);
c.With("@id", copy.Id);
Unique(c.ExecuteNonQuery, CopyCollision(copy));
},
ct);
}
public Task<ExportCopy?> GetCopyAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {CopyColumns} FROM export_copy WHERE id = @id").With("@id", id), ReadCopy), ct);
public Task<ExportCopy?> FindCurrentCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(identity);
return db.ReadAsync(
c => ReadFirst(
BindIdentity(c.Command(CurrentCopySql), identity),
ReadCopy),
ct);
}
public Task<ExportCopy?> FindLatestCopyAsync(ExportCopyIdentity identity, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(identity);
return db.ReadAsync(
c => ReadFirst(BindIdentity(c.Command(LatestCopySql), identity), ReadCopy),
ct);
}
public Task<IReadOnlyList<ExportCopy>> ListCopiesBySha256Async(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync<IReadOnlyList<ExportCopy>>(
c => ReadAll(
c.Command(CopiesBySha256Sql).With("@h", sha),
ReadCopy),
ct);
}
public Task<ExportCopy?> FindCopyByPathAsync(long destinationId, string relativePath, CancellationToken ct = default)
{
var path = ExportValues.Path(relativePath);
return db.ReadAsync(
c => ReadFirst(
c.Command(CopyByPathSql).With("@d", destinationId).With("@p", path),
ReadCopy),
ct);
}
public Task<IReadOnlyList<ExportCopy>> ListCopiesAsync(long destinationId, ExportCopyState? state = null, long afterId = 0, int limit = 500, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportCopy>>(
c =>
{
var command = c.Command(CopiesOfDestinationSql(state is not null))
.With("@d", destinationId).With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000));
if (state is { } s)
{
command.With("@s", Sql.Enum(s));
}
return ReadAll(command, ReadCopy);
},
ct);
public Task<IReadOnlyDictionary<ExportCopyState, int>> CountCopiesAsync(long destinationId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<ExportCopyState, int>>(
c =>
{
var counts = Enum.GetValues<ExportCopyState>().ToDictionary(s => s, _ => 0);
using var r = c.Command(CountCopiesSql).With("@d", destinationId).ExecuteReader();
while (r.Read())
{
counts[r.GetEnum<ExportCopyState>(0)] = r.GetInt32(1);
}
return counts;
},
ct);
public Task<ExportCopy> RelinkOrphanCopyAsync(long copyId, long accountId, long? mediaId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var select = $"SELECT {CopyColumns} FROM export_copy WHERE id = @id";
var stored = ReadFirst(w.Command(select).With("@id", copyId), ReadCopy)
?? throw new KeyNotFoundException($"Copia {copyId} non trovata.");
if (stored.AccountId is not null)
{
throw new InvalidOperationException($"La copia {copyId} ha già il suo account.");
}
Unique(
w.Command("UPDATE export_copy SET account_id = @a, media_id = coalesce(@m, media_id), state_changed_at = @at WHERE id = @id")
.With("@a", accountId).With("@m", Sql.Int(mediaId)).With("@at", Sql.Time(at)).With("@id", copyId).ExecuteNonQuery,
$"L'account {accountId} ha già una copia corrente uguale alla copia {copyId}.");
return ReadFirst(w.Command(select).With("@id", copyId), ReadCopy)!;
},
ct);
public Task<int> SupersedeCopiesAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
{
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
var replacement = ExportValues.Sha(newSha256, nameof(newSha256));
if (string.Equals(old, replacement, StringComparison.Ordinal))
{
throw new ArgumentException("Il file nuovo ha lo stesso SHA-256 di quello vecchio.", nameof(newSha256));
}
return db.WriteAsync(
w =>
{
// The library file goes back to an earlier one (A→B→A: «Tieni il più grande» is not transitive, and a rebuild
// keeps the file on disk): its copies match the library again. The newest Superseded row of each identity
// becomes Copied again, unless a current row of that identity exists (copied again meanwhile, or failed):
// then it stays Superseded by the old file, as history. Removed rows only lose the stamp.
var revived = w.Command("""
UPDATE export_copy SET state = 'Copied', superseded_by_sha256 = NULL, state_changed_at = @at
WHERE id IN (
SELECT max(s.id) FROM export_copy s
WHERE s.account_id = @a AND s.superseded_by_sha256 = @old AND s.source_sha256 = @new AND s.state = 'Superseded'
AND NOT EXISTS (
SELECT 1 FROM export_copy c
WHERE c.destination_id = s.destination_id AND c.source_sha256 = s.source_sha256 AND c.account_id = s.account_id
AND c.variant = s.variant AND c.format = s.format AND ifnull(c.frame_at_ms, -1) = ifnull(s.frame_at_ms, -1)
AND c.state IN ('Copied', 'Failed'))
GROUP BY s.destination_id, s.variant, s.format, ifnull(s.frame_at_ms, -1))
""").With("@a", accountId).With("@old", old).With("@new", replacement).With("@at", Sql.Time(at)).ExecuteNonQuery();
var unstamped = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = NULL
WHERE account_id = @a AND superseded_by_sha256 = @old AND source_sha256 = @new AND state = 'Removed'
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
// Rows superseded by the old file move to the new one first, so the rows changed below are not counted twice.
var moved = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = @new
WHERE account_id = @a AND superseded_by_sha256 = @old AND source_sha256 <> @new
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
var superseded = w.Command("""
UPDATE export_copy SET state = 'Superseded', superseded_by_sha256 = @new, state_changed_at = @at
WHERE account_id = @a AND source_sha256 = @old AND state = 'Copied'
""").With("@a", accountId).With("@old", old).With("@new", replacement).With("@at", Sql.Time(at)).ExecuteNonQuery();
var stamped = w.Command("""
UPDATE export_copy SET superseded_by_sha256 = @new
WHERE account_id = @a AND source_sha256 = @old AND state = 'Removed'
AND (superseded_by_sha256 IS NULL OR superseded_by_sha256 <> @new)
""").With("@a", accountId).With("@old", old).With("@new", replacement).ExecuteNonQuery();
return revived + unstamped + moved + superseded + stamped;
},
ct);
}
// Jobs and their files -------------------------------------------------------------------------------------------
public Task<ExportRun> CreateRunAsync(ExportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO export_run (destination_id, kind, origin, state, started_at, completed_at, last_error)
VALUES (@destination_id, @kind, @origin, @state, @started_at, @completed_at, @last_error)
""");
BindRun(c, run);
c.ExecuteNonQuery();
return run with { Id = w.LastInsertRowId() };
},
ct);
}
public Task UpdateRunAsync(ExportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE export_run SET destination_id = @destination_id, kind = @kind, origin = @origin, state = @state,
started_at = @started_at, completed_at = @completed_at, last_error = @last_error
WHERE id = @id
""");
BindRun(c, run);
if (c.With("@id", run.Id).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Esportazione {run.Id} non trovata.");
}
},
ct);
}
public Task<ExportRun?> GetRunAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {RunColumns} FROM export_run WHERE id = @id").With("@id", runId), ReadRun), ct);
public Task<IReadOnlyList<ExportRun>> ListRunsAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(c => ReadAll(c.Command($"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC"), ReadRun), ct);
public Task<IReadOnlyList<ExportRun>> ListUnfinishedRunsAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(
c =>
{
// Read through the partial index; the handful of unfinished runs is ordered here, not by a sort in SQLite.
var runs = ReadAll(c.Command(UnfinishedRunsSql), ReadRun);
runs.Sort((a, b) => a.Id.CompareTo(b.Id));
return runs;
},
ct);
public Task AddItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(items);
foreach (var item in items)
{
ArgumentNullException.ThrowIfNull(item, nameof(items));
if (item.AccountId is null)
{
throw new ArgumentException("Un file da esportare si aggiunge sempre con il suo account effettivo.", nameof(items));
}
// NULLs are distinct in ux_export_item_file: an item without its file could be added twice on resume.
if (item.MediaId is null)
{
throw new ArgumentException("Un file da esportare si aggiunge sempre con il suo file della libreria.", nameof(items));
}
ExportValues.ValidateShape(item.Variant, item.Format, item.FrameAt);
}
return db.WriteAsync(
w =>
{
foreach (var item in items)
{
var c = w.Command("""
INSERT INTO export_item (run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state, note,
relative_path, copy_id, last_error)
VALUES (@run_id, @media_id, @account_id, @source_sha256, @variant, @format, @frame_at_ms, @state, @note,
@relative_path, @copy_id, @last_error)
ON CONFLICT DO NOTHING
""");
BindItem(c, item);
c.ExecuteNonQuery();
}
},
ct);
}
public Task UpdateItemsAsync(IReadOnlyList<ExportItem> items, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(items);
return db.WriteAsync(
w =>
{
foreach (var item in items)
{
// Job, file and request (variant, format, frame) are the identity of the item in ux_export_item_file:
// they are never rewritten, and the file is cleared only by its deletion (ON DELETE SET NULL).
var c = w.Command("""
UPDATE export_item SET account_id = coalesce(@account_id, account_id), source_sha256 = @source_sha256,
state = @state, note = @note, relative_path = @relative_path, copy_id = @copy_id, last_error = @last_error
WHERE id = @id AND run_id = @run_id AND variant = @variant AND format = @format
AND ifnull(frame_at_ms, -1) = @frame_key AND (media_id IS NULL OR media_id = @media_id)
""");
BindItem(c, item);
if (c.With("@id", item.Id).With("@frame_key", ExportValues.FrameKey(item.FrameAt)).ExecuteNonQuery() == 0)
{
if (w.Command("SELECT COUNT(*) FROM export_item WHERE id = @id AND run_id = @r").With("@id", item.Id).With("@r", item.RunId).ScalarInt64() == 0)
{
throw new KeyNotFoundException($"File di esportazione {item.Id} non trovato.");
}
throw new ArgumentException(
$"Il file, la variante, il formato e l'istante del file di esportazione {item.Id} non cambiano.", nameof(items));
}
}
},
ct);
}
public Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct);
public Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
return db.ReadAsync<IReadOnlyList<ExportItem>>(
c =>
{
var command = c.Command(ItemsOfRunSql(query.State is not null))
.With("@r", query.RunId).With("@after", query.AfterId).With("@limit", (long)Math.Clamp(query.Limit, 1, 10_000));
if (query.State is { } state)
{
command.With("@s", Sql.Enum(state));
}
return ReadAll(command, ReadItem);
},
ct);
}
public Task<ExportRunSummary> GetRunSummaryAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var byState = Enum.GetValues<ExportItemState>().ToDictionary(s => s, _ => 0);
var total = 0;
using var r = c.Command("SELECT state, COUNT(*) FROM export_item WHERE run_id = @r GROUP BY state").With("@r", runId).ExecuteReader();
while (r.Read())
{
var count = r.GetInt32(1);
byState[r.GetEnum<ExportItemState>(0)] = count;
total += count;
}
return new ExportRunSummary(total, byState);
},
ct);
public Task DeleteRunAsync(long runId, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
// Items go by cascade; copies and files in the destination are never touched here.
w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery();
},
ct);
}
+54
View File
@@ -0,0 +1,54 @@
using System.Text;
using Febe.Core.Domain;
namespace Febe.Data.Stores;
/// <summary>Checks and normal forms shared by the export and conversion stores. The CHECKs of 0003 stay as the last line of defence.</summary>
internal static class ExportValues
{
/// <summary>A SHA-256 as 64 hex characters, stored lower case.</summary>
public static string Sha(string? value, string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value, name);
var text = value.Trim();
if (text.Length != 64 || !text.All(char.IsAsciiHexDigit))
{
throw new ArgumentException("Uno SHA-256 è fatto di 64 cifre esadecimali.", name);
}
return text.ToLowerInvariant();
}
public static string? OptionalSha(string? value, string name) => value is null ? null : Sha(value, name);
/// <summary>
/// A path relative to a destination root: '/' separated and NFC, so the same name is always the same text
/// (export_copy.relative_path also compares ASCII letters without case).
/// </summary>
public static string Path(string? value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value);
return value.Replace('\\', '/').Normalize(NormalizationForm.FormC);
}
public static string? OptionalPath(string? value) => value is null ? null : Path(value);
/// <summary>The frame instant as the identity indexes see it: milliseconds, or -1 for no frame.</summary>
public static long FrameKey(TimeSpan? frameAt) => frameAt is { } f ? (long)f.TotalMilliseconds : -1;
/// <summary>The pairs of variant and format the schema accepts: Whole with Original, Converted with another format, Frame with a picture at an instant.</summary>
public static void ValidateShape(ExportVariant variant, ExportFormat format, TimeSpan? frameAt)
{
var valid = variant switch
{
ExportVariant.Whole => format == ExportFormat.Original && frameAt is null,
ExportVariant.Converted => format != ExportFormat.Original && frameAt is null,
ExportVariant.Frame => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless && frameAt is { } f && f >= TimeSpan.Zero,
_ => false,
};
if (!valid)
{
throw new ArgumentException($"Variante {variant} e formato {format} non vanno insieme{(frameAt is null ? string.Empty : " con un istante")}.", nameof(variant));
}
}
}
@@ -0,0 +1,151 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
{
private const string Columns =
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
/// <summary>The queue of the conversion by key (@after, @limit), also read by the plan tests.</summary>
internal const string PendingSql = $"SELECT {Columns} FROM media_conversion WHERE state = 'Pending' AND id > @after ORDER BY id LIMIT @limit";
private static MediaConversion Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
MediaId = r.GetInt64(1),
Format = r.GetEnum<ExportFormat>(2),
State = r.GetEnum<MediaConversionState>(3),
SourceSha256 = r.GetString(4),
RelativePath = r.GetTextOrNull(5),
Bytes = r.GetInt64OrNull(6),
Sha256 = r.GetTextOrNull(7),
CreatedAt = r.GetTime(8),
ConvertedAt = r.GetTimeOrNull(9),
StateChangedAt = r.GetTimeOrNull(10),
LastError = r.GetTextOrNull(11),
};
private static List<MediaConversion> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<MediaConversion>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
private static void Validate(MediaConversion conversion)
{
ArgumentNullException.ThrowIfNull(conversion);
if (conversion.Format == ExportFormat.Original)
{
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(conversion));
}
if (conversion.State is not (MediaConversionState.Pending or MediaConversionState.Failed)
&& (conversion.RelativePath is null || conversion.Bytes is null || conversion.Sha256 is null || conversion.ConvertedAt is null))
{
throw new ArgumentException("Un file convertito ha percorso, byte, SHA-256 e data della conversione.", nameof(conversion));
}
}
// The path is relative to the account folder and written as given, like media.relative_path.
private static void Bind(SqliteCommand c, MediaConversion conversion) =>
c.With("@media_id", conversion.MediaId)
.With("@format", Sql.Enum(conversion.Format))
.With("@state", Sql.Enum(conversion.State))
.With("@source_sha256", ExportValues.Sha(conversion.SourceSha256, nameof(conversion.SourceSha256)))
.With("@relative_path", Sql.Text(conversion.RelativePath))
.With("@bytes", Sql.Int(conversion.Bytes))
.With("@sha256", Sql.Text(ExportValues.OptionalSha(conversion.Sha256, nameof(conversion.Sha256))))
.With("@created_at", Sql.Time(conversion.CreatedAt))
.With("@converted_at", Sql.Time(conversion.ConvertedAt))
.With("@state_changed_at", Sql.Time(conversion.StateChangedAt))
.With("@last_error", Sql.Text(conversion.LastError));
/// <summary>Runs a write guarded by ux_media_conversion_current; a collision is a <see cref="DuplicateRecordException"/>.</summary>
private static int Execute(SqliteCommand command, MediaConversion conversion)
{
try
{
return command.ExecuteNonQuery();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(
$"Il file {conversion.MediaId} ha già una conversione in {conversion.Format} in coda, fatta o non riuscita.", ex);
}
}
public Task<MediaConversion> AddAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at,
state_changed_at, last_error)
VALUES (@media_id, @format, @state, @source_sha256, @relative_path, @bytes, @sha256, @created_at, @converted_at,
@state_changed_at, @last_error)
""");
Bind(c, conversion);
Execute(c, conversion);
var id = w.LastInsertRowId();
using var r = w.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id).ExecuteReader();
r.Read();
return Read(r);
},
ct);
}
public Task UpdateAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
// The original and the format are the identity of a conversion: they are never rewritten.
var c = w.Command("""
UPDATE media_conversion SET state = @state, source_sha256 = @source_sha256, relative_path = @relative_path, bytes = @bytes,
sha256 = @sha256, created_at = @created_at, converted_at = @converted_at, state_changed_at = @state_changed_at,
last_error = @last_error
WHERE id = @id AND media_id = @media_id AND format = @format
""");
Bind(c, conversion);
if (Execute(c.With("@id", conversion.Id), conversion) == 0)
{
throw new KeyNotFoundException($"Conversione {conversion.Id} del file {conversion.MediaId} in {conversion.Format} non trovata.");
}
},
ct);
}
public Task<MediaConversion?> GetAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id)).FirstOrDefault(), ct);
public Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE media_id = @m ORDER BY id").With("@m", mediaId)),
ct);
public Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE sha256 = @h ORDER BY id").With("@h", sha)),
ct);
}
public Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<MediaConversion>>(
c => ReadAll(c.Command(PendingSql)
.With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
}
@@ -0,0 +1,69 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
{
private const int KeysPerQuery = 500;
private static VideoAnalysis Read(SqliteDataReader r) =>
new(r.GetString(0), r.GetInt32(1), r.GetEnum<VideoAnalysisOutcome>(2), r.GetTime(3));
public Task<VideoAnalysis?> GetAsync(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c =>
{
using var r = c.Command("""
SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1
""").With("@h", sha).ExecuteReader();
return r.Read() ? Read(r) : null;
},
ct);
}
public Task<IReadOnlyDictionary<string, VideoAnalysis>> GetManyAsync(IReadOnlyCollection<string> sha256s, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(sha256s);
var keys = sha256s.Select(s => ExportValues.Sha(s, nameof(sha256s))).Distinct(StringComparer.Ordinal).ToList();
return db.ReadAsync<IReadOnlyDictionary<string, VideoAnalysis>>(
c =>
{
var result = new Dictionary<string, VideoAnalysis>(StringComparer.Ordinal);
foreach (var chunk in keys.Chunk(KeysPerQuery))
{
using var command = c.Command(string.Empty);
command.CommandText = $"SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})";
using var r = command.ExecuteReader();
while (r.Read())
{
var analysis = Read(r);
if (!result.TryGetValue(analysis.Sha256, out var known) || known.Algorithm < analysis.Algorithm)
{
result[analysis.Sha256] = analysis;
}
}
}
return result;
},
ct);
}
public Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(analysis);
var sha = ExportValues.Sha(analysis.Sha256, nameof(analysis));
ArgumentOutOfRangeException.ThrowIfLessThan(analysis.Algorithm, 1, nameof(analysis));
return db.WriteAsync(
w => w.Command("""
INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at) VALUES (@h, @alg, @o, @at)
ON CONFLICT (sha256, algorithm) DO UPDATE SET outcome = excluded.outcome, analyzed_at = excluded.analyzed_at
""").With("@h", sha).With("@alg", (long)analysis.Algorithm).With("@o", Sql.Enum(analysis.Outcome)).With("@at", Sql.Time(analysis.AnalyzedAt))
.ExecuteNonQuery(),
ct);
}
}