IngestBatchPreparer.cs 11 KB

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