IngestBatchPreparer.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using System.Text.Json;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
  6. {
  7. private static readonly UTF8Encoding StrictUtf8 = new(false, true);
  8. public PreparedIngestBatch Prepare(
  9. IngestDatasetIdentity identity,
  10. string sourceSchemaVersion,
  11. ReadOnlySpan<byte> payload,
  12. IngestLimits limits,
  13. IngestSourceWindow? window = null,
  14. IngestPayloadFormat format = IngestPayloadFormat.Json)
  15. {
  16. var contract = ResolveContract(identity, sourceSchemaVersion, payload.Length, limits);
  17. var bytes = payload.ToArray();
  18. var batchId = Guid.NewGuid();
  19. var receivedAt = DateTimeOffset.UtcNow;
  20. var events = IndexEvents(bytes, batchId, contract, limits, format);
  21. var batch = new RawIngestBatch(batchId, identity, receivedAt, contract.Snapshot(), events.Count,
  22. bytes, PurchaseOrderSchemaRegistry.ComputeSha256(bytes), window);
  23. return new PreparedIngestBatch(batch, events);
  24. }
  25. private IngestContract ResolveContract(IngestDatasetIdentity identity, string sourceSchemaVersion, int length, IngestLimits limits)
  26. {
  27. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxBodyBytes);
  28. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxRecords);
  29. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxJsonDepth);
  30. var contract = schemas.Find(identity.DatasetKey, sourceSchemaVersion)
  31. ?? throw new IngestContractException(IngestContractError.UnknownSchema);
  32. if (length > limits.MaxBodyBytes)
  33. throw new IngestContractException(IngestContractError.BodyTooLarge);
  34. return contract;
  35. }
  36. private static IReadOnlyList<RawIngestEvent> IndexEvents(
  37. byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits, IngestPayloadFormat format)
  38. {
  39. try
  40. {
  41. if (format == IngestPayloadFormat.Ndjson)
  42. return IndexNdjson(bytes, batchId, contract, limits);
  43. ValidateJson(bytes, limits.MaxJsonDepth);
  44. var root = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth });
  45. root.Read();
  46. var data = FindUniqueProperty(root, "data"u8);
  47. var list = FindUniqueProperty(data, "list"u8);
  48. if (list.TokenType != JsonTokenType.StartArray)
  49. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  50. var events = new List<RawIngestEvent>();
  51. while (list.Read() && list.TokenType != JsonTokenType.EndArray)
  52. {
  53. if (list.TokenType != JsonTokenType.StartObject)
  54. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  55. if (events.Count == limits.MaxRecords)
  56. throw new IngestContractException(IngestContractError.TooManyRecords);
  57. var offset = checked((int)list.TokenStartIndex);
  58. list.Skip();
  59. var length = checked((int)list.BytesConsumed) - offset;
  60. events.Add(CreateEvent(bytes.AsMemory(offset, length), batchId, events.Count, contract, offset, limits.MaxJsonDepth, $"/data/list/{events.Count}"));
  61. }
  62. if (events.Count == 0)
  63. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  64. return events.AsReadOnly();
  65. }
  66. catch (JsonException)
  67. {
  68. throw new IngestContractException(IngestContractError.InvalidJson);
  69. }
  70. catch (DecoderFallbackException)
  71. {
  72. throw new IngestContractException(IngestContractError.InvalidJson);
  73. }
  74. }
  75. private static IReadOnlyList<RawIngestEvent> IndexNdjson(
  76. byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits)
  77. {
  78. var events = new List<RawIngestEvent>();
  79. for (var start = 0; start < bytes.Length;)
  80. {
  81. var remaining = bytes.AsSpan(start);
  82. var newline = remaining.IndexOf((byte)'\n');
  83. var line = newline < 0 ? remaining : remaining[..newline];
  84. var length = line.Length;
  85. if (newline >= 0 && !line.IsEmpty && line[^1] == (byte)'\r')
  86. line = line[..^1];
  87. var contentLength = line.Length;
  88. while (!line.IsEmpty && line[0] is (byte)' ' or (byte)'\t')
  89. line = line[1..];
  90. if (line.IsEmpty || line.Contains((byte)'\r'))
  91. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  92. ValidateJson(line, limits.MaxJsonDepth);
  93. var reader = new Utf8JsonReader(line, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth });
  94. if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject)
  95. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  96. if (events.Count == limits.MaxRecords)
  97. throw new IngestContractException(IngestContractError.TooManyRecords);
  98. var offset = start + contentLength - line.Length;
  99. reader.Skip();
  100. events.Add(CreateEvent(bytes.AsMemory(offset, checked((int)reader.BytesConsumed)), batchId,
  101. events.Count, contract, offset, limits.MaxJsonDepth, $"/lines/{events.Count + 1}"));
  102. start += length + 1;
  103. }
  104. if (events.Count == 0)
  105. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  106. return events.AsReadOnly();
  107. }
  108. private static void ValidateJson(ReadOnlySpan<byte> bytes, int maxDepth)
  109. {
  110. StrictUtf8.GetCharCount(bytes);
  111. if (bytes.IsEmpty)
  112. throw new IngestContractException(IngestContractError.InvalidJson);
  113. var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = int.MaxValue });
  114. while (reader.Read())
  115. {
  116. if ((reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) && reader.CurrentDepth >= maxDepth)
  117. throw new IngestContractException(IngestContractError.JsonTooDeep);
  118. if (reader.ValueIsEscaped && (reader.TokenType is JsonTokenType.PropertyName or JsonTokenType.String))
  119. {
  120. try
  121. {
  122. // Also reject invalid escaped Unicode, even in fields unused by this contract.
  123. reader.GetString();
  124. }
  125. catch (InvalidOperationException)
  126. {
  127. throw new IngestContractException(IngestContractError.InvalidJson);
  128. }
  129. }
  130. }
  131. }
  132. private static Utf8JsonReader FindUniqueProperty(Utf8JsonReader reader, ReadOnlySpan<byte> name)
  133. {
  134. if (reader.TokenType != JsonTokenType.StartObject)
  135. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  136. var found = false;
  137. Utf8JsonReader value = default;
  138. while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
  139. {
  140. var matches = reader.ValueTextEquals(name);
  141. reader.Read();
  142. if (matches)
  143. {
  144. if (found)
  145. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  146. found = true;
  147. value = reader;
  148. }
  149. reader.Skip();
  150. }
  151. if (!found)
  152. throw new IngestContractException(IngestContractError.InvalidEnvelope);
  153. return value;
  154. }
  155. private static RawIngestEvent CreateEvent(
  156. ReadOnlyMemory<byte> payload, Guid batchId, int ordinal, IngestContract contract, int offset, int maxDepth,
  157. string sourcePosition)
  158. {
  159. using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = maxDepth });
  160. var row = document.RootElement;
  161. var keyParts = new List<string>();
  162. foreach (var field in contract.KeyFields)
  163. {
  164. var value = UniqueString(row, field.Name);
  165. if (!IsKeyPart(value, field.MaxLength))
  166. break;
  167. keyParts.Add(value!);
  168. }
  169. var businessKey = keyParts.Count > 0 && keyParts.Count == contract.KeyFields.Count
  170. ? string.Join('#', keyParts)
  171. : null;
  172. var timeField = contract.SourceTimeField;
  173. var timestamp = timeField is null ? null : UniqueString(row, timeField);
  174. var sourceTime = timestamp is { Length: >= 6 }
  175. && (timestamp.EndsWith('Z') || timestamp[^6] is '+' or '-')
  176. && row.GetProperty(timeField!).TryGetDateTimeOffset(out _)
  177. ? timestamp
  178. : null;
  179. return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, contract.ObjectCode, sourcePosition, offset,
  180. payload.Length, Convert.ToHexString(SHA256.HashData(payload.Span)).ToLowerInvariant(),
  181. businessKey, sourceTime);
  182. }
  183. private static bool IsKeyPart(string? value, int maxLength) =>
  184. !string.IsNullOrWhiteSpace(value) && value.Length <= maxLength && !value.Contains('#');
  185. private static string? UniqueString(JsonElement row, string name)
  186. {
  187. string? value = null;
  188. var found = false;
  189. foreach (var property in row.EnumerateObject())
  190. {
  191. if (!property.NameEquals(name))
  192. continue;
  193. if (found || property.Value.ValueKind != JsonValueKind.String)
  194. return null;
  195. found = true;
  196. value = property.Value.GetString();
  197. }
  198. return value;
  199. }
  200. }