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
173 changes: 173 additions & 0 deletions dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,179 @@ public async Task AllNodesMalformed_ThrowsNamingTheNode()
Assert.Contains("http://127.0.0.1:", ex.Message); // node URL for diagnosability
}

[Fact]
public async Task AWhollyThrottledPool_CostsOneUpstreamCallPerLookup()
{
// A 429 parks the node; calling every parked node anyway turns one lookup
// into one 429 per node while the whole pool is throttling us, which is
// exactly the load the park exists to shed. Within the parks, a lookup
// may probe ONE parked node, never all of them.
await using var a = new StubNode(() => 429);
await using var b = new StubNode(() => 429);
await using var c = new StubNode(() => 429);
long now = 0;
var client = new HiveRpcClient(new[] { a.Url, b.Url, c.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);

await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.Equal(3, a.Hits + b.Hits + c.Hits); // unparked at the start: each asked once

now += 1_000; // well inside every park
await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.Equal(4, a.Hits + b.Hits + c.Hits);
}

[Fact]
public async Task AWhollyThrottledPool_ThrowsUpstreamRateLimited_WithTheShortestPark()
{
await using var a = new StubNode(() => 429);
await using var b = new StubNode(() => 429);
long now = 0;
var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);

var first = await Assert.ThrowsAsync<HiveRpcClient.UpstreamRateLimitedException>(() =>
client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.True(first.RetryAfterMs > 0);

// Skipped as parked counts as throttled too, not as "no nodes".
now += 4_000;
var second = await Assert.ThrowsAsync<HiveRpcClient.UpstreamRateLimitedException>(() =>
client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.InRange(second.RetryAfterMs, 1, first.RetryAfterMs);
}

[Fact]
public async Task ThrottledAndDown_IsNotReportedAsThrottled()
{
// A node that is down is a different failure: callers must not be told
// to back off and come back when part of the reason is an outage.
await using var throttled = new StubNode(() => 429);
await using var down = new StubNode(() => 500);
var client = new HiveRpcClient(new[] { throttled.Url, down.Url }, timeoutMs: 500, failoverThreshold: 1);

var ex = await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.IsNotType<HiveRpcClient.UpstreamRateLimitedException>(ex);
}

[Fact]
public async Task AParkedDeadNodeAndAThrottledNode_IsNotReportedAsThrottled()
{
// A node already parked for failing is left out of the ordering, so it
// never fails inside the call; it is still an outage, not throttling.
await using var dead = new StubNode(() => -1);
await using var throttled = new StubNode(() => 429);
long now = 0;
var client = new HiveRpcClient(new[] { dead.Url, throttled.Url }, timeoutMs: 200, failoverThreshold: 1, clock: () => now);
for (var i = 0; i < 3; i++)
{
if (i > 0) now += 61_000; // past the throttled node's park, inside nothing
await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
}
Assert.True(client.HealthSnapshot()[0]!["parked_for_ms"]!.GetValue<long>() > 0);

var ex = await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.IsNotType<HiveRpcClient.UpstreamRateLimitedException>(ex);
}

[Fact]
public async Task AParkedNode_StillServes_OnceEveryUnparkedNodeHasFailed()
{
// The one-probe allowance is what keeps a throttled pool recoverable:
// a node whose limit has lifted early is found before its park ends.
var throttledStatus = 429;
await using var throttled = new StubNode(() => throttledStatus);
await using var down = new StubNode(() => 500);
long now = 0;
var client = new HiveRpcClient(new[] { throttled.Url, down.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);

await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
throttledStatus = 200;
now += 1_000;
var result = await client.Call("condenser_api", "get_accounts", new JsonArray());
Assert.Equal("served-by", result![0]!["name"]!.GetValue<string>());
Assert.Equal(2, throttled.Hits);
}

[Fact]
public async Task ANodeThrottledMidCall_DoesNotTakeTheProbeFromTheSoonestPark()
{
// The ordering is a snapshot. A node another call parks while this one
// runs is the furthest from lapsing, so it must not take the single
// probe; the soonest-lapsing parked node gets it.
HiveRpcClient client = null!;
long now = 0;
await using var a = new StubNode(() => { client.Health.RecordRateLimited(1, null); return 500; });
await using var b = new StubNode(() => 429);
await using var c = new StubNode(() => 200);
client = new HiveRpcClient(new[] { a.Url, b.Url, c.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);
client.Health.RecordRateLimited(2, null); // c parked first: lapses first
now = 5_000;

var result = await client.Call("condenser_api", "get_accounts", new JsonArray());
Assert.Equal("served-by", result![0]!["name"]!.GetValue<string>());
Assert.Equal(0, b.Hits);
Assert.Equal(1, c.Hits);
}

[Fact]
public async Task ARefusedProbe_PassesToTheNextParkedNode()
{
// c is parked (soonest) after this call's snapshot and deferred; then,
// still inside the pass, it goes down. At probe time it is refused with
// no request sent, so the probe passes to the next parked node, b.
HiveRpcClient client = null!;
long now = 0;
await using var a = new StubNode(() => { client.Health.RecordRateLimited(1, 1); return 500; });
await using var c = new StubNode(() => 200);
await using var d = new StubNode(() =>
{
for (var i = 0; i < 3; i++) client.Health.RecordFailure(1, 10, CallClass.Cheap, timedOut: true);
return 500;
});
await using var b = new StubNode(() => 200);
client = new HiveRpcClient(new[] { a.Url, c.Url, d.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);
client.Health.RecordRateLimited(3, null); // b parked before the call: last in the snapshot

var result = await client.Call("condenser_api", "get_accounts", new JsonArray());
Assert.Equal("served-by", result![0]!["name"]!.GetValue<string>());
Assert.Equal(0, c.Hits);
Assert.Equal(1, b.Hits);
}

[Fact]
public async Task ANodeDownAndThrottled_IsAnOutage_EvenAfterTheProbeIsSpent()
{
HiveRpcClient client = null!;
long now = 0;
await using var x = new StubNode(() =>
{
client.Health.RecordRateLimited(1, null);
client.Health.RecordRateLimited(2, null);
for (var i = 0; i < 3; i++) client.Health.RecordFailure(2, 10, CallClass.Cheap, timedOut: true);
return 429;
});
await using var y = new StubNode(() => 429);
await using var z = new StubNode(() => 429);
client = new HiveRpcClient(new[] { x.Url, y.Url, z.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);

var ex = await Assert.ThrowsAnyAsync<Exception>(() => client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.IsNotType<HiveRpcClient.UpstreamRateLimitedException>(ex);
}

[Fact]
public async Task RetryAfter_CountsAParkThatLapsedDuringTheCall()
{
// The first node's park lapses while the second is answering: it can
// serve now, so the advised wait is the minimum, not the second's park.
long now = 0;
await using var a = new StubNode(() => 429);
await using var b = new StubNode(() => { now += 11_000; return 429; });
var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now);

var ex = await Assert.ThrowsAsync<HiveRpcClient.UpstreamRateLimitedException>(() =>
client.Call("condenser_api", "get_accounts", new JsonArray()));
Assert.Equal(1, ex.RetryAfterMs);
}

[Fact]
public async Task AllNodesDown_Throws()
{
Expand Down
35 changes: 35 additions & 0 deletions dotnet/EcencyApi.Tests/SsrRpcTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,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 163 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 @@ -266,6 +266,41 @@
Assert.Equal(SsrRpc.Outcome.Unavailable, r.Outcome);
}

[Fact]
public async Task A_throttled_upstream_answers_503_RATELIMITED_with_Retry_After_and_is_counted()
{
// Distinct from UNAVAILABLE (502): the consumer must be able to tell
// "the nodes are throttling this host" from "this proxy is broken", or it
// trips its breaker and sends every read to the same throttling nodes.
await using var stub = new RpcStub { Status = 429 };
Use(stub);
SsrRpc.SecretDigest = SsrRpc.Digest("right-secret");
try
{
var r = await SsrRpc.Resolve(Post, P("a", "b"));
Assert.Equal(SsrRpc.Outcome.RateLimited, r.Outcome);

var ctx = Request("POST", "/private-api/ssr/rpc", "right-secret",
"{\"api\":\"bridge\",\"method\":\"get_post\",\"params\":{\"author\":\"a\",\"permlink\":\"c\"}}");
await SsrRpc.Rpc(ctx);
Assert.Equal(503, ctx.Response.StatusCode);
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}'");

var stats = Request("GET", "/private-api/ssr/stats", "right-secret");
await SsrRpc.Stats(stats);
var body = JsonNode.Parse(ResponseText(stats))!;
var m = body["methods"]!["bridge.get_post"]!;
Assert.Equal(2, m["rate_limited"]!.GetValue<long>());
Assert.Equal(0, m["error"]!.GetValue<long>());
}
finally
{
SsrRpc.SecretDigest = null;
}
}

[Fact]
public async Task Fills_in_progress_are_bounded_so_distinct_keys_queue_instead_of_piling_up()
{
Expand Down Expand Up @@ -389,8 +424,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 427 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 428 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
1 change: 1 addition & 0 deletions dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ internal static (string Key, string Line) RecoveryReadFailureLog(string method,
HttpRequestException => "http_error",
// The RPC client's own node failure type (unreachable, bad status, bad body).
_ when type == "NodeUnavailableException" => "http_error",
HiveRpcClient.UpstreamRateLimitedException => "http_error",
HiveRpcClient.RpcException => "rpc_error",
FormatException or System.Text.Json.JsonException => "parse_error",
_ => "other",
Expand Down
21 changes: 18 additions & 3 deletions dotnet/EcencyApi/Handlers/SsrRpc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ namespace EcencyApi.Handlers;
/// - A lookup that outlives the budget answers 504 while the upstream call
/// completes in the background and fills the cache; an RPC-level error
/// answers 502. Either way the consumer falls back to its own node pool.
/// - A lookup that failed only because every node is rate-limiting this host
/// 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.
/// - No per-request logging (invariant 6); counters on /stats instead.
/// </summary>
public static partial class SsrRpc
Expand Down Expand Up @@ -152,7 +156,7 @@ public bool TryExpire(int budgetMs)

internal sealed class Counter
{
public long Hit, Miss, Coalesced, Error, Timeout;
public long Hit, Miss, Coalesced, Error, Timeout, RateLimited;
// Fills that outran the lookup budget. Distinct from Timeout, which is
// counted once per waiting reader: one slow fill on a hot key is one
// slow fill and many timeouts.
Expand Down Expand Up @@ -226,9 +230,9 @@ internal static string CacheKey(MethodPolicy policy, JsonNode? @params) =>

// ---- core ----------------------------------------------------------------

internal enum Outcome { Hit, Miss, Coalesced, Timeout, RpcError, Unavailable }
internal enum Outcome { Hit, Miss, Coalesced, Timeout, RpcError, Unavailable, RateLimited }

internal readonly record struct Resolution(Outcome Outcome, byte[] Bytes, string? Error);
internal readonly record struct Resolution(Outcome Outcome, byte[] Bytes, string? Error, int RetryAfterMs = 0);

/// <summary>
/// Answer one allowlisted call from the cache, or from one shared upstream
Expand Down Expand Up @@ -318,6 +322,11 @@ internal static async Task<Resolution> Resolve(MethodPolicy policy, JsonNode @pa
Interlocked.Increment(ref counter.Timeout);
return new Resolution(Outcome.Timeout, Array.Empty<byte>(), "budget exceeded");
}
catch (HiveRpcClient.UpstreamRateLimitedException e)
{
Interlocked.Increment(ref counter.RateLimited);
return new Resolution(Outcome.RateLimited, Array.Empty<byte>(), e.Message, e.RetryAfterMs);
}
catch (HiveRpcClient.RpcException e)
{
Interlocked.Increment(ref counter.Error);
Expand Down Expand Up @@ -479,6 +488,11 @@ public static async Task Rpc(HttpContext ctx)
case Outcome.Timeout:
await ctx.SendJson(504, new JsonObject { ["error"] = "Upstream Timeout" });
return;
case Outcome.RateLimited:
// long: a node may send a Retry-After near int.MaxValue ms.
ctx.Response.Headers.RetryAfter = ((resolution.RetryAfterMs + 999L) / 1000).ToString(System.Globalization.CultureInfo.InvariantCulture);
await ctx.SendJson(503, new JsonObject { ["error"] = "Upstream Rate Limited" });
return;
default:
await ctx.SendJson(502, new JsonObject { ["error"] = resolution.Error ?? "Upstream Error" });
return;
Expand Down Expand Up @@ -511,6 +525,7 @@ public static async Task Stats(HttpContext ctx)
["coalesced"] = Interlocked.Read(ref c.Coalesced),
["error"] = Interlocked.Read(ref c.Error),
["timeout"] = Interlocked.Read(ref c.Timeout),
["rate_limited"] = Interlocked.Read(ref c.RateLimited),
["slow_fill"] = Interlocked.Read(ref c.SlowFill),
["upstream_ms"] = Math.Round(c.ReadUpstreamMs(), 1),
};
Expand Down
Loading
Loading