EdgeTimeWatermark.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Globalization;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  4. public sealed record EdgeRelationalTimeSettings(string Column, int DelaySeconds, int LookbackSeconds, int RetentionSeconds)
  5. {
  6. public bool IsValid() => Column is { Length: > 0 and <= 63 } && Column.All(ch => char.IsAsciiLetterOrDigit(ch) || ch == '_')
  7. && DelaySeconds > 0 && LookbackSeconds >= DelaySeconds && RetentionSeconds > (long)LookbackSeconds + DelaySeconds;
  8. }
  9. public static class EdgeTimeWatermark
  10. {
  11. private const string BoundaryPrefix = "until:";
  12. private const string PagePrefix = "page:";
  13. public static string Encode(DateTimeOffset value) => FormattableString.Invariant($"{BoundaryPrefix}{value.UtcTicks}");
  14. public static DateTimeOffset Decode(string? value)
  15. {
  16. if (value is null || !value.StartsWith(BoundaryPrefix, StringComparison.Ordinal)
  17. || !long.TryParse(value.AsSpan(BoundaryPrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var ticks)
  18. || ticks < 0 || ticks > DateTime.MaxValue.Ticks)
  19. throw new EdgeContractException("EDGE_TIME_BOUNDARY_INVALID");
  20. return new DateTimeOffset(ticks, TimeSpan.Zero);
  21. }
  22. public static string Page(string checkpoint) => PagePrefix + checkpoint;
  23. public static bool AdvancesPage(string? from, string? to, bool incremental)
  24. {
  25. if (to?.StartsWith(PagePrefix, StringComparison.Ordinal) != true) return false;
  26. try
  27. {
  28. if (incremental)
  29. {
  30. var next = RelationalTimePosition.Parse(to[PagePrefix.Length..]);
  31. if (from?.StartsWith(BoundaryPrefix, StringComparison.Ordinal) == true)
  32. {
  33. _ = Decode(from);
  34. return true;
  35. }
  36. return from?.StartsWith(PagePrefix, StringComparison.Ordinal) == true
  37. && next.CompareTo(RelationalTimePosition.Parse(from[PagePrefix.Length..])) > 0;
  38. }
  39. return long.TryParse(to.AsSpan(PagePrefix.Length), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var nextKey)
  40. && (from is null || (from.StartsWith(PagePrefix, StringComparison.Ordinal)
  41. && long.TryParse(from.AsSpan(PagePrefix.Length), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var previous)
  42. && nextKey > previous));
  43. }
  44. catch (ConnectorContractException)
  45. {
  46. return false;
  47. }
  48. }
  49. }