E3: conversione della libreria in sottofondo con righe sempre vere
La libreria può ora tenere accanto a ogni originale una copia nel formato scelto, preparata in sottofondo senza mai sostituire o cancellare l'originale. - LongWorkGate ha un permesso di sottofondo che il lavoro in primo piano (importazione, copie, ricostruzione) interrompe; il salvataggio in corso si aspetta al più CommitWait. - La coda e il lavoratore: nuovi file accodati all'arrivo, quelli già in libreria solo su richiesta, pausa, nuovo tentativo, attesa durante una sessione del motore o con poco spazio, nomi liberi e adozione di un file identico già presente. - Le righe di media_conversion restano vere in ogni via: eliminazione (Ricorda e Consenti il ritorno, con RemoveWithConversionsAsync per il vincolo RESTRICT), perdente del ripasso dei doppioni, file cambiato (superate e riaccodate), ricostruzione (conta e riconosce i convertiti, accoda solo Pending), importazione (una copia convertita o un fotogramma non rientra come file nuovo). - FebeApp avvia il lavoratore con InBackground; la demo mai. _febe.jsonl non cambia. La prova RecordsCannotBeDeletedFromUnderTheirCopies usa ora una riga Converted: RemoveAsync toglie da sé le righe senza file, e il vincolo si verifica sia in SQL sia attraverso il magazzino. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b746aff45d
commit
724c5bda6f
25 files changed
+2621
-38
No files matched your search
@@ -148,8 +148,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
|
||||
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(
|
||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||
|
||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(removedConversionIds);
|
||||
var removed = removedConversionIds.Distinct().ToList();
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
|
||||
@@ -163,11 +168,69 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
|
||||
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();
|
||||
|
||||
// The conversions for the library of its files (tappa E3): nothing left to convert or retry; the
|
||||
// converted files that go (or are gone) are «Tolto», the others stay as they are.
|
||||
w.Command("""
|
||||
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id)
|
||||
""").With("@id", entryId).ExecuteNonQuery();
|
||||
if (removed.Count > 0)
|
||||
{
|
||||
var own = new HashSet<long>();
|
||||
using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id")
|
||||
.With("@id", entryId).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
own.Add(r.GetInt64(0));
|
||||
}
|
||||
}
|
||||
|
||||
MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at);
|
||||
}
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
MediaConversionStore.DeleteRowsWithoutFile(w, entryId);
|
||||
try
|
||||
{
|
||||
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||
}
|
||||
catch (SqliteException ex) when (ex.IsConstraintViolation())
|
||||
{
|
||||
// ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record.
|
||||
throw new InvalidOperationException(
|
||||
"L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex);
|
||||
}
|
||||
},
|
||||
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<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync<IReadOnlyList<MediaConversion>>(
|
||||
w =>
|
||||
{
|
||||
var list = new List<MediaConversion>();
|
||||
using (var r = w.Command($"""
|
||||
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||
WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id
|
||||
""").With("@id", entryId).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(MediaConversionStore.ReadRow(r));
|
||||
}
|
||||
}
|
||||
|
||||
w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery();
|
||||
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -829,6 +829,22 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
/// <summary>The first item of a file of a job in a form (ux_export_item_file).</summary>
|
||||
internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f";
|
||||
|
||||
public Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlySet<string>>(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command("SELECT DISTINCT copy_sha256 FROM export_copy WHERE variant IN ('Converted', 'Frame') AND copy_sha256 IS NOT NULL");
|
||||
using var r = command.ExecuteReader();
|
||||
var set = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (r.Read())
|
||||
{
|
||||
set.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
return set;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) =>
|
||||
db.ReadAsync(
|
||||
c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data.Stores;
|
||||
|
||||
/// <summary>The queue, the commit and the hooks of the conversion for the library (tappa E3, WP2.3).</summary>
|
||||
internal sealed partial class MediaConversionStore
|
||||
{
|
||||
/// <summary>The same columns of the alias <c>mc</c>, for joins.</summary>
|
||||
private const string JoinedColumns =
|
||||
"mc.id, mc.media_id, mc.format, mc.state, mc.source_sha256, mc.relative_path, mc.bytes, mc.sha256, mc.created_at, mc.converted_at, mc.state_changed_at, mc.last_error";
|
||||
|
||||
/// <summary>The columns of the alias <c>mc</c>, for other stores reading rows with <see cref="ReadRow"/>.</summary>
|
||||
internal const string JoinedColumnList = JoinedColumns;
|
||||
|
||||
/// <summary>The present library files of the alias <c>m</c>, as the conversion for the library sees them.</summary>
|
||||
private const string PresentMedia = "m.state IN ('Downloaded', 'Imported') AND m.sha256 IS NOT NULL AND m.relative_path IS NOT NULL";
|
||||
|
||||
/// <summary>A Failed row whose code says it never converts (animated, not decodable, CMYK…): its first code.</summary>
|
||||
internal const string AsIsCondition = "last_error LIKE 'AsIs%'";
|
||||
|
||||
/// <summary>One row read in the order of <see cref="JoinedColumnList"/>.</summary>
|
||||
internal static MediaConversion ReadRow(SqliteDataReader r) => Read(r);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c => ReadAll(c.Command($"""
|
||||
SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||
WHERE m.entry_id = @e ORDER BY mc.media_id, mc.id
|
||||
""").With("@e", entryId)),
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mediaIds);
|
||||
var ids = mediaIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<MediaConversion>>([]);
|
||||
}
|
||||
|
||||
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c =>
|
||||
{
|
||||
var list = new List<MediaConversion>();
|
||||
foreach (var chunk in ids.Chunk(500))
|
||||
{
|
||||
using var command = c.Command(string.Empty);
|
||||
command.CommandText = $"SELECT {Columns} FROM media_conversion WHERE media_id IN ({command.AddList("m", chunk)})";
|
||||
list.AddRange(ReadAll(command));
|
||||
}
|
||||
|
||||
return list.OrderBy(x => x.MediaId).ThenBy(x => x.Id).ToList();
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<string>>(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command("""
|
||||
SELECT DISTINCT mc.relative_path FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.relative_path IS NOT NULL AND mc.state IN ('Converted', 'Superseded', 'Removed')
|
||||
""").With("@a", accountId);
|
||||
using var r = command.ExecuteReader();
|
||||
var list = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c => ReadAll(c.Command($"""
|
||||
SELECT {JoinedColumns} FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.relative_path = @p ORDER BY mc.id
|
||||
""").With("@a", accountId).With("@p", relativePath)),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var list = ids.Distinct().ToList();
|
||||
return list.Count == 0 ? Task.FromResult(0) : db.WriteAsync(w => MarkRemoved(w, list, at), ct);
|
||||
}
|
||||
|
||||
/// <summary>«Tolto» for these ids among the Converted and Superseded rows, inside the caller's transaction.</summary>
|
||||
internal static int MarkRemoved(WriteContext w, IReadOnlyCollection<long> ids, DateTimeOffset at)
|
||||
{
|
||||
var changed = 0;
|
||||
foreach (var chunk in ids.Chunk(500))
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
command.CommandText = $"""
|
||||
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at
|
||||
WHERE state IN ('Converted', 'Superseded') AND id IN ({command.AddList("i", chunk)})
|
||||
""";
|
||||
changed += command.With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
public Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery();
|
||||
return w.Command("""
|
||||
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at WHERE media_id = @m AND state IN ('Converted', 'Superseded')
|
||||
""").With("@m", mediaId).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
},
|
||||
ct);
|
||||
|
||||
/// <summary>The rows without a file left (Pending, Failed, Removed) of an entry's files go, inside the caller's transaction.</summary>
|
||||
internal static int DeleteRowsWithoutFile(WriteContext w, long entryId) =>
|
||||
w.Command("""
|
||||
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed', 'Removed')
|
||||
AND media_id IN (SELECT id FROM media WHERE entry_id = @e)
|
||||
""").With("@e", entryId).ExecuteNonQuery();
|
||||
|
||||
public Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
|
||||
var now = ExportValues.Sha(newSha256, nameof(newSha256));
|
||||
if (old == now)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<long>>([]);
|
||||
}
|
||||
|
||||
return db.WriteAsync<IReadOnlyList<long>>(
|
||||
w =>
|
||||
{
|
||||
var media = new List<long>();
|
||||
using (var find = w.Connection.Command("""
|
||||
SELECT DISTINCT mc.media_id FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.source_sha256 = @old AND m.sha256 = @new
|
||||
AND mc.state IN ('Pending', 'Converted', 'Failed')
|
||||
ORDER BY mc.media_id
|
||||
""", w.Transaction))
|
||||
{
|
||||
find.With("@a", accountId).With("@old", old).With("@new", now);
|
||||
using var r = find.ExecuteReader();
|
||||
while (r.Read())
|
||||
{
|
||||
media.Add(r.GetInt64(0));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chunk in media.Chunk(500))
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
var list = command.AddList("m", chunk);
|
||||
|
||||
// Converted from the old bytes: history, its file stays. The queue and the failures take the new
|
||||
// bytes (a verdict, «AsIs» included, was about the old ones) and are tried again.
|
||||
command.CommandText = $"""
|
||||
UPDATE media_conversion SET state = 'Superseded', state_changed_at = @at
|
||||
WHERE state = 'Converted' AND source_sha256 = @old AND media_id IN ({list});
|
||||
UPDATE media_conversion SET state = 'Pending', source_sha256 = @new, last_error = NULL, state_changed_at = @at
|
||||
WHERE state IN ('Pending', 'Failed') AND source_sha256 = @old AND media_id IN ({list});
|
||||
""";
|
||||
command.With("@at", Sql.Time(at)).With("@old", old).With("@new", now).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return media;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command("DELETE FROM media_conversion WHERE state = 'Pending' AND format = @f").With("@f", Sql.Enum(format)).ExecuteNonQuery(),
|
||||
ct);
|
||||
|
||||
public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command("DELETE FROM media_conversion WHERE id = @id AND state = 'Pending'").With("@id", id).ExecuteNonQuery() > 0,
|
||||
ct);
|
||||
|
||||
public Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command($"""
|
||||
SELECT state, CASE WHEN state = 'Failed' AND {AsIsCondition} THEN 1 ELSE 0 END, COUNT(*)
|
||||
FROM media_conversion GROUP BY 1, 2
|
||||
""");
|
||||
using var r = command.ExecuteReader();
|
||||
int pending = 0, converted = 0, failed = 0, asIs = 0, superseded = 0, removed = 0;
|
||||
while (r.Read())
|
||||
{
|
||||
var n = (int)r.GetInt64(2);
|
||||
switch (r.GetString(0))
|
||||
{
|
||||
case "Pending":
|
||||
pending += n;
|
||||
break;
|
||||
case "Converted":
|
||||
converted += n;
|
||||
break;
|
||||
case "Failed" when r.GetInt64(1) == 1:
|
||||
asIs += n;
|
||||
break;
|
||||
case "Failed":
|
||||
failed += n;
|
||||
break;
|
||||
case "Superseded":
|
||||
superseded += n;
|
||||
break;
|
||||
case "Removed":
|
||||
removed += n;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new MediaConversionCounts(pending, converted, failed, asIs, superseded, removed);
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(requests);
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
var valid = requests.Select(r =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(r);
|
||||
if (r.Format == ExportFormat.Original)
|
||||
{
|
||||
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(requests));
|
||||
}
|
||||
|
||||
return r with { SourceSha256 = ExportValues.Sha(r.SourceSha256, nameof(r.SourceSha256)) };
|
||||
}).ToList();
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var added = 0;
|
||||
foreach (var r in valid)
|
||||
{
|
||||
// A current row (Pending, Converted, or Failed, which holds the slot) is left as it is.
|
||||
added += w.Command("""
|
||||
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||
SELECT @m, @f, 'Pending', @s, @at WHERE EXISTS (SELECT 1 FROM media WHERE id = @m)
|
||||
ON CONFLICT DO NOTHING
|
||||
""").With("@m", r.MediaId).With("@f", Sql.Enum(r.Format)).With("@s", r.SourceSha256).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return added;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>The present files of a kind that convert into <paramref name="format"/>, as a condition on the alias <c>m</c>.</summary>
|
||||
private static string ExistingCondition(SqliteCommand command, MediaKind kind, ExportFormat format)
|
||||
{
|
||||
var excluded = LibraryConversionRules.ExcludedExtensions(format);
|
||||
var sql = new StringBuilder($"m.kind = @k AND {PresentMedia}");
|
||||
command.With("@k", Sql.Enum(kind));
|
||||
for (var i = 0; i < excluded.Count; i++)
|
||||
{
|
||||
// LIKE compares ASCII letters without case, as the extension rule does.
|
||||
sql.Append(CultureInfo.InvariantCulture, $" AND m.relative_path NOT LIKE @x{i}");
|
||||
command.With(string.Create(CultureInfo.InvariantCulture, $"@x{i}"), "%" + excluded[i]);
|
||||
}
|
||||
|
||||
return sql.ToString();
|
||||
}
|
||||
|
||||
private static List<(MediaKind Kind, ExportFormat Format)> Kinds(ExportFormat? photo, ExportFormat? video)
|
||||
{
|
||||
var kinds = new List<(MediaKind, ExportFormat)>();
|
||||
if (photo is { } p && p != ExportFormat.Original)
|
||||
{
|
||||
if (!ExportFormats.IsPhotoFormat(p))
|
||||
{
|
||||
throw new ArgumentException("Il formato non è adatto alle foto.", nameof(photo));
|
||||
}
|
||||
|
||||
kinds.Add((MediaKind.Photo, p));
|
||||
}
|
||||
|
||||
if (video is { } v && v != ExportFormat.Original)
|
||||
{
|
||||
if (!ExportFormats.IsVideoFormat(v))
|
||||
{
|
||||
throw new ArgumentException("Il formato non è adatto ai video.", nameof(video));
|
||||
}
|
||||
|
||||
kinds.Add((MediaKind.Video, v));
|
||||
}
|
||||
|
||||
return kinds;
|
||||
}
|
||||
|
||||
public Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
var kinds = Kinds(photo, video);
|
||||
if (kinds.Count == 0)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var added = 0;
|
||||
foreach (var (kind, format) in kinds)
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
var where = ExistingCondition(command, kind, format);
|
||||
|
||||
// One statement; a file with a current row in the format (a Failed one included) keeps it.
|
||||
command.CommandText = $"""
|
||||
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||
SELECT m.id, @f, 'Pending', m.sha256, @at FROM media m WHERE {where} ORDER BY m.id
|
||||
ON CONFLICT DO NOTHING
|
||||
""";
|
||||
added += command.With("@f", Sql.Enum(format)).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return added;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var kinds = Kinds(photo, video);
|
||||
if (kinds.Count == 0)
|
||||
{
|
||||
return Task.FromResult((0, 0L));
|
||||
}
|
||||
|
||||
return db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
var files = 0;
|
||||
long bytes = 0;
|
||||
foreach (var (kind, format) in kinds)
|
||||
{
|
||||
using var command = c.Command(string.Empty);
|
||||
var where = ExistingCondition(command, kind, format);
|
||||
command.CommandText = $"""
|
||||
SELECT COUNT(*), COALESCE(SUM(m.bytes), 0) FROM media m
|
||||
WHERE {where} AND NOT EXISTS (
|
||||
SELECT 1 FROM media_conversion mc WHERE mc.media_id = m.id AND mc.format = @f AND mc.state IN ('Pending', 'Converted', 'Failed'))
|
||||
""";
|
||||
command.With("@f", Sql.Enum(format));
|
||||
using var r = command.ExecuteReader();
|
||||
if (r.Read())
|
||||
{
|
||||
files += (int)r.GetInt64(0);
|
||||
bytes += r.GetInt64(1);
|
||||
}
|
||||
}
|
||||
|
||||
return (files, bytes);
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(commit);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(commit.RelativePath);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(commit.Bytes);
|
||||
if (commit.Format == ExportFormat.Original)
|
||||
{
|
||||
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(commit));
|
||||
}
|
||||
|
||||
var source = ExportValues.Sha(commit.SourceSha256, nameof(commit.SourceSha256));
|
||||
var sha = ExportValues.Sha(commit.Sha256, nameof(commit.Sha256));
|
||||
return db.WriteAsync(w => Commit(w, commit, source, sha), ct);
|
||||
}
|
||||
|
||||
private static MediaConversionCommitOutcome Commit(WriteContext w, MediaConversionCommit commit, string source, string sha)
|
||||
{
|
||||
SqliteCommand Bind(SqliteCommand c) =>
|
||||
c.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).With("@s", source).With("@p", commit.RelativePath)
|
||||
.With("@b", commit.Bytes).With("@h", sha).With("@at", Sql.Time(commit.At)).With("@e", Sql.Text(commit.Notes));
|
||||
|
||||
var recorded = Bind(w.Command($"""
|
||||
UPDATE media_conversion SET state = 'Converted', relative_path = @p, bytes = @b, sha256 = @h, converted_at = @at,
|
||||
state_changed_at = @at, last_error = @e
|
||||
WHERE id = @id AND media_id = @m AND format = @f AND state = 'Pending' AND source_sha256 = @s
|
||||
AND EXISTS (SELECT 1 FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia})
|
||||
""")).With("@id", commit.ConversionId).ExecuteNonQuery();
|
||||
if (recorded == 1)
|
||||
{
|
||||
return MediaConversionCommitOutcome.Recorded;
|
||||
}
|
||||
|
||||
var present = w.Command($"SELECT COUNT(*) FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}")
|
||||
.With("@m", commit.MediaId).With("@s", source).ScalarInt64() > 0;
|
||||
if (!present)
|
||||
{
|
||||
return MediaConversionCommitOutcome.SourceGone;
|
||||
}
|
||||
|
||||
long? currentId = null;
|
||||
string? currentState = null;
|
||||
using (var r = w.Command("SELECT id, state FROM media_conversion WHERE media_id = @m AND format = @f AND state IN ('Pending', 'Converted', 'Failed')")
|
||||
.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).ExecuteReader())
|
||||
{
|
||||
if (r.Read())
|
||||
{
|
||||
currentId = r.GetInt64(0);
|
||||
currentState = r.GetString(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (currentState == "Converted")
|
||||
{
|
||||
return MediaConversionCommitOutcome.SlotTaken;
|
||||
}
|
||||
|
||||
if (currentId is { } id)
|
||||
{
|
||||
Bind(w.Command("""
|
||||
UPDATE media_conversion SET state = 'Converted', source_sha256 = @s, relative_path = @p, bytes = @b, sha256 = @h,
|
||||
converted_at = @at, state_changed_at = @at, last_error = @e
|
||||
WHERE id = @id AND media_id = @m AND format = @f
|
||||
""")).With("@id", id).ExecuteNonQuery();
|
||||
return MediaConversionCommitOutcome.Upserted;
|
||||
}
|
||||
|
||||
// The row went (the setting was turned off meanwhile): the file just written stays recorded.
|
||||
Bind(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 (@m, @f, 'Converted', @s, @p, @b, @h, @at, @at, @at, @e)
|
||||
""")).ExecuteNonQuery();
|
||||
return MediaConversionCommitOutcome.Upserted;
|
||||
}
|
||||
|
||||
public Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command($"""
|
||||
UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at
|
||||
WHERE state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition}))
|
||||
""").With("@at", Sql.Time(at)).ExecuteNonQuery(),
|
||||
ct);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data.Stores;
|
||||
|
||||
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
|
||||
internal sealed partial 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";
|
||||
|
||||
Reference in new issue
Block a user