| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 |
- using System.Data.Common;
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
- using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- namespace Admin.NET.DataPlatform.Edge;
- internal sealed class EdgeEngine(EdgeLocalState local, byte[] key, EdgeQueue queue, EdgeTransport transport, IConfiguration config)
- {
- private readonly MdpApiPullClient api = new(new MdpApiPullEgress(config), config);
- private readonly Queue<DateTimeOffset> requests = new();
- private EdgeTask? current = local.ReadTask(key);
- private string? lastError;
- private DateTimeOffset retryAfter;
- private int failures;
- internal EdgeTask? Current => Volatile.Read(ref current);
- internal async Task<bool> WorkAsync(CancellationToken token)
- {
- try
- {
- if (retryAfter > DateTimeOffset.UtcNow) return true;
- using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
- if (certificate.NotAfter.ToUniversalTime() <= DateTime.UtcNow.AddDays(1))
- await transport.RotateAsync(local, key, certificate, token);
- using var active = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
- using var client = transport.Connect(active);
- var usage = queue.Usage();
- var report = new EdgeReport(typeof(EdgeEngine).Assembly.GetName().Version?.ToString() ?? "1.0.0",
- usage.Pending, usage.Bytes, usage.FreeBytes, lastError);
- var task = await EdgeTransport.PostAsync<EdgeReport, EdgeTask>(client, "/api/v1/edge/heartbeat", report, token);
- if (task is not null) local.WriteTask(task, key);
- Volatile.Write(ref current, task);
- foreach (var settled in task?.SettledPages ?? [])
- {
- if (queue.ReadRejected(settled) is not { } archived) continue;
- var recovered = await transport.SendAsync(client, archived, token);
- queue.SettleRejection(archived, recovered);
- }
- if (queue.Next() is { } pending)
- await SendAsync(client, pending, token);
- else if (task is { State: "READY" } && task.LeaseUntil > DateTimeOffset.UtcNow)
- {
- if (task.Mode == EdgeProtocol.ApiPull)
- {
- var batch = await ReadApiAsync(task, token);
- queue.Buffer(batch);
- await SendAsync(client, batch, token);
- }
- else if (task.Mode == EdgeProtocol.Database)
- {
- await CaptureDatabaseAsync(task, token);
- if (queue.Next(task.Stream) is { } first) await SendAsync(client, first, token);
- }
- }
- EdgeLocalState.AtomicWrite(Path.Combine(local.DirectoryPath, "health"), Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToString("O")));
- failures = 0;
- lastError = null;
- return true;
- }
- catch (Exception error) when (!token.IsCancellationRequested && error is EdgeContractException or MdpApiPullException
- or ConnectorContractException or DbException or HttpRequestException or IOException or CryptographicException
- or JsonException or OperationCanceledException)
- {
- lastError = error switch
- {
- EdgeContractException edge => edge.Code,
- MdpApiPullException pull => pull.Code,
- ConnectorContractException connector => connector.Code.ToString(),
- _ => error.GetType().Name
- };
- if (lastError == "EDGE_DEVICE_FORBIDDEN") Volatile.Write(ref current, null);
- failures = Math.Min(failures + 1, 8);
- var delay = error is MdpApiPullException { Retry: { } retry }
- ? Math.Max(Math.Pow(2, failures), retry.TotalSeconds) : Math.Pow(2, failures);
- retryAfter = DateTimeOffset.UtcNow.AddSeconds(Math.Clamp(delay, 2, 86400));
- Console.Error.WriteLine(lastError);
- return false;
- }
- }
- private async Task SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token)
- {
- var receipt = await transport.SendAsync(client, batch, token);
- queue.Record(batch, receipt);
- if (receipt.Status == EdgeProtocol.Rejected)
- Console.Error.WriteLine("EDGE_REMOTE_REJECTED");
- }
- private async Task<EdgeBatch> ReadApiAsync(EdgeTask task, CancellationToken token)
- {
- if (task.ApiPlan is null || task.Position is null)
- throw new EdgeContractException("EDGE_TASK_INVALID");
- var plan = JsonSerializer.Deserialize<MdpApiPullPlan>(task.ApiPlan, EdgeProtocol.Json)
- ?? throw new EdgeContractException("EDGE_TASK_INVALID");
- plan.Validate();
- if (task.PageCount >= plan.MaxPages) throw new EdgeContractException("PULL_PAGE_LIMIT");
- var position = JsonSerializer.Deserialize<MdpApiPullPosition>(task.Position, EdgeProtocol.Json)
- ?? throw new EdgeContractException("EDGE_TASK_INVALID");
- var response = await api.FetchAsync(task.TenantId, task.SourceId, plan, position, token, _ =>
- {
- var now = DateTimeOffset.UtcNow;
- while (requests.TryPeek(out var oldest) && oldest.AddMinutes(1) <= now) requests.Dequeue();
- var cap = Math.Clamp(config.GetValue("Edge:SourceRequestsPerMinute", 60), 1, 1000);
- if (requests.Count >= cap)
- throw new MdpApiPullException("PULL_LOCAL_RATE_LIMITED", TimeSpan.FromSeconds(60));
- requests.Enqueue(now);
- return Task.CompletedTask;
- });
- return EdgeBatch.Create(task.Stream, task.PageKey(), task.Position,
- null, response.Body) with
- {
- EffectiveUrl = response.Effective.AbsoluteUri[..Math.Min(response.Effective.AbsoluteUri.Length, 2048)],
- NextLink = response.NextLink, Diagnostic = response.LinkDiagnostic, ReceiverConfirmsNext = true
- };
- }
- private async Task CaptureDatabaseAsync(EdgeTask task, CancellationToken token)
- {
- var approved = task.Relational ?? throw new EdgeContractException("EDGE_TASK_INVALID");
- var localMapping = config.GetSection("Edge:Relational").Get<EdgeRelationalSettings>();
- if (!Equivalent(approved, localMapping))
- throw new EdgeContractException("EDGE_RELATIONAL_TARGET_FORBIDDEN");
- var connection = LocalCredential(approved.SecretRef) ?? throw new EdgeContractException("EDGE_SOURCE_CREDENTIAL_UNAVAILABLE");
- var binding = new ConnectorBinding(new(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, task.SourceCode, task.DatasetKey),
- task.SchemaVersion, task.ConfigVersion);
- var execution = new ConnectorExecution(binding, approved.Driver, NativeRelationalDriver.Version,
- ConnectorManifest.FactoryAgent, ConnectorManifest.Database);
- var mapping = new RelationalSourceMapping(execution, approved.SecretRef, approved.Database, approved.Schema, approved.Table,
- approved.PositionColumn, approved.Columns)
- {
- IncludeFactoryInEnvelope = true,
- ChangeVersionColumn = approved.ChangeVersionColumn,
- DeleteColumn = approved.DeleteColumn
- };
- Task<string> Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(connection);
- IRelationalSourceDriver driver = approved.Driver == OdbcRelationalDriver.Id
- ? new OdbcRelationalDriver(mapping, approved.OdbcFamily ?? "", Resolve) : new NativeRelationalDriver(mapping, Resolve);
- await using var session = await driver.OpenReadOnlyAsync(execution, approved.SecretRef, token);
- if (task.Position != task.StartPosition || task.PageCount != 0)
- throw new EdgeContractException("EDGE_SNAPSHOT_REQUIRES_ORIGINAL_OUTBOX");
- if (approved.Time is { } time)
- {
- if (session is not IRelationalTimeSnapshotSource timeSnapshots)
- throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
- var timePosition = task.Position;
- var completed = approved.Incremental ? EdgeTimeWatermark.Decode(timePosition) : (DateTimeOffset?)null;
- var request = new RelationalTimeCapture(time.Column, completed, time.DelaySeconds, time.LookbackSeconds,
- time.RetentionSeconds, ReplayOnly: false);
- await queue.BufferSnapshotAsync(async add =>
- {
- var snapshot = await timeSnapshots.CaptureTimeAsync(approved.PageSize, (candidate, ordinal, _) =>
- {
- var next = EdgeTimeWatermark.Page(candidate.NextCheckpoint ?? throw new EdgeContractException("EDGE_POSITION_INVALID"));
- add(EdgeBatch.Create(task.Stream, $"db-{ordinal}", timePosition, next, candidate.Payload.ToArray()));
- timePosition = next;
- return Task.CompletedTask;
- }, request, token);
- add(EdgeBatch.Create(task.Stream, "db-end", timePosition, EdgeTimeWatermark.Encode(snapshot.To), []));
- });
- return;
- }
- if (session is not IRelationalSnapshotSource snapshots)
- throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
- var position = task.Position;
- var log = approved.Incremental ? new RelationalLogWindow(position is null ? null :
- long.Parse(position, CultureInfo.InvariantCulture)) : null;
- await queue.BufferSnapshotAsync(async add =>
- {
- await snapshots.CaptureAsync(approved.PageSize, (candidate, ordinal, _) =>
- {
- var batch = EdgeBatch.Create(task.Stream, $"db-{ordinal}", position, candidate.NextCheckpoint, candidate.Payload.ToArray());
- add(batch);
- position = candidate.NextCheckpoint;
- return Task.CompletedTask;
- }, token, log);
- add(EdgeBatch.Create(task.Stream, "db-end", position, position, []));
- });
- }
- private static bool Equivalent(EdgeRelationalSettings allowed, EdgeRelationalSettings? local) =>
- local is not null && allowed.Columns is not null && local.Columns is not null
- && allowed.Columns.SequenceEqual(local.Columns, StringComparer.Ordinal)
- && (allowed with { Columns = local.Columns, Incremental = local.Incremental, PageSize = local.PageSize })
- == local;
- internal static string? LocalCredential(string name)
- {
- if (!name.StartsWith("MDP_EDGE_SECRET_", StringComparison.Ordinal) || name.Length > 80
- || name.Any(ch => !(char.IsAsciiLetterUpper(ch) || char.IsAsciiDigit(ch) || ch == '_')))
- return null;
- var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
- if (!string.IsNullOrEmpty(directory) && File.Exists(Path.Combine(directory, name)))
- return File.ReadAllText(Path.Combine(directory, name)).Trim();
- return Environment.GetEnvironmentVariable(name);
- }
- }
|