MdpEdgeDeviceService.Handoff.cs 6.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System.Globalization;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed record MdpEdgeHandoffInput(Guid PreviousDeviceId, string Reason);
  7. public sealed partial class MdpEdgeDeviceService
  8. {
  9. private const string HandedOff = "HANDED_OFF";
  10. public async Task HandoffAsync(long tenant, long factory, long dataset, Guid id, long actor, MdpEdgeHandoffInput input)
  11. {
  12. RequireEnabled();
  13. var reason = input.Reason?.Trim();
  14. Require(actor > 0 && input.PreviousDeviceId != Guid.Empty && input.PreviousDeviceId != id &&
  15. reason is { Length: > 0 and <= 240 } && !reason.Any(char.IsControl), "EDGE_HANDOFF_INVALID");
  16. var deviceId = id.ToString("D");
  17. var previousId = input.PreviousDeviceId.ToString("D");
  18. using var db = MdpIngestDatabase.Open(host);
  19. await Tx(db, async () =>
  20. {
  21. var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  22. WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  23. AND state IN ('APPROVED','ACTIVE') FOR UPDATE
  24. """, new { deviceId, tenant, factory, dataset }) ?? throw new EdgeContractException("EDGE_DEVICE_NOT_FOUND");
  25. Require(device.ConfigJson is null, "EDGE_TASK_ACTIVE");
  26. var binding = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
  27. var previous = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  28. WHERE device_id=@previousId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  29. AND source_id=@SourceId AND state='REVOKED' AND config_json IS NOT NULL
  30. AND COALESCE(task_phase,'')<>@handedOff FOR UPDATE
  31. """, new { previousId, tenant, factory, dataset, device.SourceId, handedOff = HandedOff })
  32. ?? throw new EdgeContractException("EDGE_HANDOFF_REQUIRED");
  33. Require(await CountOtherTaskOwnersAsync(db, previous) == 0, "EDGE_HANDOFF_REQUIRED");
  34. var historicalTask = ReadTask(previous);
  35. await MdpEdgeRoute.RequireNoDirectRunAsync(db, tenant, factory, dataset, device.SourceId,
  36. allowHistory: historicalTask.Mode == EdgeProtocol.ApiPush);
  37. var task = await ResumeTaskAsync(db, previous, historicalTask);
  38. if (task.State != "COMPLETE")
  39. {
  40. var (_, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
  41. Require(task.SchemaVersion == binding.SourceSchemaVersion && task.ConfigVersion == contract.ConfigVersion,
  42. "EDGE_CONFIGURATION_STALE");
  43. }
  44. var generation = checked(device.Generation + 1);
  45. task = task with { Stream = deviceId + "-" + generation.ToString(CultureInfo.InvariantCulture) };
  46. await StoreTaskAsync(db, deviceId, generation, task);
  47. await db.Ado.ExecuteCommandAsync("""
  48. UPDATE mdp_edge_device SET task_phase=@handedOff WHERE device_id=@previousId
  49. """, new { handedOff = HandedOff, previousId });
  50. await AuditAsync(db, dataset, actor, "EDGE_TASK_HANDOFF", $"{previousId} -> {task.Stream}: {reason}");
  51. return true;
  52. });
  53. }
  54. private static async Task<EdgeTask> ResumeTaskAsync(ISqlSugarClient db, Device previous, EdgeTask task)
  55. {
  56. if (task.Mode == EdgeProtocol.ApiPush) return task with { State = "READY" };
  57. if (task.Mode == EdgeProtocol.ApiPull) return task with { State = task.Position is null ? "COMPLETE" : "READY" };
  58. Require(task.Mode == EdgeProtocol.Database && task.Relational is not null, "EDGE_TASK_INVALID");
  59. // The terminal empty page is durable even for rows revoked before handoff support.
  60. var completed = await db.Ado.GetIntAsync("""
  61. SELECT COUNT(*) FROM mdp_edge_receipt
  62. WHERE device_id=@DeviceId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
  63. AND source_id=@SourceId AND generation=@Generation AND idem_key=@terminal
  64. AND JSON_UNQUOTE(JSON_EXTRACT(receipt_json,'$.status'))=@empty
  65. """, new { previous.DeviceId, previous.TenantId, previous.FactoryId, previous.DatasetId, previous.SourceId,
  66. previous.Generation, terminal = Encoding.ASCII.GetBytes("db-end"), empty = EdgeProtocol.Empty }) > 0;
  67. if (completed) return task with { State = "COMPLETE" };
  68. // A partially confirmed full or time-window snapshot still needs its original outbox.
  69. Require(task.PageCount == 0 && task.Position == task.StartPosition ||
  70. task.Relational is { Incremental: true, Time: null } &&
  71. long.TryParse(task.Position, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out _),
  72. "EDGE_HANDOFF_SNAPSHOT_REQUIRED");
  73. return task with { State = "READY", PageCount = 0, RowCount = 0 };
  74. }
  75. private static Task<int> CountOtherTaskOwnersAsync(ISqlSugarClient db, Device device) =>
  76. db.Ado.GetIntAsync("""
  77. SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@TenantId AND factory_id=@FactoryId
  78. AND dataset_id=@DatasetId AND source_id=@SourceId AND device_id<>@DeviceId
  79. AND config_json IS NOT NULL AND (state<>'REVOKED' OR COALESCE(task_phase,'')<>@handedOff)
  80. """, new { device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, device.DeviceId, handedOff = HandedOff });
  81. private static Task<int> StoreTaskAsync(ISqlSugarClient db, string deviceId, long generation, EdgeTask task) =>
  82. db.Ado.ExecuteCommandAsync("""
  83. UPDATE mdp_edge_device SET config_generation=@generation,config_json=@json,position_text=@Position,
  84. task_phase=@State,page_count=@PageCount,row_count=@RowCount WHERE device_id=@deviceId
  85. """, new { deviceId, generation, json = JsonSerializer.Serialize(task, EdgeProtocol.Json),
  86. task.Position, task.State, task.PageCount, task.RowCount });
  87. }