MdpEdgeDeviceService.Receive.cs 20 KB

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