MdpBatchFactory.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Globalization;
  2. using System.Text.Json;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  4. internal static class MdpBatchFactory
  5. {
  6. // Identity fields are part of the signed JSON. Accept string IDs so JavaScript senders retain precision.
  7. internal static bool TryRead(byte[] payload, long tenant, long configuredFactory, bool fromBatch, out long factory)
  8. {
  9. factory = configuredFactory;
  10. try
  11. {
  12. using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = MdpIngestProtocol.Limits.MaxJsonDepth });
  13. var root = document.RootElement;
  14. if (root.ValueKind != JsonValueKind.Object || !TryId(root, "factoryId", out var requested)
  15. || !TryId(root, "tenantId", out var claimedTenant) || claimedTenant.HasValue && claimedTenant != tenant)
  16. return false;
  17. if (fromBatch && !requested.HasValue || !fromBatch && requested.HasValue && requested != configuredFactory)
  18. return false;
  19. factory = requested ?? configuredFactory;
  20. if (fromBatch && root.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.Object
  21. && data.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
  22. {
  23. foreach (var row in list.EnumerateArray())
  24. {
  25. if (row.ValueKind != JsonValueKind.Object || !TryId(row, "factoryId", out var rowFactory)
  26. || rowFactory.HasValue && rowFactory != factory || !TryId(row, "tenantId", out var rowTenant)
  27. || rowTenant.HasValue && rowTenant != tenant) return false;
  28. }
  29. }
  30. return factory > 0;
  31. }
  32. catch (JsonException)
  33. {
  34. return false;
  35. }
  36. }
  37. private static bool TryId(JsonElement root, string field, out long? value)
  38. {
  39. value = null;
  40. foreach (var property in root.EnumerateObject())
  41. {
  42. if (!property.NameEquals(field)) continue;
  43. if (value.HasValue || property.Value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number)
  44. || !long.TryParse(property.Value.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var id) || id <= 0)
  45. return false;
  46. value = id;
  47. }
  48. return true;
  49. }
  50. }