using System.Globalization; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed record MdpEdgeTaskInput(string Mode, string? ApiPlan, EdgeRelationalSettings? Relational, string? ResumePosition = null); public sealed partial class MdpEdgeDeviceService { public async Task ConfigureAsync(long tenant, long factory, long dataset, Guid id, long actor, MdpEdgeTaskInput input) { RequireEnabled(); using var db = MdpIngestDatabase.Open(host); await Tx(db, async () => { var deviceId = id.ToString("D"); var device = await db.Ado.SqlQuerySingleAsync(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"); var binding = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true); Require(device.Phase is null or "COMPLETE", "EDGE_TASK_ACTIVE"); await MdpEdgeRoute.RequireNoDirectRunAsync(db, tenant, factory, dataset, device.SourceId, allowHistory: input.Mode == EdgeProtocol.ApiPush); Require(await db.Ado.GetIntAsync(""" SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@SourceId AND device_id<>@deviceId AND config_json IS NOT NULL """, new { tenant, factory, dataset, device.SourceId, deviceId }) == 0, "EDGE_HANDOFF_REQUIRED"); string? position = input.ResumePosition; if (input.Mode == EdgeProtocol.ApiPull) { var api = ParseApiPlan(input.ApiPlan); Require(input.Relational is null && position is null, "EDGE_TASK_INVALID"); position = JsonSerializer.Serialize(api.Begin(DateTimeOffset.UtcNow, null), EdgeProtocol.Json); } else if (input.Mode == EdgeProtocol.Database) { Require(input.ApiPlan is null && input.Relational is { PageSize: >= 1 and <= 100, Columns.Length: > 0 and <= 100 }, "EDGE_TASK_INVALID"); var relational = input.Relational!; if (relational.Time is { } time) { Require(relational.Driver == Admin.NET.Plugin.AiDOP.DataPlatform.Relational.NativeRelationalDriver.PostgreSqlId && relational.SourceGeneration is > 0 && time.IsValid(), "EDGE_TIME_SOURCE_UNSUPPORTED"); if (relational.Incremental) { var previous = device.ConfigJson is null ? null : ReadTask(device).Relational; Require(previous is not null && SameTimeSource(previous, relational) && device.Position is not null && (position is null || position == device.Position), "EDGE_TIME_BASELINE_REQUIRED"); position = device.Position; _ = EdgeTimeWatermark.Decode(position); } else { Require(position is null, "EDGE_TIME_BASELINE_REQUIRED"); } } else { if (relational.Incremental && position is null) position = device.Position; Require(position is null || long.TryParse(position, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "EDGE_TASK_INVALID"); } if (relational.SourceGeneration is > 0) Require(relational.ChangeVersionColumn is { Length: > 0 } column && relational.Columns.Contains(column) && (relational.DeleteColumn is null || relational.Columns.Contains(relational.DeleteColumn)), "EDGE_TASK_INVALID"); else Require(relational.SourceGeneration is null && relational.ChangeVersionColumn is null && relational.DeleteColumn is null, "EDGE_TASK_INVALID"); } else { Require(input.Mode == EdgeProtocol.ApiPush && input.ApiPlan is null && input.Relational is null && position is null, "EDGE_TASK_INVALID"); } var (_, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding); var generation = checked(device.Generation + 1); var task = new EdgeTask(deviceId + "-" + generation.ToString(CultureInfo.InvariantCulture), input.Mode, tenant, factory, device.SourceId, dataset, binding.SourceCode, binding.DatasetKey, binding.SourceSchemaVersion, contract.ConfigVersion, position, "READY", input.ApiPlan, input.Relational); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET config_generation=@generation,config_json=@json,position_text=@position, task_phase='READY',page_count=0,row_count=0 WHERE device_id=@deviceId """, new { deviceId, generation, position, json = JsonSerializer.Serialize(task, EdgeProtocol.Json) }); await AuditAsync(db, dataset, actor, "EDGE_TASK_APPROVED", task.Stream); return true; }); } public async Task FindReceiptAsync(X509Certificate2 certificate, Guid id) { RequireEnabled(); using var db = MdpIngestDatabase.Open(host); var device = await AuthenticateAsync(db, certificate, false); return await FindAsync(db, device, id); } public async Task ReceiveAsync(X509Certificate2 certificate, EdgeBatch batch, CancellationToken token) { RequireEnabled(); batch.Validate(); using var db = MdpIngestDatabase.Open(host); return await Tx(db, async () => { var device = await AuthenticateAsync(db, certificate, true); var previous = await FindAsync(db, device, batch.BatchId); if (previous is not null) { Require(previous.Confirms(batch) || previous.Rejects(batch), "EDGE_BATCH_CONFLICT"); return previous; } var task = await RecoveryTaskAsync(db, device, includeSettled: false); Require(task.Stream == batch.Stream && task.State == "READY" && device.SeenAt is { } seen && DateTime.UtcNow - seen < TimeSpan.FromSeconds(60), "EDGE_TASK_STALE"); Require(task.Mode == EdgeProtocol.ApiPush ? batch.Position is null && batch.NextPosition is null : batch.Position == device.Position && !batch.Ndjson, "EDGE_POSITION_STALE"); Require(batch.ReceiverConfirmsNext == (task.Mode == EdgeProtocol.ApiPull) && (!batch.ReceiverConfirmsNext || batch.NextPosition is null && batch.Key == task.PageKey()), "EDGE_POSITION_INVALID"); var binding = await BoundAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, true); Require(binding.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE"); await RequireWriterAsync(db, device, binding.SourceCode); var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(binding); Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE"); if (task.Mode == EdgeProtocol.ApiPush && await ExistingPushAsync(db, device, batch, task.SchemaVersion) is { } replay) return replay; var preparer = new IngestBatchPreparer(schemas); var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, binding.SourceCode, binding.DatasetKey); var limits = MdpIngestProtocol.Limits; var window = task.Mode switch { EdgeProtocol.ApiPull => new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime), EdgeProtocol.Database when task.Relational?.SourceGeneration is > 0 => new IngestSourceWindow(null, null, IngestSourceWindow.VerifiedRelationalSnapshot) { SourceGeneration = task.Relational.SourceGeneration }, _ => null }; var archiveKey = Encoding.ASCII.GetBytes("\0edge-" + batch.BatchId.ToString("D")); var captured = preparer.CaptureApiPage(scope, task.SchemaVersion, batch.Body, limits, window) with { BatchId = batch.BatchId }; await MdpIngestReceiveService.PersistRawWithJournalAsync(db, captured, [], batch.Body, archiveKey, captured.ReceivedAt, token); var confirmation = batch.NextPosition; var isCompleted = false; PreparedIngestBatch? prepared = null; string? code = null; try { if (task.Mode == EdgeProtocol.ApiPull) { var result = await ParseApiPageAsync(db, device, task, batch, preparer, scope, window!, ParseApiPlan(task.ApiPlan)); prepared = result.Prepared; confirmation = result.ConfirmedPosition; isCompleted = confirmation is null; } else if (task.Mode == EdgeProtocol.Database && batch.Body.Length == 0) { if (task.Relational?.Time is not null) { var boundary = EdgeTimeWatermark.Decode(batch.NextPosition); Require(boundary <= DateTimeOffset.UtcNow.AddMinutes(5) && (task.StartPosition is null || boundary >= EdgeTimeWatermark.Decode(task.StartPosition)), "EDGE_TIME_BOUNDARY_INVALID"); } else { Require(batch.NextPosition == batch.Position, "EDGE_POSITION_INVALID"); } isCompleted = true; } else { prepared = preparer.Prepare(scope, task.SchemaVersion, batch.Body, limits, window, format: batch.Ndjson ? IngestPayloadFormat.Ndjson : IngestPayloadFormat.Json); if (task.Mode == EdgeProtocol.Database) { if (task.Relational?.Time is not null) Require(EdgeTimeWatermark.AdvancesPage(batch.Position, batch.NextPosition, task.Relational.Incremental), "EDGE_POSITION_INVALID"); else { var from = batch.Position is null ? long.MinValue : ParsePosition(batch.Position); var to = ParsePosition(batch.NextPosition); Require(to > from, "EDGE_POSITION_INVALID"); if (task.Relational?.UpperPosition is { } upper) Require(to <= upper, "EDGE_POSITION_INVALID"); } } } Require(prepared is null || MdpBatchFactory.RowsMatch(prepared), "EDGE_BATCH_SCOPE_INVALID"); } catch (Exception error) when (error is EdgeContractException or MdpApiPullException or IngestContractException or JsonException) { code = error switch { EdgeContractException edge => edge.Code, MdpApiPullException pull => pull.Code, IngestContractException contractError => "EDGE_" + contractError.Code.ToString().ToUpperInvariant(), _ => "EDGE_INVALID_JSON" }; } var count = code is null ? prepared?.Events.Count ?? 0 : 0; var key = task.Mode == EdgeProtocol.ApiPush ? Encoding.ASCII.GetBytes(batch.Key) : archiveKey; if (count > 0) { var accepted = prepared! with { Batch = prepared!.Batch with { BatchId = batch.BatchId, ReceivedAt = captured.ReceivedAt }, Events = prepared.Events.Select(item => item with { BatchId = batch.BatchId }).ToArray() }; await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, accepted, key, device.FactoryId, token, useCapturedRaw: true); } if (count == 0) await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, scope, code is null ? IngestBatchJournal.RawEmpty : IngestBatchJournal.RawRejected, 0, code); var status = code is not null ? EdgeProtocol.Rejected : count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted; var receipt = new EdgeReceipt(batch.BatchId, batch.Digest, status, batch.BatchId, code is null ? confirmation : batch.Position, code, batch.Position); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_edge_receipt(batch_id,device_id,tenant_id,factory_id,dataset_id,source_id,generation, idem_key,digest,position_hash,receipt_json) VALUES (@batchId,@DeviceId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Generation,@key,@Digest,@positionHash,@json) """, new { batchId = batch.BatchId.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId, device.Generation, key = Encoding.ASCII.GetBytes(batch.Key), batch.Digest, positionHash = batch.Position is null ? null : HashText(batch.Position), json = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) }); if (task.Mode == EdgeProtocol.ApiPull && code is not null) await RecordRejectedPageAsync(db, device, batch); if (task.Mode != EdgeProtocol.ApiPush) await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET position_text=@ConfirmedPosition,task_phase=@phase, page_count=page_count+@pages,row_count=row_count+@count WHERE device_id=@DeviceId """, new { device.DeviceId, receipt.ConfirmedPosition, phase = code is not null ? "BLOCKED" : isCompleted ? "COMPLETE" : "READY", pages = code is null ? 1 : 0, count }); token.ThrowIfCancellationRequested(); return receipt; }); } private static async Task ExistingPushAsync(ISqlSugarClient db, Device device, EdgeBatch batch, string schema) { var stored = await db.Ado.SqlQuerySingleAsync(""" SELECT b.batch_id AS BatchId,b.payload_sha256 AS Digest,b.source_schema_version AS SchemaVersion, (SELECT e.source_position FROM mdp_ingest_raw_event e WHERE e.batch_id=b.batch_id AND e.record_ordinal=0) AS FirstPosition FROM mdp_ingest_raw_batch b WHERE b.tenant_id=@TenantId AND b.factory_id=@FactoryId AND b.source_id=@SourceId AND b.dataset_id=@DatasetId AND b.idempotency_key=@key AND b.accepted_record_count>0 """, new { device.TenantId, device.FactoryId, device.SourceId, device.DatasetId, key = Encoding.ASCII.GetBytes(batch.Key) }); if (stored is null) return null; Require(stored.Digest == batch.Digest && stored.SchemaVersion == schema && batch.Ndjson == (stored.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true), "EDGE_BATCH_CONFLICT"); return new EdgeReceipt(batch.BatchId, batch.Digest, EdgeProtocol.Accepted, Guid.Parse(stored.BatchId), null); } private sealed class PushReceipt { public string BatchId { get; set; } = ""; public string Digest { get; set; } = ""; public string SchemaVersion { get; set; } = ""; public string? FirstPosition { get; set; } } private static long ParsePosition(string? value) => long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed) ? parsed : throw new EdgeContractException("EDGE_POSITION_INVALID"); private static async Task FindAsync(ISqlSugarClient db, Device device, Guid id) { var json = await db.Ado.SqlQuerySingleAsync(""" SELECT receipt_json FROM mdp_edge_receipt WHERE batch_id=@batchId AND device_id=@DeviceId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId """, new { batchId = id.ToString("D"), device.DeviceId, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId }); return string.IsNullOrEmpty(json) ? null : JsonSerializer.Deserialize(json, EdgeProtocol.Json); } private static EdgeTask ReadTask(Device device) { var configured = device.ConfigJson is null ? null : JsonSerializer.Deserialize(device.ConfigJson, EdgeProtocol.Json); if (configured is null) throw new EdgeContractException("EDGE_TASK_ABSENT"); return configured with { StartPosition = configured.Position, Position = device.Position, State = device.Phase!, PageCount = device.PageCount, RowCount = device.RowCount }; } private static bool SameTimeSource(EdgeRelationalSettings previous, EdgeRelationalSettings next) => previous.Time == next.Time && previous.Driver == next.Driver && previous.Database == next.Database && previous.Schema == next.Schema && previous.Table == next.Table && previous.PositionColumn == next.PositionColumn && previous.SourceGeneration == next.SourceGeneration && previous.ChangeVersionColumn == next.ChangeVersionColumn && previous.DeleteColumn == next.DeleteColumn && previous.Columns.SequenceEqual(next.Columns, StringComparer.Ordinal); private static MdpApiPullPlan ParseApiPlan(string? json) { Require(json is { Length: > 0 and <= 65536 }, "EDGE_TASK_INVALID"); var plan = JsonSerializer.Deserialize(json!, EdgeProtocol.Json) ?? throw new EdgeContractException("EDGE_TASK_INVALID"); plan.Validate(); return plan; } private static async Task BoundAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source, bool locked) { var key = await db.Ado.GetStringAsync(""" SELECT dataset_key FROM mdp_ingest_dataset WHERE id=@dataset AND tenant_id=@tenant AND factory_id=@factory AND enabled=1 """ + (locked ? " FOR UPDATE" : ""), new { tenant, factory, dataset }); Require(!string.IsNullOrEmpty(key), "EDGE_SCOPE_UNAVAILABLE"); return await new MdpIngestDatasetRegistry(db).ResolveActiveBindingAsync(tenant, factory, source, key) ?? throw new EdgeContractException("EDGE_SCOPE_UNAVAILABLE"); } private static async Task RequireWriterAsync(ISqlSugarClient db, Device device, string sourceCode) { var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, device.TenantId, device.FactoryId, device.DatasetId, device.SourceId); MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified); if (migration is not null) { Require(migration.NewSourceCode == sourceCode, "EDGE_WRITER_FORBIDDEN"); return; } var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(device.TenantId, "PURCHASE"); Require(string.Equals(authority?.SourceSystem, sourceCode, StringComparison.OrdinalIgnoreCase), "EDGE_WRITER_FORBIDDEN"); } }