Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions dotnet/EcencyApi.Tests/SsrRpcTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@
var tasks = Enumerable.Range(0, 12).Select(_ => SsrRpc.Resolve(Post, P("a", "b"))).ToArray();
var results = await Task.WhenAll(tasks);
Assert.Equal(1, stub.Hits);
Assert.Single(results.Where(r => r.Outcome == SsrRpc.Outcome.Miss));

Check warning on line 179 in dotnet/EcencyApi.Tests/SsrRpcTests.cs

View workflow job for this annotation

GitHub Actions / test

Do not use a Where clause to filter before calling Assert.Single. Use the overload of Assert.Single that accepts a filtering function. (https://xunit.net/xunit.analyzers/rules/xUnit2031)
Assert.Equal(11, results.Count(r => r.Outcome == SsrRpc.Outcome.Coalesced));
var bodies = results.Select(r => Encoding.UTF8.GetString(r.Bytes)).Distinct().ToArray();
Assert.Single(bodies);
Expand Down Expand Up @@ -244,6 +244,75 @@
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()
{
Expand Down Expand Up @@ -399,6 +468,12 @@
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);
Expand Down Expand Up @@ -536,8 +611,8 @@
await Task.Delay(180);
var c = SsrRpc.Resolve(Post, P("k", "2")); // fresh reader at ~190ms, coalesces
await Task.WhenAll(a, b, c);
Assert.Equal(SsrRpc.Outcome.Timeout, a.Result.Outcome);

Check warning on line 614 in dotnet/EcencyApi.Tests/SsrRpcTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)
Assert.Equal(SsrRpc.Outcome.Timeout, b.Result.Outcome);

Check warning on line 615 in dotnet/EcencyApi.Tests/SsrRpcTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)
// Judged by the fresh attach, not by the original enqueue: the fill ran.
await Task.Delay(500);
Assert.Equal(2, stub.Hits);
Expand Down Expand Up @@ -703,6 +778,8 @@
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
Expand Down
55 changes: 52 additions & 3 deletions dotnet/EcencyApi/Handlers/SsrRpc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
public static partial class SsrRpc
Expand All @@ -42,9 +46,53 @@ public static partial class SsrRpc
/// between nodes, so the pool is ordered for them from their own latency
/// profile (see <see cref="CallClass"/>). Required, not defaulted: a new
/// method has to be classified, not silently filed as cheap.</param>
internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallClass Class, string? Fallback = null)
/// <param name="LongTtlMs">TTL for an answer <paramref name="LongWhen"/>
/// 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
/// <paramref name="TtlMs"/> and is asked again soon.
/// Null keeps <paramref name="TtlMs"/> for every answer.</param>
internal sealed record MethodPolicy(string Api, string Method, int TtlMs, CallClass Class, string? Fallback = null,
int? LongTtlMs = null, Func<JsonNode, JsonNode?, bool>? 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;

/// <summary>
/// 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.
/// </summary>
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<string>(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:
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
25 changes: 25 additions & 0 deletions dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,31 @@ internal HiveRpcClient(string[] nodes, int timeoutMs, int failoverThreshold, Fun

public IReadOnlyList<string> Nodes => _nodes;

/// <summary>
/// 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.
/// </summary>
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();
}

/// <summary>
/// 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
Expand Down
21 changes: 21 additions & 0 deletions dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,27 @@ public void EndAttempt(int nodeIndex)
}
}

/// <summary>
/// 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.
/// </summary>
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;
}
}

/// <summary>Per-node state and lifetime counters, for the stats endpoint.</summary>
public List<NodeView> Snapshot()
{
Expand Down
Loading