using System.Data; using System.Data.Common; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational; internal sealed partial class NativeReadSession { private sealed record TimeSelection(string Column, DateTimeOffset From, DateTimeOffset To); private TimeSelection? _timeSelection; private long? _snapshotFence; public async Task CaptureTimeAsync(int pageSize, Func freeze, RelationalTimeCapture request, CancellationToken token) { if (dialect != SourceDialect.PostgreSql || odbc || _snapshot is not null || request.DelaySeconds <= 0 || request.LookbackSeconds < request.DelaySeconds || request.RetentionSeconds <= (long)request.LookbackSeconds + request.DelaySeconds || (request.ReplayOnly && request.Completed is null) || !(await ProbeAsync(token)).Full) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); ArgumentOutOfRangeException.ThrowIfLessThan(pageSize, 1); ArgumentOutOfRangeException.ThrowIfGreaterThan(pageSize, 100); await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead, token); _snapshot = transaction; try { await using var clockQuery = CreateCommand(); clockQuery.CommandText = "SELECT clock_timestamp()"; if (await clockQuery.ExecuteScalarAsync(token) is not DateTime { Kind: DateTimeKind.Utc } clock) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); var sourceNow = new DateTimeOffset(clock); if (request.Completed is null && request.FenceTable is { } fenceTable && request.FenceColumn is { } fenceColumn) { if (!SafeFenceIdentifier(fenceTable) || !SafeFenceIdentifier(fenceColumn)) throw new ConnectorContractException(ConnectorError.InvalidManifest); await using var fence = CreateCommand(); fence.CommandText = $"SELECT COUNT(*),MAX({Quote(fenceColumn)}) FROM {Quote(mapping.Schema)}.{Quote(fenceTable)}"; await using var record = await fence.ExecuteReaderAsync(token); if (!await record.ReadAsync(token) || Convert.ToInt64(record.GetValue(0)) != 1 || record.IsDBNull(1) || record.GetValue(1) is not long revision || revision <= 0) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); _snapshotFence = revision; } var upper = sourceNow.AddSeconds(-request.DelaySeconds); DateTimeOffset? lower = null; if (request.Completed is { } last) { var window = RelationalTimeWindow.Plan(last, sourceNow, TimeSpan.FromSeconds(request.LookbackSeconds), TimeSpan.FromSeconds(request.DelaySeconds), sourceNow.AddSeconds(-request.RetentionSeconds)); lower = window.FromInclusive; upper = request.ReplayOnly ? last : window.ToInclusive; _timeSelection = new(request.Column, lower.Value, upper); } await using var count = CreateCommand(); count.CommandText = _timeSelection is { } scope ? $"SELECT COUNT(*) FROM {Table} WHERE {Quote(scope.Column)} BETWEEN $1 AND $2" : $"SELECT COUNT(*) FROM {Table}"; if (_timeSelection is not null) BindTimeBounds(count, _timeSelection); var expected = Convert.ToInt64(await count.ExecuteScalarAsync(token)); long rows = 0; var pages = 0; string? checkpoint = null; do { var page = await ReadPageAsync(new(checkpoint, pageSize), token); if (page is null) break; if (page.Payload.Length > 3_000_000) throw new ConnectorContractException(ConnectorError.InvalidBatch); using var payload = JsonDocument.Parse(page.Payload); rows += payload.RootElement.GetProperty("data").GetProperty("list").GetArrayLength(); await freeze(page, ++pages, token); checkpoint = page.HasMore ? page.NextCheckpoint : null; } while (checkpoint is not null); if (rows != expected) throw new ConnectorContractException(ConnectorError.InvalidBatch); await transaction.RollbackAsync(token); return new(rows, pages, lower, upper, _snapshotFence); } finally { _timeSelection = null; _snapshotFence = null; _snapshot = null; } } private static bool SafeFenceIdentifier(string value) => value.Length is > 0 and <= 63 && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch == '_'); private DbCommand CreateTimePageCommand(TimeSelection scope, RelationalTimePosition? after, int take) { var time = Quote(scope.Column); var position = Quote(mapping.PositionColumn); var filter = $"{time} BETWEEN $1 AND $2"; var command = CreateCommand(); BindTimeBounds(command, scope); if (after is { } checkpoint) { filter += $" AND ({time},{position}) > ($3,$4)"; Add(command, "after_time", DbType.DateTime, checkpoint.Time.UtcDateTime); Add(command, "after_key", DbType.Int64, checkpoint.Key); } var limit = after.HasValue ? "$5" : "$3"; Add(command, "take", DbType.Int32, take); command.CommandText = $""" SELECT CAST({position} AS DECIMAL(20,0)), {PageColumns}, {time} FROM {Table} src WHERE {filter} ORDER BY src.{time},src.{position} LIMIT {limit} """; return command; } private static void BindTimeBounds(DbCommand command, TimeSelection scope) { Add(command, "from", DbType.DateTime, scope.From.UtcDateTime); Add(command, "to", DbType.DateTime, scope.To.UtcDateTime); } }