EdgeProtocol.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using System.Text.Json;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  5. public static class EdgeProtocol
  6. {
  7. public const int MaxBodyBytes = 1024 * 1024;
  8. public const int MaxPositionLength = 8192;
  9. public const string Buffered = "buffered";
  10. public const string Accepted = "accepted";
  11. public const string Empty = "empty";
  12. public const string Rejected = "rejected";
  13. public const string Database = "database";
  14. public const string ApiPull = "api-pull";
  15. public const string ApiPush = "api-push";
  16. public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
  17. public static string Digest(ReadOnlySpan<byte> bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
  18. }
  19. public sealed record EdgeBatch(Guid BatchId, string Stream, string Key, string Digest, string? Position,
  20. string? NextPosition, byte[] Body, string? EffectiveUrl = null, string? NextLink = null, string? Diagnostic = null,
  21. bool Ndjson = false, bool ReceiverConfirmsNext = false)
  22. {
  23. public static EdgeBatch Create(string stream, string key, string? position, string? nextPosition, byte[] body)
  24. {
  25. var batch = new EdgeBatch(StableId(stream, key), stream, key, EdgeProtocol.Digest(body), position, nextPosition, body.ToArray());
  26. batch.Validate();
  27. return batch;
  28. }
  29. public void Validate()
  30. {
  31. if (!ValidKey(Stream, 96) || !ValidKey(Key, 128)
  32. || Body is null || Body.Length > EdgeProtocol.MaxBodyBytes || BatchId != StableId(Stream, Key)
  33. || Digest != EdgeProtocol.Digest(Body)
  34. || Position?.Length > EdgeProtocol.MaxPositionLength || NextPosition?.Length > EdgeProtocol.MaxPositionLength
  35. || EffectiveUrl?.Length > 2048 || NextLink?.Length > 2048 || Diagnostic?.Length > 80)
  36. throw new EdgeContractException("EDGE_BATCH_INVALID");
  37. }
  38. private static bool ValidKey(string? value, int limit) =>
  39. value is { Length: > 0 } && value.Length <= limit && value.All(ch => ch is >= '!' and <= '~');
  40. private static Guid StableId(string stream, string key) =>
  41. new(SHA256.HashData(Encoding.UTF8.GetBytes(stream + "\n" + key)).AsSpan(0, 16));
  42. }
  43. public sealed record EdgeReceipt(Guid BatchId, string Digest, string Status, Guid? RawBatchId, string? ConfirmedPosition,
  44. string? Diagnostic = null, string? SourcePosition = null)
  45. {
  46. public bool Confirms(EdgeBatch batch) =>
  47. BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty
  48. && Status is EdgeProtocol.Accepted or EdgeProtocol.Empty
  49. && (batch.ReceiverConfirmsNext ? SourcePosition == batch.Position : ConfirmedPosition == batch.NextPosition);
  50. public bool Rejects(EdgeBatch batch) =>
  51. BatchId == batch.BatchId && Digest == batch.Digest && RawBatchId is { } id && id != Guid.Empty
  52. && Status == EdgeProtocol.Rejected && ConfirmedPosition == batch.Position;
  53. }
  54. public sealed record EdgeRegistration(string Activation, string RequestPem);
  55. public sealed record EdgeCertificate(Guid DeviceId, string CertificatePem);
  56. public sealed record EdgeRenewal(string RequestPem);
  57. public sealed record EdgeReport(string Version, int Pending, long BufferedBytes, long FreeBytes, string? LastError);
  58. public sealed record EdgeRelationalSettings(string Driver, string Database, string Schema, string Table,
  59. string PositionColumn, string[] Columns, string SecretRef, int PageSize = 100, bool Incremental = false,
  60. string? OdbcFamily = null, long? UpperPosition = null, string? ChangeVersionColumn = null,
  61. string? DeleteColumn = null, long? SourceGeneration = null, EdgeRelationalTimeSettings? Time = null);
  62. public sealed record EdgeTask(string Stream, string Mode, long TenantId, long FactoryId, long SourceId, long DatasetId,
  63. string SourceCode, string DatasetKey, string SchemaVersion, string ConfigVersion, string? Position,
  64. string State, string? ApiPlan = null, EdgeRelationalSettings? Relational = null, DateTimeOffset? LeaseUntil = null, int PageCount = 0, long RowCount = 0,
  65. int RecoveryAttempt = 0, IReadOnlyList<Guid>? SettledPages = null, string? StartPosition = null)
  66. {
  67. public string PageKey()
  68. {
  69. if (Mode != EdgeProtocol.ApiPull || Position is null || RecoveryAttempt < 0)
  70. throw new EdgeContractException("EDGE_POSITION_INVALID");
  71. var hash = EdgeProtocol.Digest(Encoding.UTF8.GetBytes(Position));
  72. return RecoveryAttempt == 0 ? "page-" + hash : FormattableString.Invariant($"page-{hash}-{RecoveryAttempt}");
  73. }
  74. }
  75. public sealed class EdgeContractException(string code) : Exception(code)
  76. {
  77. public string Code { get; } = code;
  78. }