using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge; public static class EdgeProtocol { public const int MaxBodyBytes = 1024 * 1024; public const int MaxPositionLength = 8192; public const string Buffered = "buffered"; public const string Accepted = "accepted"; public const string Empty = "empty"; public const string Rejected = "rejected"; public const string Database = "database"; public const string ApiPull = "api-pull"; public const string ApiPush = "api-push"; public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); public static string Digest(ReadOnlySpan bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); } public sealed record EdgeBatch(Guid BatchId, string Stream, string Key, string Digest, string? Position, string? NextPosition, byte[] Body, string? EffectiveUrl = null, string? NextLink = null, string? Diagnostic = null, bool Ndjson = false, bool ReceiverConfirmsNext = false) { public static EdgeBatch Create(string stream, string key, string? position, string? nextPosition, byte[] body) { var batch = new EdgeBatch(StableId(stream, key), stream, key, EdgeProtocol.Digest(body), position, nextPosition, body.ToArray()); batch.Validate(); return batch; } public void Validate() { if (!ValidKey(Stream, 96) || !ValidKey(Key, 128) || Body is null || Body.Length > EdgeProtocol.MaxBodyBytes || BatchId != StableId(Stream, Key) || Digest != EdgeProtocol.Digest(Body) || Position?.Length > EdgeProtocol.MaxPositionLength || NextPosition?.Length > EdgeProtocol.MaxPositionLength || EffectiveUrl?.Length > 2048 || NextLink?.Length > 2048 || Diagnostic?.Length > 80) throw new EdgeContractException("EDGE_BATCH_INVALID"); } private static bool ValidKey(string? value, int limit) => value is { Length: > 0 } && value.Length <= limit && value.All(ch => ch is >= '!' and <= '~'); private static Guid StableId(string stream, string key) => new(SHA256.HashData(Encoding.UTF8.GetBytes(stream + "\n" + key)).AsSpan(0, 16)); } public sealed record EdgeReceipt(Guid BatchId, string Digest, string Status, Guid? RawBatchId, string? ConfirmedPosition, string? Diagnostic = null, string? SourcePosition = null) { public bool Confirms(EdgeBatch batch) => BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty && Status is EdgeProtocol.Accepted or EdgeProtocol.Empty && (batch.ReceiverConfirmsNext ? SourcePosition == batch.Position : ConfirmedPosition == batch.NextPosition); public bool Rejects(EdgeBatch batch) => BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty && Status == EdgeProtocol.Rejected && ConfirmedPosition == batch.Position; } public sealed record EdgeRegistration(string Activation, string RequestPem); public sealed record EdgeCertificate(Guid DeviceId, string CertificatePem); public sealed record EdgeRenewal(string RequestPem); public sealed record EdgeReport(string Version, int Pending, long BufferedBytes, long FreeBytes, string? LastError); public sealed record EdgeRelationalSettings(string Driver, string Database, string Schema, string Table, string PositionColumn, string[] Columns, string SecretRef, int PageSize = 100, bool Incremental = false, string? OdbcFamily = null, long? UpperPosition = null, string? ChangeVersionColumn = null, string? DeleteColumn = null, long? SourceGeneration = null, EdgeRelationalTimeSettings? Time = null); public sealed record EdgeTask(string Stream, string Mode, long TenantId, long FactoryId, long SourceId, long DatasetId, string SourceCode, string DatasetKey, string SchemaVersion, string ConfigVersion, string? Position, string State, string? ApiPlan = null, EdgeRelationalSettings? Relational = null, DateTimeOffset? LeaseUntil = null, int PageCount = 0, long RowCount = 0, int RecoveryAttempt = 0, IReadOnlyList? SettledPages = null, string? StartPosition = null) { public string PageKey() { if (Mode != EdgeProtocol.ApiPull || Position is null || RecoveryAttempt < 0) throw new EdgeContractException("EDGE_POSITION_INVALID"); var hash = EdgeProtocol.Digest(Encoding.UTF8.GetBytes(Position)); return RecoveryAttempt == 0 ? "page-" + hash : FormattableString.Invariant($"page-{hash}-{RecoveryAttempt}"); } } public sealed class EdgeContractException(string code) : Exception(code) { public string Code { get; } = code; }