diff --git a/dotnet/EcencyApi.Tests/SsrRpcTests.cs b/dotnet/EcencyApi.Tests/SsrRpcTests.cs index ac73882c..857c986d 100644 --- a/dotnet/EcencyApi.Tests/SsrRpcTests.cs +++ b/dotnet/EcencyApi.Tests/SsrRpcTests.cs @@ -244,6 +244,75 @@ public async Task Ttl_expiry_goes_upstream_again() Assert.Equal(2, stub.Hits); } + [Fact] + public void Only_rate_limit_parks_are_reported_not_failure_parks() + { + // A failure park follows this client's own short timeouts; a consumer + // with longer ones may still get an answer from that node. + var clock = 1_000L; + var tracker = new NodeHealthTracker(3, () => clock); + for (var i = 0; i < 10; i++) tracker.RecordFailure(0, 2000, CallClass.Cheap, timedOut: true); + tracker.RecordRateLimited(1, 5_000); + var parked = tracker.RateLimitedForMsAll(); + Assert.Equal(0, parked[0]); + Assert.Equal(5_000, parked[1]); + Assert.Equal(0, parked[2]); + clock += 2_000; + Assert.Equal(3_000, tracker.RateLimitedForMsAll()[1]); + } + + [Fact] + public async Task A_found_profile_list_outlives_the_short_ttl_while_an_empty_one_does_not() + { + await using var stub = new RpcStub + { + RawBody = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":[{\"name\":\"a\",\"post_count\":9}]}", + }; + Use(stub); + var shortLived = SsrRpc.Allowlist["bridge.get_profiles"] with { TtlMs = 150 }; + var found = new JsonObject { ["accounts"] = new JsonArray("a") }; + Assert.Equal(SsrRpc.Outcome.Miss, (await SsrRpc.Resolve(shortLived, found)).Outcome); + await Task.Delay(300); + Assert.Equal(SsrRpc.Outcome.Hit, (await SsrRpc.Resolve(shortLived, found)).Outcome); + Assert.Equal(1, stub.Hits); + + // An account a node does not know yet: asked again soon, not in an hour. + stub.RawBody = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":[]}"; + var missing = new JsonObject { ["accounts"] = new JsonArray("new-account") }; + Assert.Equal(SsrRpc.Outcome.Miss, (await SsrRpc.Resolve(shortLived, missing)).Outcome); + await Task.Delay(300); + Assert.Equal(SsrRpc.Outcome.Miss, (await SsrRpc.Resolve(shortLived, missing)).Outcome); + Assert.Equal(3, stub.Hits); + } + + [Theory] + [InlineData("[\"a\"]", "[{\"name\":\"a\"}]", true)] + [InlineData("[\"a\",\"b\"]", "[{\"name\":\"b\"},{\"name\":\"a\"}]", true)] + // A node that does not know `new` yet leaves it out: the list stays short. + [InlineData("[\"a\",\"new\"]", "[{\"name\":\"a\"}]", false)] + [InlineData("[\"a\"]", "[]", false)] + [InlineData("[\"a\"]", "null", false)] + [InlineData("[]", "[{\"name\":\"a\"}]", false)] + public void Only_a_profile_list_naming_every_asked_account_is_long_lived(string asked, string answer, bool complete) + { + var @params = new JsonObject { ["accounts"] = JsonNode.Parse(asked) }; + Assert.Equal(complete, SsrRpc.IsCompleteProfileList(@params, JsonNode.Parse(answer))); + } + + [Fact] + public void Only_the_profile_list_is_long_lived() + { + Assert.True(SsrRpc.Allowlist["bridge.get_profiles"].LongTtlMs >= 30 * 60_000); + // get_profile is cross-checked against get_accounts by the full-account + // read, and posts can be edited at any age: both stay short. + foreach (var (key, policy) in SsrRpc.Allowlist) + { + if (key == "bridge.get_profiles") continue; + Assert.Null(policy.LongTtlMs); + Assert.True(policy.TtlMs <= 300_000, key); + } + } + [Fact] public async Task Budget_exceeded_answers_timeout_while_the_fill_still_lands_in_the_cache() { @@ -399,6 +468,12 @@ public async Task A_throttled_upstream_answers_503_RATELIMITED_with_Retry_After_ Assert.Equal("RATELIMITED", ctx.Response.Headers["X-Ssr-Cache"].ToString()); Assert.True(int.TryParse(ctx.Response.Headers.RetryAfter.ToString(), out var secs) && secs >= 1, $"Retry-After '{ctx.Response.Headers.RetryAfter}'"); + // The parked node is named (authority=ms) so the consumer's fallback + // can skip it instead of drawing its own 429 from it. + var parks = ctx.Response.Headers["X-Ssr-Node-Parks"].ToString(); + var authority = new Uri(stub.Url).Authority; + Assert.StartsWith(authority + "=", parks); + Assert.True(long.Parse(parks[(authority.Length + 1)..]) > 0, parks); var stats = Request("GET", "/private-api/ssr/stats", "right-secret"); await SsrRpc.Stats(stats); @@ -703,6 +778,8 @@ public async Task A_null_result_is_served_as_json_null_with_a_json_content_type( await SsrRpc.Rpc(ctx); Assert.True(ctx.Response.StatusCode == 200, $"status {ctx.Response.StatusCode}: {ResponseText(ctx)}"); Assert.StartsWith("application/json", ctx.Response.ContentType); + // A healthy pool names no node. + Assert.False(ctx.Response.Headers.ContainsKey("X-Ssr-Node-Parks")); Assert.Equal("null", ResponseText(ctx)); } finally diff --git a/dotnet/EcencyApi/Handlers/SsrRpc.cs b/dotnet/EcencyApi/Handlers/SsrRpc.cs index 250b39d2..9e073db9 100644 --- a/dotnet/EcencyApi/Handlers/SsrRpc.cs +++ b/dotnet/EcencyApi/Handlers/SsrRpc.cs @@ -32,6 +32,10 @@ namespace EcencyApi.Handlers; /// answers 503 RATELIMITED with a Retry-After. The proxy itself is fine, so /// a consumer must not count it toward a breaker that would send its other /// reads straight to the same throttling nodes. +/// - Every answer names the nodes the cache's client has rate-limit parked +/// (X-Ssr-Node-Parks: authority=ms,...), so a consumer that falls back to +/// its own pool can skip them instead of re-learning each 429 with a request +/// of its own from the same address. /// - No per-request logging (invariant 6); counters on /stats instead. /// public static partial class SsrRpc @@ -42,9 +46,53 @@ public static partial class SsrRpc /// between nodes, so the pool is ordered for them from their own latency /// profile (see ). Required, not defaulted: a new /// method has to be classified, not silently filed as cheap. - internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallClass Class, string? Fallback = null) + /// TTL for an answer + /// accepts, given the request params and the answer; any other answer (a + /// list missing an account a node does not know yet, a null) keeps + /// and is asked again soon. + /// Null keeps for every answer. + internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallClass Class, string? Fallback = null, + int? LongTtlMs = null, Func? LongWhen = null) { public string Key => $"{Api}.{Method}"; + + public int TtlFor(JsonNode @params, JsonNode? result) => + LongTtlMs is { } ttl && LongWhen is { } accept && accept(@params, result) ? ttl : TtlMs; + } + + // bridge.get_profiles for the author of the page being rendered: read once + // per post render, and the same author repeats across renders far beyond a + // minute (a crawl walks one author's posts), while the fields a render reads + // (display name, reputation, post count) change on a much longer scale. + // Only get_profiles: get_profile is cross-checked against get_accounts by + // the full-account read, and the two must stay equally fresh. Posts stay + // short however old they are: an edit after payout changes nothing a cache + // could key on, and its author is sent straight back to the page. + private const int ProfilesTtlMs = 60 * 60_000; + + /// + /// Whether a get_profiles answer names every account the request asked for. + /// A node leaves out an account it does not know yet (a new one, or one its + /// hivemind has not indexed), and the whole list is cached under one key, so + /// a partial answer must stay short or that account stays missing for the + /// long TTL. + /// + internal static bool IsCompleteProfileList(JsonNode @params, JsonNode? result) + { + if (result is not JsonArray profiles || profiles.Count == 0) return false; + if (@params is not JsonObject p || p["accounts"] is not JsonArray asked || asked.Count == 0) return false; + var found = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var profile in profiles) + { + if (profile is JsonObject o && o["name"] is JsonValue n && JsVal.TryGetStringLenient(n, out var name)) + found.Add(name); + } + foreach (var account in asked) + { + if (account is not JsonValue a || !JsVal.TryGetStringLenient(a, out var wanted) || !found.Contains(wanted)) + return false; + } + return true; } // TTLs follow how fast each read legitimately changes for a page render: @@ -72,7 +120,7 @@ internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallCl new MethodPolicy("bridge", "get_discussion_v2", 30_000, CallClass.Heavy, Fallback: "get_discussion"), new MethodPolicy("bridge", "get_post_v2", 30_000, CallClass.Cheap, Fallback: "get_post"), new MethodPolicy("bridge", "get_profile", 60_000, CallClass.Cheap), - new MethodPolicy("bridge", "get_profiles", 60_000, CallClass.Cheap), + new MethodPolicy("bridge", "get_profiles", 60_000, CallClass.Cheap, LongTtlMs: ProfilesTtlMs, LongWhen: IsCompleteProfileList), new MethodPolicy("bridge", "get_community", 300_000, CallClass.Cheap), new MethodPolicy("bridge", "list_communities", 300_000, CallClass.Cheap), new MethodPolicy("condenser_api", "get_accounts", 30_000, CallClass.Cheap), @@ -433,7 +481,7 @@ private static async Task Fill(MethodPolicy policy, JsonNode @params, string key } var bytes = Encoding.UTF8.GetBytes(result is null ? "null" : JsJson.Stringify(result)); counter.RecordUpstream(Environment.TickCount64 - started); - Cache.Set(key, bytes, policy.TtlMs); + Cache.Set(key, bytes, policy.TtlFor(@params, result)); tcs.TrySetResult(bytes); } catch (Exception e) @@ -485,6 +533,7 @@ public static async Task Rpc(HttpContext ctx) var resolution = await Resolve(policy, @params); ctx.Response.Headers["X-Ssr-Cache"] = resolution.Outcome.ToString().ToUpperInvariant(); + if (Client.RateLimitedNodesHeader() is { } parks) ctx.Response.Headers["X-Ssr-Node-Parks"] = parks; switch (resolution.Outcome) { case Outcome.Hit: diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index a3276999..e6217000 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -86,6 +86,31 @@ internal HiveRpcClient(string[] nodes, int timeoutMs, int failoverThreshold, Fun public IReadOnlyList Nodes => _nodes; + /// + /// The nodes this client has rate-limit parked, as `authority=ms` pairs joined + /// by commas (authority is host plus any non-default port, the form a + /// consumer's node URL reduces to), or null when none is. Lets a consumer that + /// falls back to its own pool from the same address skip a node that is + /// throttling that address, instead of drawing the same 429 itself. Failure + /// parks are left out: they follow this client's own timeouts, which a + /// consumer with longer ones need not share. + /// + public string? RateLimitedNodesHeader() + { + var parked = _health.RateLimitedForMsAll(); + System.Text.StringBuilder? sb = null; + for (var i = 0; i < parked.Length; i++) + { + if (parked[i] <= 0) continue; + sb ??= new System.Text.StringBuilder(); + if (sb.Length > 0) sb.Append(','); + sb.Append(Uri.TryCreate(_nodes[i], UriKind.Absolute, out var u) ? u.Authority : _nodes[i]) + .Append('=') + .Append(parked[i].ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + return sb?.ToString(); + } + /// /// Per-node health for an internal stats endpoint: which node carries the /// traffic, which one times out, which one is parked. Hosts only; these are diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index 95aab542..af6cf73b 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -381,6 +381,27 @@ public void EndAttempt(int nodeIndex) } } + /// + /// How long each node stays rate-limit parked, 0 when it is not. Only the + /// node's own throttling: a failure park reflects this client's timeouts, + /// which another client with its own may not share. One lock and one small + /// array, so it is cheap enough to read on every response. + /// + public long[] RateLimitedForMsAll() + { + lock (_lock) + { + var now = NowMs; + var result = new long[_health.Length]; + for (var i = 0; i < _health.Length; i++) + { + var h = _health[i]; + result[i] = Math.Max(0, h.RateLimitedUntilMs - now); + } + return result; + } + } + /// Per-node state and lifetime counters, for the stats endpoint. public List Snapshot() {