| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System.Globalization;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- internal static class MdpBatchFactory
- {
- // Identity fields are part of the signed JSON. Accept string IDs so JavaScript senders retain precision.
- internal static bool TryRead(byte[] payload, long tenant, long configuredFactory, bool fromBatch, out long factory)
- {
- factory = configuredFactory;
- try
- {
- using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = MdpIngestProtocol.Limits.MaxJsonDepth });
- var root = document.RootElement;
- if (root.ValueKind != JsonValueKind.Object || !TryId(root, "factoryId", out var requested)
- || !TryId(root, "tenantId", out var claimedTenant) || claimedTenant.HasValue && claimedTenant != tenant)
- return false;
- if (fromBatch && !requested.HasValue || !fromBatch && requested.HasValue && requested != configuredFactory)
- return false;
- factory = requested ?? configuredFactory;
- if (fromBatch && root.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.Object
- && data.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
- {
- foreach (var row in list.EnumerateArray())
- {
- if (!RowMatches(row, tenant, factory)) return false;
- }
- }
- return factory > 0;
- }
- catch (JsonException)
- {
- return false;
- }
- }
- internal static bool TryResolve(long configuredFactory, bool fromBatch, long? requested, out long factory)
- {
- factory = requested ?? configuredFactory;
- return factory > 0 && (fromBatch ? requested.HasValue : factory == configuredFactory);
- }
- internal static bool RowsMatch(PreparedIngestBatch prepared)
- {
- var identity = prepared.Batch.Identity;
- foreach (var row in prepared.Events)
- {
- using var document = JsonDocument.Parse(prepared.Batch.Payload.Slice(row.PayloadOffset, row.PayloadLength));
- if (!RowMatches(document.RootElement, identity.TenantId, identity.FactoryId))
- return false;
- }
- return true;
- }
- private static bool RowMatches(JsonElement row, long tenant, long factory) =>
- row.ValueKind == JsonValueKind.Object && TryId(row, "factoryId", out var rowFactory)
- && (!rowFactory.HasValue || rowFactory == factory) && TryId(row, "tenantId", out var rowTenant)
- && (!rowTenant.HasValue || rowTenant == tenant);
- private static bool TryId(JsonElement root, string field, out long? value)
- {
- value = null;
- foreach (var property in root.EnumerateObject())
- {
- if (!property.NameEquals(field)) continue;
- if (value.HasValue || property.Value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number)
- || !long.TryParse(property.Value.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var id) || id <= 0)
- return false;
- value = id;
- }
- return true;
- }
- }
|