| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System.Globalization;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed record MdpEdgeHandoffInput(Guid PreviousDeviceId, string Reason);
- public sealed partial class MdpEdgeDeviceService
- {
- private const string HandedOff = "HANDED_OFF";
- public async Task HandoffAsync(long tenant, long factory, long dataset, Guid id, long actor, MdpEdgeHandoffInput input)
- {
- RequireEnabled();
- var reason = input.Reason?.Trim();
- Require(actor > 0 && input.PreviousDeviceId != Guid.Empty && input.PreviousDeviceId != id &&
- reason is { Length: > 0 and <= 240 } && !reason.Any(char.IsControl), "EDGE_HANDOFF_INVALID");
- var deviceId = id.ToString("D");
- var previousId = input.PreviousDeviceId.ToString("D");
- using var db = MdpIngestDatabase.Open(host);
- await Tx(db, async () =>
- {
- var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
- WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
- AND state IN ('APPROVED','ACTIVE') FOR UPDATE
- """, new { deviceId, tenant, factory, dataset }) ?? throw new EdgeContractException("EDGE_DEVICE_NOT_FOUND");
- Require(device.ConfigJson is null, "EDGE_TASK_ACTIVE");
- var binding = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
- var previous = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
- WHERE device_id=@previousId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
- AND source_id=@SourceId AND state='REVOKED' AND config_json IS NOT NULL
- AND COALESCE(task_phase,'')<>@handedOff FOR UPDATE
- """, new { previousId, tenant, factory, dataset, device.SourceId, handedOff = HandedOff })
- ?? throw new EdgeContractException("EDGE_HANDOFF_REQUIRED");
- Require(await CountOtherTaskOwnersAsync(db, previous) == 0, "EDGE_HANDOFF_REQUIRED");
- var historicalTask = ReadTask(previous);
- await MdpEdgeRoute.RequireNoDirectRunAsync(db, tenant, factory, dataset, device.SourceId,
- allowHistory: historicalTask.Mode == EdgeProtocol.ApiPush);
- var task = await ResumeTaskAsync(db, previous, historicalTask);
- if (task.State != "COMPLETE")
- {
- var (_, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding);
- Require(task.SchemaVersion == binding.SourceSchemaVersion && task.ConfigVersion == contract.ConfigVersion,
- "EDGE_CONFIGURATION_STALE");
- }
- var generation = checked(device.Generation + 1);
- task = task with { Stream = deviceId + "-" + generation.ToString(CultureInfo.InvariantCulture) };
- await StoreTaskAsync(db, deviceId, generation, task);
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_device SET task_phase=@handedOff WHERE device_id=@previousId
- """, new { handedOff = HandedOff, previousId });
- await AuditAsync(db, dataset, actor, "EDGE_TASK_HANDOFF", $"{previousId} -> {task.Stream}: {reason}");
- return true;
- });
- }
- private static async Task<EdgeTask> ResumeTaskAsync(ISqlSugarClient db, Device previous, EdgeTask task)
- {
- if (task.Mode == EdgeProtocol.ApiPush) return task with { State = "READY" };
- if (task.Mode == EdgeProtocol.ApiPull) return task with { State = task.Position is null ? "COMPLETE" : "READY" };
- Require(task.Mode == EdgeProtocol.Database && task.Relational is not null, "EDGE_TASK_INVALID");
- // The terminal empty page is durable even for rows revoked before handoff support.
- var completed = await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_edge_receipt
- WHERE device_id=@DeviceId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
- AND source_id=@SourceId AND generation=@Generation AND idem_key=@terminal
- AND JSON_UNQUOTE(JSON_EXTRACT(receipt_json,'$.status'))=@empty
- """, new { previous.DeviceId, previous.TenantId, previous.FactoryId, previous.DatasetId, previous.SourceId,
- previous.Generation, terminal = Encoding.ASCII.GetBytes("db-end"), empty = EdgeProtocol.Empty }) > 0;
- if (completed) return task with { State = "COMPLETE" };
- // A partially confirmed full or time-window snapshot still needs its original outbox.
- Require(task.PageCount == 0 && task.Position == task.StartPosition ||
- task.Relational is { Incremental: true, Time: null } &&
- long.TryParse(task.Position, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out _),
- "EDGE_HANDOFF_SNAPSHOT_REQUIRED");
- return task with { State = "READY", PageCount = 0, RowCount = 0 };
- }
- private static Task<int> CountOtherTaskOwnersAsync(ISqlSugarClient db, Device device) =>
- db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@TenantId AND factory_id=@FactoryId
- AND dataset_id=@DatasetId AND source_id=@SourceId AND device_id<>@DeviceId
- AND config_json IS NOT NULL AND (state<>'REVOKED' OR COALESCE(task_phase,'')<>@handedOff)
- """, new { device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, device.DeviceId, handedOff = HandedOff });
- private static Task<int> StoreTaskAsync(ISqlSugarClient db, string deviceId, long generation, EdgeTask task) =>
- db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_device SET config_generation=@generation,config_json=@json,position_text=@Position,
- task_phase=@State,page_count=@PageCount,row_count=@RowCount WHERE device_id=@deviceId
- """, new { deviceId, generation, json = JsonSerializer.Serialize(task, EdgeProtocol.Json),
- task.Position, task.State, task.PageCount, task.RowCount });
- }
|