diff --git a/CLAUDE.md b/CLAUDE.md index b1b4776d..ab5ef07a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,7 +62,7 @@ Handlers are `public static async Task Name(HttpContext ctx)` methods on static 3. **Express-compatible response behavior is a contract**: strings send as `text/html`, a bare JSON number sends as its string form, a JSON `null` upstream body sends as an empty body with no content-type, malformed request JSON yields 500 "Server Error", unmatched GETs get the 200 template page while other methods get the 404 finalhandler page. 4. **Upstream requests always carry a `{}` JSON body** (even GETs) with bare `application/json` content type — this matches what upstreams have always received (verified against recorded production traffic). Review bots repeatedly flag this; it is correct. 5. **`get_accounts` with a missing username must serialize as JSON `[null]`**, never the string `"null"` — `@null` is a real Hive account. -6. **No hot-path logging.** The service defaults to Warning level and writes ~3 lines at startup; container logs are size-capped but must stay quiet. Don't add `Console.WriteLine` or Information-level logging to request paths. +6. **No hot-path logging.** The service defaults to Warning level and writes ~3 lines at startup; container logs are size-capped but must stay quiet. Don't add `Console.WriteLine` or Information-level logging to request paths. The one deliberate exception is the `node-trace` measurement (`NodeTrace`): one line per node per active minute, written by a timer, never on a request. 7. **Numbers are JavaScript doubles end to end — raw-literal preservation is NOT a goal.** The Node service parsed every request body and upstream response with `JSON.parse` (doubles) and re-emitted with `JSON.stringify`, so integers above 2^53 have always rounded on these paths (e.g. `18446744073709551615` → `18446744073709552000`). `JsJson.Stringify` reproduces this byte-for-byte on purpose. Do not flag double-rounding on payload/response serialization as precision loss, and do not "fix" it by preserving raw literals — either direction breaks parity. The single deliberate exception is the Solana lamports raw-text scan (`PrivateApi.Chain`), which keeps `ToJsonString` because it extracts a u64 from raw text before any parse. 8. **Lone-surrogate `\u` escapes are valid input and output.** JavaScript strings are arbitrary UTF-16, so `JSON.parse`/`JSON.stringify` accept and re-emit lone surrogates; System.Text.Json throws on them in BOTH directions (string materialization AND the writer, regardless of encoder). All string extraction must go through `JsVal.TryGetStringLenient` and all tree serialization of client/upstream data through `JsJson.Stringify` — never raw `GetValue`/`TryGetValue` or `ToJsonString` on such data. Suggesting a switch back to the strict System.Text.Json APIs reintroduces production 500s. diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index cf2baa1f..1be2415a 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -25,6 +25,9 @@ private sealed class StubNode : IAsyncDisposable /// answer with a well-formed account whose posting_json_metadata is empty. public bool ServesMetadata = true; + /// Headers added to every response. + public Dictionary Headers = new(); + // A healthy node's get_accounts result. Account-metadata presence matters: // GetAccounts prefers a node that serves it, so the default stub carries it. private string AccountResultBody => @@ -62,7 +65,8 @@ private async Task Loop() { requestBody = await reader.ReadToEndAsync(); } - var status = _handler(MethodOf(requestBody)); + var method = MethodOf(requestBody); + var status = _handler(method); byte[] body; if (status == 200) { @@ -108,11 +112,21 @@ private async Task Loop() "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":[\"invalid\"]}"); status = 200; } + else if (status == -6) + { + // hivemind without the method asked for. + var bare = method[(method.LastIndexOf('.') + 1)..]; + body = Encoding.UTF8.GetBytes( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32602,\"message\":\"Assert Exception:unknown method: bridge_api" + + bare + "\"}}"); + status = 200; + } else { body = Encoding.UTF8.GetBytes("rate limited"); } + foreach (var (k, v) in Headers) ctx.Response.Headers[k] = v; ctx.Response.StatusCode = status; ctx.Response.ContentType = "application/json"; ctx.Response.ContentLength64 = body.Length; @@ -448,6 +462,123 @@ public async Task RateLimits_DoNotCountTowardFailureParking() Assert.Equal(0, view["parked_for_ms"]!.GetValue()); } + [Fact] + public void TheNodeTrace_HoldsAMinuteBackLongerThanThePoolsTimeout() + { + var client = new HiveRpcClient(new[] { "https://a.example" }, timeoutMs: 30_000, failoverThreshold: 1, + clock: null, traceLog: _ => { }); + Assert.Equal(35_000, client.Trace.GraceMs); // the timeout, plus scheduling slack + } + + [Fact] + public async Task TheNodeTrace_RecordsEveryUpstreamRequest_WithoutChangingRouting() + { + // The throttled node is still tried first and the call still lands on + // the good node; the trace saw one 429 on one and one answer on the + // other, in the second they were sent. + await using var throttled = new StubNode(() => 429); + await using var good = new StubNode(() => 200); + long unixMs = 1_700_000_040_000; + var lines = new List(); + var client = new HiveRpcClient(new[] { throttled.Url, good.Url }, timeoutMs: 500, failoverThreshold: 1, + clock: null, traceClock: () => unixMs, traceLog: lines.Add); + + Assert.NotNull(await client.Call("condenser_api", "get_accounts", new JsonArray())); + + Assert.Equal(1, throttled.Hits); + Assert.Equal(1, good.Hits); + unixMs += 60_000 + NodeTrace.DefaultGraceMs; + client.Trace.Flush(); + Assert.Equal(2, lines.Count); + Assert.Contains(" rl=1,", lines.Single(l => l.Contains("node=127.0.0.1:" + new Uri(throttled.Url).Port + " "))); + Assert.Contains(" ok=1,", lines.Single(l => l.Contains("node=127.0.0.1:" + new Uri(good.Url).Port + " "))); + } + + [Fact] + public async Task TheNodeTrace_CountsATimeoutApart() + { + await using var hung = new StubNode(() => -1); + long unixMs = 1_700_000_040_000; + var lines = new List(); + var client = new HiveRpcClient(new[] { hung.Url }, timeoutMs: 200, failoverThreshold: 1, + clock: null, traceClock: () => unixMs, traceLog: lines.Add); + + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + + unixMs += 60_000 + NodeTrace.DefaultGraceMs; + client.Trace.Flush(); + var line = Assert.Single(lines); + Assert.Contains(" timeout=1,", line); + Assert.Contains(" fail=- ", line); + } + + [Fact] + public async Task TheNodeTrace_KeepsA5xxApart_WithTheLimitersHeaders() + { + await using var overloaded = new StubNode(() => 503); + overloaded.Headers["Server"] = "nginx"; + overloaded.Headers["X-RateLimit-Limit"] = "10"; + await using var good = new StubNode(() => 200); + long unixMs = 1_700_000_040_000; + var lines = new List(); + var client = new HiveRpcClient(new[] { overloaded.Url, good.Url }, timeoutMs: 500, failoverThreshold: 1, + clock: null, traceClock: () => unixMs, traceLog: lines.Add); + + Assert.NotNull(await client.Call("condenser_api", "get_accounts", new JsonArray())); + + unixMs += 60_000 + NodeTrace.DefaultGraceMs; + client.Trace.Flush(); + var line = lines.Single(l => l.Contains("node=127.0.0.1:" + new Uri(overloaded.Url).Port + " ")); + Assert.Contains(" e5xx=1,", line); + Assert.Contains(" fail=- ", line); + Assert.Contains(" hdr=503|", line); + Assert.Contains("server:", line); + Assert.Contains("x-ratelimit-limit:10", line); + } + + [Fact] + public async Task TheNodeTrace_SamplesTheHeadersOfAnyRefusal_WithItsStatus() + { + // A WAF's 403 is a limiter answer too. + await using var blocked = new StubNode(() => 403); + blocked.Headers["Server"] = "cloudflare"; + long unixMs = 1_700_000_040_000; + var lines = new List(); + var client = new HiveRpcClient(new[] { blocked.Url }, timeoutMs: 500, failoverThreshold: 1, + clock: null, traceClock: () => unixMs, traceLog: lines.Add); + + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + + unixMs += 60_000 + NodeTrace.DefaultGraceMs; + client.Trace.Flush(); + var line = Assert.Single(lines); + Assert.Contains(" fail=1,", line); + Assert.Contains(" hdr=403|", line); + Assert.Contains("server:cloudflare", line); + } + + [Fact] + public async Task TheNodeTrace_CountsTheV1Fallback_AsASecondRequest() + { + // `unknown method`, then the v1 method on the same node: two requests + // its limiter counted, both answered. + await using var old = new StubNode(m => m.EndsWith("_v2") ? -6 : 200); + long unixMs = 1_700_000_040_000; + var lines = new List(); + var client = new HiveRpcClient(new[] { old.Url }, timeoutMs: 500, failoverThreshold: 1, + clock: null, traceClock: () => unixMs, traceLog: lines.Add); + + await client.CallMethod("bridge.get_post_v2", new JsonObject { ["author"] = "a", ["permlink"] = "p" }, + fallback: ("bridge.get_post", new JsonObject { ["author"] = "a", ["permlink"] = "p" }, "bridge.*_v2")); + + Assert.Equal(2, old.Hits); + unixMs += 60_000 + NodeTrace.DefaultGraceMs; + client.Trace.Flush(); + var line = Assert.Single(lines); + Assert.Contains(" sent=2,", line); + Assert.Contains(" ok=2,", line); + } + [Fact] public async Task ASuccessClearsAFailurePark() { diff --git a/dotnet/EcencyApi.Tests/NodeTraceTests.cs b/dotnet/EcencyApi.Tests/NodeTraceTests.cs new file mode 100644 index 00000000..d061b90f --- /dev/null +++ b/dotnet/EcencyApi.Tests/NodeTraceTests.cs @@ -0,0 +1,267 @@ +using EcencyApi.Infrastructure; +using Xunit; + +namespace EcencyApi.Tests; + +/// +/// The node trace records, per node and per second, the upstream requests sent +/// and how each ended, and logs each node's minute as one line, so a node's +/// limiter can be fitted offline (its rate, its burst, whether it counts +/// refused requests). +/// +public class NodeTraceTests +{ + private const long T0 = 1_700_000_040_000; // a minute boundary (unix ms) + + private static (NodeTrace Trace, List Lines, Action SetNow) Make(params string[] nodes) + { + long now = T0; + var lines = new List(); + var trace = new NodeTrace(nodes, () => now, lines.Add, "ssr"); + return (trace, lines, t => now = t); + } + + private static int[] Field(string line, string name) + { + var part = line.Split(' ').Single(p => p.StartsWith(name + "=")); + var value = part[(name.Length + 1)..]; + return value == "-" ? new int[60] : value.Split(',').Select(int.Parse).ToArray(); + } + + [Fact] + public void AMinute_IsLoggedAsOneLinePerNode_WithEachSecondsCounts() + { + var (trace, lines, setNow) = Make("a.example", "b.example"); + trace.Record(0, T0 + 500, NodeTrace.Outcome.Answered); + trace.Record(0, T0 + 900, NodeTrace.Outcome.RateLimited); + trace.Record(0, T0 + 59_100, NodeTrace.Outcome.Failed); + trace.Record(1, T0 + 3_000, NodeTrace.Outcome.Answered); + + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Equal(2, lines.Count); + var a = lines.Single(l => l.Contains(" node=a.example ")); + Assert.StartsWith("node-trace pool=ssr ", a); + Assert.Contains(" minute=" + T0 / 1000 + " ", a); + var sent = Field(a, "sent"); + Assert.Equal(60, sent.Length); + Assert.Equal(2, sent[0]); + Assert.Equal(1, sent[59]); + Assert.Equal(1, Field(a, "ok")[0]); + Assert.Equal(1, Field(a, "rl")[0]); + Assert.Equal(1, Field(a, "fail")[59]); + Assert.Equal(1, Field(lines.Single(l => l.Contains(" node=b.example ")), "ok")[3]); + } + + [Fact] + public void AMinute_IsHeldBackUntilItsSlowRequestsCanHaveEnded() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 59_000, NodeTrace.Outcome.Answered); + + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs - 1); + trace.Flush(); + Assert.Empty(lines); + + // A slow request sent in that minute ends now: still its minute. + trace.Record(0, T0 + 59_500, NodeTrace.Outcome.Failed); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + var line = Assert.Single(lines); + Assert.Equal(2, Field(line, "sent")[59]); + } + + [Fact] + public void AGraceLongerThanTheDefault_HoldsTheMinuteBackThatLong() + { + long now = T0; + var lines = new List(); + var trace = new NodeTrace(new[] { "a.example" }, () => now, lines.Add, "ssr", graceMs: 40_000); + trace.Record(0, T0 + 59_000, NodeTrace.Outcome.Answered); + + now = T0 + 60_000 + 40_000 - 1; + trace.Flush(); + Assert.Empty(lines); + + // Sent at the end of the minute, ended after a 39s timeout: still its minute. + trace.Record(0, T0 + 59_900, NodeTrace.Outcome.Timeout); + now = T0 + 60_000 + 40_000; + trace.Flush(); + Assert.Equal(2, Field(Assert.Single(lines), "sent")[59]); + } + + [Fact] + public void AGraceOutsideItsBounds_IsClampedToThem() + { + Assert.Equal(NodeTrace.DefaultGraceMs, new NodeTrace(new[] { "a.example" }, () => T0, _ => { }, "ssr", graceMs: 1_000).GraceMs); + Assert.Equal(NodeTrace.MaxGraceMs, new NodeTrace(new[] { "a.example" }, () => T0, _ => { }, "ssr", graceMs: 2 * 3_600_000).GraceMs); + Assert.True(NodeTrace.MaxGraceMs < (NodeTrace.MaxOpenMinutes - 2) * 60_000L); + } + + [Fact] + public void ARequestEndingAfterItsMinuteWasLogged_IsCountedAsLate_OnTheNextLine() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + trace.Record(0, T0 + 2_000, NodeTrace.Outcome.Failed); // its minute is gone + trace.Record(0, T0 + 61_000, NodeTrace.Outcome.Answered); + setNow(T0 + 120_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Equal(2, lines.Count); + Assert.Contains(" late=1", lines[1]); + Assert.Contains(" late=0", lines[0]); + } + + [Fact] + public void AMinuteANodeWasNotSentAnything_IsNotLogged() + { + var (trace, lines, setNow) = Make("a.example", "b.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Single(lines); + } + + [Fact] + public void RetryAfters_AreSummarisedPerMinute() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.RateLimited, retryAfterMs: 3_000); + trace.Record(0, T0 + 2_000, NodeTrace.Outcome.RateLimited, retryAfterMs: 1_000); + trace.Record(0, T0 + 3_000, NodeTrace.Outcome.RateLimited); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Contains(" retry_after=2:1000:3000", Assert.Single(lines)); + } + + [Fact] + public void Recording_NeverWrites_SoASlowLogCannotHoldUpARequest() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Record(0, T0 + 60_000 + NodeTrace.DefaultGraceMs, NodeTrace.Outcome.Answered); + + Assert.Empty(lines); + trace.Flush(); + Assert.Single(lines); + } + + [Fact] + public async Task TheFlushTimer_LogsAnIdleNodesLastMinute() + { + long now = T0; + var written = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var trace = new NodeTrace(new[] { "a.example" }, () => Interlocked.Read(ref now), l => written.TrySetResult(l), "ssr"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + Interlocked.Exchange(ref now, T0 + 60_000 + NodeTrace.DefaultGraceMs); // no request follows + + using (trace.StartFlushing(TimeSpan.FromMilliseconds(20))) + { + Assert.Contains(" node=a.example ", await written.Task.WaitAsync(TimeSpan.FromSeconds(10))); + } + } + + [Fact] + public void WhileTheLogIsStalled_OnlyTheNewestMinutesAreKept() + { + var (trace, lines, setNow) = Make("a.example"); + for (var i = 0; i <= NodeTrace.MaxOpenMinutes; i++) + trace.Record(0, T0 + i * 60_000L, NodeTrace.Outcome.Answered); + setNow(T0 + (NodeTrace.MaxOpenMinutes + 1) * 60_000L + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Equal(NodeTrace.MaxOpenMinutes, lines.Count); + Assert.DoesNotContain(lines, l => l.Contains(" minute=" + T0 / 1000 + " ")); + } + + [Fact] + public void ALineTheLogFailsOn_DoesNotLoseTheOthers() + { + long now = T0; + var lines = new List(); + var trace = new NodeTrace(new[] { "a.example", "b.example" }, () => now, + l => { if (l.Contains("node=a.example")) throw new IOException("busy"); lines.Add(l); }, "ssr"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + trace.Record(1, T0 + 1_000, NodeTrace.Outcome.Answered); + now = T0 + 60_000 + NodeTrace.DefaultGraceMs; + trace.Flush(); + + Assert.Contains(" node=b.example ", Assert.Single(lines)); + } + + [Fact] + public void Timeouts_5xxAndOtherFailures_AreCountedApart() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Timeout); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.ServerError); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.ServerError); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Failed); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + var line = Assert.Single(lines); + Assert.Equal(4, Field(line, "sent")[1]); + Assert.Equal(1, Field(line, "timeout")[1]); + Assert.Equal(2, Field(line, "e5xx")[1]); + Assert.Equal(1, Field(line, "fail")[1]); + Assert.Contains(" ok=- ", line); + } + + [Fact] + public void AnsweredLatency_IsSummedAndItsMaximumKept_AndInFlightItsMaximum() + { + var (trace, lines, setNow) = Make("a.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered, latencyMs: 100, inFlight: 3); + trace.Record(0, T0 + 1_500, NodeTrace.Outcome.Answered, latencyMs: 400, inFlight: 7); + trace.Record(0, T0 + 1_600, NodeTrace.Outcome.RateLimited, latencyMs: 9_000, inFlight: 2); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + var line = Assert.Single(lines); + Assert.Equal(500, Field(line, "ok_ms")[1]); + Assert.Equal(400, Field(line, "max_ms")[1]); + Assert.Equal(7, Field(line, "inflight")[1]); + } + + [Fact] + public void TheFirstLimiterHeadersOfTheMinute_AreKept_AsOneToken() + { + var (trace, lines, setNow) = Make("a.example", "b.example"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.RateLimited, headers: "server:nginx/1.2 (Ubuntu);ratelimit-limit:10"); + trace.Record(0, T0 + 2_000, NodeTrace.Outcome.RateLimited, headers: "server:other"); + trace.Record(1, T0 + 2_000, NodeTrace.Outcome.Answered); + setNow(T0 + 60_000 + NodeTrace.DefaultGraceMs); + trace.Flush(); + + Assert.Contains(" hdr=server:nginx/1.2_(Ubuntu);ratelimit-limit:10 ", lines.Single(l => l.Contains("node=a.example"))); + Assert.Contains(" hdr=- ", lines.Single(l => l.Contains("node=b.example"))); + } + + [Fact] + public void TheDefaultClock_IsUnixTime() + { + var clock = NodeTrace.MonotonicUnixMs(); + Assert.InRange(clock() - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), -1_000, 1_000); + } + + [Fact] + public void AFailingLog_DoesNotReachTheCaller() + { + long now = T0; + var trace = new NodeTrace(new[] { "a.example" }, () => now, _ => throw new IOException("stdout closed"), "ssr"); + trace.Record(0, T0 + 1_000, NodeTrace.Outcome.Answered); + now = T0 + 60_000 + NodeTrace.DefaultGraceMs; + + trace.Flush(); // the log throws + } +} diff --git a/dotnet/EcencyApi/Handlers/SsrRpc.cs b/dotnet/EcencyApi/Handlers/SsrRpc.cs index ff93de88..250b39d2 100644 --- a/dotnet/EcencyApi/Handlers/SsrRpc.cs +++ b/dotnet/EcencyApi/Handlers/SsrRpc.cs @@ -96,7 +96,8 @@ internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallCl internal static HiveRpcClient Client = new( Config.SsrRpcNodes ?? HiveClients.DefaultNodes.ToArray(), timeoutMs: Config.SsrNodeTimeoutMs, - failoverThreshold: 1); + failoverThreshold: 1, + name: "ssr"); internal static BytesCache Cache = new(Config.SsrCacheBytes); diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 14ef95fd..a3276999 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -35,6 +35,9 @@ public sealed class HiveRpcClient private readonly int _timeoutMs; private readonly int _failoverThreshold; private readonly NodeHealthTracker _health; + private readonly Func _traceClock; + // Upstream requests in flight per node, for the trace. + private readonly int[] _inFlight; private readonly Func _clock; private int _seq; @@ -47,21 +50,40 @@ public sealed class HiveRpcClient // timeoutMs 2000 / failoverThreshold 2 mirror the dhive Client options the // Node service constructed its clients with. - public HiveRpcClient(string[] nodes, int timeoutMs = 2000, int failoverThreshold = 2) - : this(nodes, timeoutMs, failoverThreshold, null) + /// Names this pool in the node trace's log lines. + public HiveRpcClient(string[] nodes, int timeoutMs = 2000, int failoverThreshold = 2, string name = "default") + : this(nodes, timeoutMs, failoverThreshold, null, name: name) { } /// Test seam for the health tracker's notion of time. - internal HiveRpcClient(string[] nodes, int timeoutMs, int failoverThreshold, Func? clock) + /// Test seam: unix ms for the node trace. + /// Test seam: where the node trace writes its lines. + internal HiveRpcClient(string[] nodes, int timeoutMs, int failoverThreshold, Func? clock, + Func? traceClock = null, Action? traceLog = null, string name = "default") { _nodes = nodes; _timeoutMs = timeoutMs; _failoverThreshold = Math.Max(1, failoverThreshold); _health = new NodeHealthTracker(nodes.Length, clock); _clock = clock ?? (() => Environment.TickCount64); + _traceClock = traceClock ?? NodeTrace.MonotonicUnixMs(); + _inFlight = new int[nodes.Length]; + // host[:port], so nodes on one host stay apart. + Trace = new NodeTrace( + nodes.Select(n => Uri.TryCreate(n, UriKind.Absolute, out var u) ? u.Authority : n).ToArray(), + _traceClock, traceLog ?? Console.WriteLine, name, + // A request ends within the timeout (its body read included); the rest is scheduling slack. + graceMs: timeoutMs + 5_000L); + // Tests flush by hand; the service logs due minutes from a timer, never a request. + if (traceLog == null) _traceFlusher = Trace.StartFlushing(TimeSpan.FromSeconds(5)); } + private readonly IDisposable? _traceFlusher; + + /// Per-node, per-second upstream requests and outcomes; see NodeTrace. + internal NodeTrace Trace { get; } + public IReadOnlyList Nodes => _nodes; /// @@ -321,7 +343,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => JsonNode? result; try { - result = await CallNode(node, useFallback ? fallbackBody! : body); + result = await TracedCallNode(nodeIndex, useFallback ? fallbackBody! : body); } catch (RpcException e) when (fallbackBody != null && !useFallback && IsUnknownMethod(e.Message, method)) { @@ -334,7 +356,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // Rank the node on the v1 answer it will give from now on, // not on the probe that does not recur within the TTL. started = NowMs; - result = await CallNode(node, fallbackBody); + result = await TracedCallNode(nodeIndex, fallbackBody); } if (validateResult != null && !validateResult(result)) { @@ -463,6 +485,10 @@ private sealed class NodeUnavailableException : Exception public bool IsRateLimit { get; } public bool IsTimeout { get; } public int? RetryAfterMs { get; } + /// The HTTP status, when the node answered with one. + public int? StatusCode { get; init; } + /// A 429 or 5xx's limiter headers, for the node trace. + public string? LimitHeaders { get; init; } public Exception? Cause { get; private set; } public NodeUnavailableException(string message, bool advanceImmediately, @@ -481,6 +507,75 @@ public NodeUnavailableException(string message, bool advanceImmediately, // skip it now rather than burning a retry that will fail the same way. private static bool IsOverloadStatus(int status) => status is 429 or 502 or 503 or 504; + // What a refusing node says about itself, for the trace: the status, the + // IETF RateLimit-* and common X-RateLimit-* headers, Retry-After, and who + // answered (Server, Via). Never throws: it must not change how the + // failure is handled. + private static string? LimitHeadersOf(HttpResponseMessage resp, int status) + { + try + { + var parts = resp.Headers.Concat(resp.Content.Headers) + .Where(h => h.Key.Contains("ratelimit", StringComparison.OrdinalIgnoreCase) + || h.Key.Equals("Retry-After", StringComparison.OrdinalIgnoreCase) + || h.Key.Equals("Server", StringComparison.OrdinalIgnoreCase) + || h.Key.Equals("Via", StringComparison.OrdinalIgnoreCase)) + .Select(h => $"{h.Key.ToLowerInvariant()}:{string.Join(',', h.Value)}"); + return $"{status}|{string.Join(';', parts)}"; + } + catch + { + return null; + } + } + + // Every upstream request goes through here, so the trace sees each one, + // including failovers, same-node retries, the v1 fallback and the extra + // requests a preference makes. The node's own error is an answer. + private async Task TracedCallNode(int nodeIndex, string body) + { + var sentAt = _traceClock(); + var inFlight = Interlocked.Increment(ref _inFlight[nodeIndex]); + var started = Environment.TickCount64; + int Elapsed() => (int)Math.Min(int.MaxValue, Environment.TickCount64 - started); + try + { + var result = await CallNode(_nodes[nodeIndex], body); + Trace.Record(nodeIndex, sentAt, NodeTrace.Outcome.Answered, latencyMs: Elapsed(), inFlight: inFlight); + return result; + } + catch (RpcException) + { + Trace.Record(nodeIndex, sentAt, NodeTrace.Outcome.Answered, latencyMs: Elapsed(), inFlight: inFlight); + throw; + } + catch (NodeUnavailableException e) + { + var outcome = e.IsRateLimit ? NodeTrace.Outcome.RateLimited + : e.IsTimeout ? NodeTrace.Outcome.Timeout + : e.StatusCode >= 500 ? NodeTrace.Outcome.ServerError + : NodeTrace.Outcome.Failed; + Trace.Record(nodeIndex, sentAt, outcome, e.RetryAfterMs, inFlight: inFlight, headers: e.LimitHeaders); + throw; + } + catch (OperationCanceledException) + { + // The per-node timeout firing while the body was read: headers came, + // the body stalled. + Trace.Record(nodeIndex, sentAt, NodeTrace.Outcome.Timeout, inFlight: inFlight); + throw; + } + catch + { + Trace.Record(nodeIndex, sentAt, NodeTrace.Outcome.Failed, inFlight: inFlight); + throw; + } + finally + { + Interlocked.Decrement(ref _inFlight[nodeIndex]); + } + } + private async Task CallNode(string node, string body) { using var req = new HttpRequestMessage(HttpMethod.Post, node) @@ -517,7 +612,11 @@ public NodeUnavailableException(string message, bool advanceImmediately, $"RPC node {node} returned {status}", advanceImmediately: IsOverloadStatus(status), isRateLimit: status == 429, - retryAfterMs: retryAfter); + retryAfterMs: retryAfter) + { + StatusCode = status, + LimitHeaders = LimitHeadersOf(resp, status), + }; } var text = await resp.Content.ReadAsStringAsync(cts.Token); diff --git a/dotnet/EcencyApi/Infrastructure/NodeTrace.cs b/dotnet/EcencyApi/Infrastructure/NodeTrace.cs new file mode 100644 index 00000000..d8f527e1 --- /dev/null +++ b/dotnet/EcencyApi/Infrastructure/NodeTrace.cs @@ -0,0 +1,228 @@ +namespace EcencyApi.Infrastructure; + +/// +/// Records, per node and per second, the upstream requests the pool sent and +/// how each ended, and logs each node's minute as one line: +/// +/// node-trace pool=ssr node=api.example minute=<unix s> sent=… ok=… rl=… timeout=… e5xx=… fail=… ok_ms=… max_ms=… inflight=… retry_after=n:min:max hdr=… late=n +/// +/// Each count field holds 60 comma-separated values, by the second the request +/// was sent (when a limiter counts it), or `-` when all are 0. `ok_ms` and +/// `max_ms` are the summed and the longest latency of answered requests; +/// `inflight` the most requests in flight to the node when one was sent. +/// `ok` counts every JSON-RPC answer, whether or not the caller could use it: +/// the node's limiter let it through. A 200 that is not JSON-RPC is `fail`, +/// though it passed the limiter too, so fit the limiter on `sent` and `rl`. +/// `hdr` is the first 429 or 5xx's limiter headers that minute, if any. +/// +/// It changes nothing in routing. It exists to fit each node's limiter offline +/// from what it does under real load: its sustained rate, the burst it allows +/// after a rest, whether it delays rather than refuses, whether it limits +/// concurrency rather than rate, and what it says about itself. +/// +/// A minute is logged once its slowest requests can have ended +/// ( after it closes, plus up to one flush period), by 's +/// timer: recording never writes, so a slow or blocked log cannot hold up a +/// request, and an idle node's last minute is still logged. A request that ends later still is +/// counted as `late` on the node's next line. A minute a node was sent nothing +/// is not logged. +/// +public sealed class NodeTrace +{ + public enum Outcome { Answered, RateLimited, Timeout, ServerError, Failed } + + /// The least a minute is held back after it closes. + public const long DefaultGraceMs = 15_000; + + /// The most, well inside . + public const long MaxGraceMs = 10 * 60_000; + + /// + /// How long a minute is held back after it closes: longer than the pool's + /// per-node timeout, so every request sent in it has ended and been counted. + /// + public long GraceMs { get; } + + private const int MaxHeaderSample = 300; + + /// Per node; past it (the log stalled) the oldest minute is dropped. + public const int MaxOpenMinutes = 60; + + private sealed class Minute + { + public readonly int[] Sent = new int[60], Ok = new int[60], RateLimited = new int[60], + Timeout = new int[60], ServerError = new int[60], Failed = new int[60], + OkMs = new int[60], MaxMs = new int[60], InFlight = new int[60]; + public int RetryAfters; + public int RetryAfterMin = int.MaxValue, RetryAfterMax; + public string? Headers; + } + + private readonly object _lock = new(); + private readonly string[] _names; + private readonly Func _unixMs; + private readonly Action _log; + private readonly string _poolName; + // Per node, the minutes (unix minute index) not yet logged. + private readonly Dictionary[] _open; + private readonly int[] _late; + private long _loggedThrough = long.MinValue; + private int _flushing; + + public NodeTrace(IReadOnlyList nodeNames, Func unixMs, Action log, string poolName, + long graceMs = DefaultGraceMs) + { + GraceMs = Math.Clamp(graceMs, DefaultGraceMs, MaxGraceMs); + _names = nodeNames.ToArray(); + _unixMs = unixMs; + _log = log; + _poolName = poolName; + _open = _names.Select(_ => new Dictionary()).ToArray(); + _late = new int[_names.Length]; + } + + /// + /// Unix ms read once and advanced by the monotonic tick count: a wall-clock + /// step (NTP) cannot send requests back into minutes already logged, or + /// log minutes early. + /// + public static Func MonotonicUnixMs() + { + var anchorUnix = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var anchorTick = Environment.TickCount64; + return () => anchorUnix + (Environment.TickCount64 - anchorTick); + } + + private static long MinuteOf(long ms) => (long)Math.Floor(ms / 60_000.0); + + /// One upstream request to the node, sent at (unix ms). + /// How long it took; recorded for answered requests. + /// Requests in flight to the node when it was sent, itself included. + /// The limiter's headers on a 429 or 5xx, if any. + public void Record(int nodeIndex, long sentAtMs, Outcome outcome, int? retryAfterMs = null, + int latencyMs = 0, int inFlight = 0, string? headers = null) + { + try + { + lock (_lock) + { + var minute = MinuteOf(sentAtMs); + if (minute <= _loggedThrough) + { + _late[nodeIndex]++; + } + else + { + var open = _open[nodeIndex]; + if (!open.TryGetValue(minute, out var m)) + { + open[minute] = m = new Minute(); + if (open.Count > MaxOpenMinutes) open.Remove(open.Keys.Min()); + } + var s = (int)((sentAtMs - minute * 60_000) / 1000); + m.Sent[s]++; + m.InFlight[s] = Math.Max(m.InFlight[s], inFlight); + switch (outcome) + { + case Outcome.Answered: + m.Ok[s]++; + m.OkMs[s] += latencyMs; + m.MaxMs[s] = Math.Max(m.MaxMs[s], latencyMs); + break; + case Outcome.RateLimited: m.RateLimited[s]++; break; + case Outcome.Timeout: m.Timeout[s]++; break; + case Outcome.ServerError: m.ServerError[s]++; break; + default: m.Failed[s]++; break; + } + if (retryAfterMs is { } wait) + { + m.RetryAfters++; + m.RetryAfterMin = Math.Min(m.RetryAfterMin, wait); + m.RetryAfterMax = Math.Max(m.RetryAfterMax, wait); + } + if (m.Headers == null && !string.IsNullOrEmpty(headers)) m.Headers = Sanitize(headers); + } + } + } + catch + { + // The trace is best effort: never the caller's failure. + } + } + + /// Logs the minutes that are due. A flush still writing is not joined. + public void Flush() + { + if (Interlocked.Exchange(ref _flushing, 1) == 1) return; + try + { + List? due; + lock (_lock) due = TakeDue(); + Write(due); + } + catch + { + // The trace is best effort. + } + finally + { + Volatile.Write(ref _flushing, 0); + } + } + + /// Flushes every off the request path, until disposed. + public IDisposable StartFlushing(TimeSpan period) => new Timer(_ => Flush(), null, period, period); + + // One token on a space-separated line, bounded. + private static string Sanitize(string headers) + { + var s = new string(headers.Select(c => char.IsWhiteSpace(c) || char.IsControl(c) ? '_' : c).ToArray()); + return s.Length > MaxHeaderSample ? s[..MaxHeaderSample] : s; + } + + private static string Field(int[] values) => values.All(v => v == 0) ? "-" : string.Join(',', values); + + // Under the lock. + private List? TakeDue() + { + var through = MinuteOf(_unixMs() - GraceMs) - 1; + if (through <= _loggedThrough) return null; + List? lines = null; + for (var i = 0; i < _names.Length; i++) + { + var open = _open[i]; + foreach (var minute in open.Keys.Where(k => k <= through).OrderBy(k => k).ToList()) + { + var m = open[minute]; + open.Remove(minute); + var ra = m.RetryAfters == 0 ? "0" : $"{m.RetryAfters}:{m.RetryAfterMin}:{m.RetryAfterMax}"; + (lines ??= new()).Add( + $"node-trace pool={_poolName} node={_names[i]} minute={minute * 60}" + + $" sent={Field(m.Sent)} ok={Field(m.Ok)} rl={Field(m.RateLimited)}" + + $" timeout={Field(m.Timeout)} e5xx={Field(m.ServerError)} fail={Field(m.Failed)}" + + $" ok_ms={Field(m.OkMs)} max_ms={Field(m.MaxMs)} inflight={Field(m.InFlight)}" + + $" retry_after={ra} hdr={m.Headers ?? "-"} late={_late[i]}"); + _late[i] = 0; + } + } + _loggedThrough = through; + return lines; + } + + // Outside the lock, line by line: a line the log fails on loses only itself. + private void Write(List? lines) + { + if (lines == null) return; + foreach (var line in lines) + { + try + { + _log(line); + } + catch + { + // The trace is best effort. + } + } + } +}