using System.Text; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core; public sealed class IngestBatchPreparer(ISchemaRegistry schemas) { private static readonly UTF8Encoding StrictUtf8 = new(false, true); public PreparedIngestBatch Prepare( IngestDatasetIdentity identity, string sourceSchemaVersion, ReadOnlySpan payload, IngestLimits limits, IngestSourceWindow? window = null) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxBodyBytes); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxRecords); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxJsonDepth); var contract = schemas.Find(identity.DatasetKey, sourceSchemaVersion) ?? throw new IngestContractException(IngestContractError.UnknownSchema); if (payload.Length > limits.MaxBodyBytes) throw new IngestContractException(IngestContractError.BodyTooLarge); var bytes = payload.ToArray(); var batchId = Guid.NewGuid(); var receivedAt = DateTimeOffset.UtcNow; var events = IndexEvents(bytes, batchId, contract, limits); var batch = new RawIngestBatch(batchId, identity, receivedAt, contract.Snapshot(), events.Count, bytes, PurchaseOrderSchemaRegistry.ComputeSha256(bytes), window); return new PreparedIngestBatch(batch, events); } private static IReadOnlyList IndexEvents( byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits) { try { ValidateJson(bytes, limits.MaxJsonDepth); var root = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth }); root.Read(); var data = FindUniqueProperty(root, "data"u8); var list = FindUniqueProperty(data, "list"u8); if (list.TokenType != JsonTokenType.StartArray) throw new IngestContractException(IngestContractError.InvalidEnvelope); var names = contract.FieldMapJson == null ? null : JsonSerializer.Deserialize>(contract.FieldMapJson); var events = new List(); while (list.Read() && list.TokenType != JsonTokenType.EndArray) { if (list.TokenType != JsonTokenType.StartObject) throw new IngestContractException(IngestContractError.InvalidEnvelope); if (events.Count == limits.MaxRecords) throw new IngestContractException(IngestContractError.TooManyRecords); var offset = checked((int)list.TokenStartIndex); list.Skip(); var length = checked((int)list.BytesConsumed) - offset; events.Add(CreateEvent(bytes.AsMemory(offset, length), batchId, events.Count, contract.ObjectCode, offset, limits.MaxJsonDepth, names)); } if (events.Count == 0) throw new IngestContractException(IngestContractError.InvalidEnvelope); return events.AsReadOnly(); } catch (JsonException) { throw new IngestContractException(IngestContractError.InvalidJson); } catch (DecoderFallbackException) { throw new IngestContractException(IngestContractError.InvalidJson); } } private static void ValidateJson(ReadOnlySpan bytes, int maxDepth) { StrictUtf8.GetCharCount(bytes); if (bytes.IsEmpty) throw new IngestContractException(IngestContractError.InvalidJson); var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = int.MaxValue }); while (reader.Read()) { if ((reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) && reader.CurrentDepth >= maxDepth) throw new IngestContractException(IngestContractError.JsonTooDeep); if (reader.ValueIsEscaped && (reader.TokenType is JsonTokenType.PropertyName or JsonTokenType.String)) { try { // Also reject invalid escaped Unicode, even in fields unused by this contract. reader.GetString(); } catch (InvalidOperationException) { throw new IngestContractException(IngestContractError.InvalidJson); } } } } private static Utf8JsonReader FindUniqueProperty(Utf8JsonReader reader, ReadOnlySpan name) { if (reader.TokenType != JsonTokenType.StartObject) throw new IngestContractException(IngestContractError.InvalidEnvelope); var found = false; Utf8JsonReader value = default; while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName) { var matches = reader.ValueTextEquals(name); reader.Read(); if (matches) { if (found) throw new IngestContractException(IngestContractError.InvalidEnvelope); found = true; value = reader; } reader.Skip(); } if (!found) throw new IngestContractException(IngestContractError.InvalidEnvelope); return value; } private static RawIngestEvent CreateEvent( ReadOnlyMemory payload, Guid batchId, int ordinal, string objectCode, int offset, int maxDepth, Dictionary? names) { using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = maxDepth }); var row = document.RootElement; var orderNumber = UniqueString(row, names?["PoNo"] ?? "PoNo"); var orderLine = UniqueString(row, names?["PoLine"] ?? "PoLine"); var sourceBusinessKey = IsKeyPart(orderNumber, 100) && IsKeyPart(orderLine, 50) ? $"{orderNumber}#{orderLine}" : null; var sourceUpdatedAt = UniqueString(row, names?["sourceUpdatedAt"] ?? "sourceUpdatedAt"); var sourceTime = sourceUpdatedAt is { Length: >= 6 } && (sourceUpdatedAt.EndsWith('Z') || sourceUpdatedAt[^6] is '+' or '-') && row.GetProperty(names?["sourceUpdatedAt"] ?? "sourceUpdatedAt").TryGetDateTimeOffset(out _) ? sourceUpdatedAt : null; return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, objectCode, $"/data/list/{ordinal}", offset, payload.Length, PurchaseOrderSchemaRegistry.ComputeSha256(payload.Span), sourceBusinessKey, sourceTime); } private static bool IsKeyPart(string? value, int maxLength) => !string.IsNullOrWhiteSpace(value) && value.Length <= maxLength && !value.Contains('#'); private static string? UniqueString(JsonElement row, string name) { string? value = null; var found = false; foreach (var property in row.EnumerateObject()) { if (!property.NameEquals(name)) continue; if (found || property.Value.ValueKind != JsonValueKind.String) return null; found = true; value = property.Value.GetString(); } return value; } }