| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- using System.Globalization;
- using System.Text.Json;
- 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 (row.ValueKind != JsonValueKind.Object || !TryId(row, "factoryId", out var rowFactory)
- || rowFactory.HasValue && rowFactory != factory || !TryId(row, "tenantId", out var rowTenant)
- || rowTenant.HasValue && rowTenant != tenant) return false;
- }
- }
- return factory > 0;
- }
- catch (JsonException)
- {
- return false;
- }
- }
- 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;
- }
- }
|