using System.Security.Cryptography; 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, IngestPayloadFormat format = IngestPayloadFormat.Json) => Prepare(identity, sourceSchemaVersion, payload, limits, window, format, null); public PreparedIngestBatch PrepareApiPage(IngestDatasetIdentity identity, string sourceSchemaVersion, ReadOnlySpan payload, IngestLimits limits, IReadOnlyList arrayPath, IngestSourceWindow? window = null) => Prepare(identity, sourceSchemaVersion, payload, limits, window, IngestPayloadFormat.Json, arrayPath); public RawIngestBatch CaptureApiPage(IngestDatasetIdentity identity, string sourceSchemaVersion, ReadOnlySpan payload, IngestLimits limits, IngestSourceWindow? window = null) { var contract = ResolveContract(identity, sourceSchemaVersion, payload.Length, limits); return RawBatch(Guid.NewGuid(), identity, DateTimeOffset.UtcNow, contract, payload.ToArray(), 0, window); } private PreparedIngestBatch Prepare(IngestDatasetIdentity identity, string sourceSchemaVersion, ReadOnlySpan payload, IngestLimits limits, IngestSourceWindow? window, IngestPayloadFormat format, IReadOnlyList? arrayPath) { var contract = ResolveContract(identity, sourceSchemaVersion, payload.Length, limits); var bytes = payload.ToArray(); var batchId = Guid.NewGuid(); var receivedAt = DateTimeOffset.UtcNow; var events = IndexEvents(bytes, batchId, contract, limits, format, arrayPath); return new PreparedIngestBatch(RawBatch(batchId, identity, receivedAt, contract, bytes, events.Count, window), events); } private IngestContract ResolveContract(IngestDatasetIdentity identity, string sourceSchemaVersion, int length, IngestLimits limits) { 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 (length > limits.MaxBodyBytes) throw new IngestContractException(IngestContractError.BodyTooLarge); return contract; } private static RawIngestBatch RawBatch(Guid batchId, IngestDatasetIdentity identity, DateTimeOffset receivedAt, IngestContract contract, byte[] bytes, int count, IngestSourceWindow? window) => new(batchId, identity, receivedAt, contract.Snapshot(), count, bytes, Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(), window); private static IReadOnlyList IndexEvents( byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits, IngestPayloadFormat format, IReadOnlyList? arrayPath) { try { if (format == IngestPayloadFormat.Ndjson) return IndexNdjson(bytes, batchId, contract, limits); ValidateJson(bytes, limits.MaxJsonDepth); var root = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth }); root.Read(); var path = arrayPath ?? ["data", "list"]; var list = root; foreach (var part in path) list = FindUniqueProperty(list, Encoding.UTF8.GetBytes(part)); var pointer = string.Concat(path.Select(part => "/" + part.Replace("~", "~0").Replace("/", "~1"))); if (list.TokenType != JsonTokenType.StartArray) throw new IngestContractException(IngestContractError.InvalidEnvelope); 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, offset, limits.MaxJsonDepth, $"{pointer}/{events.Count}")); } if (events.Count == 0 && arrayPath is null) throw new IngestContractException(IngestContractError.InvalidEnvelope); return events.AsReadOnly(); } catch (JsonException) { throw new IngestContractException(IngestContractError.InvalidJson); } catch (DecoderFallbackException) { throw new IngestContractException(IngestContractError.InvalidJson); } } private static IReadOnlyList IndexNdjson( byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits) { var events = new List(); for (var start = 0; start < bytes.Length;) { var remaining = bytes.AsSpan(start); var newline = remaining.IndexOf((byte)'\n'); var line = newline < 0 ? remaining : remaining[..newline]; var length = line.Length; if (newline >= 0 && !line.IsEmpty && line[^1] == (byte)'\r') line = line[..^1]; var contentLength = line.Length; while (!line.IsEmpty && line[0] is (byte)' ' or (byte)'\t') line = line[1..]; if (line.IsEmpty || line.Contains((byte)'\r')) throw new IngestContractException(IngestContractError.InvalidEnvelope); ValidateJson(line, limits.MaxJsonDepth); var reader = new Utf8JsonReader(line, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth }); if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) throw new IngestContractException(IngestContractError.InvalidEnvelope); if (events.Count == limits.MaxRecords) throw new IngestContractException(IngestContractError.TooManyRecords); var offset = start + contentLength - line.Length; reader.Skip(); events.Add(CreateEvent(bytes.AsMemory(offset, checked((int)reader.BytesConsumed)), batchId, events.Count, contract, offset, limits.MaxJsonDepth, $"/lines/{events.Count + 1}")); start += length + 1; } if (events.Count == 0) throw new IngestContractException(IngestContractError.InvalidEnvelope); return events.AsReadOnly(); } 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, IngestContract contract, int offset, int maxDepth, string sourcePosition) { using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = maxDepth }); var row = document.RootElement; var keyParts = new List(); foreach (var field in contract.KeyFields) { var value = UniqueString(row, field.Name); if (!IsKeyPart(value, field.MaxLength)) break; keyParts.Add(value!); } var businessKey = keyParts.Count > 0 && keyParts.Count == contract.KeyFields.Count ? string.Join('#', keyParts) : null; var timeField = contract.SourceTimeField; var timestamp = timeField is null ? null : UniqueString(row, timeField); var sourceTime = timestamp is { Length: >= 6 } && (timestamp.EndsWith('Z') || timestamp[^6] is '+' or '-') && row.GetProperty(timeField!).TryGetDateTimeOffset(out _) ? timestamp : null; return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, contract.ObjectCode, sourcePosition, offset, payload.Length, Convert.ToHexString(SHA256.HashData(payload.Span)).ToLowerInvariant(), businessKey, 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; } }