MdpEdgeDeviceService.Receive.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using System.Globalization;
  2. using System.Security.Cryptography.X509Certificates;
  3. using System.Text;
  4. using System.Text.Json;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  7. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  8. public sealed record MdpEdgeTaskInput(string Mode, string? ApiPlan, EdgeRelationalSettings? Relational, string? ResumePosition = null);
  9. public sealed partial class MdpEdgeDeviceService
  10. {
  11. public async Task ConfigureAsync(long tenant, long factory, long dataset, Guid id, long actor, MdpEdgeTaskInput input)
  12. {
  13. RequireEnabled();
  14. using var db = MdpIngestDatabase.Open(host);
  15. await Tx(db, async () =>
  16. {
  17. var deviceId = id.ToString("D");
  18. var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  19. WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  20. AND state IN ('APPROVED','ACTIVE') FOR UPDATE
  21. """, new { deviceId, tenant, factory, dataset }) ?? throw new EdgeContractException("EDGE_DEVICE_NOT_FOUND");
  22. var binding = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
  23. Require(device.Phase is null or "COMPLETE", "EDGE_TASK_ACTIVE");
  24. await MdpEdgeRoute.RequireNoDirectRunAsync(db, tenant, factory, dataset, device.SourceId, allowHistory: input.Mode == EdgeProtocol.ApiPush);
  25. Require(await CountOtherTaskOwnersAsync(db, device) == 0, "EDGE_HANDOFF_REQUIRED");
  26. string? position = input.ResumePosition;
  27. if (input.Mode == EdgeProtocol.ApiPull)
  28. {
  29. var api = ParseApiPlan(input.ApiPlan);
  30. Require(input.Relational is null && position is null, "EDGE_TASK_INVALID");
  31. position = JsonSerializer.Serialize(api.Begin(DateTimeOffset.UtcNow, null), EdgeProtocol.Json);
  32. }
  33. else if (input.Mode == EdgeProtocol.Database)
  34. {
  35. Require(input.ApiPlan is null && input.Relational is { PageSize: >= 1 and <= 100, Columns.Length: > 0 and <= 100 },
  36. "EDGE_TASK_INVALID");
  37. var relational = input.Relational!;
  38. if (relational.Time is { } time)
  39. {
  40. Require(relational.Driver == Admin.NET.Plugin.AiDOP.DataPlatform.Relational.NativeRelationalDriver.PostgreSqlId
  41. && relational.SourceGeneration is > 0 && time.IsValid(), "EDGE_TIME_SOURCE_UNSUPPORTED");
  42. if (relational.Incremental)
  43. {
  44. var previous = device.ConfigJson is null ? null : ReadTask(device).Relational;
  45. Require(previous is not null && SameTimeSource(previous, relational) && device.Position is not null
  46. && (position is null || position == device.Position), "EDGE_TIME_BASELINE_REQUIRED");
  47. position = device.Position;
  48. _ = EdgeTimeWatermark.Decode(position);
  49. }
  50. else
  51. {
  52. Require(position is null, "EDGE_TIME_BASELINE_REQUIRED");
  53. }
  54. }
  55. else
  56. {
  57. if (relational.Incremental && position is null) position = device.Position;
  58. Require(position is null || long.TryParse(position, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "EDGE_TASK_INVALID");
  59. }
  60. if (relational.SourceGeneration is > 0)
  61. Require(relational.ChangeVersionColumn is { Length: > 0 } column && relational.Columns.Contains(column)
  62. && (relational.DeleteColumn is null || relational.Columns.Contains(relational.DeleteColumn)), "EDGE_TASK_INVALID");
  63. else
  64. Require(relational.SourceGeneration is null && relational.ChangeVersionColumn is null && relational.DeleteColumn is null,
  65. "EDGE_TASK_INVALID");
  66. }
  67. else
  68. {
  69. Require(input.Mode == EdgeProtocol.ApiPush && input.ApiPlan is null && input.Relational is null && position is null, "EDGE_TASK_INVALID");
  70. }
  71. var (_, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
  72. var generation = checked(device.Generation + 1);
  73. var task = new EdgeTask(deviceId + "-" + generation.ToString(CultureInfo.InvariantCulture), input.Mode,
  74. tenant, factory, device.SourceId, dataset, binding.SourceCode, binding.DatasetKey, binding.SourceSchemaVersion,
  75. contract.ConfigVersion, position, "READY", input.ApiPlan, input.Relational);
  76. await StoreTaskAsync(db, deviceId, generation, task);
  77. await AuditAsync(db, dataset, actor, "EDGE_TASK_APPROVED", task.Stream);
  78. return true;
  79. });
  80. }
  81. public async Task<EdgeReceipt?> FindReceiptAsync(X509Certificate2 certificate, Guid id)
  82. {
  83. RequireEnabled();
  84. using var db = MdpIngestDatabase.Open(host);
  85. var device = await AuthenticateAsync(db, certificate, false);
  86. return await FindAsync(db, device, id);
  87. }
  88. public async Task<EdgeReceipt> ReceiveAsync(X509Certificate2 certificate, EdgeBatch batch, CancellationToken token)
  89. {
  90. RequireEnabled();
  91. batch.Validate();
  92. using var db = MdpIngestDatabase.Open(host);
  93. return await Tx(db, async () =>
  94. {
  95. var device = await AuthenticateAsync(db, certificate, true);
  96. var previous = await FindAsync(db, device, batch.BatchId);
  97. if (previous is not null)
  98. {
  99. Require(previous.Confirms(batch) || previous.Rejects(batch), "EDGE_BATCH_CONFLICT");
  100. return previous;
  101. }
  102. var task = await RecoveryTaskAsync(db, device, includeSettled: false);
  103. Require(task.Stream == batch.Stream && task.State == "READY" && device.SeenAt is { } seen
  104. && DateTime.UtcNow - seen < TimeSpan.FromSeconds(60), "EDGE_TASK_STALE");
  105. Require(task.Mode == EdgeProtocol.ApiPush ? batch.Position is null && batch.NextPosition is null
  106. : batch.Position == device.Position && !batch.Ndjson, "EDGE_POSITION_STALE");
  107. Require(batch.ReceiverConfirmsNext == (task.Mode == EdgeProtocol.ApiPull)
  108. && (!batch.ReceiverConfirmsNext || batch.NextPosition is null && batch.Key == task.PageKey()), "EDGE_POSITION_INVALID");
  109. var binding = await BoundAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, true);
  110. Require(binding.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
  111. await RequireWriterAsync(db, device, binding.SourceCode);
  112. var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
  113. Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE");
  114. if (task.Mode == EdgeProtocol.ApiPush && await ExistingPushAsync(db, device, batch, task.SchemaVersion) is { } replay)
  115. return replay;
  116. var preparer = new IngestBatchPreparer(schemas);
  117. var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, binding.SourceCode, binding.DatasetKey);
  118. var limits = MdpIngestProtocol.Limits;
  119. var window = task.Mode switch
  120. {
  121. EdgeProtocol.ApiPull => new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime),
  122. EdgeProtocol.Database when task.Relational?.SourceGeneration is > 0 =>
  123. new IngestSourceWindow(null, null, IngestSourceWindow.VerifiedRelationalSnapshot) { SourceGeneration = task.Relational.SourceGeneration },
  124. _ => null
  125. };
  126. var archiveKey = Encoding.ASCII.GetBytes("\0edge-" + batch.BatchId.ToString("D"));
  127. var captured = preparer.CaptureApiPage(scope, task.SchemaVersion, batch.Body, limits, window) with { BatchId = batch.BatchId };
  128. await MdpIngestReceiveService.PersistRawWithJournalAsync(db, captured, [], batch.Body, archiveKey, captured.ReceivedAt, token);
  129. var confirmation = batch.NextPosition;
  130. var isCompleted = false;
  131. PreparedIngestBatch? prepared = null;
  132. string? code = null;
  133. try
  134. {
  135. if (task.Mode == EdgeProtocol.ApiPull)
  136. {
  137. var result = await ParseApiPageAsync(db, device, task, batch, preparer, scope, window!, ParseApiPlan(task.ApiPlan));
  138. prepared = result.Prepared;
  139. confirmation = result.ConfirmedPosition;
  140. isCompleted = confirmation is null;
  141. }
  142. else if (task.Mode == EdgeProtocol.Database && batch.Body.Length == 0)
  143. {
  144. if (task.Relational?.Time is not null)
  145. {
  146. var boundary = EdgeTimeWatermark.Decode(batch.NextPosition);
  147. Require(boundary <= DateTimeOffset.UtcNow.AddMinutes(5) &&
  148. (task.StartPosition is null || boundary >= EdgeTimeWatermark.Decode(task.StartPosition)), "EDGE_TIME_BOUNDARY_INVALID");
  149. }
  150. else
  151. {
  152. Require(batch.NextPosition == batch.Position, "EDGE_POSITION_INVALID");
  153. }
  154. isCompleted = true;
  155. }
  156. else
  157. {
  158. prepared = preparer.Prepare(scope, task.SchemaVersion, batch.Body, limits,
  159. window, format: batch.Ndjson ? IngestPayloadFormat.Ndjson : IngestPayloadFormat.Json);
  160. if (task.Mode == EdgeProtocol.Database)
  161. {
  162. if (task.Relational?.Time is not null)
  163. Require(EdgeTimeWatermark.AdvancesPage(batch.Position, batch.NextPosition, task.Relational.Incremental),
  164. "EDGE_POSITION_INVALID");
  165. else
  166. {
  167. var from = batch.Position is null ? long.MinValue : ParsePosition(batch.Position);
  168. var to = ParsePosition(batch.NextPosition);
  169. Require(to > from, "EDGE_POSITION_INVALID");
  170. if (task.Relational?.UpperPosition is { } upper)
  171. Require(to <= upper, "EDGE_POSITION_INVALID");
  172. }
  173. }
  174. }
  175. Require(prepared is null || MdpBatchFactory.RowsMatch(prepared), "EDGE_BATCH_SCOPE_INVALID");
  176. }
  177. catch (Exception error) when (error is EdgeContractException or MdpApiPullException or IngestContractException or JsonException)
  178. {
  179. code = error switch
  180. {
  181. EdgeContractException edge => edge.Code,
  182. MdpApiPullException pull => pull.Code,
  183. IngestContractException contractError => "EDGE_" + contractError.Code.ToString().ToUpperInvariant(),
  184. _ => "EDGE_INVALID_JSON"
  185. };
  186. }
  187. var count = code is null ? prepared?.Events.Count ?? 0 : 0;
  188. var key = task.Mode == EdgeProtocol.ApiPush ? Encoding.ASCII.GetBytes(batch.Key) : archiveKey;
  189. if (count > 0)
  190. {
  191. var accepted = prepared! with { Batch = prepared!.Batch with { BatchId = batch.BatchId, ReceivedAt = captured.ReceivedAt },
  192. Events = prepared.Events.Select(item => item with { BatchId = batch.BatchId }).ToArray() };
  193. await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, accepted, key, device.FactoryId, token, useCapturedRaw: true);
  194. }
  195. if (count == 0)
  196. await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, scope,
  197. code is null ? IngestBatchJournal.RawEmpty : IngestBatchJournal.RawRejected, 0, code);
  198. var status = code is not null ? EdgeProtocol.Rejected : count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted;
  199. var receipt = new EdgeReceipt(batch.BatchId, batch.Digest, status, batch.BatchId, code is null ? confirmation : batch.Position, code, batch.Position);
  200. await db.Ado.ExecuteCommandAsync("""
  201. INSERT INTO mdp_edge_receipt(batch_id,device_id,tenant_id,factory_id,dataset_id,source_id,generation,
  202. idem_key,digest,position_hash,receipt_json)
  203. VALUES (@batchId,@DeviceId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Generation,@key,@Digest,@positionHash,@json)
  204. """, new { batchId = batch.BatchId.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId,
  205. device.DatasetId, device.SourceId, device.Generation, key = Encoding.ASCII.GetBytes(batch.Key), batch.Digest,
  206. positionHash = batch.Position is null ? null : HashText(batch.Position), json = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) });
  207. if (task.Mode == EdgeProtocol.ApiPull && code is not null)
  208. await RecordRejectedPageAsync(db, device, batch);
  209. if (task.Mode != EdgeProtocol.ApiPush)
  210. await db.Ado.ExecuteCommandAsync("""
  211. UPDATE mdp_edge_device SET position_text=@ConfirmedPosition,task_phase=@phase,
  212. page_count=page_count+@pages,row_count=row_count+@count WHERE device_id=@DeviceId
  213. """, new { device.DeviceId, receipt.ConfirmedPosition, phase = code is not null ? "BLOCKED" : isCompleted ? "COMPLETE" : "READY",
  214. pages = code is null ? 1 : 0, count });
  215. token.ThrowIfCancellationRequested();
  216. return receipt;
  217. });
  218. }
  219. private static async Task<EdgeReceipt?> ExistingPushAsync(ISqlSugarClient db, Device device, EdgeBatch batch, string schema)
  220. {
  221. var stored = await db.Ado.SqlQuerySingleAsync<PushReceipt>("""
  222. SELECT b.batch_id AS BatchId,b.payload_sha256 AS Digest,b.source_schema_version AS SchemaVersion,
  223. (SELECT e.source_position FROM mdp_ingest_raw_event e WHERE e.batch_id=b.batch_id AND e.record_ordinal=0) AS FirstPosition
  224. FROM mdp_ingest_raw_batch b WHERE b.tenant_id=@TenantId AND b.factory_id=@FactoryId AND b.source_id=@SourceId
  225. AND b.dataset_id=@DatasetId AND b.idempotency_key=@key AND b.accepted_record_count>0
  226. """, new { device.TenantId, device.FactoryId, device.SourceId, device.DatasetId, key = Encoding.ASCII.GetBytes(batch.Key) });
  227. if (stored is null) return null;
  228. Require(stored.Digest == batch.Digest && stored.SchemaVersion == schema &&
  229. batch.Ndjson == (stored.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true), "EDGE_BATCH_CONFLICT");
  230. return new EdgeReceipt(batch.BatchId, batch.Digest, EdgeProtocol.Accepted, Guid.Parse(stored.BatchId), null);
  231. }
  232. private sealed class PushReceipt
  233. {
  234. public string BatchId { get; set; } = "";
  235. public string Digest { get; set; } = "";
  236. public string SchemaVersion { get; set; } = "";
  237. public string? FirstPosition { get; set; }
  238. }
  239. private static long ParsePosition(string? value) =>
  240. long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed)
  241. ? parsed : throw new EdgeContractException("EDGE_POSITION_INVALID");
  242. private static async Task<EdgeReceipt?> FindAsync(ISqlSugarClient db, Device device, Guid id)
  243. {
  244. var json = await db.Ado.SqlQuerySingleAsync<string>("""
  245. SELECT receipt_json FROM mdp_edge_receipt WHERE batch_id=@batchId AND device_id=@DeviceId
  246. AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  247. """, new { batchId = id.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId });
  248. return string.IsNullOrEmpty(json) ? null : JsonSerializer.Deserialize<EdgeReceipt>(json, EdgeProtocol.Json);
  249. }
  250. private static EdgeTask ReadTask(Device device)
  251. {
  252. var configured = device.ConfigJson is null ? null : JsonSerializer.Deserialize<EdgeTask>(device.ConfigJson, EdgeProtocol.Json);
  253. if (configured is null) throw new EdgeContractException("EDGE_TASK_ABSENT");
  254. return configured with { StartPosition = configured.Position, Position = device.Position,
  255. State = device.Phase!, PageCount = device.PageCount, RowCount = device.RowCount };
  256. }
  257. private static bool SameTimeSource(EdgeRelationalSettings previous, EdgeRelationalSettings next) =>
  258. previous.Time == next.Time && previous.Driver == next.Driver && previous.Database == next.Database &&
  259. previous.Schema == next.Schema && previous.Table == next.Table && previous.PositionColumn == next.PositionColumn &&
  260. previous.SourceGeneration == next.SourceGeneration && previous.ChangeVersionColumn == next.ChangeVersionColumn &&
  261. previous.DeleteColumn == next.DeleteColumn && previous.Columns.SequenceEqual(next.Columns, StringComparer.Ordinal);
  262. private static MdpApiPullPlan ParseApiPlan(string? json)
  263. {
  264. Require(json is { Length: > 0 and <= 65536 }, "EDGE_TASK_INVALID");
  265. var plan = JsonSerializer.Deserialize<MdpApiPullPlan>(json!, EdgeProtocol.Json) ?? throw new EdgeContractException("EDGE_TASK_INVALID");
  266. plan.Validate();
  267. return plan;
  268. }
  269. private static async Task<MdpIngestActiveBinding> BoundAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source, bool locked)
  270. {
  271. var key = await db.Ado.GetStringAsync("""
  272. SELECT dataset_key FROM mdp_ingest_dataset WHERE id=@dataset AND tenant_id=@tenant AND factory_id=@factory AND enabled=1
  273. """ + (locked ? " FOR UPDATE" : ""), new { tenant, factory, dataset });
  274. Require(!string.IsNullOrEmpty(key), "EDGE_SCOPE_UNAVAILABLE");
  275. return await new MdpIngestDatasetRegistry(db).ResolveActiveBindingAsync(tenant, factory, source, key)
  276. ?? throw new EdgeContractException("EDGE_SCOPE_UNAVAILABLE");
  277. }
  278. private static async Task RequireWriterAsync(ISqlSugarClient db, Device device, string sourceCode)
  279. {
  280. var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId);
  281. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  282. if (migration is not null)
  283. {
  284. Require(migration.NewSourceCode == sourceCode, "EDGE_WRITER_FORBIDDEN");
  285. return;
  286. }
  287. var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(device.TenantId, "PURCHASE");
  288. Require(string.Equals(authority?.SourceSystem, sourceCode, StringComparison.OrdinalIgnoreCase), "EDGE_WRITER_FORBIDDEN");
  289. }
  290. }