using System.Globalization; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.AspNetCore.WebUtilities; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed record MdpApiPullPlan( string Url, string Method = "GET", string ResponsePath = "", string Mode = "page", string PositionParameter = "page", string PageSizeParameter = "limit", int PageSize = 50, long FirstPosition = 1, string? NextCursorPath = null, string? TotalPath = null, string? SourceTimePath = null, string? BusinessKeyPath = null, DateTimeOffset? InitialFromUtc = null, string Auth = "none", string? CredentialRef = null, string? TokenUrl = null, string? TokenScope = null, string? PostJson = null, bool ReadOnlyPost = false, bool StableWindow = false, int MaxPages = 100, int LookbackSeconds = 0, int PollSeconds = 0, IReadOnlyDictionary? Query = null) { private static readonly Regex Name = new(@"\A[A-Za-z_][A-Za-z0-9_.-]{0,79}\z"); private static readonly Regex SecretRef = new(@"\AMDP_API_PULL_SECRET_[A-Z0-9_]{1,64}\z"); private static readonly string[] WatermarkParameters = ["from", "until", "afterTime", "afterKey"]; internal Uri Endpoint => new(Url, UriKind.Absolute); internal void Validate() { Require(Uri.TryCreate(Url, UriKind.Absolute, out var endpoint) && endpoint.Scheme == "https" && endpoint.UserInfo.Length == 0 && endpoint.Fragment.Length == 0 && endpoint.Query.Length == 0 && Url.Length <= 1500); Require(Method == "GET" || Method == "POST" && ReadOnlyPost && PostJson is { Length: <= 8192 }); if (Method == "POST") { using var json = JsonDocument.Parse(PostJson!); Require(json.RootElement.ValueKind == JsonValueKind.Object && !ContainsCredential(json.RootElement)); } Require(Mode is "single" or "page" or "offset" or "cursor" or "link" or "time"); Require(PageSize is > 0 and <= 100 && MaxPages is > 0 and <= 500 && FirstPosition >= 0); Require(Name.IsMatch(PositionParameter) && Name.IsMatch(PageSizeParameter) && !PositionParameter.Equals(PageSizeParameter, StringComparison.OrdinalIgnoreCase)); var reserved = new HashSet([PositionParameter, PageSizeParameter], StringComparer.OrdinalIgnoreCase); if (Mode == "time") Require(WatermarkParameters.All(reserved.Add)); if (Query is not null) Require(Query.Count <= 12 && Query.All(pair => Name.IsMatch(pair.Key) && !CredentialName(pair.Key) && reserved.Add(pair.Key) && pair.Value is { Length: <= 180 } && !pair.Value.Any(char.IsControl))); Require(Mode is not ("page" or "offset" or "time") || StableWindow); Require(Mode != "cursor" || !string.IsNullOrEmpty(NextCursorPath)); Require(Mode != "time" || InitialFromUtc.HasValue && !string.IsNullOrEmpty(SourceTimePath) && !string.IsNullOrEmpty(BusinessKeyPath)); Require(LookbackSeconds is >= 0 and <= 86400 && PollSeconds is 0 or >= 60 and <= 86400); foreach (var value in new[] { ResponsePath, NextCursorPath, TotalPath, SourceTimePath, BusinessKeyPath }) Require(value is null || value.Length <= 112 && Path(value).All(Name.IsMatch)); Require(Auth is "none" or "basic" or "apiKey" or "oauth2"); Require(Auth == "none" ? CredentialRef is null : CredentialRef is not null && SecretRef.IsMatch(CredentialRef)); Require(Auth != "oauth2" || Uri.TryCreate(TokenUrl, UriKind.Absolute, out var token) && token.Scheme == "https" && token.Query.Length == 0 && token.UserInfo.Length == 0 && token.Fragment.Length == 0); Require(TokenScope is null || TokenScope.Length <= 240 && !TokenScope.Any(char.IsControl)); } internal static string[] Path(string? path) => string.IsNullOrEmpty(path) ? [] : path.Split('.'); internal MdpApiPullPosition Begin(DateTimeOffset now, DateTimeOffset? confirmedUntil) => new(FirstPosition, null, null, null, null, Mode == "time" ? confirmedUntil?.AddSeconds(-LookbackSeconds) ?? InitialFromUtc : null, Mode == "time" ? now : null); internal Uri RequestUri(MdpApiPullPosition position) { if (position.Link is { } link) return new Uri(link, UriKind.Absolute); var query = new Dictionary(); if (Query is not null) foreach (var (name, value) in Query) query.Add(name, value); if (Mode != "single") query.Add(PageSizeParameter, PageSize.ToString(CultureInfo.InvariantCulture)); if (Mode is "page" or "offset") query.Add(PositionParameter, position.Number.ToString(CultureInfo.InvariantCulture)); if (Mode == "cursor" && position.Cursor is not null) query.Add(PositionParameter, position.Cursor); if (Mode == "time") { query.Add("from", Format(position.From)); query.Add("until", Format(position.Until)); if (position.AfterTime.HasValue) { query.Add("afterTime", Format(position.AfterTime)); query.Add("afterKey", position.AfterKey); } } return new Uri(QueryHelpers.AddQueryString(Url, query)); } internal MdpApiPullPosition? Next(MdpApiPullPosition current, JsonElement root, int count, Uri effective, string? nextLink, long receivedBefore = 0) { var total = Value(root, TotalPath); var more = count >= PageSize; if (TotalPath is not null) { Require(total.ValueKind == JsonValueKind.Number && total.TryGetInt64(out var value) && value >= receivedBefore + count, "PULL_TOTAL_INVALID"); more = total.GetInt64() > receivedBefore + count; } MdpApiPullPosition? next = Mode switch { "single" => null, "page" when more && count > 0 => current with { Number = checked(current.Number + 1) }, "offset" when more && count > 0 => current with { Number = checked(current.Number + count) }, "cursor" => ReadCursor(current, root), "link" => ReadLink(current, effective, nextLink), "time" => ReadTime(current, root, more), _ => null }; if (TotalPath is not null && (next is null) == more) throw new MdpApiPullException("PULL_TOTAL_MISMATCH"); if (next == current) throw new MdpApiPullException("PULL_POSITION_STALLED"); return next; } private MdpApiPullPosition? ReadCursor(MdpApiPullPosition position, JsonElement root) { var cursor = Value(root, NextCursorPath); if (cursor.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null; Require(cursor.ValueKind == JsonValueKind.String, "PULL_CURSOR_INVALID"); var text = cursor.GetString(); if (string.IsNullOrEmpty(text)) return null; Require(text.Length <= 1400 && !text.Any(char.IsControl), "PULL_CURSOR_INVALID"); return position with { Cursor = text }; } private MdpApiPullPosition? ReadLink(MdpApiPullPosition position, Uri effective, string? next) { if (next is null) return null; Require(next.Length <= 1800 && Uri.TryCreate(effective, next, out var candidate) && MdpApiPullEgress.SameOrigin(Endpoint, candidate), "PULL_LINK_FORBIDDEN"); return position with { Link = new Uri(effective, next).AbsoluteUri }; } private MdpApiPullPosition? ReadTime(MdpApiPullPosition position, JsonElement root, bool more) { var rows = Value(root, ResponsePath, emptyMeansRoot: true); Require(rows.ValueKind == JsonValueKind.Array, "PULL_RESPONSE_PATH_INVALID"); var time = position.AfterTime; var key = position.AfterKey; foreach (var row in rows.EnumerateArray()) { var timestamp = Value(row, SourceTimePath); var businessKey = Value(row, BusinessKeyPath); Require(timestamp.ValueKind == JsonValueKind.String && timestamp.TryGetDateTimeOffset(out _) && businessKey.ValueKind == JsonValueKind.String, "PULL_WATERMARK_INVALID"); var nextTime = timestamp.GetDateTimeOffset(); var nextKey = businessKey.GetString()!; Require(nextKey.Length is > 0 and <= 180 && !nextKey.Any(char.IsControl) && nextTime >= position.From && nextTime < position.Until && (time is null || nextTime > time || nextTime == time && string.CompareOrdinal(nextKey, key) > 0), "PULL_WATERMARK_NOT_ORDERED"); time = nextTime; key = nextKey; } if (more && time == position.AfterTime && key == position.AfterKey) throw new MdpApiPullException("PULL_POSITION_STALLED"); return more ? position with { AfterTime = time, AfterKey = key } : null; } internal static JsonElement Value(JsonElement root, string? path, bool emptyMeansRoot = false) { if (string.IsNullOrEmpty(path)) return emptyMeansRoot ? root : default; foreach (var part in Path(path)) { if (root.ValueKind != JsonValueKind.Object) return default; var matches = root.EnumerateObject().Where(property => property.NameEquals(part)).Take(2).ToArray(); if (matches.Length > 1) throw new MdpApiPullException("PULL_RESPONSE_PATH_AMBIGUOUS"); if (matches.Length == 0) return default; root = matches[0].Value; } return root; } private static bool ContainsCredential(JsonElement value) => value.ValueKind switch { JsonValueKind.Object => value.EnumerateObject().Any(property => CredentialName(property.Name) || ContainsCredential(property.Value)), JsonValueKind.Array => value.EnumerateArray().Any(ContainsCredential), _ => false }; private static bool CredentialName(string value) => value.Replace("_", "").Replace("-", "") .Replace(".", "").ToUpperInvariant() is "AUTHORIZATION" or "PASSWORD" or "CLIENTSECRET" or "ACCESSTOKEN" or "REFRESHTOKEN" or "APIKEY" or "XAPIKEY" or "TOKEN" or "COOKIE" or "SIGNATURE" or "SECRET" or "CREDENTIAL"; private static string? Format(DateTimeOffset? value) => value?.UtcDateTime.ToString("O", CultureInfo.InvariantCulture); private static void Require(bool value, string code = "PULL_CONFIG_INVALID") { if (!value) throw new MdpApiPullException(code); } } internal sealed record MdpApiPullPosition(long Number, string? Cursor, string? Link, DateTimeOffset? AfterTime, string? AfterKey, DateTimeOffset? From, DateTimeOffset? Until);