using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
namespace Chronos.Data.Sync;
/// The sync_links table and the sync columns of local sequences (origin, sync state).
internal sealed class SyncLinkStore(ChronosDatabase db)
{
private const string Columns =
"server, remote_id, local_id, title, frame_count, total_bytes, render_count, remote_status, remote_settings_version, " +
"remote_frames_version, remote_updated_at, base_local_settings, base_remote_settings, diff_local_frames, diff_remote_frames, " +
"diff_local_renders, diff_remote_renders, missing_remote, missing_local, exports_to_get, exports_to_get_bytes, exports_to_send, " +
"exports_to_send_bytes, conflict_local_settings, conflict_remote_settings, conflict_remote, proxies_cached, proxies_frames_version, error, synced_at, " +
"diff_remote_updated_at";
private static readonly string UpsertSql = SqlDialect.Upsert("sync_links", Columns.Split(", "), 2);
private static readonly JobState[] Active = [JobState.Queued, JobState.Running, JobState.Paused];
private readonly DbAccess _db = new(db.Database);
public Task> ListAsync(string server, CancellationToken cancellationToken) =>
_db.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [server], Map, cancellationToken);
public Task GetAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
_db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], Map, cancellationToken);
public Task FindByLocalAsync(string server, Guid localId, CancellationToken cancellationToken) =>
_db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND local_id = $2", [server, localId], Map, cancellationToken);
public Task UpsertAsync(SyncLink l, CancellationToken cancellationToken) =>
_db.ExecuteAsync(UpsertSql,
[
l.Server, l.RemoteId, l.LocalId, l.Title, l.FrameCount, l.TotalBytes, l.RenderCount, (int)l.RemoteStatus, l.RemoteSettingsVersion,
l.RemoteFramesVersion, l.RemoteUpdatedAt, l.BaseLocalSettings, l.BaseRemoteSettings, l.DiffLocalFrames, l.DiffRemoteFrames,
l.DiffLocalRenders, l.DiffRemoteRenders, l.MissingRemote, l.MissingLocal, l.ExportsToGet, l.ExportsToGetBytes, l.ExportsToSend,
l.ExportsToSendBytes, l.ConflictLocalSettings, l.ConflictRemoteSettings,
l.ConflictRemote is { } remote ? JsonSerializer.Serialize(remote, SyncPayloadJson.Default.SyncPayload) : null,
l.ProxiesCached, l.ProxiesFramesVersion, l.Error, l.SyncedAt, l.DiffRemoteUpdatedAt,
], cancellationToken);
public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
_db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
/// Records where a local sequence stands for the Library; touches neither its versions nor its update time.
public Task SetLocalStateAsync(Guid localId, SyncState state, CancellationToken cancellationToken) =>
_db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken);
/// Marks a local sequence as downloaded from the server.
public Task SetOriginAsync(Guid localId, SequenceOrigin origin, CancellationToken cancellationToken) =>
_db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken);
/// Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads).
public async Task>> ActiveTransfersAsync(CancellationToken cancellationToken)
{
var jobs = new List();
foreach (var kind in new[] { JobKind.UploadCommit, JobKind.Download })
{
foreach (var state in Active)
{
string? cursor = null;
do
{
var page = await db.Jobs.ListAsync(state, kind, 500, cursor, cancellationToken).ConfigureAwait(false);
jobs.AddRange(page.Items.Where(j => j.TargetIds.Count > 0));
cursor = page.NextCursor;
}
while (cursor is not null);
}
}
return jobs.GroupBy(j => j.TargetIds[0]).ToDictionary(g => g.Key, g => (IReadOnlyList)[.. g]);
}
private static SyncLink Map(DbRow r) => new()
{
Server = r.GetString(0),
RemoteId = r.GetGuid(1),
LocalId = r.GetGuidOrNull(2),
Title = r.GetString(3),
FrameCount = r.GetInt32(4),
TotalBytes = r.GetInt64(5),
RenderCount = r.GetInt32(6),
RemoteStatus = (SequenceStatus)r.GetInt32(7),
RemoteSettingsVersion = r.GetInt32(8),
RemoteFramesVersion = r.GetInt32(9),
RemoteUpdatedAt = r.GetDateTimeOffset(10),
BaseLocalSettings = r.GetInt32OrNull(11),
BaseRemoteSettings = r.GetInt32OrNull(12),
DiffLocalFrames = r.GetInt32OrNull(13),
DiffRemoteFrames = r.GetInt32OrNull(14),
DiffLocalRenders = r.GetInt32OrNull(15),
DiffRemoteRenders = r.GetInt32OrNull(16),
MissingRemote = r.GetInt32(17),
MissingLocal = r.GetInt32(18),
ExportsToGet = r.GetInt32(19),
ExportsToGetBytes = r.GetInt64(20),
ExportsToSend = r.GetInt32(21),
ExportsToSendBytes = r.GetInt64(22),
ConflictLocalSettings = r.GetInt32OrNull(23),
ConflictRemoteSettings = r.GetInt32OrNull(24),
ConflictRemote = r.GetStringOrNull(25) is { } json ? JsonSerializer.Deserialize(json, SyncPayloadJson.Default.SyncPayload) : null,
ProxiesCached = r.GetInt32(26),
ProxiesFramesVersion = r.GetInt32OrNull(27),
Error = r.GetStringOrNull(28),
SyncedAt = r.GetDateTimeOffsetOrNull(29),
DiffRemoteUpdatedAt = r.GetDateTimeOffsetOrNull(30),
};
}