using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
{
private const string Columns =
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
/// The queue of the conversion by key (@after, @limit), also read by the plan tests.
internal const string PendingSql = $"SELECT {Columns} FROM media_conversion WHERE state = 'Pending' AND id > @after ORDER BY id LIMIT @limit";
private static MediaConversion Read(SqliteDataReader r) => new()
{
Id = r.GetInt64(0),
MediaId = r.GetInt64(1),
Format = r.GetEnum(2),
State = r.GetEnum(3),
SourceSha256 = r.GetString(4),
RelativePath = r.GetTextOrNull(5),
Bytes = r.GetInt64OrNull(6),
Sha256 = r.GetTextOrNull(7),
CreatedAt = r.GetTime(8),
ConvertedAt = r.GetTimeOrNull(9),
StateChangedAt = r.GetTimeOrNull(10),
LastError = r.GetTextOrNull(11),
};
private static List ReadAll(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List();
while (r.Read())
{
list.Add(Read(r));
}
return list;
}
private static void Validate(MediaConversion conversion)
{
ArgumentNullException.ThrowIfNull(conversion);
if (conversion.Format == ExportFormat.Original)
{
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(conversion));
}
if (conversion.State is not (MediaConversionState.Pending or MediaConversionState.Failed)
&& (conversion.RelativePath is null || conversion.Bytes is null || conversion.Sha256 is null || conversion.ConvertedAt is null))
{
throw new ArgumentException("Un file convertito ha percorso, byte, SHA-256 e data della conversione.", nameof(conversion));
}
}
// The path is relative to the account folder and written as given, like media.relative_path.
private static void Bind(SqliteCommand c, MediaConversion conversion) =>
c.With("@media_id", conversion.MediaId)
.With("@format", Sql.Enum(conversion.Format))
.With("@state", Sql.Enum(conversion.State))
.With("@source_sha256", ExportValues.Sha(conversion.SourceSha256, nameof(conversion.SourceSha256)))
.With("@relative_path", Sql.Text(conversion.RelativePath))
.With("@bytes", Sql.Int(conversion.Bytes))
.With("@sha256", Sql.Text(ExportValues.OptionalSha(conversion.Sha256, nameof(conversion.Sha256))))
.With("@created_at", Sql.Time(conversion.CreatedAt))
.With("@converted_at", Sql.Time(conversion.ConvertedAt))
.With("@state_changed_at", Sql.Time(conversion.StateChangedAt))
.With("@last_error", Sql.Text(conversion.LastError));
/// Runs a write guarded by ux_media_conversion_current; a collision is a .
private static int Execute(SqliteCommand command, MediaConversion conversion)
{
try
{
return command.ExecuteNonQuery();
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException(
$"Il file {conversion.MediaId} ha giĆ una conversione in {conversion.Format} in coda, fatta o non riuscita.", ex);
}
}
public Task AddAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
var c = w.Command("""
INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at,
state_changed_at, last_error)
VALUES (@media_id, @format, @state, @source_sha256, @relative_path, @bytes, @sha256, @created_at, @converted_at,
@state_changed_at, @last_error)
""");
Bind(c, conversion);
Execute(c, conversion);
var id = w.LastInsertRowId();
using var r = w.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id).ExecuteReader();
r.Read();
return Read(r);
},
ct);
}
public Task UpdateAsync(MediaConversion conversion, CancellationToken ct = default)
{
Validate(conversion);
return db.WriteAsync(
w =>
{
// The original and the format are the identity of a conversion: they are never rewritten.
var c = w.Command("""
UPDATE media_conversion SET state = @state, source_sha256 = @source_sha256, relative_path = @relative_path, bytes = @bytes,
sha256 = @sha256, created_at = @created_at, converted_at = @converted_at, state_changed_at = @state_changed_at,
last_error = @last_error
WHERE id = @id AND media_id = @media_id AND format = @format
""");
Bind(c, conversion);
if (Execute(c.With("@id", conversion.Id), conversion) == 0)
{
throw new KeyNotFoundException($"Conversione {conversion.Id} del file {conversion.MediaId} in {conversion.Format} non trovata.");
}
},
ct);
}
public Task GetAsync(long id, CancellationToken ct = default) =>
db.ReadAsync(c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE id = @id").With("@id", id)).FirstOrDefault(), ct);
public Task> ListByMediaAsync(long mediaId, CancellationToken ct = default) =>
db.ReadAsync>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE media_id = @m ORDER BY id").With("@m", mediaId)),
ct);
public Task> FindBySha256Async(string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync>(
c => ReadAll(c.Command($"SELECT {Columns} FROM media_conversion WHERE sha256 = @h ORDER BY id").With("@h", sha)),
ct);
}
public Task> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default) =>
db.ReadAsync>(
c => ReadAll(c.Command(PendingSql)
.With("@after", afterId).With("@limit", (long)Math.Clamp(limit, 1, 10_000))),
ct);
}