M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione

Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 16:06:15 +00:00
1 parent c803bd98b5
commit 3aeaa17da7
69 files changed
+12472

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
using Febe.Core.Storage;
using Febe.Data.Stores;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>
/// The SQLite database of Febe (spec §8): <c>Dati/febe.sqlite</c> in WAL mode, foreign keys on, busy timeout,
/// numbered migrations applied at start-up. All writes go through one queue and one connection
/// (<see cref="SqliteWriter"/>); reads use separate pooled read-only connections and never block the writer.
/// </summary>
public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
{
/// <summary>File name inside the Data folder.</summary>
public const string FileName = "febe.sqlite";
private const int BusyTimeoutMs = 10_000;
private readonly SqliteConnection _writerConnection;
private readonly string _readConnectionString;
private int _disposed;
private FebeDatabase(string path, SqliteConnection writerConnection, string readConnectionString, int schemaVersion)
{
DatabasePath = path;
_writerConnection = writerConnection;
_readConnectionString = readConnectionString;
SchemaVersion = schemaVersion;
Writer = new SqliteWriter(writerConnection);
Accounts = new AccountStore(this);
Entries = new EntryStore(this);
Media = new MediaStore(this);
Highlights = new HighlightStore(this);
Duplicates = new DuplicateStore(this);
Tasks = new TaskStore(this);
ActionLog = new ActionLogStore(this);
Sessions = new SessionStore(this);
Incidents = new IncidentStore(this);
Events = new EventStore(this);
Following = new FollowingStore(this);
Imports = new ImportStore(this);
Settings = new SettingsStore(this);
}
public IAccountStore Accounts { get; }
public IEntryStore Entries { get; }
public IMediaStore Media { get; }
public IHighlightStore Highlights { get; }
public IDuplicateStore Duplicates { get; }
public ITaskStore Tasks { get; }
public IActionLogStore ActionLog { get; }
public ISessionStore Sessions { get; }
public IIncidentStore Incidents { get; }
public IEventStore Events { get; }
public IFollowingStore Following { get; }
public IImportStore Imports { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
public string DatabasePath { get; }
public int SchemaVersion { get; }
internal SqliteWriter Writer { get; }
/// <summary>Opens (or creates) <c>febe.sqlite</c> inside the Data folder and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenAsync(string dataFolder, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
return OpenFileAsync(Path.Combine(dataFolder, FileName), ct);
}
/// <summary>Opens (or creates) a database file and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenFileAsync(string databasePath, CancellationToken ct = default) =>
Task.FromResult(Open(databasePath, MigrationRunner.LoadEmbedded(), ct));
internal static FebeDatabase Open(string databasePath, IReadOnlyList<Migration> migrations, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(databasePath);
ct.ThrowIfCancellationRequested();
var path = Path.GetFullPath(databasePath);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var writerConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate,
Cache = SqliteCacheMode.Private,
Pooling = false,
ForeignKeys = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var readConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadOnly,
Cache = SqliteCacheMode.Private,
Pooling = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var connection = new SqliteConnection(writerConnectionString);
try
{
connection.Open();
var mode = connection.Command("PRAGMA journal_mode = WAL").ExecuteScalar() as string;
if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase))
{
throw new DatabaseMigrationException(
$"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale.");
}
connection.Command("PRAGMA synchronous = NORMAL").ExecuteNonQuery();
connection.Command($"PRAGMA busy_timeout = {BusyTimeoutMs}").ExecuteNonQuery();
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
var version = MigrationRunner.Apply(connection, migrations);
return new FebeDatabase(path, connection, readConnectionString, version);
}
catch
{
connection.Dispose();
throw;
}
}
/// <summary>Queues a write; the task completes after the commit.</summary>
internal Task<T> WriteAsync<T>(Func<WriteContext, T> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
internal Task WriteAsync(Action<WriteContext> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
/// <summary>Runs a read on its own read-only connection.</summary>
internal Task<T> ReadAsync<T>(Func<SqliteConnection, T> work, CancellationToken ct)
{
if (ct.IsCancellationRequested)
{
return Task.FromCanceled<T>(ct);
}
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
try
{
using var connection = OpenReadConnection();
return Task.FromResult(work(connection));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
return Task.FromException<T>(ex);
}
}
internal SqliteConnection OpenReadConnection()
{
var connection = new SqliteConnection(_readConnectionString);
connection.Open();
return connection;
}
public Task BackupToAsync(string destinationFile, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destinationFile);
var destination = Path.GetFullPath(destinationFile);
if (File.Exists(destination))
{
throw new IOException($"La copia {destination} esiste già: Febe non la sovrascrive.");
}
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
return ReadAsync(
connection =>
{
// VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer.
connection.Command("VACUUM INTO @destination").With("@destination", destination).ExecuteNonQuery();
return true;
},
ct);
}
public Task<bool> CheckIntegrityAsync(CancellationToken ct = default) =>
ReadAsync(
connection =>
{
using var reader = connection.Command("PRAGMA quick_check").ExecuteReader();
return reader.Read() && string.Equals(reader.GetString(0), "ok", StringComparison.OrdinalIgnoreCase) && !reader.Read();
},
ct);
public Task OptimizeAsync(CancellationToken ct = default) =>
WriteAsync(context => context.Command("PRAGMA optimize").ExecuteNonQuery(), ct);
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return ValueTask.CompletedTask;
}
Writer.Dispose();
try
{
_writerConnection.Command("PRAGMA wal_checkpoint(TRUNCATE)").ExecuteNonQuery();
}
catch (SqliteException)
{
// A reader may still hold a snapshot: the checkpoint is an optimization, not a requirement.
}
_writerConnection.Dispose();
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
return ValueTask.CompletedTask;
}
}
+138
View File
@@ -0,0 +1,138 @@
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>A numbered SQL migration (src/Febe.Data/Migrations/NNNN_name.sql).</summary>
internal sealed record Migration(int Version, string Name, string Sql);
/// <summary>The database was written by a newer Febe, or a migration failed.</summary>
public sealed class DatabaseMigrationException : Exception
{
public DatabaseMigrationException()
{
}
public DatabaseMigrationException(string message)
: base(message)
{
}
public DatabaseMigrationException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Applies the numbered migrations at start-up (spec §8.3): each one inside its own transaction, with the schema
/// version in <c>PRAGMA user_version</c>, so a failed migration leaves the database at the previous version.
/// </summary>
internal static partial class MigrationRunner
{
[GeneratedRegex(@"(?:^|[._])(?<version>\d{4})_(?<name>[A-Za-z0-9_\-]+)\.sql$", RegexOptions.CultureInvariant)]
private static partial Regex MigrationName();
/// <summary>The migrations embedded in this assembly, in version order.</summary>
public static IReadOnlyList<Migration> LoadEmbedded()
{
var assembly = typeof(MigrationRunner).Assembly;
var migrations = new List<Migration>();
foreach (var resource in assembly.GetManifestResourceNames())
{
var match = MigrationName().Match(resource);
if (!match.Success)
{
continue;
}
using var stream = assembly.GetManifestResourceStream(resource)
?? throw new DatabaseMigrationException($"Migrazione {resource} non leggibile.");
using var reader = new StreamReader(stream);
migrations.Add(new Migration(
int.Parse(match.Groups["version"].Value, CultureInfo.InvariantCulture),
match.Groups["name"].Value,
reader.ReadToEnd()));
}
return Validate(migrations);
}
/// <summary>Checks that versions are 1, 2, 3, ... without gaps or duplicates and returns them ordered.</summary>
public static IReadOnlyList<Migration> Validate(IEnumerable<Migration> migrations)
{
var ordered = migrations.OrderBy(m => m.Version).ToList();
for (var i = 0; i < ordered.Count; i++)
{
if (ordered[i].Version != i + 1)
{
throw new DatabaseMigrationException(
$"Le migrazioni devono essere numerate 1, 2, 3, ... senza buchi né doppioni: trovata la {ordered[i].Version} al posto della {i + 1}.");
}
}
return ordered;
}
public static int GetVersion(SqliteConnection connection) =>
(int)connection.Command("PRAGMA user_version").ScalarInt64();
/// <summary>Applies the pending migrations. Returns the resulting version.</summary>
public static int Apply(SqliteConnection connection, IReadOnlyList<Migration> migrations)
{
var current = GetVersion(connection);
var latest = migrations.Count == 0 ? 0 : migrations[^1].Version;
if (current > latest)
{
throw new DatabaseMigrationException(
$"Il database è stato scritto da una versione più recente di Febe (schema {current}; questa versione arriva al {latest}). "
+ "Febe non lo modifica: aggiorna il programma oppure ripristina una copia da Dati/copie.");
}
if (current == latest)
{
return current;
}
// Table rebuilds in later migrations need foreign keys off; they are checked before each commit instead.
connection.Command("PRAGMA foreign_keys = OFF").ExecuteNonQuery();
try
{
foreach (var migration in migrations.Where(m => m.Version > current))
{
using var transaction = connection.BeginTransaction(deferred: false);
try
{
connection.Command(migration.Sql, transaction).ExecuteNonQuery();
using (var check = connection.Command("PRAGMA foreign_key_check", transaction).ExecuteReader())
{
if (check.Read())
{
throw new DatabaseMigrationException(
$"La migrazione {migration.Version} ({migration.Name}) lascia riferimenti non validi nella tabella {check.GetString(0)}.");
}
}
connection.Command(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction)
.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex) when (ex is SqliteException or DatabaseMigrationException)
{
transaction.Rollback();
throw ex as DatabaseMigrationException ?? new DatabaseMigrationException(
$"La migrazione {migration.Version} ({migration.Name}) non è riuscita: il database resta allo schema {GetVersion(connection)}.",
ex);
}
}
}
finally
{
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
}
return GetVersion(connection);
}
}
+291
View File
@@ -0,0 +1,291 @@
-- Febe, schema version 1 (spec §8.3).
-- Times are UTC instants stored as INTEGER Unix milliseconds. Enumerations are stored as their English names.
-- Instagram identifiers are TEXT: numeric today, but no assumption is made on their size or form (rule 10).
-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
CREATE TABLE setting (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL
) WITHOUT ROWID;
CREATE TABLE account (
id INTEGER PRIMARY KEY,
instagram_id TEXT UNIQUE,
username TEXT NOT NULL COLLATE NOCASE CHECK (length(username) > 0),
display_name TEXT,
is_private INTEGER NOT NULL DEFAULT 0 CHECK (is_private IN (0, 1)),
is_followed INTEGER NOT NULL DEFAULT 0 CHECK (is_followed IN (0, 1)),
is_mine INTEGER NOT NULL DEFAULT 0 CHECK (is_mine IN (0, 1)),
state TEXT NOT NULL,
state_changed_at INTEGER,
unreachable_reason TEXT,
keep_updated INTEGER NOT NULL DEFAULT 1 CHECK (keep_updated IN (0, 1)),
frequency TEXT NOT NULL,
custom_post_interval_min INTEGER CHECK (custom_post_interval_min IS NULL OR custom_post_interval_min > 0),
custom_story_interval_min INTEGER CHECK (custom_story_interval_min IS NULL OR custom_story_interval_min > 0),
content_types INTEGER NOT NULL CHECK (content_types >= 0),
history_depth TEXT NOT NULL,
history_last_posts INTEGER CHECK (history_last_posts IS NULL OR history_last_posts >= 0),
history_from INTEGER,
backfill_posts_per_day INTEGER NOT NULL CHECK (backfill_posts_per_day >= 0),
max_video_bytes INTEGER CHECK (max_video_bytes IS NULL OR max_video_bytes > 0),
story_videos INTEGER NOT NULL DEFAULT 1 CHECK (story_videos IN (0, 1)),
folder TEXT,
backfill_cursor TEXT,
backfill_completed_at INTEGER,
post_count INTEGER,
last_profile_check_at INTEGER,
next_profile_check_at INTEGER,
last_stories_check_at INTEGER,
next_stories_check_at INTEGER,
notices INTEGER NOT NULL DEFAULT 0,
previous_username TEXT,
renamed_at INTEGER,
format_unrecognized_at INTEGER,
added_at INTEGER NOT NULL
);
CREATE INDEX ix_account_username ON account (username);
CREATE INDEX ix_account_state ON account (state);
-- At most one account is Alberto's own profile («Tu»).
CREATE UNIQUE INDEX ux_account_mine ON account (is_mine) WHERE is_mine = 1;
CREATE TABLE entry (
id INTEGER PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES account (id) ON DELETE CASCADE,
kind TEXT NOT NULL,
instagram_id TEXT,
code TEXT,
published_at INTEGER NOT NULL,
caption TEXT,
author_username TEXT,
author_instagram_id TEXT,
state TEXT NOT NULL,
provenance TEXT NOT NULL,
discovered_at INTEGER NOT NULL,
downloaded_at INTEGER,
deleted_at INTEGER,
expires_at INTEGER,
-- Lowercase text without accents (caption and author), for the search of the library.
search_text TEXT,
UNIQUE (account_id, kind, instagram_id)
);
CREATE INDEX ix_entry_account_published ON entry (account_id, published_at);
-- The library mosaic: keyset windows by publication time, with the filter columns in the index so that windows,
-- totals and counts per day never visit the table (spec §4.6: fluid with 200,000 entries).
CREATE INDEX ix_entry_library ON entry (published_at, kind, state, account_id, provenance);
CREATE INDEX ix_entry_kind_published ON entry (kind, published_at);
CREATE INDEX ix_entry_state ON entry (state);
-- Accounts list counts and the per-account daily backfill limit, answered from the index alone.
CREATE INDEX ix_entry_account_kind ON entry (account_id, kind, state, discovered_at);
CREATE TABLE media (
id INTEGER PRIMARY KEY,
entry_id INTEGER NOT NULL REFERENCES entry (id) ON DELETE CASCADE,
position INTEGER NOT NULL CHECK (position >= 1),
kind TEXT NOT NULL,
instagram_id TEXT,
width INTEGER,
height INTEGER,
duration_ms INTEGER,
state TEXT NOT NULL,
relative_path TEXT,
bytes INTEGER CHECK (bytes IS NULL OR bytes >= 0),
sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64),
phash INTEGER,
has_thumbnail INTEGER NOT NULL DEFAULT 0 CHECK (has_thumbnail IN (0, 1)),
source_url TEXT,
cover_url TEXT,
source_seen_at INTEGER,
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
downloaded_at INTEGER,
UNIQUE (entry_id, position)
);
CREATE INDEX ix_media_sha256 ON media (sha256) WHERE sha256 IS NOT NULL;
CREATE INDEX ix_media_phash ON media (phash) WHERE phash IS NOT NULL;
CREATE INDEX ix_media_state ON media (state);
CREATE TABLE highlight (
id INTEGER PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES account (id) ON DELETE CASCADE,
instagram_id TEXT,
title TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
discovered_at INTEGER NOT NULL,
last_checked_at INTEGER,
removed_at INTEGER,
UNIQUE (account_id, instagram_id)
);
CREATE INDEX ix_highlight_account_position ON highlight (account_id, position);
CREATE TABLE highlight_entry (
highlight_id INTEGER NOT NULL REFERENCES highlight (id) ON DELETE CASCADE,
entry_id INTEGER NOT NULL REFERENCES entry (id) ON DELETE CASCADE,
position INTEGER NOT NULL,
PRIMARY KEY (highlight_id, entry_id)
) WITHOUT ROWID;
CREATE INDEX ix_highlight_entry_entry ON highlight_entry (entry_id);
CREATE TABLE task (
id INTEGER PRIMARY KEY,
kind TEXT NOT NULL,
account_id INTEGER REFERENCES account (id) ON DELETE CASCADE,
due_at INTEGER NOT NULL,
priority INTEGER NOT NULL DEFAULT 0,
state TEXT NOT NULL,
payload TEXT,
is_manual INTEGER NOT NULL DEFAULT 0 CHECK (is_manual IN (0, 1)),
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
started_at INTEGER,
completed_at INTEGER,
last_error TEXT
);
CREATE INDEX ix_task_state_due ON task (state, due_at);
CREATE INDEX ix_task_account ON task (account_id);
CREATE TABLE session (
id INTEGER PRIMARY KEY,
started_at INTEGER NOT NULL,
ended_at INTEGER,
action_count INTEGER NOT NULL DEFAULT 0,
outcome TEXT NOT NULL,
summary TEXT
);
CREATE INDEX ix_session_started ON session (started_at);
CREATE TABLE action_log (
id INTEGER PRIMARY KEY,
at INTEGER NOT NULL,
category TEXT NOT NULL,
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
session_id INTEGER REFERENCES session (id) ON DELETE SET NULL,
amount INTEGER NOT NULL DEFAULT 1 CHECK (amount >= 0)
);
CREATE INDEX ix_action_log_category_at ON action_log (category, at);
CREATE INDEX ix_action_log_account_at ON action_log (account_id, category, at);
CREATE INDEX ix_action_log_at ON action_log (at);
CREATE TABLE incident (
id INTEGER PRIMARY KEY,
at INTEGER NOT NULL,
level TEXT NOT NULL,
signal TEXT NOT NULL,
url TEXT,
stopped_until INTEGER,
resolved_at INTEGER,
session_id INTEGER REFERENCES session (id) ON DELETE SET NULL,
note TEXT
);
CREATE INDEX ix_incident_at ON incident (at);
CREATE INDEX ix_incident_open ON incident (resolved_at) WHERE resolved_at IS NULL;
CREATE TABLE event (
id INTEGER PRIMARY KEY,
at INTEGER NOT NULL,
severity TEXT NOT NULL,
code TEXT NOT NULL,
message TEXT NOT NULL,
account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
session_id INTEGER REFERENCES session (id) ON DELETE SET NULL
);
CREATE INDEX ix_event_at ON event (at);
CREATE INDEX ix_event_account ON event (account_id, id);
CREATE TABLE "following" (
id INTEGER PRIMARY KEY,
instagram_id TEXT UNIQUE,
username TEXT NOT NULL COLLATE NOCASE,
display_name TEXT,
is_private INTEGER CHECK (is_private IS NULL OR is_private IN (0, 1)),
position INTEGER NOT NULL DEFAULT 0,
read_at INTEGER NOT NULL
);
CREATE INDEX ix_following_username ON "following" (username);
CREATE INDEX ix_following_position ON "following" (position);
CREATE TABLE import_run (
id INTEGER PRIMARY KEY,
source_path TEXT NOT NULL,
source_read_only INTEGER NOT NULL DEFAULT 0 CHECK (source_read_only IN (0, 1)),
mode TEXT NOT NULL,
state TEXT NOT NULL,
started_at INTEGER NOT NULL,
analyzed_at INTEGER,
completed_at INTEGER,
last_error TEXT
);
CREATE TABLE import_file (
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES import_run (id) ON DELETE CASCADE,
relative_path TEXT NOT NULL,
folder TEXT NOT NULL,
bytes INTEGER NOT NULL DEFAULT 0,
modified_at INTEGER,
media_kind TEXT,
content_type TEXT,
width INTEGER,
height INTEGER,
duration_ms INTEGER,
sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64),
phash INTEGER,
taken_at INTEGER,
date_source TEXT,
instagram_id TEXT,
code TEXT,
probable_account TEXT,
probable_kind TEXT,
highlight_title TEXT,
outcome TEXT NOT NULL,
matched_media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
target_account_id INTEGER REFERENCES account (id) ON DELETE SET NULL,
decision TEXT NOT NULL,
state TEXT NOT NULL,
entry_id INTEGER REFERENCES entry (id) ON DELETE SET NULL,
destination_path TEXT,
last_error TEXT,
UNIQUE (run_id, relative_path)
);
CREATE INDEX ix_import_file_run_state ON import_file (run_id, state);
CREATE INDEX ix_import_file_run_folder ON import_file (run_id, folder);
CREATE INDEX ix_import_file_sha256 ON import_file (sha256) WHERE sha256 IS NOT NULL;
-- Foreign keys with ON DELETE actions need an index on the child column, or each parent delete scans the table.
CREATE INDEX ix_import_file_matched_media ON import_file (matched_media_id) WHERE matched_media_id IS NOT NULL;
CREATE INDEX ix_import_file_entry ON import_file (entry_id) WHERE entry_id IS NOT NULL;
CREATE INDEX ix_import_file_target_account ON import_file (target_account_id) WHERE target_account_id IS NOT NULL;
CREATE TABLE duplicate_pair (
id INTEGER PRIMARY KEY,
origin TEXT NOT NULL,
reason TEXT NOT NULL,
existing_media_id INTEGER REFERENCES media (id) ON DELETE CASCADE,
existing_import_file_id INTEGER REFERENCES import_file (id) ON DELETE CASCADE,
candidate_media_id INTEGER REFERENCES media (id) ON DELETE CASCADE,
candidate_import_file_id INTEGER REFERENCES import_file (id) ON DELETE CASCADE,
distance INTEGER,
decision TEXT NOT NULL,
created_at INTEGER NOT NULL,
decided_at INTEGER,
-- Exactly one reference per side.
CHECK ((existing_media_id IS NULL) <> (existing_import_file_id IS NULL)),
CHECK ((candidate_media_id IS NULL) <> (candidate_import_file_id IS NULL))
);
CREATE INDEX ix_duplicate_pair_decision ON duplicate_pair (decision, id);
CREATE INDEX ix_duplicate_pair_existing_media ON duplicate_pair (existing_media_id);
CREATE INDEX ix_duplicate_pair_candidate_media ON duplicate_pair (candidate_media_id);
CREATE INDEX ix_duplicate_pair_existing_file ON duplicate_pair (existing_import_file_id);
CREATE INDEX ix_duplicate_pair_candidate_file ON duplicate_pair (candidate_import_file_id);
+123
View File
@@ -0,0 +1,123 @@
using System.Globalization;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>Conversions between domain values and SQLite columns.</summary>
internal static class Sql
{
/// <summary>UTC instant → Unix milliseconds.</summary>
public static long Time(DateTimeOffset value) => value.ToUnixTimeMilliseconds();
public static object Time(DateTimeOffset? value) => value is { } v ? v.ToUnixTimeMilliseconds() : DBNull.Value;
public static DateTimeOffset ToTime(long ms) => DateTimeOffset.FromUnixTimeMilliseconds(ms);
public static object Text(string? value) => value is null ? DBNull.Value : value;
public static object Int(long? value) => value is { } v ? v : DBNull.Value;
public static object Int(int? value) => value is { } v ? v : DBNull.Value;
public static object Bool(bool value) => value ? 1L : 0L;
public static object Bool(bool? value) => value is { } v ? (v ? 1L : 0L) : DBNull.Value;
public static object Enum<T>(T value)
where T : struct, Enum => value.ToString();
public static object Enum<T>(T? value)
where T : struct, Enum => value is { } v ? v.ToString() : DBNull.Value;
public static object Hash(ulong? value) => value is { } v ? unchecked((long)v) : DBNull.Value;
public static object Duration(TimeSpan? value) => value is { } v ? (long)v.TotalMilliseconds : DBNull.Value;
public static object Minutes(TimeSpan? value) => value is { } v ? (long)Math.Round(v.TotalMinutes) : DBNull.Value;
public static T ParseEnum<T>(string text)
where T : struct, Enum => System.Enum.Parse<T>(text, ignoreCase: false);
// Reader helpers -----------------------------------------------------------------------------
public static string? GetTextOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetString(i);
public static long? GetInt64OrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt64(i);
public static int? GetInt32OrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt32(i);
public static bool GetBool(this SqliteDataReader r, int i) => r.GetInt64(i) != 0;
public static bool? GetBoolOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : r.GetInt64(i) != 0;
public static DateTimeOffset GetTime(this SqliteDataReader r, int i) => ToTime(r.GetInt64(i));
public static DateTimeOffset? GetTimeOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : ToTime(r.GetInt64(i));
public static T GetEnum<T>(this SqliteDataReader r, int i)
where T : struct, Enum => ParseEnum<T>(r.GetString(i));
public static T? GetEnumOrNull<T>(this SqliteDataReader r, int i)
where T : struct, Enum => r.IsDBNull(i) ? null : ParseEnum<T>(r.GetString(i));
public static ulong? GetHashOrNull(this SqliteDataReader r, int i) => r.IsDBNull(i) ? null : unchecked((ulong)r.GetInt64(i));
public static TimeSpan? GetDurationOrNull(this SqliteDataReader r, int i) =>
r.IsDBNull(i) ? null : TimeSpan.FromMilliseconds(r.GetInt64(i));
public static TimeSpan? GetMinutesOrNull(this SqliteDataReader r, int i) =>
r.IsDBNull(i) ? null : TimeSpan.FromMinutes(r.GetInt64(i));
// Command helpers ----------------------------------------------------------------------------
public static SqliteCommand Command(this SqliteConnection connection, string sql, SqliteTransaction? transaction = null)
{
var command = connection.CreateCommand();
command.CommandText = sql;
command.Transaction = transaction;
return command;
}
/// <summary>Sets a parameter, adding it the first time: a prepared command can be run again with new values.</summary>
public static SqliteCommand With(this SqliteCommand command, string name, object? value)
{
if (command.Parameters.Contains(name))
{
command.Parameters[name].Value = value ?? DBNull.Value;
}
else
{
command.Parameters.AddWithValue(name, value ?? DBNull.Value);
}
return command;
}
/// <summary>Adds parameters @p0, @p1, ... and returns the comma-separated list of their names, for IN (...).</summary>
public static string AddList<T>(this SqliteCommand command, string prefix, IEnumerable<T> values)
{
var names = new List<string>();
var i = 0;
foreach (var value in values)
{
var name = string.Create(CultureInfo.InvariantCulture, $"@{prefix}{i++}");
command.Parameters.AddWithValue(name, (object?)value ?? DBNull.Value);
names.Add(name);
}
return names.Count == 0 ? "NULL" : string.Join(", ", names);
}
public static long ScalarInt64(this SqliteCommand command)
{
var value = command.ExecuteScalar();
return value is null or DBNull ? 0 : Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
/// <summary>True for SQLITE_CONSTRAINT errors (unique, check, foreign key, not null).</summary>
public static bool IsConstraintViolation(this SqliteException exception) => exception.SqliteErrorCode == 19;
/// <summary>True for a UNIQUE or PRIMARY KEY constraint violation.</summary>
public static bool IsUniqueViolation(this SqliteException exception) =>
exception.SqliteErrorCode == 19 && exception.SqliteExtendedErrorCode is 2067 or 1555;
}
+324
View File
@@ -0,0 +1,324 @@
using System.Threading.Channels;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>
/// The active transaction of the writer, passed to each write. Commands are prepared once per batch and reused
/// (same SQL text, new parameter values), then disposed when the batch ends.
/// </summary>
internal sealed class WriteContext(SqliteConnection connection, SqliteTransaction transaction) : IDisposable
{
private readonly Dictionary<string, SqliteCommand> _commands = new(StringComparer.Ordinal);
public SqliteConnection Connection { get; } = connection;
public SqliteTransaction Transaction { get; } = transaction;
/// <summary>
/// The prepared command for this SQL in the current batch. Callers set every parameter they use (see
/// <see cref="Sql.With"/>) and close readers before running the same SQL again.
/// </summary>
public SqliteCommand Command(string sql)
{
if (!_commands.TryGetValue(sql, out var command))
{
command = Connection.Command(sql, Transaction);
_commands[sql] = command;
}
return command;
}
public long LastInsertRowId() => Command("SELECT last_insert_rowid()").ScalarInt64();
public void Dispose()
{
foreach (var command in _commands.Values)
{
command.Dispose();
}
_commands.Clear();
}
}
/// <summary>
/// The single writer of the database (spec §8.3: «Un solo scrittore: le scritture passano da una coda»).
/// <para>
/// Every write is queued on a channel and executed by one dedicated thread on one dedicated connection. Writes that
/// are queued together share one transaction (group commit), each inside its own savepoint: a failing write is rolled
/// back alone and reports its exception; the others commit. A write's task completes only after the commit.
/// </para>
/// </summary>
internal sealed class SqliteWriter : IDisposable
{
private const int MaxBatch = 64;
private const string Savepoint = "febe_write";
private readonly SqliteConnection _connection;
private readonly Channel<WorkItem> _queue = Channel.CreateUnbounded<WorkItem>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false,
});
private readonly Thread _thread;
private int _executing;
private int _maxObservedConcurrency;
private int _disposed;
public SqliteWriter(SqliteConnection connection)
{
_connection = connection;
_thread = new Thread(Run)
{
IsBackground = true,
Name = "Febe database writer",
};
_thread.Start();
}
/// <summary>Highest number of writes seen executing at the same time (always 1): checked by the tests.</summary>
internal int MaxObservedConcurrency => Volatile.Read(ref _maxObservedConcurrency);
/// <summary>The managed thread id of the writer thread.</summary>
internal int ThreadId => _thread.ManagedThreadId;
public Task<T> ExecuteAsync<T>(Func<WriteContext, T> work, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(work);
if (ct.IsCancellationRequested)
{
return Task.FromCanceled<T>(ct);
}
var item = new WorkItem<T>(work, ct);
if (!_queue.Writer.TryWrite(item))
{
item.Dispose();
return Task.FromException<T>(new ObjectDisposedException(nameof(SqliteWriter), "Il database è chiuso."));
}
return item.Task;
}
public Task ExecuteAsync(Action<WriteContext> work, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(work);
return ExecuteAsync<bool>(
context =>
{
work(context);
return true;
},
ct);
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
_queue.Writer.TryComplete();
_thread.Join();
}
private void Run()
{
var reader = _queue.Reader;
var batch = new List<WorkItem>(MaxBatch);
while (true)
{
bool more;
try
{
more = reader.WaitToReadAsync().AsTask().GetAwaiter().GetResult();
}
catch (ChannelClosedException)
{
more = false;
}
if (!more)
{
return;
}
batch.Clear();
while (batch.Count < MaxBatch && reader.TryRead(out var item))
{
batch.Add(item);
}
ProcessBatch(batch);
}
}
private void ProcessBatch(List<WorkItem> batch)
{
var started = new List<WorkItem>(batch.Count);
foreach (var item in batch)
{
if (item.TryStart())
{
started.Add(item);
}
else
{
item.Dispose(); // cancelled while queued
}
}
if (started.Count == 0)
{
return;
}
var succeeded = new List<WorkItem>(started.Count);
SqliteTransaction? transaction = null;
WriteContext? context = null;
try
{
transaction = _connection.BeginTransaction(deferred: false);
context = new WriteContext(_connection, transaction);
foreach (var item in started)
{
transaction.Save(Savepoint);
var executing = Interlocked.Increment(ref _executing);
UpdateMax(executing);
try
{
item.Execute(context);
transaction.Release(Savepoint);
succeeded.Add(item);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
transaction.Rollback(Savepoint);
transaction.Release(Savepoint);
item.Fail(ex);
}
finally
{
Interlocked.Decrement(ref _executing);
}
}
transaction.Commit();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
try
{
transaction?.Rollback();
}
catch (SqliteException)
{
// The transaction may already be gone; the original error is what matters.
}
catch (InvalidOperationException)
{
}
foreach (var item in started)
{
item.Fail(ex); // no effect on items that already failed on their own
}
return;
}
finally
{
context?.Dispose();
transaction?.Dispose();
}
foreach (var item in succeeded)
{
item.Complete();
}
}
private void UpdateMax(int executing)
{
int seen;
while (executing > (seen = Volatile.Read(ref _maxObservedConcurrency)))
{
if (Interlocked.CompareExchange(ref _maxObservedConcurrency, executing, seen) == seen)
{
return;
}
}
}
private abstract class WorkItem : IDisposable
{
private const int Queued = 0;
private const int Started = 1;
private const int Cancelled = 2;
private readonly CancellationTokenRegistration _registration;
private int _state;
protected WorkItem(CancellationToken ct)
{
if (ct.CanBeCanceled)
{
_registration = ct.Register(static s => ((WorkItem)s!).OnCancel(), this);
}
CancellationToken = ct;
}
protected CancellationToken CancellationToken { get; }
/// <summary>Queued → started. False when the caller cancelled first.</summary>
public bool TryStart() => Interlocked.CompareExchange(ref _state, Started, Queued) == Queued;
public abstract void Execute(WriteContext context);
public abstract void Complete();
public abstract void Fail(Exception exception);
public void Dispose() => _registration.Dispose();
protected abstract void SetCancelled();
private void OnCancel()
{
if (Interlocked.CompareExchange(ref _state, Cancelled, Queued) == Queued)
{
SetCancelled();
}
}
}
private sealed class WorkItem<T>(Func<WriteContext, T> work, CancellationToken ct) : WorkItem(ct)
{
private readonly TaskCompletionSource<T> _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private T _result = default!;
public Task<T> Task => _completion.Task;
public override void Execute(WriteContext context) => _result = work(context);
public override void Complete()
{
Dispose();
_completion.TrySetResult(_result);
}
public override void Fail(Exception exception)
{
Dispose();
_completion.TrySetException(exception);
}
protected override void SetCancelled() => _completion.TrySetCanceled(CancellationToken);
}
}
+459
View File
@@ -0,0 +1,459 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class AccountStore(FebeDatabase db) : IAccountStore
{
internal const string Columns =
"a.id, a.instagram_id, a.username, a.display_name, a.is_private, a.is_followed, a.is_mine, a.state, a.state_changed_at, "
+ "a.unreachable_reason, a.keep_updated, a.frequency, a.custom_post_interval_min, a.custom_story_interval_min, a.content_types, "
+ "a.history_depth, a.history_last_posts, a.history_from, a.backfill_posts_per_day, a.max_video_bytes, a.story_videos, a.folder, "
+ "a.backfill_cursor, a.backfill_completed_at, a.post_count, a.last_profile_check_at, a.next_profile_check_at, "
+ "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at";
internal const int ColumnCount = 34;
private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'"));
internal static Account Read(SqliteDataReader r, int o = 0) => new()
{
Id = r.GetInt64(o),
InstagramId = r.GetTextOrNull(o + 1),
Username = r.GetString(o + 2),
DisplayName = r.GetTextOrNull(o + 3),
IsPrivate = r.GetBool(o + 4),
IsFollowed = r.GetBool(o + 5),
IsMine = r.GetBool(o + 6),
State = r.GetEnum<AccountState>(o + 7),
StateChangedAt = r.GetTimeOrNull(o + 8),
UnreachableReason = r.GetEnumOrNull<UnreachableReason>(o + 9),
KeepUpdated = r.GetBool(o + 10),
Frequency = r.GetEnum<Frequency>(o + 11),
CustomPostInterval = r.GetMinutesOrNull(o + 12),
CustomStoryInterval = r.GetMinutesOrNull(o + 13),
ContentTypes = (ContentTypes)r.GetInt32(o + 14),
Limits = new AccountLimits
{
Depth = r.GetEnum<HistoryDepth>(o + 15),
LastPosts = r.GetInt32OrNull(o + 16),
FromDate = r.GetTimeOrNull(o + 17),
BackfillPostsPerDay = r.GetInt32(o + 18),
MaxVideoBytes = r.GetInt64OrNull(o + 19),
StoryVideos = r.GetBool(o + 20),
},
Folder = r.GetTextOrNull(o + 21),
BackfillCursor = r.GetTextOrNull(o + 22),
BackfillCompletedAt = r.GetTimeOrNull(o + 23),
PostCount = r.GetInt32OrNull(o + 24),
LastProfileCheckAt = r.GetTimeOrNull(o + 25),
NextProfileCheckAt = r.GetTimeOrNull(o + 26),
LastStoriesCheckAt = r.GetTimeOrNull(o + 27),
NextStoriesCheckAt = r.GetTimeOrNull(o + 28),
Notices = (AccountNotices)r.GetInt32(o + 29),
PreviousUsername = r.GetTextOrNull(o + 30),
RenamedAt = r.GetTimeOrNull(o + 31),
FormatUnrecognizedAt = r.GetTimeOrNull(o + 32),
AddedAt = r.GetTime(o + 33),
};
private static void Bind(SqliteCommand c, Account a)
{
c.With("@instagram_id", Sql.Text(Normalize(a.InstagramId)))
.With("@username", NormalizeUsername(a.Username))
.With("@display_name", Sql.Text(a.DisplayName))
.With("@is_private", Sql.Bool(a.IsPrivate))
.With("@is_followed", Sql.Bool(a.IsFollowed))
.With("@is_mine", Sql.Bool(a.IsMine))
.With("@state", Sql.Enum(a.State))
.With("@state_changed_at", Sql.Time(a.StateChangedAt))
.With("@unreachable_reason", Sql.Enum(a.UnreachableReason))
.With("@keep_updated", Sql.Bool(a.KeepUpdated))
.With("@frequency", Sql.Enum(a.Frequency))
.With("@custom_post_interval_min", Sql.Minutes(a.CustomPostInterval))
.With("@custom_story_interval_min", Sql.Minutes(a.CustomStoryInterval))
.With("@content_types", (long)a.ContentTypes)
.With("@history_depth", Sql.Enum(a.Limits.Depth))
.With("@history_last_posts", Sql.Int(a.Limits.LastPosts))
.With("@history_from", Sql.Time(a.Limits.FromDate))
.With("@backfill_posts_per_day", (long)a.Limits.BackfillPostsPerDay)
.With("@max_video_bytes", Sql.Int(a.Limits.MaxVideoBytes))
.With("@story_videos", Sql.Bool(a.Limits.StoryVideos))
.With("@folder", Sql.Text(a.Folder))
.With("@backfill_cursor", Sql.Text(a.BackfillCursor))
.With("@backfill_completed_at", Sql.Time(a.BackfillCompletedAt))
.With("@post_count", Sql.Int(a.PostCount))
.With("@last_profile_check_at", Sql.Time(a.LastProfileCheckAt))
.With("@next_profile_check_at", Sql.Time(a.NextProfileCheckAt))
.With("@last_stories_check_at", Sql.Time(a.LastStoriesCheckAt))
.With("@next_stories_check_at", Sql.Time(a.NextStoriesCheckAt))
.With("@notices", (long)a.Notices)
.With("@previous_username", Sql.Text(a.PreviousUsername))
.With("@renamed_at", Sql.Time(a.RenamedAt))
.With("@format_unrecognized_at", Sql.Time(a.FormatUnrecognizedAt))
.With("@added_at", Sql.Time(a.AddedAt));
}
private static string? Normalize(string? instagramId) => string.IsNullOrWhiteSpace(instagramId) ? null : instagramId.Trim();
private static string NormalizeUsername(string username) => username.Trim().TrimStart('@');
private static void Validate(Account account)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentException.ThrowIfNullOrWhiteSpace(account.Username);
if (account.Limits.BackfillPostsPerDay < 0)
{
throw new ArgumentException("Il massimo di storico al giorno non può essere negativo.", nameof(account));
}
if (account.Frequency == Frequency.Custom && (account.CustomPostInterval is null || account.CustomStoryInterval is null))
{
throw new ArgumentException("Con la frequenza «Su misura» servono i due intervalli.", nameof(account));
}
}
public Task<Account?> GetAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.id = @id").With("@id", accountId)), ct);
public Task<Account?> FindByInstagramIdAsync(string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync(
c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.instagram_id = @id").With("@id", instagramId.Trim())),
ct);
}
public Task<Account?> FindByUsernameAsync(string username, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(username);
var name = username.Trim().TrimStart('@');
return db.ReadAsync(
c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.username = @u ORDER BY a.id LIMIT 1").With("@u", name)),
ct);
}
public Task<Account?> GetMineAsync(CancellationToken ct = default) =>
db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.is_mine = 1")), ct);
public Task<IReadOnlyList<Account>> ListAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Account>>(
c =>
{
using var r = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader();
var list = new List<Account>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
},
ct);
public Task<IReadOnlyList<AccountSummary>> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<AccountSummary>>(
c =>
{
// One pass over the (account, kind, state, discovered) index for every account at once.
var counts = new Dictionary<long, (int Entries, int Posts, int NewPosts, int NewStories)>();
var sql = $"""
SELECT e.account_id,
SUM(e.kind <> 'ProfilePicture' AND e.state IN ({Visible})),
SUM(e.kind = 'Post' AND e.state IN ({Visible})),
SUM(e.kind = 'Post' AND e.discovered_at >= @since),
SUM(e.kind = 'Story' AND e.discovered_at >= @since)
FROM entry e GROUP BY e.account_id
""";
using (var r = c.Command(sql).With("@since", Sql.Time(newSince)).ExecuteReader())
{
while (r.Read())
{
counts[r.GetInt64(0)] = (r.GetInt32(1), r.GetInt32(2), r.GetInt32(3), r.GetInt32(4));
}
}
using var accounts = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader();
var list = new List<AccountSummary>();
while (accounts.Read())
{
var account = Read(accounts);
var (entries, posts, newPosts, newStories) = counts.GetValueOrDefault(account.Id);
list.Add(new AccountSummary(account, entries, posts, newPosts, newStories));
}
return list;
},
ct);
public Task<AccountStats> GetStatsAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var sql = $"""
SELECT e.kind, COUNT(*), MAX(e.published_at) FROM entry e
WHERE e.account_id = @a AND e.state IN ({Visible}) GROUP BY e.kind
""";
var stats = new AccountStats { AccountId = accountId };
DateTimeOffset? last = null;
using (var r = c.Command(sql).With("@a", accountId).ExecuteReader())
{
while (r.Read())
{
var kind = r.GetEnum<EntryKind>(0);
var count = r.GetInt32(1);
var max = r.GetTimeOrNull(2);
stats = kind switch
{
EntryKind.Post => stats with { Posts = count },
EntryKind.Story => stats with { Stories = count },
EntryKind.Highlight => stats with { HighlightItems = count },
EntryKind.Tagged => stats with { Tagged = count },
EntryKind.ProfilePicture => stats with { ProfilePictures = count },
_ => stats,
};
if (kind != EntryKind.ProfilePicture && max is { } m && (last is null || m > last))
{
last = m;
}
}
}
var bytes = c.Command("""
SELECT COALESCE(SUM(m.bytes), 0) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.state IN ('Downloaded', 'Imported')
""").With("@a", accountId).ScalarInt64();
var pending = c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.state IN ('ToDownload', 'Expired')
""").With("@a", accountId).ScalarInt64();
var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL")
.With("@a", accountId).ScalarInt64();
return stats with
{
EntriesInLibrary = stats.Posts + stats.Stories + stats.HighlightItems + stats.Tagged,
Bytes = bytes,
PendingFiles = (int)pending,
HighlightCollections = (int)collections,
LastPublishedAt = last,
};
},
ct);
public Task<Account> AddAsync(Account account, CancellationToken ct = default)
{
Validate(account);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO account (instagram_id, username, display_name, is_private, is_followed, is_mine, state, state_changed_at,
unreachable_reason, keep_updated, frequency, custom_post_interval_min, custom_story_interval_min, content_types,
history_depth, history_last_posts, history_from, backfill_posts_per_day, max_video_bytes, story_videos, folder,
backfill_cursor, backfill_completed_at, post_count, last_profile_check_at, next_profile_check_at,
last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at)
VALUES (@instagram_id, @username, @display_name, @is_private, @is_followed, @is_mine, @state, @state_changed_at,
@unreachable_reason, @keep_updated, @frequency, @custom_post_interval_min, @custom_story_interval_min, @content_types,
@history_depth, @history_last_posts, @history_from, @backfill_posts_per_day, @max_video_bytes, @story_videos, @folder,
@backfill_cursor, @backfill_completed_at, @post_count, @last_profile_check_at, @next_profile_check_at,
@last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at)
""");
Bind(c, account);
try
{
c.ExecuteNonQuery();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(
account.IsMine
? "Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente."
: "Esiste già un account con lo stesso identificativo Instagram.",
ex);
}
return account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) };
},
ct);
}
public Task UpdateAsync(Account account, CancellationToken ct = default)
{
Validate(account);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE account SET instagram_id = @instagram_id, username = @username, display_name = @display_name,
is_private = @is_private, is_followed = @is_followed, is_mine = @is_mine, state = @state, state_changed_at = @state_changed_at,
unreachable_reason = @unreachable_reason, keep_updated = @keep_updated, frequency = @frequency,
custom_post_interval_min = @custom_post_interval_min, custom_story_interval_min = @custom_story_interval_min,
content_types = @content_types, history_depth = @history_depth, history_last_posts = @history_last_posts,
history_from = @history_from, backfill_posts_per_day = @backfill_posts_per_day, max_video_bytes = @max_video_bytes,
story_videos = @story_videos, folder = @folder, backfill_cursor = @backfill_cursor,
backfill_completed_at = @backfill_completed_at, post_count = @post_count,
last_profile_check_at = @last_profile_check_at, next_profile_check_at = @next_profile_check_at,
last_stories_check_at = @last_stories_check_at, next_stories_check_at = @next_stories_check_at, notices = @notices,
previous_username = @previous_username, renamed_at = @renamed_at, format_unrecognized_at = @format_unrecognized_at,
added_at = @added_at
WHERE id = @id
""");
Bind(c, account);
c.With("@id", account.Id);
try
{
RequireOne(c.ExecuteNonQuery(), account.Id);
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException("Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente.", ex);
}
},
ct);
}
public Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default) =>
db.WriteAsync(
w => RequireOne(
w.Command("""
UPDATE account SET state = @state, unreachable_reason = @reason,
state_changed_at = CASE WHEN state = @state THEN state_changed_at ELSE @at END
WHERE id = @id
""")
.With("@state", Sql.Enum(state))
.With("@reason", state == AccountState.Unreachable ? Sql.Enum(reason) : DBNull.Value)
.With("@at", Sql.Time(at))
.With("@id", accountId)
.ExecuteNonQuery(),
accountId),
ct);
public Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(times);
return db.WriteAsync(
w => RequireOne(
w.Command("""
UPDATE account SET
last_profile_check_at = COALESCE(@lp, last_profile_check_at),
next_profile_check_at = COALESCE(@np, next_profile_check_at),
last_stories_check_at = COALESCE(@ls, last_stories_check_at),
next_stories_check_at = COALESCE(@ns, next_stories_check_at),
post_count = COALESCE(@pc, post_count),
is_private = COALESCE(@pr, is_private),
is_followed = COALESCE(@fo, is_followed),
display_name = COALESCE(@dn, display_name)
WHERE id = @id
""")
.With("@lp", Sql.Time(times.LastProfileCheckAt))
.With("@np", Sql.Time(times.NextProfileCheckAt))
.With("@ls", Sql.Time(times.LastStoriesCheckAt))
.With("@ns", Sql.Time(times.NextStoriesCheckAt))
.With("@pc", Sql.Int(times.PostCount))
.With("@pr", Sql.Bool(times.IsPrivate))
.With("@fo", Sql.Bool(times.IsFollowed))
.With("@dn", Sql.Text(times.DisplayName))
.With("@id", accountId)
.ExecuteNonQuery(),
accountId),
ct);
}
public Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default) =>
db.WriteAsync(
w => RequireOne(
w.Command("UPDATE account SET backfill_cursor = @c, backfill_completed_at = @d WHERE id = @id")
.With("@c", Sql.Text(cursor))
.With("@d", Sql.Time(completedAt))
.With("@id", accountId)
.ExecuteNonQuery(),
accountId),
ct);
public Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(newUsername);
var name = newUsername.Trim().TrimStart('@');
return db.WriteAsync(
w =>
{
string? oldName;
using (var r = w.Command("SELECT username, folder FROM account WHERE id = @id").With("@id", accountId).ExecuteReader())
{
if (!r.Read())
{
throw new KeyNotFoundException($"Account {accountId} non trovato.");
}
oldName = r.GetString(0);
}
if (string.Equals(oldName, name, StringComparison.Ordinal))
{
return;
}
// A default folder follows the user name: pin it to the old name so the folder is kept (spec §4.2).
w.Command("""
UPDATE account SET folder = COALESCE(folder, @pinned), previous_username = username, username = @u,
renamed_at = @at, notices = notices | @renamed
WHERE id = @id
""")
.With("@pinned", WindowsFileNames.SanitizeSegment(oldName))
.With("@u", name)
.With("@at", Sql.Time(at))
.With("@renamed", (long)AccountNotices.Renamed)
.With("@id", accountId)
.ExecuteNonQuery();
},
ct);
}
public Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => RequireOne(
w.Command("""
UPDATE account SET notices = notices | @n,
format_unrecognized_at = CASE WHEN (@n & @uf) <> 0 THEN @at ELSE format_unrecognized_at END,
renamed_at = CASE WHEN (@n & @rn) <> 0 THEN @at ELSE renamed_at END
WHERE id = @id
""")
.With("@n", (long)notices)
.With("@uf", (long)AccountNotices.UnrecognizedFormat)
.With("@rn", (long)AccountNotices.Renamed)
.With("@at", Sql.Time(at))
.With("@id", accountId)
.ExecuteNonQuery(),
accountId),
ct);
public Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default) =>
db.WriteAsync(
w => RequireOne(
w.Command("UPDATE account SET notices = notices & ~@n WHERE id = @id")
.With("@n", (long)notices)
.With("@id", accountId)
.ExecuteNonQuery(),
accountId),
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);
private static Account? ReadOne(SqliteCommand command)
{
using var r = command.ExecuteReader();
return r.Read() ? Read(r) : null;
}
private static void RequireOne(int rows, long accountId)
{
if (rows == 0)
{
throw new KeyNotFoundException($"Account {accountId} non trovato.");
}
}
}
+111
View File
@@ -0,0 +1,111 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class DuplicateStore(FebeDatabase db) : IDuplicateStore
{
private const string Columns =
"id, origin, reason, existing_media_id, existing_import_file_id, candidate_media_id, candidate_import_file_id, distance, decision, created_at, decided_at";
private static DuplicatePair Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
Origin = r.GetEnum<DuplicateOrigin>(1),
Reason = r.GetEnum<DuplicateReason>(2),
ExistingMediaId = r.GetInt64OrNull(3),
ExistingImportFileId = r.GetInt64OrNull(4),
CandidateMediaId = r.GetInt64OrNull(5),
CandidateImportFileId = r.GetInt64OrNull(6),
Distance = r.GetInt32OrNull(7),
Decision = r.GetEnum<DuplicateDecision>(8),
CreatedAt = r.GetTime(9),
DecidedAt = r.GetTimeOrNull(10),
};
private static List<DuplicatePair> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<DuplicatePair>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<DuplicatePair> AddAsync(DuplicatePair pair, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(pair);
if ((pair.ExistingMediaId is null) == (pair.ExistingImportFileId is null)
|| (pair.CandidateMediaId is null) == (pair.CandidateImportFileId is null))
{
throw new ArgumentException("Ogni lato di una coppia di doppioni è un file della libreria oppure un file dell'importazione, non entrambi.", nameof(pair));
}
return db.WriteAsync(
w =>
{
var existing = ReadAll(w.Command($"""
SELECT {Columns} FROM duplicate_pair WHERE decision = 'Pending'
AND existing_media_id IS @em AND existing_import_file_id IS @ef
AND candidate_media_id IS @cm AND candidate_import_file_id IS @cf
LIMIT 1
""")
.With("@em", Sql.Int(pair.ExistingMediaId)).With("@ef", Sql.Int(pair.ExistingImportFileId))
.With("@cm", Sql.Int(pair.CandidateMediaId)).With("@cf", Sql.Int(pair.CandidateImportFileId)));
if (existing.Count > 0)
{
return existing[0];
}
w.Command("""
INSERT INTO duplicate_pair (origin, reason, existing_media_id, existing_import_file_id, candidate_media_id,
candidate_import_file_id, distance, decision, created_at, decided_at)
VALUES (@o, @r, @em, @ef, @cm, @cf, @d, @dec, @c, @dd)
""")
.With("@o", Sql.Enum(pair.Origin)).With("@r", Sql.Enum(pair.Reason))
.With("@em", Sql.Int(pair.ExistingMediaId)).With("@ef", Sql.Int(pair.ExistingImportFileId))
.With("@cm", Sql.Int(pair.CandidateMediaId)).With("@cf", Sql.Int(pair.CandidateImportFileId))
.With("@d", Sql.Int(pair.Distance)).With("@dec", Sql.Enum(pair.Decision))
.With("@c", Sql.Time(pair.CreatedAt)).With("@dd", Sql.Time(pair.DecidedAt))
.ExecuteNonQuery();
return pair with { Id = w.LastInsertRowId() };
},
ct);
}
public Task<DuplicatePair?> GetAsync(long pairId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM duplicate_pair WHERE id = @id").With("@id", pairId)).FirstOrDefault(), ct);
public Task<IReadOnlyList<DuplicatePair>> ListPendingAsync(DuplicateOrigin? origin = null, long afterId = 0, int limit = 200, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<DuplicatePair>>(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM duplicate_pair WHERE decision = 'Pending' AND id > @after AND (@o IS NULL OR origin = @o)
ORDER BY id LIMIT @limit
""").With("@after", afterId).With("@o", Sql.Enum(origin)).With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
public Task<int> CountPendingAsync(DuplicateOrigin? origin = null, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("SELECT COUNT(*) FROM duplicate_pair WHERE decision = 'Pending' AND (@o IS NULL OR origin = @o)")
.With("@o", Sql.Enum(origin)).ScalarInt64(),
ct);
public Task DecideAsync(long pairId, DuplicateDecision decision, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
if (w.Command("UPDATE duplicate_pair SET decision = @d, decided_at = @at WHERE id = @id")
.With("@d", Sql.Enum(decision))
.With("@at", decision == DuplicateDecision.Pending ? DBNull.Value : Sql.Time(at))
.With("@id", pairId)
.ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Coppia {pairId} non trovata.");
}
},
ct);
}
+635
View File
@@ -0,0 +1,635 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class TaskStore(FebeDatabase db) : ITaskStore
{
private const string Columns =
"id, kind, account_id, due_at, priority, state, payload, is_manual, attempts, created_at, started_at, completed_at, last_error";
private static EngineTask Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
Kind = r.GetEnum<EngineTaskKind>(1),
AccountId = r.GetInt64OrNull(2),
DueAt = r.GetTime(3),
Priority = r.GetInt32(4),
State = r.GetEnum<EngineTaskState>(5),
Payload = r.GetTextOrNull(6),
IsManual = r.GetBool(7),
Attempts = r.GetInt32(8),
CreatedAt = r.GetTime(9),
StartedAt = r.GetTimeOrNull(10),
CompletedAt = r.GetTimeOrNull(11),
LastError = r.GetTextOrNull(12),
};
private static List<EngineTask> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<EngineTask>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<EngineTask> EnqueueAsync(EngineTask task, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(task);
return db.WriteAsync(
w =>
{
var existing = ReadAll(w.Command($"""
SELECT {Columns} FROM task WHERE state = 'Pending' AND kind = @k AND account_id IS @a AND payload IS @p
ORDER BY id LIMIT 1
""").With("@k", Sql.Enum(task.Kind)).With("@a", Sql.Int(task.AccountId)).With("@p", Sql.Text(task.Payload)));
if (existing.Count > 0)
{
var current = existing[0];
var merged = current with
{
DueAt = task.DueAt < current.DueAt ? task.DueAt : current.DueAt,
Priority = Math.Max(task.Priority, current.Priority),
IsManual = current.IsManual || task.IsManual,
};
w.Command("UPDATE task SET due_at = @d, priority = @p, is_manual = @m WHERE id = @id")
.With("@d", Sql.Time(merged.DueAt)).With("@p", (long)merged.Priority).With("@m", Sql.Bool(merged.IsManual))
.With("@id", current.Id).ExecuteNonQuery();
return merged;
}
w.Command("""
INSERT INTO task (kind, account_id, due_at, priority, state, payload, is_manual, attempts, created_at, started_at, completed_at, last_error)
VALUES (@k, @a, @d, @p, 'Pending', @pl, @m, @at, @c, NULL, NULL, NULL)
""")
.With("@k", Sql.Enum(task.Kind)).With("@a", Sql.Int(task.AccountId)).With("@d", Sql.Time(task.DueAt))
.With("@p", (long)task.Priority).With("@pl", Sql.Text(task.Payload)).With("@m", Sql.Bool(task.IsManual))
.With("@at", (long)task.Attempts).With("@c", Sql.Time(task.CreatedAt))
.ExecuteNonQuery();
return task with { Id = w.LastInsertRowId(), State = EngineTaskState.Pending, StartedAt = null, CompletedAt = null, LastError = null };
},
ct);
}
public Task<EngineTask?> GetAsync(long taskId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM task WHERE id = @id").With("@id", taskId)).FirstOrDefault(), ct);
public Task<IReadOnlyList<EngineTask>> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<EngineTask>>(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM task WHERE state = 'Pending' AND due_at <= @now
ORDER BY priority DESC, due_at, id LIMIT @limit
""").With("@now", Sql.Time(now)).With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
public Task<IReadOnlyList<EngineTask>> ListPendingAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<EngineTask>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM task WHERE state = 'Pending' ORDER BY due_at, priority DESC, id LIMIT @limit")
.With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
public Task<bool> TryStartAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE task SET state = 'Running', started_at = @at WHERE id = @id AND state = 'Pending'")
.With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery() == 1,
ct);
public Task CompleteAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => Require(w.Command("UPDATE task SET state = 'Done', completed_at = @at, last_error = NULL WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(), taskId),
ct);
public Task FailAsync(long taskId, DateTimeOffset at, string error, DateTimeOffset? retryAt, CancellationToken ct = default) =>
db.WriteAsync(
w => Require(w.Command("""
UPDATE task SET attempts = attempts + 1, last_error = @e,
state = CASE WHEN @retry IS NULL THEN 'Failed' ELSE 'Pending' END,
due_at = COALESCE(@retry, due_at),
completed_at = CASE WHEN @retry IS NULL THEN @at ELSE NULL END,
started_at = CASE WHEN @retry IS NULL THEN started_at ELSE NULL END
WHERE id = @id
""").With("@e", error).With("@retry", Sql.Time(retryAt)).With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(), taskId),
ct);
public Task RescheduleAsync(long taskId, DateTimeOffset dueAt, CancellationToken ct = default) =>
db.WriteAsync(
w => Require(w.Command("UPDATE task SET due_at = @d WHERE id = @id").With("@d", Sql.Time(dueAt)).With("@id", taskId).ExecuteNonQuery(), taskId),
ct);
public Task CancelAsync(long taskId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE task SET state = 'Cancelled', completed_at = @at WHERE id = @id AND state IN ('Pending', 'Running')")
.With("@at", Sql.Time(at)).With("@id", taskId).ExecuteNonQuery(),
ct);
public Task<int> CancelForAccountAsync(long accountId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE task SET state = 'Cancelled', completed_at = @at WHERE account_id = @a AND state = 'Pending'")
.With("@at", Sql.Time(at)).With("@a", accountId).ExecuteNonQuery(),
ct);
public Task<int> RequeueRunningAsync(CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("UPDATE task SET state = 'Pending', started_at = NULL WHERE state = 'Running'").ExecuteNonQuery(), ct);
public Task<int> PurgeFinishedAsync(DateTimeOffset before, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("DELETE FROM task WHERE state IN ('Done', 'Failed', 'Cancelled') AND completed_at < @b")
.With("@b", Sql.Time(before)).ExecuteNonQuery(),
ct);
private static void Require(int rows, long taskId)
{
if (rows == 0)
{
throw new KeyNotFoundException($"Attività {taskId} non trovata.");
}
}
}
internal sealed class ActionLogStore(FebeDatabase db) : IActionLogStore
{
private static readonly TimeSpan Window = TimeSpan.FromMinutes(60);
public Task<ActionLogRecord> AppendAsync(ActionLogRecord record, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentOutOfRangeException.ThrowIfNegative(record.Amount);
return db.WriteAsync(
w =>
{
w.Command("INSERT INTO action_log (at, category, account_id, session_id, amount) VALUES (@at, @c, @a, @s, @n)")
.With("@at", Sql.Time(record.At)).With("@c", Sql.Enum(record.Category)).With("@a", Sql.Int(record.AccountId))
.With("@s", Sql.Int(record.SessionId)).With("@n", record.Amount)
.ExecuteNonQuery();
return record with { Id = w.LastInsertRowId() };
},
ct);
}
public Task<long> SumAsync(ActionKind category, DateTimeOffset from, DateTimeOffset to, long? accountId = null, CancellationToken ct = default) =>
db.ReadAsync(
c => c.Command("""
SELECT COALESCE(SUM(amount), 0) FROM action_log
WHERE category = @c AND at >= @f AND at < @t AND (@a IS NULL OR account_id = @a)
""").With("@c", Sql.Enum(category)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@a", Sql.Int(accountId))
.ScalarInt64(),
ct);
public Task<IReadOnlyDictionary<ActionKind, BudgetUsage>> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zone);
var (dayStart, dayEnd) = LocalCalendar.DayBounds(now, zone);
var hourStart = now - Window;
var from = hourStart < dayStart ? hourStart : dayStart;
return db.ReadAsync<IReadOnlyDictionary<ActionKind, BudgetUsage>>(
c =>
{
// Rolling window (now − 60 min, now]; the action at exactly now − 60 min has left the window.
using var r = c.Command("""
SELECT category,
COALESCE(SUM(CASE WHEN at > @hs AND at <= @now THEN amount ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN at >= @ds AND at < @de THEN amount ELSE 0 END), 0)
FROM action_log WHERE at >= @from AND at < @de
GROUP BY category
""")
.With("@hs", Sql.Time(hourStart)).With("@now", Sql.Time(now)).With("@ds", Sql.Time(dayStart))
.With("@de", Sql.Time(dayEnd)).With("@from", Sql.Time(from))
.ExecuteReader();
var usage = Enum.GetValues<ActionKind>().ToDictionary(k => k, _ => default(BudgetUsage));
while (r.Read())
{
if (Enum.TryParse<ActionKind>(r.GetString(0), out var kind))
{
usage[kind] = new BudgetUsage(r.GetInt64(1), r.GetInt64(2));
}
}
return usage;
},
ct);
}
public Task<DateTimeOffset?> GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var command = category is { } k
? c.Command("SELECT MAX(at) FROM action_log WHERE category = @c").With("@c", Sql.Enum(k))
: c.Command("SELECT MAX(at) FROM action_log WHERE category <> @c").With("@c", Sql.Enum(ActionKind.DataDownload));
var value = command.ExecuteScalar();
return value is long ms ? Sql.ToTime(ms) : (DateTimeOffset?)null;
},
ct);
public Task<IReadOnlyList<ActionLogRecord>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ActionLogRecord>>(
c =>
{
using var r = c.Command("""
SELECT id, at, category, account_id, session_id, amount FROM action_log WHERE at >= @f AND at < @t ORDER BY at, id
""").With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ExecuteReader();
var list = new List<ActionLogRecord>();
while (r.Read())
{
list.Add(new ActionLogRecord
{
Id = r.GetInt64(0),
At = r.GetTime(1),
Category = r.GetEnum<ActionKind>(2),
AccountId = r.GetInt64OrNull(3),
SessionId = r.GetInt64OrNull(4),
Amount = r.GetInt64(5),
});
}
return list;
},
ct);
public Task<int> PruneAsync(DateTimeOffset before, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM action_log WHERE at < @b").With("@b", Sql.Time(before)).ExecuteNonQuery(), ct);
}
internal sealed class SessionStore(FebeDatabase db) : ISessionStore
{
private const string Columns = "id, started_at, ended_at, action_count, outcome, summary";
private static SessionRecord Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
StartedAt = r.GetTime(1),
EndedAt = r.GetTimeOrNull(2),
ActionCount = r.GetInt32(3),
Outcome = r.GetEnum<SessionOutcome>(4),
Summary = r.GetTextOrNull(5),
};
private static List<SessionRecord> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<SessionRecord>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<SessionRecord> StartAsync(DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
w.Command("INSERT INTO session (started_at, outcome) VALUES (@at, 'Running')").With("@at", Sql.Time(at)).ExecuteNonQuery();
return new SessionRecord { Id = w.LastInsertRowId(), StartedAt = at, Outcome = SessionOutcome.Running };
},
ct);
public Task EndAsync(long sessionId, DateTimeOffset at, SessionOutcome outcome, int actionCount, string? summary = null, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
if (w.Command("UPDATE session SET ended_at = @at, outcome = @o, action_count = @n, summary = @s WHERE id = @id")
.With("@at", Sql.Time(at)).With("@o", Sql.Enum(outcome)).With("@n", (long)actionCount).With("@s", Sql.Text(summary))
.With("@id", sessionId).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Sessione {sessionId} non trovata.");
}
},
ct);
public Task<SessionRecord?> GetAsync(long sessionId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM session WHERE id = @id").With("@id", sessionId)).FirstOrDefault(), ct);
public Task<SessionRecord?> GetLastAsync(CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM session ORDER BY started_at DESC, id DESC LIMIT 1")).FirstOrDefault(), ct);
public Task<IReadOnlyList<SessionRecord>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<SessionRecord>>(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM session WHERE started_at < @t AND (ended_at IS NULL OR ended_at > @f) ORDER BY started_at, id
""").With("@f", Sql.Time(from)).With("@t", Sql.Time(to))),
ct);
public Task<int> CloseInterruptedAsync(DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("""
UPDATE session SET ended_at = MAX(@at, started_at), outcome = 'Interrupted'
WHERE ended_at IS NULL
""").With("@at", Sql.Time(at)).ExecuteNonQuery(),
ct);
}
internal sealed class IncidentStore(FebeDatabase db) : IIncidentStore
{
private const string Columns = "id, at, level, signal, url, stopped_until, resolved_at, session_id, note";
private static Incident Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
At = r.GetTime(1),
Level = r.GetEnum<SignalLevel>(2),
Signal = r.GetString(3),
Url = r.GetTextOrNull(4),
StoppedUntil = r.GetTimeOrNull(5),
ResolvedAt = r.GetTimeOrNull(6),
SessionId = r.GetInt64OrNull(7),
Note = r.GetTextOrNull(8),
};
private static List<Incident> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<Incident>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<Incident> OpenAsync(Incident incident, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(incident);
ArgumentException.ThrowIfNullOrWhiteSpace(incident.Signal);
return db.WriteAsync(
w =>
{
w.Command("""
INSERT INTO incident (at, level, signal, url, stopped_until, resolved_at, session_id, note)
VALUES (@at, @l, @s, @u, @su, @r, @sid, @n)
""")
.With("@at", Sql.Time(incident.At)).With("@l", Sql.Enum(incident.Level)).With("@s", incident.Signal)
.With("@u", Sql.Text(incident.Url)).With("@su", Sql.Time(incident.StoppedUntil)).With("@r", Sql.Time(incident.ResolvedAt))
.With("@sid", Sql.Int(incident.SessionId)).With("@n", Sql.Text(incident.Note))
.ExecuteNonQuery();
return incident with { Id = w.LastInsertRowId() };
},
ct);
}
public Task ResolveAsync(long incidentId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
if (w.Command("UPDATE incident SET resolved_at = COALESCE(resolved_at, @at) WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", incidentId).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Arresto {incidentId} non trovato.");
}
},
ct);
public Task<Incident?> GetAsync(long incidentId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE id = @id").With("@id", incidentId)).FirstOrDefault(), ct);
public Task<IReadOnlyList<Incident>> ListOpenAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Incident>>(c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE resolved_at IS NULL ORDER BY at, id")), ct);
public Task<IReadOnlyList<Incident>> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Incident>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM incident WHERE at >= @f AND at < @t ORDER BY at, id")
.With("@f", Sql.Time(from)).With("@t", Sql.Time(to))),
ct);
public Task<int> CountAsync(SignalLevel level, DateTimeOffset since, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("SELECT COUNT(*) FROM incident WHERE level = @l AND at >= @s")
.With("@l", Sql.Enum(level)).With("@s", Sql.Time(since)).ScalarInt64(),
ct);
}
internal sealed class EventStore(FebeDatabase db) : IEventStore
{
private const string Columns = "id, at, severity, code, message, account_id, session_id";
private static EventRecord Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
At = r.GetTime(1),
Severity = r.GetEnum<EventSeverity>(2),
Code = r.GetString(3),
Message = r.GetString(4),
AccountId = r.GetInt64OrNull(5),
SessionId = r.GetInt64OrNull(6),
};
private static List<EventRecord> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<EventRecord>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<EventRecord> AppendAsync(EventRecord record, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentException.ThrowIfNullOrWhiteSpace(record.Code);
ArgumentNullException.ThrowIfNull(record.Message);
return db.WriteAsync(
w =>
{
w.Command("INSERT INTO event (at, severity, code, message, account_id, session_id) VALUES (@at, @sv, @c, @m, @a, @s)")
.With("@at", Sql.Time(record.At)).With("@sv", Sql.Enum(record.Severity)).With("@c", record.Code)
.With("@m", record.Message).With("@a", Sql.Int(record.AccountId)).With("@s", Sql.Int(record.SessionId))
.ExecuteNonQuery();
return record with { Id = w.LastInsertRowId() };
},
ct);
}
public Task<IReadOnlyList<EventRecord>> ListAsync(EventQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
var severities = Enum.GetValues<EventSeverity>().Where(s => query.MinSeverity is null || s >= query.MinSeverity).Select(s => s.ToString());
return db.ReadAsync<IReadOnlyList<EventRecord>>(
c =>
{
var command = c.Command(string.Empty);
var list = command.AddList("sv", severities);
command.CommandText = $"""
SELECT {Columns} FROM event
WHERE (@before IS NULL OR id < @before) AND (@a IS NULL OR account_id = @a) AND severity IN ({list})
AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t)
ORDER BY id DESC LIMIT @limit
""";
command.With("@before", Sql.Int(query.BeforeId)).With("@a", Sql.Int(query.AccountId))
.With("@f", Sql.Time(query.From)).With("@t", Sql.Time(query.To))
.With("@limit", (long)Math.Clamp(query.Limit, 1, 1000));
return ReadAll(command);
},
ct);
}
public Task<IReadOnlyList<EventRecord>> ListAfterAsync(long afterId, int limit = 200, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<EventRecord>>(
c => ReadAll(c.Command($"SELECT {Columns} FROM event WHERE id > @after ORDER BY id LIMIT @limit")
.With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 1000))),
ct);
public Task<int> PruneAsync(DateTimeOffset before, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM event WHERE at < @b").With("@b", Sql.Time(before)).ExecuteNonQuery(), ct);
}
internal sealed class FollowingStore(FebeDatabase db) : IFollowingStore
{
public Task UpsertAsync(IReadOnlyList<FollowingRecord> records, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(records);
return db.WriteAsync(
w =>
{
foreach (var record in records)
{
ArgumentException.ThrowIfNullOrWhiteSpace(record.Username);
var instagramId = EntryMapping.NormalizeId(record.InstagramId);
var username = record.Username.Trim().TrimStart('@');
object? id = null;
if (instagramId is not null)
{
id = w.Command("SELECT id FROM \"following\" WHERE instagram_id = @i").With("@i", instagramId).ExecuteScalar();
}
id ??= w.Command("SELECT id FROM \"following\" WHERE username = @u AND (instagram_id IS NULL OR @i IS NULL) ORDER BY id LIMIT 1")
.With("@u", username).With("@i", Sql.Text(instagramId)).ExecuteScalar();
if (id is long existing)
{
w.Command("""
UPDATE "following" SET instagram_id = COALESCE(@i, instagram_id), username = @u, display_name = @d,
is_private = @p, position = @pos, read_at = @r
WHERE id = @id
""")
.With("@i", Sql.Text(instagramId)).With("@u", username).With("@d", Sql.Text(record.DisplayName))
.With("@p", Sql.Bool(record.IsPrivate)).With("@pos", (long)record.Position).With("@r", Sql.Time(record.ReadAt))
.With("@id", existing).ExecuteNonQuery();
}
else
{
w.Command("""
INSERT INTO "following" (instagram_id, username, display_name, is_private, position, read_at)
VALUES (@i, @u, @d, @p, @pos, @r)
""")
.With("@i", Sql.Text(instagramId)).With("@u", username).With("@d", Sql.Text(record.DisplayName))
.With("@p", Sql.Bool(record.IsPrivate)).With("@pos", (long)record.Position).With("@r", Sql.Time(record.ReadAt))
.ExecuteNonQuery();
}
}
},
ct);
}
public Task<IReadOnlyList<FollowingRecord>> ListAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<FollowingRecord>>(
c =>
{
using var r = c.Command("""
SELECT instagram_id, username, display_name, is_private, position, read_at FROM "following" ORDER BY position, id
""").ExecuteReader();
var list = new List<FollowingRecord>();
while (r.Read())
{
list.Add(new FollowingRecord
{
InstagramId = r.GetTextOrNull(0),
Username = r.GetString(1),
DisplayName = r.GetTextOrNull(2),
IsPrivate = r.GetBoolOrNull(3),
Position = r.GetInt32(4),
ReadAt = r.GetTime(5),
});
}
return list;
},
ct);
public Task<int> CountAsync(CancellationToken ct = default) =>
db.ReadAsync(c => (int)c.Command("SELECT COUNT(*) FROM \"following\"").ScalarInt64(), ct);
public Task<DateTimeOffset?> GetLastReadAtAsync(CancellationToken ct = default) =>
db.ReadAsync(
c => c.Command("SELECT MAX(read_at) FROM \"following\"").ExecuteScalar() is long ms ? Sql.ToTime(ms) : (DateTimeOffset?)null,
ct);
public Task<int> RemoveNotReadSinceAsync(DateTimeOffset readStartedAt, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM \"following\" WHERE read_at < @s").With("@s", Sql.Time(readStartedAt)).ExecuteNonQuery(), ct);
public Task ClearAsync(CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM \"following\"").ExecuteNonQuery(), ct);
}
internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore
{
public Task<string?> GetAsync(string key, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
return db.ReadAsync(c => c.Command("SELECT value FROM setting WHERE key = @k").With("@k", key).ExecuteScalar() as string, ct);
}
public Task SetAsync(string key, string? value, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
return db.WriteAsync(w => Set(w, key, value), ct);
}
public Task SetManyAsync(IReadOnlyDictionary<string, string?> values, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(values);
foreach (var key in values.Keys)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
}
return db.WriteAsync(
w =>
{
foreach (var (key, value) in values)
{
Set(w, key, value);
}
},
ct);
}
public Task<IReadOnlyDictionary<string, string>> GetAllAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<string, string>>(
c =>
{
using var r = c.Command("SELECT key, value FROM setting ORDER BY key").ExecuteReader();
var values = new Dictionary<string, string>(StringComparer.Ordinal);
while (r.Read())
{
values[r.GetString(0)] = r.GetString(1);
}
return values;
},
ct);
private static void Set(WriteContext w, string key, string? value)
{
if (value is null)
{
w.Command("DELETE FROM setting WHERE key = @k").With("@k", key).ExecuteNonQuery();
}
else
{
w.Command("INSERT INTO setting (key, value) VALUES (@k, @v) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
.With("@k", key).With("@v", value).ExecuteNonQuery();
}
}
}
+191
View File
@@ -0,0 +1,191 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
/// <summary>Column lists and readers shared by the entry, media and highlight stores.</summary>
internal static class EntryMapping
{
public const string EntryColumns =
"e.id, e.account_id, e.kind, e.instagram_id, e.code, e.published_at, e.caption, e.author_username, e.author_instagram_id, "
+ "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at";
public const int EntryColumnCount = 15;
public const string MediaColumns =
"m.id, m.entry_id, m.position, m.kind, m.instagram_id, m.width, m.height, m.duration_ms, m.state, m.relative_path, m.bytes, "
+ "m.sha256, m.phash, m.has_thumbnail, m.source_url, m.cover_url, m.source_seen_at, m.attempts, m.last_error, m.downloaded_at";
public const int MediaColumnCount = 20;
/// <summary>
/// Tile columns; the query must join <c>media c</c> (the cover, see <see cref="TileFrom"/>). The user name is a
/// correlated subquery on purpose: with a join, SQLite (with ANALYZE statistics) drives the query from the small
/// account table and sorts every entry, which costs a second on 200,000 entries instead of a millisecond.
/// </summary>
public const string TileColumns =
"e.id, e.account_id, (SELECT a.username FROM account a WHERE a.id = e.account_id), e.kind, e.published_at, e.state, e.provenance, "
+ "(SELECT COUNT(*) FROM media mc WHERE mc.entry_id = e.id), "
+ "c.id, c.kind, c.width, c.height, c.duration_ms, c.sha256, c.has_thumbnail";
/// <summary>The cover is the first file present, or the first file.</summary>
public const string TileFrom =
"FROM entry e "
+ "LEFT JOIN media c ON c.id = (SELECT m1.id FROM media m1 WHERE m1.entry_id = e.id "
+ "ORDER BY (m1.state IN ('Downloaded', 'Imported')) DESC, m1.position LIMIT 1)";
public static readonly string VisibleStates = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'"));
public static Entry ReadEntry(SqliteDataReader r, int o = 0) => new()
{
Id = r.GetInt64(o),
AccountId = r.GetInt64(o + 1),
Kind = r.GetEnum<EntryKind>(o + 2),
InstagramId = r.GetTextOrNull(o + 3),
Code = r.GetTextOrNull(o + 4),
PublishedAt = r.GetTime(o + 5),
Caption = r.GetTextOrNull(o + 6),
AuthorUsername = r.GetTextOrNull(o + 7),
AuthorInstagramId = r.GetTextOrNull(o + 8),
State = r.GetEnum<EntryState>(o + 9),
Provenance = r.GetEnum<Provenance>(o + 10),
DiscoveredAt = r.GetTime(o + 11),
DownloadedAt = r.GetTimeOrNull(o + 12),
DeletedAt = r.GetTimeOrNull(o + 13),
ExpiresAt = r.GetTimeOrNull(o + 14),
};
public static Media ReadMedia(SqliteDataReader r, int o = 0) => new()
{
Id = r.GetInt64(o),
EntryId = r.GetInt64(o + 1),
Position = r.GetInt32(o + 2),
Kind = r.GetEnum<MediaKind>(o + 3),
InstagramId = r.GetTextOrNull(o + 4),
Width = r.GetInt32OrNull(o + 5),
Height = r.GetInt32OrNull(o + 6),
Duration = r.GetDurationOrNull(o + 7),
State = r.GetEnum<MediaState>(o + 8),
RelativePath = r.GetTextOrNull(o + 9),
Bytes = r.GetInt64OrNull(o + 10),
Sha256 = r.GetTextOrNull(o + 11),
PerceptualHash = r.GetHashOrNull(o + 12),
HasThumbnail = r.GetBool(o + 13),
SourceUrl = r.GetTextOrNull(o + 14),
CoverUrl = r.GetTextOrNull(o + 15),
SourceSeenAt = r.GetTimeOrNull(o + 16),
Attempts = r.GetInt32(o + 17),
LastError = r.GetTextOrNull(o + 18),
DownloadedAt = r.GetTimeOrNull(o + 19),
};
public static Core.Storage.LibraryTile ReadTile(SqliteDataReader r) => new(
EntryId: r.GetInt64(0),
AccountId: r.GetInt64(1),
Username: r.GetString(2),
Kind: r.GetEnum<EntryKind>(3),
PublishedAt: r.GetTime(4),
State: r.GetEnum<EntryState>(5),
Provenance: r.GetEnum<Provenance>(6),
MediaCount: r.GetInt32(7),
CoverMediaId: r.GetInt64OrNull(8),
CoverKind: r.GetEnumOrNull<MediaKind>(9),
CoverWidth: r.GetInt32OrNull(10),
CoverHeight: r.GetInt32OrNull(11),
CoverDuration: r.GetDurationOrNull(12),
CoverSha256: r.GetTextOrNull(13),
CoverHasThumbnail: !r.IsDBNull(14) && r.GetBool(14));
public static void BindEntry(SqliteCommand c, Entry e) =>
c.With("@account_id", e.AccountId)
.With("@kind", Sql.Enum(e.Kind))
.With("@instagram_id", Sql.Text(NormalizeId(e.InstagramId)))
.With("@code", Sql.Text(e.Code))
.With("@published_at", Sql.Time(e.PublishedAt))
.With("@caption", Sql.Text(e.Caption))
.With("@author_username", Sql.Text(e.AuthorUsername))
.With("@author_instagram_id", Sql.Text(e.AuthorInstagramId))
.With("@state", Sql.Enum(e.State))
.With("@provenance", Sql.Enum(e.Provenance))
.With("@discovered_at", Sql.Time(e.DiscoveredAt))
.With("@downloaded_at", Sql.Time(e.DownloadedAt))
.With("@deleted_at", Sql.Time(e.DeletedAt))
.With("@expires_at", Sql.Time(e.ExpiresAt))
.With("@search_text", TextSearch.ForEntry(e.Caption, e.AuthorUsername));
public static void BindMedia(SqliteCommand c, Media m) =>
c.With("@entry_id", m.EntryId)
.With("@position", (long)m.Position)
.With("@kind", Sql.Enum(m.Kind))
.With("@instagram_id", Sql.Text(NormalizeId(m.InstagramId)))
.With("@width", Sql.Int(m.Width))
.With("@height", Sql.Int(m.Height))
.With("@duration_ms", Sql.Duration(m.Duration))
.With("@state", Sql.Enum(m.State))
.With("@relative_path", Sql.Text(m.RelativePath))
.With("@bytes", Sql.Int(m.Bytes))
.With("@sha256", Sql.Text(m.Sha256?.ToLowerInvariant()))
.With("@phash", Sql.Hash(m.PerceptualHash))
.With("@has_thumbnail", Sql.Bool(m.HasThumbnail))
.With("@source_url", Sql.Text(m.SourceUrl))
.With("@cover_url", Sql.Text(m.CoverUrl))
.With("@source_seen_at", Sql.Time(m.SourceSeenAt))
.With("@attempts", (long)m.Attempts)
.With("@last_error", Sql.Text(m.LastError))
.With("@downloaded_at", Sql.Time(m.DownloadedAt));
public const string InsertMediaSql = """
INSERT INTO media (entry_id, position, kind, instagram_id, width, height, duration_ms, state, relative_path, bytes, sha256, phash,
has_thumbnail, source_url, cover_url, source_seen_at, attempts, last_error, downloaded_at)
VALUES (@entry_id, @position, @kind, @instagram_id, @width, @height, @duration_ms, @state, @relative_path, @bytes, @sha256, @phash,
@has_thumbnail, @source_url, @cover_url, @source_seen_at, @attempts, @last_error, @downloaded_at)
""";
public static string? NormalizeId(string? id) => string.IsNullOrWhiteSpace(id) ? null : id.Trim();
/// <summary>Files of an entry; <paramref name="command"/> creates (or reuses) a command for a SQL text.</summary>
public static List<Media> ReadMediaOf(Func<string, SqliteCommand> command, long entryId)
{
using var r = command($"SELECT {MediaColumns} FROM media m WHERE m.entry_id = @e ORDER BY m.position")
.With("@e", entryId).ExecuteReader();
var list = new List<Media>();
while (r.Read())
{
list.Add(ReadMedia(r));
}
return list;
}
public static Entry? ReadEntryById(Func<string, SqliteCommand> command, long entryId)
{
using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.id = @id").With("@id", entryId).ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
}
/// <summary>Recomputes and stores the state of an entry from its files. Returns the new state.</summary>
public static EntryState RecomputeState(WriteContext w, long entryId, DateTimeOffset? downloadedAt = null)
{
var entry = ReadEntryById(w.Command, entryId)
?? throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
var states = new List<MediaState>();
using (var r = w.Command("SELECT state FROM media WHERE entry_id = @e").With("@e", entryId).ExecuteReader())
{
while (r.Read())
{
states.Add(r.GetEnum<MediaState>(0));
}
}
var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, states);
var becameComplete = state is EntryState.Downloaded or EntryState.Imported && entry.DownloadedAt is null;
w.Command("UPDATE entry SET state = @s, downloaded_at = CASE WHEN @c = 1 THEN @d ELSE downloaded_at END WHERE id = @id")
.With("@s", Sql.Enum(state))
.With("@c", becameComplete && downloadedAt is not null ? 1L : 0L)
.With("@d", Sql.Time(downloadedAt))
.With("@id", entryId)
.ExecuteNonQuery();
return state;
}
}
+521
View File
@@ -0,0 +1,521 @@
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
using static Febe.Data.Stores.EntryMapping;
namespace Febe.Data.Stores;
internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
public Task<Entry?> GetAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadEntryById(sql => c.Command(sql), entryId), ct);
public Task<EntryWithMedia?> GetWithMediaAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var entry = ReadEntryById(sql => c.Command(sql), entryId);
return entry is null ? null : new EntryWithMedia(entry, ReadMediaOf(sql => c.Command(sql), entryId));
},
ct);
public Task<Entry?> FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync(c => FindIdentity(sql => c.Command(sql), accountId, kind, instagramId.Trim()), ct);
}
public async Task<bool> IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) =>
await FindAsync(accountId, kind, instagramId, ct).ConfigureAwait(false) is not null;
public Task<IReadOnlySet<string>> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection<string> instagramIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(instagramIds);
var ids = instagramIds.Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).Distinct(StringComparer.Ordinal).ToList();
return db.ReadAsync<IReadOnlySet<string>>(
c =>
{
var known = new HashSet<string>(StringComparer.Ordinal);
foreach (var chunk in ids.Chunk(500))
{
var command = c.Command(string.Empty).With("@a", accountId).With("@k", Sql.Enum(kind));
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT instagram_id FROM entry WHERE account_id = @a AND kind = @k AND instagram_id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
known.Add(r.GetString(0));
}
}
return known;
},
ct);
}
public Task<IReadOnlyList<Entry>> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync<IReadOnlyList<Entry>>(
c => ReadEntries(c.Command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.instagram_id = @i ORDER BY e.id")
.With("@a", accountId).With("@i", instagramId.Trim())),
ct);
}
public Task<Entry?> FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default)
{
var ms = Sql.Time(publishedAt);
var tol = (long)Math.Abs(tolerance.TotalMilliseconds);
return db.ReadAsync(
c =>
{
using var r = c.Command($"""
SELECT {EntryColumns} FROM entry e
WHERE e.account_id = @a AND e.kind = @k AND e.published_at BETWEEN @from AND @to
ORDER BY abs(e.published_at - @p), e.id LIMIT 1
""")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@from", ms - tol).With("@to", ms + tol).With("@p", ms)
.ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
},
ct);
}
public Task<AddEntryResult> AddAsync(Entry entry, IReadOnlyList<Media> media, CancellationToken ct = default)
{
Validate(entry, media);
return db.WriteAsync(w => Add(w, entry, media), ct);
}
public Task<IReadOnlyList<AddEntryResult>> AddManyAsync(IReadOnlyList<NewEntry> entries, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entries);
foreach (var item in entries)
{
Validate(item.Entry, item.Media);
}
return db.WriteAsync<IReadOnlyList<AddEntryResult>>(w => entries.Select(item => Add(w, item.Entry, item.Media)).ToList(), ct);
}
public Task UpdateAsync(Entry entry, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entry);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption,
author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state,
provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at,
deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text
WHERE id = @id
""");
BindEntry(c, entry);
c.With("@id", entry.Id);
try
{
if (c.ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entry.Id} non trovato.");
}
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException("Esiste già un elemento con lo stesso identificativo Instagram per questo account e tipo.", ex);
}
},
ct);
}
public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
if (w.Command("UPDATE entry SET state = @s WHERE id = @id").With("@s", Sql.Enum(state)).With("@id", entryId).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
},
ct);
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => RecomputeState(w, entryId), ct);
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery();
if (rows == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
w.Command("""
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
WHERE entry_id = @id
""").With("@id", entryId).ExecuteNonQuery();
},
ct);
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct);
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
{
options ??= new EntryListOptions();
return db.ReadAsync<IReadOnlyList<Entry>>(
c =>
{
var command = c.Command(string.Empty).With("@a", accountId).With("@limit", (long)Math.Clamp(options.Limit, 1, 10_000));
var sql = new StringBuilder($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a");
if (options.Kind is { } kind)
{
sql.Append(" AND e.kind = @k");
command.With("@k", Sql.Enum(kind));
}
if (options.States is { Count: > 0 } states)
{
sql.Append(" AND e.state IN (").Append(command.AddList("s", states.Select(s => s.ToString()))).Append(')');
}
if (options.Before is { } before)
{
sql.Append(" AND (e.published_at, e.id) < (@bp, @bi)");
command.With("@bp", Sql.Time(before.PublishedAt)).With("@bi", before.EntryId);
}
sql.Append(" ORDER BY e.published_at DESC, e.id DESC LIMIT @limit");
command.CommandText = sql.ToString();
return ReadEntries(command);
},
ct);
}
public Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("""
SELECT COUNT(*) FROM entry WHERE account_id = @a AND kind = @k AND discovered_at >= @f AND discovered_at < @t
""").With("@a", accountId).With("@k", Sql.Enum(kind)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64(),
ct);
public Task<LibraryPage> QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
var limit = Math.Clamp(query.Limit, 1, 1000);
return db.ReadAsync(
c =>
{
// Phase 1: keys only, so that sorting never computes the tile columns of rows outside the window.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, query.Filter);
var newer = query.Direction == LibraryDirection.Newer;
var sql = new StringBuilder($"SELECT e.id FROM entry e WHERE {where}");
if (query.Cursor is { } cursor)
{
sql.Append(newer ? " AND (e.published_at, e.id) > (@cp, @ci)" : " AND (e.published_at, e.id) < (@cp, @ci)");
command.With("@cp", Sql.Time(cursor.PublishedAt)).With("@ci", cursor.EntryId);
}
// With a text search the whole table is scanned and the matches sorted: about a tenth of a second on
// 200,000 entries whether the word is rare or common, instead of walking the index row by row.
var order = string.IsNullOrWhiteSpace(query.Filter.Search) ? "e.published_at" : "+e.published_at";
sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC");
sql.Append(" LIMIT @limit");
command.With("@limit", (long)limit + 1);
command.CommandText = sql.ToString();
var ids = new List<long>(limit + 1);
using (var r = command.ExecuteReader())
{
while (r.Read())
{
ids.Add(r.GetInt64(0));
}
}
var moreInDirection = ids.Count > limit;
if (moreInDirection)
{
ids.RemoveAt(ids.Count - 1);
}
if (newer)
{
ids.Reverse();
}
// Phase 2: the tiles of the window, in display order.
var tiles = TilesOf(c, ids);
if (tiles.Count == 0)
{
return new LibraryPage(tiles, null, null);
}
var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId);
var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId);
bool hasOlder, hasNewer;
if (newer)
{
hasNewer = moreInDirection;
hasOlder = Exists(c, query.Filter, last, older: true);
}
else
{
hasOlder = moreInDirection;
hasNewer = query.Cursor is not null && Exists(c, query.Filter, first, older: false);
}
return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null);
},
ct);
}
public Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}";
using var r = command.ExecuteReader();
r.Read();
return new LibraryTotals(r.GetInt32(0), r.GetInt32(1));
},
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
ArgumentNullException.ThrowIfNull(zone);
return db.ReadAsync<IReadOnlyList<DayCount>>(
c =>
{
// Stream the publication times in index order and fold them into local days here: no time zone logic
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
DateOnly day = default;
var count = 0;
using (var r = command.ExecuteReader())
{
while (r.Read())
{
var ms = r.GetInt64(0);
if (ms < dayStart || ms >= dayEnd)
{
if (count > 0)
{
days.Add(new DayCount(day, count));
}
day = LocalCalendar.Today(Sql.ToTime(ms), zone);
var (start, end) = LocalCalendar.DayBounds(day, zone);
(dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0);
}
count++;
}
}
if (count > 0)
{
days.Add(new DayCount(day, count));
}
days.Reverse();
return days;
},
ct);
}
public Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyList<LibraryTile>>(c => TilesOf(c, entryIds), ct);
}
// ---------------------------------------------------------------------------------------------
/// <summary>Tiles of the given entries, in the given order (unknown keys are skipped).</summary>
private static List<LibraryTile> TilesOf(SqliteConnection c, IReadOnlyList<long> entryIds)
{
var byId = new Dictionary<long, LibraryTile>(entryIds.Count);
foreach (var chunk in entryIds.Distinct().Chunk(500))
{
using var command = c.Command(string.Empty);
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT {TileColumns} {TileFrom} WHERE e.id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
var tile = ReadTile(r);
byId[tile.EntryId] = tile;
}
}
return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList();
}
private static void Validate(Entry entry, IReadOnlyList<Media> media)
{
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(media);
if (media.Select(m => m.Position).Distinct().Count() != media.Count)
{
throw new ArgumentException("Le posizioni dei file di un elemento devono essere distinte.", nameof(media));
}
if (media.Any(m => m.Position < 1))
{
throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media));
}
}
private static AddEntryResult Add(WriteContext w, Entry entry, IReadOnlyList<Media> media)
{
var instagramId = NormalizeId(entry.InstagramId);
if (instagramId is not null && FindIdentity(w.Command, entry.AccountId, entry.Kind, instagramId) is { } existing)
{
return new AddEntryResult(new EntryWithMedia(existing, ReadMediaOf(w.Command, existing.Id)), false);
}
var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, media.Select(m => m.State).ToList());
var stored = entry with { InstagramId = instagramId, State = state };
var insert = w.Command("""
INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state,
provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text)
VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state,
@provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text)
""");
BindEntry(insert, stored);
insert.ExecuteNonQuery();
var entryId = w.LastInsertRowId();
stored = stored with { Id = entryId };
var files = new List<Media>(media.Count);
foreach (var file in media.OrderBy(m => m.Position))
{
var row = file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) };
var command = w.Command(InsertMediaSql);
BindMedia(command, row);
command.ExecuteNonQuery();
files.Add(row with { Id = w.LastInsertRowId() });
}
return new AddEntryResult(new EntryWithMedia(stored, files), true);
}
private static Entry? FindIdentity(Func<string, SqliteCommand> command, long accountId, EntryKind kind, string instagramId)
{
using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.instagram_id = @i")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@i", instagramId).ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
}
private static List<Entry> ReadEntries(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<Entry>();
while (r.Read())
{
list.Add(ReadEntry(r));
}
return list;
}
private static bool Exists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId);
return command.ScalarInt64() != 0;
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter)
{
var parts = new List<string>();
var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible;
// The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the
// publication index is what keeps a window fast over 200,000 entries, with or without ANALYZE statistics.
parts.Add($"+e.state IN ({command.AddList("st", states.Select(x => x.ToString()))})");
parts.Add(filter.Kind switch
{
LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')",
LibraryKindFilter.Posts => "e.kind = 'Post'",
LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')",
LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')",
LibraryKindFilter.Stories => "e.kind = 'Story'",
LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))",
LibraryKindFilter.Tagged => "e.kind = 'Tagged'",
LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null),
});
if (filter.AccountIds is { } accounts)
{
parts.Add($"e.account_id IN ({command.AddList("ac", accounts)})");
}
if (filter.From is { } from)
{
parts.Add("e.published_at >= @from");
command.With("@from", Sql.Time(from));
}
if (filter.To is { } to)
{
parts.Add("e.published_at < @to");
command.With("@to", Sql.Time(to));
}
if (filter.Provenance is { } provenance)
{
parts.Add("e.provenance = @prov");
command.With("@prov", Sql.Enum(provenance));
}
var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0)
{
// Accounts are few: match their names here, accent-insensitively, then filter entries by key.
var matching = new List<long>();
using (var r = c.Command("SELECT id, username, display_name FROM account").ExecuteReader())
{
while (r.Read())
{
var name = TextSearch.Normalize(r.GetString(1));
var display = TextSearch.Normalize(r.GetTextOrNull(2));
var bare = term.TrimStart('@');
if (name.Contains(bare, StringComparison.Ordinal) || display.Contains(term, StringComparison.Ordinal))
{
matching.Add(r.GetInt64(0));
}
}
}
command.With("@q", TextSearch.LikePattern(term));
parts.Add(matching.Count == 0
? "e.search_text LIKE @q ESCAPE '\\'"
: $"(e.search_text LIKE @q ESCAPE '\\' OR e.account_id IN ({command.AddList("sa", matching)}))");
}
return string.Join(" AND ", parts);
}
}
+195
View File
@@ -0,0 +1,195 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class HighlightStore(FebeDatabase db) : IHighlightStore
{
private const string Columns = "h.id, h.account_id, h.instagram_id, h.title, h.position, h.discovered_at, h.last_checked_at, h.removed_at";
private static Highlight Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
AccountId = r.GetInt64(1),
InstagramId = r.GetTextOrNull(2),
Title = r.GetString(3),
Position = r.GetInt32(4),
DiscoveredAt = r.GetTime(5),
LastCheckedAt = r.GetTimeOrNull(6),
RemovedAt = r.GetTimeOrNull(7),
};
private static List<Highlight> ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<Highlight>();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
public Task<Highlight?> GetAsync(long highlightId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM highlight h WHERE h.id = @id").With("@id", highlightId)).FirstOrDefault(), ct);
public Task<IReadOnlyList<Highlight>> ListAsync(long accountId, bool includeRemoved = false, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Highlight>>(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM highlight h WHERE h.account_id = @a {(includeRemoved ? string.Empty : "AND h.removed_at IS NULL")}
ORDER BY h.removed_at IS NOT NULL, h.position, h.id
""").With("@a", accountId)),
ct);
public Task<Highlight?> FindAsync(long accountId, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync(
c => ReadAll(c.Command($"SELECT {Columns} FROM highlight h WHERE h.account_id = @a AND h.instagram_id = @i")
.With("@a", accountId).With("@i", instagramId.Trim())).FirstOrDefault(),
ct);
}
public Task<Highlight?> FindByTitleAsync(long accountId, string title, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(title);
return db.ReadAsync(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM highlight h WHERE h.account_id = @a AND h.title = @t
ORDER BY h.removed_at IS NOT NULL, h.id LIMIT 1
""").With("@a", accountId).With("@t", title)).FirstOrDefault(),
ct);
}
public Task<Highlight> UpsertAsync(Highlight highlight, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(highlight);
ArgumentException.ThrowIfNullOrWhiteSpace(highlight.Title);
var instagramId = EntryMapping.NormalizeId(highlight.InstagramId);
return db.WriteAsync(
w =>
{
long? id = highlight.Id > 0 ? highlight.Id : null;
if (id is null && instagramId is not null)
{
id = w.Command("SELECT id FROM highlight WHERE account_id = @a AND instagram_id = @i")
.With("@a", highlight.AccountId).With("@i", instagramId).ExecuteScalar() as long?;
}
if (id is { } existing)
{
var exists = w.Command("SELECT COUNT(*) FROM highlight WHERE id = @id AND account_id = @a")
.With("@id", existing).With("@a", highlight.AccountId).ScalarInt64() > 0;
if (!exists)
{
throw new KeyNotFoundException($"Raccolta {existing} non trovata per l'account {highlight.AccountId}.");
}
w.Command("""
UPDATE highlight SET instagram_id = COALESCE(@i, instagram_id), title = @t, position = @p,
last_checked_at = COALESCE(@lc, last_checked_at), removed_at = @r
WHERE id = @id
""")
.With("@i", Sql.Text(instagramId))
.With("@t", highlight.Title)
.With("@p", (long)highlight.Position)
.With("@lc", Sql.Time(highlight.LastCheckedAt))
.With("@r", Sql.Time(highlight.RemovedAt))
.With("@id", existing)
.ExecuteNonQuery();
}
else
{
w.Command("""
INSERT INTO highlight (account_id, instagram_id, title, position, discovered_at, last_checked_at, removed_at)
VALUES (@a, @i, @t, @p, @d, @lc, @r)
""")
.With("@a", highlight.AccountId)
.With("@i", Sql.Text(instagramId))
.With("@t", highlight.Title)
.With("@p", (long)highlight.Position)
.With("@d", Sql.Time(highlight.DiscoveredAt))
.With("@lc", Sql.Time(highlight.LastCheckedAt))
.With("@r", Sql.Time(highlight.RemovedAt))
.ExecuteNonQuery();
id = w.LastInsertRowId();
}
return ReadAll(w.Command($"SELECT {Columns} FROM highlight h WHERE h.id = @id").With("@id", id.Value)).Single();
},
ct);
}
public Task SetOrderAsync(long accountId, IReadOnlyList<long> highlightIdsInOrder, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(highlightIdsInOrder);
return db.WriteAsync(
w =>
{
for (var i = 0; i < highlightIdsInOrder.Count; i++)
{
w.Command("UPDATE highlight SET position = @p WHERE id = @id AND account_id = @a")
.With("@p", (long)i).With("@id", highlightIdsInOrder[i]).With("@a", accountId).ExecuteNonQuery();
}
},
ct);
}
public Task MarkRemovedAsync(long highlightId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE highlight SET removed_at = COALESCE(removed_at, @at) WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", highlightId).ExecuteNonQuery(),
ct);
public Task<IReadOnlyList<HighlightItem>> ListItemsAsync(long highlightId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<HighlightItem>>(
c =>
{
using var r = c.Command("SELECT highlight_id, entry_id, position FROM highlight_entry WHERE highlight_id = @h ORDER BY position, entry_id")
.With("@h", highlightId).ExecuteReader();
var list = new List<HighlightItem>();
while (r.Read())
{
list.Add(new HighlightItem(r.GetInt64(0), r.GetInt64(1), r.GetInt32(2)));
}
return list;
},
ct);
public Task SetItemsAsync(long highlightId, IReadOnlyList<long> entryIdsInOrder, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIdsInOrder);
return db.WriteAsync(
w =>
{
w.Command("DELETE FROM highlight_entry WHERE highlight_id = @h").With("@h", highlightId).ExecuteNonQuery();
var position = 0;
foreach (var entryId in entryIdsInOrder.Distinct())
{
w.Command("INSERT INTO highlight_entry (highlight_id, entry_id, position) VALUES (@h, @e, @p)")
.With("@h", highlightId).With("@e", entryId).With("@p", (long)position++).ExecuteNonQuery();
}
},
ct);
}
public Task AddItemAsync(long highlightId, long entryId, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("""
INSERT INTO highlight_entry (highlight_id, entry_id, position)
VALUES (@h, @e, (SELECT COALESCE(MAX(position) + 1, 0) FROM highlight_entry WHERE highlight_id = @h))
ON CONFLICT (highlight_id, entry_id) DO NOTHING
""").With("@h", highlightId).With("@e", entryId).ExecuteNonQuery(),
ct);
public Task<IReadOnlyList<Highlight>> ListForEntryAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Highlight>>(
c => ReadAll(c.Command($"""
SELECT {Columns} FROM highlight h JOIN highlight_entry he ON he.highlight_id = h.id
WHERE he.entry_id = @e ORDER BY h.position, h.id
""").With("@e", entryId)),
ct);
}
+311
View File
@@ -0,0 +1,311 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class ImportStore(FebeDatabase db) : IImportStore
{
private const string RunColumns = "id, source_path, source_read_only, mode, state, started_at, analyzed_at, completed_at, last_error";
private const string FileColumns =
"id, run_id, relative_path, folder, bytes, modified_at, media_kind, content_type, width, height, duration_ms, sha256, phash, "
+ "taken_at, date_source, instagram_id, code, probable_account, probable_kind, highlight_title, outcome, matched_media_id, "
+ "target_account_id, decision, state, entry_id, destination_path, last_error";
private static ImportRun ReadRun(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
SourcePath = r.GetString(1),
SourceReadOnly = r.GetBool(2),
Mode = r.GetEnum<ImportMode>(3),
State = r.GetEnum<ImportRunState>(4),
StartedAt = r.GetTime(5),
AnalyzedAt = r.GetTimeOrNull(6),
CompletedAt = r.GetTimeOrNull(7),
LastError = r.GetTextOrNull(8),
};
private static ImportFile ReadFile(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
RunId = r.GetInt64(1),
RelativePath = r.GetString(2),
Folder = r.GetString(3),
Bytes = r.GetInt64(4),
ModifiedAt = r.GetTimeOrNull(5),
MediaKind = r.GetEnumOrNull<MediaKind>(6),
ContentType = r.GetTextOrNull(7),
Width = r.GetInt32OrNull(8),
Height = r.GetInt32OrNull(9),
Duration = r.GetDurationOrNull(10),
Sha256 = r.GetTextOrNull(11),
PerceptualHash = r.GetHashOrNull(12),
TakenAt = r.GetTimeOrNull(13),
DateSource = r.GetEnumOrNull<ImportDateSource>(14),
InstagramId = r.GetTextOrNull(15),
Code = r.GetTextOrNull(16),
ProbableAccount = r.GetTextOrNull(17),
ProbableKind = r.GetEnumOrNull<EntryKind>(18),
HighlightTitle = r.GetTextOrNull(19),
Outcome = r.GetEnum<ImportOutcome>(20),
MatchedMediaId = r.GetInt64OrNull(21),
TargetAccountId = r.GetInt64OrNull(22),
Decision = r.GetEnum<ImportDecision>(23),
State = r.GetEnum<ImportFileState>(24),
EntryId = r.GetInt64OrNull(25),
DestinationPath = r.GetTextOrNull(26),
LastError = r.GetTextOrNull(27),
};
private static List<ImportFile> ReadFiles(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<ImportFile>();
while (r.Read())
{
list.Add(ReadFile(r));
}
return list;
}
private static void BindRun(SqliteCommand c, ImportRun run) =>
c.With("@source_path", run.SourcePath)
.With("@source_read_only", Sql.Bool(run.SourceReadOnly))
.With("@mode", Sql.Enum(run.Mode))
.With("@state", Sql.Enum(run.State))
.With("@started_at", Sql.Time(run.StartedAt))
.With("@analyzed_at", Sql.Time(run.AnalyzedAt))
.With("@completed_at", Sql.Time(run.CompletedAt))
.With("@last_error", Sql.Text(run.LastError));
private static void BindFile(SqliteCommand c, ImportFile f) =>
c.With("@run_id", f.RunId)
.With("@relative_path", f.RelativePath)
.With("@folder", f.Folder)
.With("@bytes", f.Bytes)
.With("@modified_at", Sql.Time(f.ModifiedAt))
.With("@media_kind", Sql.Enum(f.MediaKind))
.With("@content_type", Sql.Text(f.ContentType))
.With("@width", Sql.Int(f.Width))
.With("@height", Sql.Int(f.Height))
.With("@duration_ms", Sql.Duration(f.Duration))
.With("@sha256", Sql.Text(f.Sha256?.ToLowerInvariant()))
.With("@phash", Sql.Hash(f.PerceptualHash))
.With("@taken_at", Sql.Time(f.TakenAt))
.With("@date_source", Sql.Enum(f.DateSource))
.With("@instagram_id", Sql.Text(f.InstagramId))
.With("@code", Sql.Text(f.Code))
.With("@probable_account", Sql.Text(f.ProbableAccount))
.With("@probable_kind", Sql.Enum(f.ProbableKind))
.With("@highlight_title", Sql.Text(f.HighlightTitle))
.With("@outcome", Sql.Enum(f.Outcome))
.With("@matched_media_id", Sql.Int(f.MatchedMediaId))
.With("@target_account_id", Sql.Int(f.TargetAccountId))
.With("@decision", Sql.Enum(f.Decision))
.With("@state", Sql.Enum(f.State))
.With("@entry_id", Sql.Int(f.EntryId))
.With("@destination_path", Sql.Text(f.DestinationPath))
.With("@last_error", Sql.Text(f.LastError));
public Task<ImportRun> CreateRunAsync(ImportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
ArgumentException.ThrowIfNullOrWhiteSpace(run.SourcePath);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO import_run (source_path, source_read_only, mode, state, started_at, analyzed_at, completed_at, last_error)
VALUES (@source_path, @source_read_only, @mode, @state, @started_at, @analyzed_at, @completed_at, @last_error)
""");
BindRun(c, run);
c.ExecuteNonQuery();
return run with { Id = w.LastInsertRowId() };
},
ct);
}
public Task UpdateRunAsync(ImportRun run, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(run);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE import_run SET source_path = @source_path, source_read_only = @source_read_only, mode = @mode, state = @state,
started_at = @started_at, analyzed_at = @analyzed_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($"Importazione {run.Id} non trovata.");
}
},
ct);
}
public Task<ImportRun?> GetRunAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
using var r = c.Command($"SELECT {RunColumns} FROM import_run WHERE id = @id").With("@id", runId).ExecuteReader();
return r.Read() ? ReadRun(r) : null;
},
ct);
public Task<IReadOnlyList<ImportRun>> ListRunsAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ImportRun>>(
c =>
{
using var r = c.Command($"SELECT {RunColumns} FROM import_run ORDER BY started_at DESC, id DESC").ExecuteReader();
var list = new List<ImportRun>();
while (r.Read())
{
list.Add(ReadRun(r));
}
return list;
},
ct);
public Task AddFilesAsync(IReadOnlyList<ImportFile> files, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(files);
return db.WriteAsync(
w =>
{
foreach (var file in files)
{
var c = w.Command("""
INSERT INTO import_file (run_id, relative_path, folder, bytes, modified_at, media_kind, content_type, width, height,
duration_ms, sha256, phash, taken_at, date_source, instagram_id, code, probable_account, probable_kind,
highlight_title, outcome, matched_media_id, target_account_id, decision, state, entry_id, destination_path, last_error)
VALUES (@run_id, @relative_path, @folder, @bytes, @modified_at, @media_kind, @content_type, @width, @height,
@duration_ms, @sha256, @phash, @taken_at, @date_source, @instagram_id, @code, @probable_account, @probable_kind,
@highlight_title, @outcome, @matched_media_id, @target_account_id, @decision, @state, @entry_id, @destination_path, @last_error)
ON CONFLICT (run_id, relative_path) DO NOTHING
""");
BindFile(c, file);
c.ExecuteNonQuery();
}
},
ct);
}
public Task UpdateFileAsync(ImportFile file, CancellationToken ct = default) => UpdateFilesAsync([file], ct);
public Task UpdateFilesAsync(IReadOnlyList<ImportFile> files, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(files);
return db.WriteAsync(
w =>
{
foreach (var file in files)
{
var c = w.Command("""
UPDATE import_file SET relative_path = @relative_path, folder = @folder, bytes = @bytes, modified_at = @modified_at,
media_kind = @media_kind, content_type = @content_type, width = @width, height = @height, duration_ms = @duration_ms,
sha256 = @sha256, phash = @phash, taken_at = @taken_at, date_source = @date_source, instagram_id = @instagram_id,
code = @code, probable_account = @probable_account, probable_kind = @probable_kind, highlight_title = @highlight_title,
outcome = @outcome, matched_media_id = @matched_media_id, target_account_id = @target_account_id,
decision = @decision, state = @state, entry_id = @entry_id, destination_path = @destination_path, last_error = @last_error
WHERE id = @id AND run_id = @run_id
""");
BindFile(c, file);
if (c.With("@id", file.Id).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"File di importazione {file.Id} non trovato.");
}
}
},
ct);
}
public Task<ImportFile?> GetFileAsync(long fileId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE id = @id").With("@id", fileId)).FirstOrDefault(), ct);
public Task<ImportFile?> FindFileAsync(long runId, string relativePath, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(relativePath);
return db.ReadAsync(
c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE run_id = @r AND relative_path = @p")
.With("@r", runId).With("@p", relativePath)).FirstOrDefault(),
ct);
}
public Task<IReadOnlyList<ImportFile>> ListFilesAsync(ImportFileQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
return db.ReadAsync<IReadOnlyList<ImportFile>>(
c => ReadFiles(c.Command($"""
SELECT {FileColumns} FROM import_file
WHERE run_id = @r AND id > @after AND (@o IS NULL OR outcome = @o) AND (@s IS NULL OR state = @s) AND (@f IS NULL OR folder = @f)
ORDER BY id LIMIT @limit
""")
.With("@r", query.RunId).With("@after", query.AfterId).With("@o", Sql.Enum(query.Outcome)).With("@s", Sql.Enum(query.State))
.With("@f", Sql.Text(query.Folder)).With("@limit", (long)Math.Clamp(query.Limit, 1, 10_000))),
ct);
}
public Task<IReadOnlyList<ImportFile>> FindFilesBySha256Async(long runId, string sha256, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sha256);
return db.ReadAsync<IReadOnlyList<ImportFile>>(
c => ReadFiles(c.Command($"SELECT {FileColumns} FROM import_file WHERE run_id = @r AND sha256 = @h ORDER BY id")
.With("@r", runId).With("@h", sha256.Trim().ToLowerInvariant())),
ct);
}
public Task<ImportSummary> GetSummaryAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var byOutcome = Enum.GetValues<ImportOutcome>().ToDictionary(o => o, _ => 0);
var byState = Enum.GetValues<ImportFileState>().ToDictionary(s => s, _ => 0);
var total = 0;
long bytes = 0;
using var r = c.Command("SELECT outcome, state, COUNT(*), COALESCE(SUM(bytes), 0) FROM import_file WHERE run_id = @r GROUP BY outcome, state")
.With("@r", runId).ExecuteReader();
while (r.Read())
{
var count = r.GetInt32(2);
byOutcome[r.GetEnum<ImportOutcome>(0)] += count;
byState[r.GetEnum<ImportFileState>(1)] += count;
total += count;
bytes += r.GetInt64(3);
}
return new ImportSummary(total, byOutcome, byState, bytes);
},
ct);
public Task<IReadOnlyList<ImportFolder>> ListFoldersAsync(long runId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ImportFolder>>(
c =>
{
using var r = c.Command("""
SELECT folder, COUNT(*), MAX(probable_account), MAX(target_account_id) FROM import_file
WHERE run_id = @r GROUP BY folder ORDER BY folder
""").With("@r", runId).ExecuteReader();
var list = new List<ImportFolder>();
while (r.Read())
{
list.Add(new ImportFolder(r.GetString(0), r.GetInt32(1), r.GetTextOrNull(2), r.GetInt64OrNull(3)));
}
return list;
},
ct);
public Task SetFolderTargetAsync(long runId, string folder, long? accountId, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(folder);
return db.WriteAsync(
w => w.Command("UPDATE import_file SET target_account_id = @a WHERE run_id = @r AND folder = @f")
.With("@a", Sql.Int(accountId)).With("@r", runId).With("@f", folder).ExecuteNonQuery(),
ct);
}
}
+228
View File
@@ -0,0 +1,228 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using static Febe.Data.Stores.EntryMapping;
namespace Febe.Data.Stores;
internal sealed class MediaStore(FebeDatabase db) : IMediaStore
{
public Task<Media?> GetAsync(long mediaId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
using var r = c.Command($"SELECT {MediaColumns} FROM media m WHERE m.id = @id").With("@id", mediaId).ExecuteReader();
return r.Read() ? ReadMedia(r) : null;
},
ct);
public Task<IReadOnlyList<Media>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Media>>(c => ReadMediaOf(sql => c.Command(sql), entryId), ct);
public Task<IReadOnlyList<MediaLocation>> FindBySha256Async(string sha256, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sha256);
var key = sha256.Trim().ToLowerInvariant();
return db.ReadAsync<IReadOnlyList<MediaLocation>>(
c =>
{
using var r = c.Command($"""
SELECT {MediaColumns}, {EntryColumns}, a.username
FROM media m JOIN entry e ON e.id = m.entry_id JOIN account a ON a.id = e.account_id
WHERE m.sha256 = @h ORDER BY m.id
""").With("@h", key).ExecuteReader();
var list = new List<MediaLocation>();
while (r.Read())
{
list.Add(new MediaLocation(ReadMedia(r), ReadEntry(r, MediaColumnCount), r.GetString(MediaColumnCount + EntryColumnCount)));
}
return list;
},
ct);
}
public Task<IReadOnlyDictionary<string, long>> MapPathsAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<string, long>>(
c =>
{
using var r = c.Command("""
SELECT m.relative_path, m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.relative_path IS NOT NULL
""").With("@a", accountId).ExecuteReader();
var map = new Dictionary<string, long>(StringComparer.Ordinal);
while (r.Read())
{
map[r.GetString(0)] = r.GetInt64(1);
}
return map;
},
ct);
public Task<IReadOnlyList<PerceptualHashRecord>> LoadPerceptualHashesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<PerceptualHashRecord>>(
c =>
{
// One pass over media in table order with a key lookup per row: CROSS JOIN keeps media as the outer loop
// and the unary + keeps SQLite off the phash and state indexes, which would turn the pass into random
// reads once ANALYZE statistics exist (several times slower on 200,000 files).
using var r = c.Command("""
SELECT m.id, e.account_id, m.phash FROM media m CROSS JOIN entry e ON e.id = m.entry_id
WHERE +m.phash IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')
""").ExecuteReader();
var list = new List<PerceptualHashRecord>();
while (r.Read())
{
list.Add(new PerceptualHashRecord(r.GetInt64(0), r.GetInt64(1), unchecked((ulong)r.GetInt64(2))));
}
return list;
},
ct);
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<PendingDownload>>(
c =>
{
using var r = c.Command($"""
SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
ORDER BY (e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position
LIMIT @limit
""").With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader();
var list = new List<PendingDownload>();
while (r.Read())
{
var o = MediaColumnCount;
list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum<EntryKind>(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)));
}
return list;
},
ct);
public Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var command = accountId is { } a
? c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' AND e.account_id = @a
""").With("@a", a)
: c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
""");
return (int)command.ScalarInt64();
},
ct);
public Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(file);
if (!EntryStateRules.IsPresent(state))
{
throw new ArgumentException("Un file salvato è «scaricato» o «importato».", nameof(state));
}
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("""
UPDATE media SET state = @state, relative_path = @path, bytes = @bytes, sha256 = @sha, phash = @phash,
width = COALESCE(@w, width), height = COALESCE(@h, height), duration_ms = COALESCE(@d, duration_ms),
has_thumbnail = @thumb, downloaded_at = @at, last_error = NULL, source_url = NULL, cover_url = NULL
WHERE id = @id
""")
.With("@state", Sql.Enum(state))
.With("@path", file.RelativePath)
.With("@bytes", file.Bytes)
.With("@sha", file.Sha256.ToLowerInvariant())
.With("@phash", Sql.Hash(file.PerceptualHash))
.With("@w", Sql.Int(file.Width))
.With("@h", Sql.Int(file.Height))
.With("@d", Sql.Duration(file.Duration))
.With("@thumb", Sql.Bool(file.HasThumbnail))
.With("@at", Sql.Time(at))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId, at);
},
ct);
}
public Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default)
{
if (state is not (MediaState.Failed or MediaState.Expired or MediaState.Skipped or MediaState.ToDownload))
{
throw new ArgumentException("Uno scaricamento non riuscito porta a «fallito», «scaduto», «saltato» o di nuovo «da scaricare».", nameof(state));
}
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("UPDATE media SET state = @state, last_error = @error, attempts = attempts + 1 WHERE id = @id")
.With("@state", Sql.Enum(state))
.With("@error", Sql.Text(error))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId, at);
},
ct);
}
public Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("""
UPDATE media SET source_url = @u, cover_url = COALESCE(@c, cover_url), source_seen_at = @at,
state = CASE WHEN state IN ('Expired', 'Failed') THEN 'ToDownload' ELSE state END
WHERE id = @id
""")
.With("@u", Sql.Text(sourceUrl))
.With("@c", Sql.Text(coverUrl))
.With("@at", Sql.Time(seenAt))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId);
},
ct);
public Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE media SET has_thumbnail = @t WHERE id = @id").With("@t", Sql.Bool(hasThumbnail)).With("@id", mediaId).ExecuteNonQuery(),
ct);
public Task UpdateAsync(Media media, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(media);
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, media.Id);
var command = w.Command("""
UPDATE media SET position = @position, kind = @kind, instagram_id = @instagram_id, width = @width, height = @height,
duration_ms = @duration_ms, state = @state, relative_path = @relative_path, bytes = @bytes, sha256 = @sha256,
phash = @phash, has_thumbnail = @has_thumbnail, source_url = @source_url, cover_url = @cover_url,
source_seen_at = @source_seen_at, attempts = @attempts, last_error = @last_error, downloaded_at = @downloaded_at
WHERE id = @id
""");
BindMedia(command, media with { EntryId = entryId });
command.With("@id", media.Id).ExecuteNonQuery();
RecomputeState(w, entryId, media.DownloadedAt);
},
ct);
}
private static long EntryOf(WriteContext w, long mediaId)
{
var value = w.Command("SELECT entry_id FROM media WHERE id = @id").With("@id", mediaId).ExecuteScalar();
return value is long entryId ? entryId : throw new KeyNotFoundException($"File {mediaId} non trovato.");
}
}