IngestBatchPreparer.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using System.Text;
  2. using System.Text.Json;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
  5. {
  6. private static readonly UTF8Encoding StrictUtf8 = new(false, true);
  7. public PreparedIngestBatch Prepare(
  8. IngestDatasetIdentity identity,
  9. string sourceSchemaVersion,
  10. ReadOnlySpan<byte> payload,
  11. IngestLimits limits,
  12. IngestSourceWindow? window = null)
  13. {
  14. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxBodyBytes);
  15. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxRecords);
  16. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxJsonDepth);
  17. var contract = schemas.Find(identity.DatasetKey, sourceSchemaVersion)
  18. ?? throw new IngestContractException(IngestContractError.UnknownSchema);
  19. if (payload.Length > limits.MaxBodyBytes)
  20. throw new IngestContractException(IngestContractError.BodyTooLarge);
  21. var bytes = payload.ToArray();
  22. var batchId = Guid.NewGuid();
  23. var receivedAt = DateTimeOffset.UtcNow;
  24. var events = IndexEvents(bytes, batchId, contract, limits);
  25. var batch = new RawIngestBatch(batchId, identity, receivedAt, contract.Snapshot(), events.Count,
  26. bytes, PurchaseOrderSchemaRegistry.ComputeSha256(bytes), window);
  27. return new PreparedIngestBatch(batch, events);
  28. }
  29. private static IReadOnlyList<RawIngestEvent> IndexEvents(
  30. byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits)
  31. {
  32. try
  33. {
  34. ValidateJson(bytes, limits.MaxJsonDepth);
  35. var root = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth });
  36. root.Read();
  37. var data = FindUniqueProperty(root, "data"u8);
  38. var list = FindUniqueProperty(data, "list"u8);
  39. if (list.TokenType != JsonTokenType.StartArray)
  40. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  41. var names = contract.FieldMapJson == null ? null : JsonSerializer.Deserialize<Dictionary<string,string>>(contract.FieldMapJson);
  42. var events = new List<RawIngestEvent>();
  43. while (list.Read() && list.TokenType != JsonTokenType.EndArray)
  44. {
  45. if (list.TokenType != JsonTokenType.StartObject)
  46. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  47. if (events.Count == limits.MaxRecords)
  48. throw new IngestContractException(IngestContractError.TooManyRecords);
  49. var offset = checked((int)list.TokenStartIndex);
  50. list.Skip();
  51. var length = checked((int)list.BytesConsumed) - offset;
  52. events.Add(CreateEvent(bytes.AsMemory(offset, length), batchId, events.Count, contract.ObjectCode, offset, limits.MaxJsonDepth, names));
  53. }
  54. if (events.Count == 0)
  55. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  56. return events.AsReadOnly();
  57. }
  58. catch (JsonException)
  59. {
  60. throw new IngestContractException(IngestContractError.InvalidJson);
  61. }
  62. catch (DecoderFallbackException)
  63. {
  64. throw new IngestContractException(IngestContractError.InvalidJson);
  65. }
  66. }
  67. private static void ValidateJson(ReadOnlySpan<byte> bytes, int maxDepth)
  68. {
  69. StrictUtf8.GetCharCount(bytes);
  70. if (bytes.IsEmpty)
  71. throw new IngestContractException(IngestContractError.InvalidJson);
  72. var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = int.MaxValue });
  73. while (reader.Read())
  74. {
  75. if ((reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) && reader.CurrentDepth >= maxDepth)
  76. throw new IngestContractException(IngestContractError.JsonTooDeep);
  77. if (reader.ValueIsEscaped && (reader.TokenType is JsonTokenType.PropertyName or JsonTokenType.String))
  78. {
  79. try
  80. {
  81. // Also reject invalid escaped Unicode, even in fields unused by this contract.
  82. reader.GetString();
  83. }
  84. catch (InvalidOperationException)
  85. {
  86. throw new IngestContractException(IngestContractError.InvalidJson);
  87. }
  88. }
  89. }
  90. }
  91. private static Utf8JsonReader FindUniqueProperty(Utf8JsonReader reader, ReadOnlySpan<byte> name)
  92. {
  93. if (reader.TokenType != JsonTokenType.StartObject)
  94. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  95. var found = false;
  96. Utf8JsonReader value = default;
  97. while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
  98. {
  99. var matches = reader.ValueTextEquals(name);
  100. reader.Read();
  101. if (matches)
  102. {
  103. if (found)
  104. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  105. found = true;
  106. value = reader;
  107. }
  108. reader.Skip();
  109. }
  110. if (!found)
  111. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  112. return value;
  113. }
  114. private static RawIngestEvent CreateEvent(
  115. ReadOnlyMemory<byte> payload, Guid batchId, int ordinal, string objectCode, int offset, int maxDepth, Dictionary<string,string>? names)
  116. {
  117. using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = maxDepth });
  118. var row = document.RootElement;
  119. var orderNumber = UniqueString(row, names?["PoNo"] ?? "PoNo");
  120. var orderLine = UniqueString(row, names?["PoLine"] ?? "PoLine");
  121. var sourceBusinessKey = IsKeyPart(orderNumber, 100) && IsKeyPart(orderLine, 50)
  122. ? $"{orderNumber}#{orderLine}"
  123. : null;
  124. var sourceUpdatedAt = UniqueString(row, names?["sourceUpdatedAt"] ?? "sourceUpdatedAt");
  125. var sourceTime = sourceUpdatedAt is { Length: >= 6 }
  126. && (sourceUpdatedAt.EndsWith('Z') || sourceUpdatedAt[^6] is '+' or '-')
  127. && row.GetProperty(names?["sourceUpdatedAt"] ?? "sourceUpdatedAt").TryGetDateTimeOffset(out _)
  128. ? sourceUpdatedAt
  129. : null;
  130. return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, objectCode, $"/data/list/{ordinal}", offset,
  131. payload.Length, PurchaseOrderSchemaRegistry.ComputeSha256(payload.Span), sourceBusinessKey, sourceTime);
  132. }
  133. private static bool IsKeyPart(string? value, int maxLength) =>
  134. !string.IsNullOrWhiteSpace(value) && value.Length <= maxLength && !value.Contains('#');
  135. private static string? UniqueString(JsonElement row, string name)
  136. {
  137. string? value = null;
  138. var found = false;
  139. foreach (var property in row.EnumerateObject())
  140. {
  141. if (!property.NameEquals(name))
  142. continue;
  143. if (found || property.Value.ValueKind != JsonValueKind.String)
  144. return null;
  145. found = true;
  146. value = property.Value.GetString();
  147. }
  148. return value;
  149. }
  150. }