MdpApiPullPlan.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using System.Globalization;
  2. using System.Text.Json;
  3. using System.Text.RegularExpressions;
  4. using Microsoft.AspNetCore.WebUtilities;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed record MdpApiPullPlan(
  7. string Url, string Method = "GET", string ResponsePath = "", string Mode = "page",
  8. string PositionParameter = "page", string PageSizeParameter = "limit", int PageSize = 50,
  9. long FirstPosition = 1, string? NextCursorPath = null, string? TotalPath = null,
  10. string? SourceTimePath = null, string? BusinessKeyPath = null, DateTimeOffset? InitialFromUtc = null,
  11. string Auth = "none", string? CredentialRef = null, string? TokenUrl = null, string? TokenScope = null,
  12. string? PostJson = null, bool ReadOnlyPost = false, bool StableWindow = false,
  13. int MaxPages = 100, int LookbackSeconds = 0, int PollSeconds = 0,
  14. IReadOnlyDictionary<string, string>? Query = null)
  15. {
  16. private static readonly Regex Name = new(@"\A[A-Za-z_][A-Za-z0-9_.-]{0,79}\z");
  17. private static readonly Regex SecretRef = new(@"\AMDP_API_PULL_SECRET_[A-Z0-9_]{1,64}\z");
  18. private static readonly string[] WatermarkParameters = ["from", "until", "afterTime", "afterKey"];
  19. internal Uri Endpoint => new(Url, UriKind.Absolute);
  20. internal void Validate()
  21. {
  22. Require(Uri.TryCreate(Url, UriKind.Absolute, out var endpoint) && endpoint.Scheme == "https"
  23. && endpoint.UserInfo.Length == 0 && endpoint.Fragment.Length == 0 && endpoint.Query.Length == 0
  24. && Url.Length <= 1500);
  25. Require(Method == "GET" || Method == "POST" && ReadOnlyPost && PostJson is { Length: <= 8192 });
  26. if (Method == "POST")
  27. {
  28. using var json = JsonDocument.Parse(PostJson!);
  29. Require(json.RootElement.ValueKind == JsonValueKind.Object && !ContainsCredential(json.RootElement));
  30. }
  31. Require(Mode is "single" or "page" or "offset" or "cursor" or "link" or "time");
  32. Require(PageSize is > 0 and <= 100 && MaxPages is > 0 and <= 500 && FirstPosition >= 0);
  33. Require(Name.IsMatch(PositionParameter) && Name.IsMatch(PageSizeParameter)
  34. && !PositionParameter.Equals(PageSizeParameter, StringComparison.OrdinalIgnoreCase));
  35. var reserved = new HashSet<string>([PositionParameter, PageSizeParameter], StringComparer.OrdinalIgnoreCase);
  36. if (Mode == "time")
  37. Require(WatermarkParameters.All(reserved.Add));
  38. if (Query is not null)
  39. Require(Query.Count <= 12 && Query.All(pair => Name.IsMatch(pair.Key) && !CredentialName(pair.Key)
  40. && reserved.Add(pair.Key) && pair.Value is { Length: <= 180 } && !pair.Value.Any(char.IsControl)));
  41. Require(Mode is not ("page" or "offset" or "time") || StableWindow);
  42. Require(Mode != "cursor" || !string.IsNullOrEmpty(NextCursorPath));
  43. Require(Mode != "time" || InitialFromUtc.HasValue && !string.IsNullOrEmpty(SourceTimePath)
  44. && !string.IsNullOrEmpty(BusinessKeyPath));
  45. Require(LookbackSeconds is >= 0 and <= 86400 && PollSeconds is 0 or >= 60 and <= 86400);
  46. foreach (var value in new[] { ResponsePath, NextCursorPath, TotalPath, SourceTimePath, BusinessKeyPath })
  47. Require(value is null || value.Length <= 112 && Path(value).All(Name.IsMatch));
  48. Require(Auth is "none" or "basic" or "apiKey" or "oauth2");
  49. Require(Auth == "none" ? CredentialRef is null : CredentialRef is not null && SecretRef.IsMatch(CredentialRef));
  50. Require(Auth != "oauth2" || Uri.TryCreate(TokenUrl, UriKind.Absolute, out var token) && token.Scheme == "https"
  51. && token.Query.Length == 0 && token.UserInfo.Length == 0 && token.Fragment.Length == 0);
  52. Require(TokenScope is null || TokenScope.Length <= 240 && !TokenScope.Any(char.IsControl));
  53. }
  54. internal static string[] Path(string? path) => string.IsNullOrEmpty(path) ? [] : path.Split('.');
  55. internal MdpApiPullPosition Begin(DateTimeOffset now, DateTimeOffset? confirmedUntil) =>
  56. new(FirstPosition, null, null, null, null,
  57. Mode == "time" ? confirmedUntil?.AddSeconds(-LookbackSeconds) ?? InitialFromUtc : null,
  58. Mode == "time" ? now : null);
  59. internal Uri RequestUri(MdpApiPullPosition position)
  60. {
  61. if (position.Link is { } link)
  62. return new Uri(link, UriKind.Absolute);
  63. var query = new Dictionary<string, string?>();
  64. if (Query is not null)
  65. foreach (var (name, value) in Query)
  66. query.Add(name, value);
  67. if (Mode != "single")
  68. query.Add(PageSizeParameter, PageSize.ToString(CultureInfo.InvariantCulture));
  69. if (Mode is "page" or "offset")
  70. query.Add(PositionParameter, position.Number.ToString(CultureInfo.InvariantCulture));
  71. if (Mode == "cursor" && position.Cursor is not null)
  72. query.Add(PositionParameter, position.Cursor);
  73. if (Mode == "time")
  74. {
  75. query.Add("from", Format(position.From));
  76. query.Add("until", Format(position.Until));
  77. if (position.AfterTime.HasValue)
  78. {
  79. query.Add("afterTime", Format(position.AfterTime));
  80. query.Add("afterKey", position.AfterKey);
  81. }
  82. }
  83. return new Uri(QueryHelpers.AddQueryString(Url, query));
  84. }
  85. internal MdpApiPullPosition? Next(MdpApiPullPosition current, JsonElement root, int count, Uri effective,
  86. string? nextLink, long receivedBefore = 0)
  87. {
  88. var total = Value(root, TotalPath);
  89. var more = count >= PageSize;
  90. if (TotalPath is not null)
  91. {
  92. Require(total.ValueKind == JsonValueKind.Number && total.TryGetInt64(out var value)
  93. && value >= receivedBefore + count, "PULL_TOTAL_INVALID");
  94. more = total.GetInt64() > receivedBefore + count;
  95. }
  96. MdpApiPullPosition? next = Mode switch
  97. {
  98. "single" => null,
  99. "page" when more && count > 0 => current with { Number = checked(current.Number + 1) },
  100. "offset" when more && count > 0 => current with { Number = checked(current.Number + count) },
  101. "cursor" => ReadCursor(current, root),
  102. "link" => ReadLink(current, effective, nextLink),
  103. "time" => ReadTime(current, root, more),
  104. _ => null
  105. };
  106. if (TotalPath is not null && (next is null) == more)
  107. throw new MdpApiPullException("PULL_TOTAL_MISMATCH");
  108. if (next == current)
  109. throw new MdpApiPullException("PULL_POSITION_STALLED");
  110. return next;
  111. }
  112. private MdpApiPullPosition? ReadCursor(MdpApiPullPosition position, JsonElement root)
  113. {
  114. var cursor = Value(root, NextCursorPath);
  115. if (cursor.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null)
  116. return null;
  117. Require(cursor.ValueKind == JsonValueKind.String, "PULL_CURSOR_INVALID");
  118. var text = cursor.GetString();
  119. if (string.IsNullOrEmpty(text)) return null;
  120. Require(text.Length <= 1400 && !text.Any(char.IsControl), "PULL_CURSOR_INVALID");
  121. return position with { Cursor = text };
  122. }
  123. private MdpApiPullPosition? ReadLink(MdpApiPullPosition position, Uri effective, string? next)
  124. {
  125. if (next is null) return null;
  126. Require(next.Length <= 1800 && Uri.TryCreate(effective, next, out var candidate)
  127. && MdpApiPullEgress.SameOrigin(Endpoint, candidate), "PULL_LINK_FORBIDDEN");
  128. return position with { Link = new Uri(effective, next).AbsoluteUri };
  129. }
  130. private MdpApiPullPosition? ReadTime(MdpApiPullPosition position, JsonElement root, bool more)
  131. {
  132. var rows = Value(root, ResponsePath, emptyMeansRoot: true);
  133. Require(rows.ValueKind == JsonValueKind.Array, "PULL_RESPONSE_PATH_INVALID");
  134. var time = position.AfterTime;
  135. var key = position.AfterKey;
  136. foreach (var row in rows.EnumerateArray())
  137. {
  138. var timestamp = Value(row, SourceTimePath);
  139. var businessKey = Value(row, BusinessKeyPath);
  140. Require(timestamp.ValueKind == JsonValueKind.String && timestamp.TryGetDateTimeOffset(out _)
  141. && businessKey.ValueKind == JsonValueKind.String, "PULL_WATERMARK_INVALID");
  142. var nextTime = timestamp.GetDateTimeOffset();
  143. var nextKey = businessKey.GetString()!;
  144. Require(nextKey.Length is > 0 and <= 180 && !nextKey.Any(char.IsControl)
  145. && nextTime >= position.From && nextTime < position.Until
  146. && (time is null || nextTime > time || nextTime == time && string.CompareOrdinal(nextKey, key) > 0),
  147. "PULL_WATERMARK_NOT_ORDERED");
  148. time = nextTime;
  149. key = nextKey;
  150. }
  151. if (more && time == position.AfterTime && key == position.AfterKey)
  152. throw new MdpApiPullException("PULL_POSITION_STALLED");
  153. return more ? position with { AfterTime = time, AfterKey = key } : null;
  154. }
  155. internal static JsonElement Value(JsonElement root, string? path, bool emptyMeansRoot = false)
  156. {
  157. if (string.IsNullOrEmpty(path)) return emptyMeansRoot ? root : default;
  158. foreach (var part in Path(path))
  159. {
  160. if (root.ValueKind != JsonValueKind.Object)
  161. return default;
  162. var matches = root.EnumerateObject().Where(property => property.NameEquals(part)).Take(2).ToArray();
  163. if (matches.Length > 1)
  164. throw new MdpApiPullException("PULL_RESPONSE_PATH_AMBIGUOUS");
  165. if (matches.Length == 0)
  166. return default;
  167. root = matches[0].Value;
  168. }
  169. return root;
  170. }
  171. private static bool ContainsCredential(JsonElement value) => value.ValueKind switch
  172. {
  173. JsonValueKind.Object => value.EnumerateObject().Any(property =>
  174. CredentialName(property.Name) || ContainsCredential(property.Value)),
  175. JsonValueKind.Array => value.EnumerateArray().Any(ContainsCredential),
  176. _ => false
  177. };
  178. private static bool CredentialName(string value) => value.Replace("_", "").Replace("-", "")
  179. .Replace(".", "").ToUpperInvariant() is "AUTHORIZATION" or "PASSWORD" or "CLIENTSECRET"
  180. or "ACCESSTOKEN" or "REFRESHTOKEN" or "APIKEY" or "XAPIKEY" or "TOKEN" or "COOKIE"
  181. or "SIGNATURE" or "SECRET" or "CREDENTIAL";
  182. private static string? Format(DateTimeOffset? value) => value?.UtcDateTime.ToString("O", CultureInfo.InvariantCulture);
  183. private static void Require(bool value, string code = "PULL_CONFIG_INVALID")
  184. {
  185. if (!value) throw new MdpApiPullException(code);
  186. }
  187. }
  188. internal sealed record MdpApiPullPosition(long Number, string? Cursor, string? Link, DateTimeOffset? AfterTime,
  189. string? AfterKey, DateTimeOffset? From, DateTimeOffset? Until);