EdgeEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System.Data.Common;
  2. using System.Globalization;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using System.Text.Json;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  7. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  8. using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
  9. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  10. namespace Admin.NET.DataPlatform.Edge;
  11. internal sealed class EdgeEngine(EdgeLocalState local, byte[] key, EdgeQueue queue, EdgeTransport transport, IConfiguration config)
  12. {
  13. private readonly MdpApiPullClient api = new(new MdpApiPullEgress(config), config);
  14. private readonly Queue<DateTimeOffset> requests = new();
  15. private EdgeTask? current = local.ReadTask(key);
  16. private string? lastError;
  17. private DateTimeOffset retryAfter;
  18. private int failures;
  19. internal EdgeTask? Current => Volatile.Read(ref current);
  20. internal async Task<bool> WorkAsync(CancellationToken token)
  21. {
  22. try
  23. {
  24. if (retryAfter > DateTimeOffset.UtcNow) return true;
  25. using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
  26. if (certificate.NotAfter.ToUniversalTime() <= DateTime.UtcNow.AddDays(1))
  27. await transport.RotateAsync(local, key, certificate, token);
  28. using var active = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
  29. using var client = transport.Connect(active);
  30. var usage = queue.Usage();
  31. var report = new EdgeReport(typeof(EdgeEngine).Assembly.GetName().Version?.ToString() ?? "1.0.0",
  32. usage.Pending, usage.Bytes, usage.FreeBytes, lastError);
  33. var task = await EdgeTransport.PostAsync<EdgeReport, EdgeTask>(client, "/api/v1/edge/heartbeat", report, token);
  34. if (task is not null) local.WriteTask(task, key);
  35. Volatile.Write(ref current, task);
  36. foreach (var settled in task?.SettledPages ?? [])
  37. {
  38. if (queue.ReadRejected(settled) is not { } archived) continue;
  39. var recovered = await transport.SendAsync(client, archived, token);
  40. queue.SettleRejection(archived, recovered);
  41. }
  42. if (queue.Next() is { } pending)
  43. await SendAsync(client, pending, token);
  44. else if (task is { State: "READY" } && task.LeaseUntil > DateTimeOffset.UtcNow)
  45. {
  46. if (task.Mode == EdgeProtocol.ApiPull)
  47. {
  48. var batch = await ReadApiAsync(task, token);
  49. queue.Buffer(batch);
  50. await SendAsync(client, batch, token);
  51. }
  52. else if (task.Mode == EdgeProtocol.Database)
  53. {
  54. await CaptureDatabaseAsync(task, token);
  55. if (queue.Next(task.Stream) is { } first) await SendAsync(client, first, token);
  56. }
  57. }
  58. EdgeLocalState.AtomicWrite(Path.Combine(local.DirectoryPath, "health"), Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToString("O")));
  59. failures = 0;
  60. lastError = null;
  61. return true;
  62. }
  63. catch (Exception error) when (!token.IsCancellationRequested && error is EdgeContractException or MdpApiPullException
  64. or ConnectorContractException or DbException or HttpRequestException or IOException or CryptographicException
  65. or JsonException or OperationCanceledException)
  66. {
  67. lastError = error switch
  68. {
  69. EdgeContractException edge => edge.Code,
  70. MdpApiPullException pull => pull.Code,
  71. ConnectorContractException connector => connector.Code.ToString(),
  72. _ => error.GetType().Name
  73. };
  74. if (lastError == "EDGE_DEVICE_FORBIDDEN") Volatile.Write(ref current, null);
  75. failures = Math.Min(failures + 1, 8);
  76. var delay = error is MdpApiPullException { Retry: { } retry }
  77. ? Math.Max(Math.Pow(2, failures), retry.TotalSeconds) : Math.Pow(2, failures);
  78. retryAfter = DateTimeOffset.UtcNow.AddSeconds(Math.Clamp(delay, 2, 86400));
  79. Console.Error.WriteLine(lastError);
  80. return false;
  81. }
  82. }
  83. private async Task SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token)
  84. {
  85. var receipt = await transport.SendAsync(client, batch, token);
  86. queue.Record(batch, receipt);
  87. if (receipt.Status == EdgeProtocol.Rejected)
  88. Console.Error.WriteLine("EDGE_REMOTE_REJECTED");
  89. }
  90. private async Task<EdgeBatch> ReadApiAsync(EdgeTask task, CancellationToken token)
  91. {
  92. if (task.ApiPlan is null || task.Position is null)
  93. throw new EdgeContractException("EDGE_TASK_INVALID");
  94. var plan = JsonSerializer.Deserialize<MdpApiPullPlan>(task.ApiPlan, EdgeProtocol.Json)
  95. ?? throw new EdgeContractException("EDGE_TASK_INVALID");
  96. plan.Validate();
  97. if (task.PageCount >= plan.MaxPages) throw new EdgeContractException("PULL_PAGE_LIMIT");
  98. var position = JsonSerializer.Deserialize<MdpApiPullPosition>(task.Position, EdgeProtocol.Json)
  99. ?? throw new EdgeContractException("EDGE_TASK_INVALID");
  100. var response = await api.FetchAsync(task.TenantId, task.SourceId, plan, position, token, _ =>
  101. {
  102. var now = DateTimeOffset.UtcNow;
  103. while (requests.TryPeek(out var oldest) && oldest.AddMinutes(1) <= now) requests.Dequeue();
  104. var cap = Math.Clamp(config.GetValue("Edge:SourceRequestsPerMinute", 60), 1, 1000);
  105. if (requests.Count >= cap)
  106. throw new MdpApiPullException("PULL_LOCAL_RATE_LIMITED", TimeSpan.FromSeconds(60));
  107. requests.Enqueue(now);
  108. return Task.CompletedTask;
  109. });
  110. return EdgeBatch.Create(task.Stream, task.PageKey(), task.Position,
  111. null, response.Body) with
  112. {
  113. EffectiveUrl = response.Effective.AbsoluteUri[..Math.Min(response.Effective.AbsoluteUri.Length, 2048)],
  114. NextLink = response.NextLink, Diagnostic = response.LinkDiagnostic, ReceiverConfirmsNext = true
  115. };
  116. }
  117. private async Task CaptureDatabaseAsync(EdgeTask task, CancellationToken token)
  118. {
  119. var approved = task.Relational ?? throw new EdgeContractException("EDGE_TASK_INVALID");
  120. var localMapping = config.GetSection("Edge:Relational").Get<EdgeRelationalSettings>();
  121. if (!Equivalent(approved, localMapping))
  122. throw new EdgeContractException("EDGE_RELATIONAL_TARGET_FORBIDDEN");
  123. var connection = LocalCredential(approved.SecretRef) ?? throw new EdgeContractException("EDGE_SOURCE_CREDENTIAL_UNAVAILABLE");
  124. var binding = new ConnectorBinding(new(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, task.SourceCode, task.DatasetKey),
  125. task.SchemaVersion, task.ConfigVersion);
  126. var execution = new ConnectorExecution(binding, approved.Driver, NativeRelationalDriver.Version,
  127. ConnectorManifest.FactoryAgent, ConnectorManifest.Database);
  128. var mapping = new RelationalSourceMapping(execution, approved.SecretRef, approved.Database, approved.Schema, approved.Table,
  129. approved.PositionColumn, approved.Columns)
  130. {
  131. IncludeFactoryInEnvelope = true,
  132. ChangeVersionColumn = approved.ChangeVersionColumn,
  133. DeleteColumn = approved.DeleteColumn
  134. };
  135. Task<string> Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(connection);
  136. IRelationalSourceDriver driver = approved.Driver == OdbcRelationalDriver.Id
  137. ? new OdbcRelationalDriver(mapping, approved.OdbcFamily ?? "", Resolve) : new NativeRelationalDriver(mapping, Resolve);
  138. await using var session = await driver.OpenReadOnlyAsync(execution, approved.SecretRef, token);
  139. if (task.Position != task.StartPosition || task.PageCount != 0)
  140. throw new EdgeContractException("EDGE_SNAPSHOT_REQUIRES_ORIGINAL_OUTBOX");
  141. if (approved.Time is { } time)
  142. {
  143. if (session is not IRelationalTimeSnapshotSource timeSnapshots)
  144. throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  145. var timePosition = task.Position;
  146. var completed = approved.Incremental ? EdgeTimeWatermark.Decode(timePosition) : (DateTimeOffset?)null;
  147. var request = new RelationalTimeCapture(time.Column, completed, time.DelaySeconds, time.LookbackSeconds,
  148. time.RetentionSeconds, ReplayOnly: false);
  149. await queue.BufferSnapshotAsync(async add =>
  150. {
  151. var snapshot = await timeSnapshots.CaptureTimeAsync(approved.PageSize, (candidate, ordinal, _) =>
  152. {
  153. var next = EdgeTimeWatermark.Page(candidate.NextCheckpoint ?? throw new EdgeContractException("EDGE_POSITION_INVALID"));
  154. add(EdgeBatch.Create(task.Stream, $"db-{ordinal}", timePosition, next, candidate.Payload.ToArray()));
  155. timePosition = next;
  156. return Task.CompletedTask;
  157. }, request, token);
  158. add(EdgeBatch.Create(task.Stream, "db-end", timePosition, EdgeTimeWatermark.Encode(snapshot.To), []));
  159. });
  160. return;
  161. }
  162. if (session is not IRelationalSnapshotSource snapshots)
  163. throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  164. var position = task.Position;
  165. var log = approved.Incremental ? new RelationalLogWindow(position is null ? null :
  166. long.Parse(position, CultureInfo.InvariantCulture)) : null;
  167. await queue.BufferSnapshotAsync(async add =>
  168. {
  169. await snapshots.CaptureAsync(approved.PageSize, (candidate, ordinal, _) =>
  170. {
  171. var batch = EdgeBatch.Create(task.Stream, $"db-{ordinal}", position, candidate.NextCheckpoint, candidate.Payload.ToArray());
  172. add(batch);
  173. position = candidate.NextCheckpoint;
  174. return Task.CompletedTask;
  175. }, token, log);
  176. add(EdgeBatch.Create(task.Stream, "db-end", position, position, []));
  177. });
  178. }
  179. private static bool Equivalent(EdgeRelationalSettings allowed, EdgeRelationalSettings? local) =>
  180. local is not null && allowed.Columns is not null && local.Columns is not null
  181. && allowed.Columns.SequenceEqual(local.Columns, StringComparer.Ordinal)
  182. && (allowed with { Columns = local.Columns, Incremental = local.Incremental, PageSize = local.PageSize })
  183. == local;
  184. internal static string? LocalCredential(string name)
  185. {
  186. if (!name.StartsWith("MDP_EDGE_SECRET_", StringComparison.Ordinal) || name.Length > 80
  187. || name.Any(ch => !(char.IsAsciiLetterUpper(ch) || char.IsAsciiDigit(ch) || ch == '_')))
  188. return null;
  189. var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
  190. if (!string.IsNullOrEmpty(directory) && File.Exists(Path.Combine(directory, name)))
  191. return File.ReadAllText(Path.Combine(directory, name)).Trim();
  192. return Environment.GetEnvironmentVariable(name);
  193. }
  194. }