diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index 654cee9c..8dd94a16 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -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(() => 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(() => 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(() => + 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(() => + 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(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(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(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + } + Assert.True(client.HealthSnapshot()[0]!["parked_for_ms"]!.GetValue() > 0); + + var ex = await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(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(() => 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()); + 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()); + 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()); + 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(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(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(() => + client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(1, ex.RetryAfterMs); + } + [Fact] public async Task AllNodesDown_Throws() { diff --git a/dotnet/EcencyApi.Tests/SsrRpcTests.cs b/dotnet/EcencyApi.Tests/SsrRpcTests.cs index 17e096dd..08729bd3 100644 --- a/dotnet/EcencyApi.Tests/SsrRpcTests.cs +++ b/dotnet/EcencyApi.Tests/SsrRpcTests.cs @@ -266,6 +266,41 @@ public async Task Unreachable_node_is_reported_as_unavailable() 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()); + Assert.Equal(0, m["error"]!.GetValue()); + } + finally + { + SsrRpc.SecretDigest = null; + } + } + [Fact] public async Task Fills_in_progress_are_bounded_so_distinct_keys_queue_instead_of_piling_up() { diff --git a/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs b/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs index 149d386a..a3cd1fd5 100644 --- a/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs +++ b/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs @@ -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", diff --git a/dotnet/EcencyApi/Handlers/SsrRpc.cs b/dotnet/EcencyApi/Handlers/SsrRpc.cs index 495098e0..f2918a48 100644 --- a/dotnet/EcencyApi/Handlers/SsrRpc.cs +++ b/dotnet/EcencyApi/Handlers/SsrRpc.cs @@ -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. /// public static partial class SsrRpc @@ -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. @@ -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); /// /// Answer one allowlisted call from the cache, or from one shared upstream @@ -318,6 +322,11 @@ internal static async Task Resolve(MethodPolicy policy, JsonNode @pa Interlocked.Increment(ref counter.Timeout); return new Resolution(Outcome.Timeout, Array.Empty(), "budget exceeded"); } + catch (HiveRpcClient.UpstreamRateLimitedException e) + { + Interlocked.Increment(ref counter.RateLimited); + return new Resolution(Outcome.RateLimited, Array.Empty(), e.Message, e.RetryAfterMs); + } catch (HiveRpcClient.RpcException e) { Interlocked.Increment(ref counter.Error); @@ -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; @@ -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), }; diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 5e39ef9e..bc01df91 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -14,6 +14,10 @@ namespace EcencyApi.Infrastructure; /// (dhive semantics — an application error, not an unhealthy node). /// - Overload statuses (429/502/503/504) advance to the next node immediately /// instead of burning a same-node retry. +/// - Only one node parked for a 429 is asked per call (the one whose park +/// lapses soonest, chosen after every unparked node was tried): while the whole pool throttles +/// this host, a call reaches one node instead of all of them. A call that +/// failed only on 429s throws . /// - An `unknown method` answer to a call that names a fallback method asks /// the same node the fallback, and marks the node and the method's family /// for a while (CallMethod). @@ -34,6 +38,9 @@ public sealed class HiveRpcClient private readonly Func _clock; private int _seq; + /// Test seam: the pool's health state, to stage parks mid-call. + internal NodeHealthTracker Health => _health; + // Per node, the fallback families it answered `unknown method` for and until // when (on _clock). Bounded by nodes x families; see CallMethod. private readonly ConcurrentDictionary<(int Node, string Family), long> _lacksUntil = new(); @@ -247,15 +254,66 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => JsonNode? unpreferred = null; var haveUnpreferred = false; var unpreferredCount = 0; + // Throttling is only reported as such when it is the whole story: any + // other failure on the way (a timeout, a 5xx, a bad body) makes it a + // plain failure, so a caller is never told to just wait out an outage. + var sawRateLimit = false; + var sawOtherFailure = false; + // Nodes this call found parked for a 429 (deferred) or saw answer 429: + // the advised wait is how long until the first of them can serve again. + var deferred = new List(); + var throttledNodes = new HashSet(); + + var ordered = _health.OrderedNodeIndices(callClass); + // A node left out of the ordering is parked for failing: part of the + // pool is down, so this call cannot be "only throttled". + if (ordered.Count < _nodes.Length) sawOtherFailure = true; + + // Every node in order, skipping the ones parked for a 429 at the moment + // they come up (the ordering is a snapshot; another call may have parked + // one since). Then ONE probe, to the deferred node whose park lapses + // soonest by then: it keeps the pool recoverable when a limit lifts + // early, while probing every parked node is the load the 429s asked us + // to stop sending. Chosen after the pass, so a node parked mid-call (the + // furthest from lapsing) cannot take the probe from an older park. A + // candidate refused at probe time (down, or probed by another call + // meanwhile) got no request, so the probe passes to the next one. + var probeSent = false; + IEnumerable<(int Node, bool Probe)> Sequence() + { + foreach (var i in ordered) yield return (i, false); + var candidates = new List(deferred); + while (!probeSent && candidates.Count > 0) + { + var next = candidates.OrderBy(i => _health.RateLimitedForMs(i)).First(); + candidates.Remove(next); + yield return (next, true); + } + } - foreach (var nodeIndex in _health.OrderedNodeIndices(callClass)) + foreach (var (nodeIndex, isProbe) in Sequence()) { var node = _nodes[nodeIndex]; for (var attempt = 0; attempt < _failoverThreshold; attempt++) { - // The ordering above is a snapshot; admission is decided now. - if (!_health.TryBeginAttempt(nodeIndex)) break; + // Admission is decided now, under one lock with the park check. + var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe); + if (admission == NodeHealthTracker.Admission.RateLimitParked) + { + sawRateLimit = true; + throttledNodes.Add(nodeIndex); + if (attempt == 0) deferred.Add(nodeIndex); + break; + } + if (admission == NodeHealthTracker.Admission.Refused) + { + // Failure-parked, or a probe of it is already in flight: an + // outage, not throttling. No request was sent. + sawOtherFailure = true; + break; + } + if (isProbe) probeSent = true; var started = NowMs; try { @@ -322,11 +380,17 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => lastError = e; if (e.IsRateLimit) { + sawRateLimit = true; + throttledNodes.Add(nodeIndex); _health.RecordRateLimited(nodeIndex, e.RetryAfterMs); } - else if (_health.RecordFailure(nodeIndex, NowMs - started, callClass, e.IsTimeout)) + else { - break; // this failure parked the node: no same-node retry + sawOtherFailure = true; + if (_health.RecordFailure(nodeIndex, NowMs - started, callClass, e.IsTimeout)) + { + break; // this failure parked the node: no same-node retry + } } if (e.AdvanceImmediately) { @@ -336,6 +400,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => catch (Exception e) { lastError = e; + sawOtherFailure = true; if (_health.RecordFailure(nodeIndex, NowMs - started, callClass)) { break; @@ -353,11 +418,36 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // account really has no metadata), so return it instead of failing. if (haveUnpreferred) return unpreferred; + if (sawRateLimit && !sawOtherFailure) + { + // A park that lapsed during the call counts as 0: that node can serve now. + var wait = throttledNodes.Min(i => _health.RateLimitedForMs(i)); + throw new UpstreamRateLimitedException( + $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, wait)); + } + // Every node exhausted — surface the last transport error (dhive throws // after cycling the whole list). throw lastError ?? new InvalidOperationException("no RPC nodes configured"); } + /// + /// Every node this call could use was rate-limiting this host: each attempt + /// answered 429, or the node was skipped while parked for an earlier 429. + /// Distinct from a pool that is down, so a caller can back off for + /// instead of sending the read elsewhere. + /// + public sealed class UpstreamRateLimitedException : Exception + { + /// Until the soonest of the parks lapses, at least 1. + public int RetryAfterMs { get; } + + public UpstreamRateLimitedException(string message, int retryAfterMs) : base(message) + { + RetryAfterMs = Math.Max(1, retryAfterMs); + } + } + /// A node is unhealthy/unreachable; try the next one. Distinct from /// RpcException (a real RPC-level error that must not fail over). private sealed class NodeUnavailableException : Exception diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index 2d963efd..95aab542 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -268,7 +268,8 @@ private void RecordLatency(NodeHealth h, CallClass callClass, double elapsedMs) /// /// Node indices ordered best-first: unparked nodes sorted by /// (recent-failure tier, latency score, config index); rate-limit-parked - /// nodes appended last as a final resort. A node parked for consecutive + /// nodes appended last as a final resort, the park that lapses soonest + /// first (a caller that probes only one of them probes the likeliest). A node parked for consecutive /// failures is left out altogether while any other node is available (it /// was not answering; a throttled node might), and probed once its park /// lapses. When every node is failure-parked all are offered, so a pool @@ -296,7 +297,8 @@ public List OrderedNodeIndices(CallClass callClass) && p.SampleCount >= LatencyMinSamples && now - p.UpdatedAtMs <= LatencyMaxAgeMs; var score = latencyUsable ? p.EwmaMs!.Value : LatencyUnprovenPriorMs; - return (Index: i, Parked: parked, Dead: dead, RecentFailure: recentFailure, Score: score); + return (Index: i, Parked: parked, ParkedUntil: parked ? h.RateLimitedUntilMs : 0, + Dead: dead, RecentFailure: recentFailure, Score: score); }) .ToList(); if (ranked.Any(x => !x.Dead)) @@ -305,6 +307,7 @@ public List OrderedNodeIndices(CallClass callClass) } return ranked .OrderBy(x => x.Parked) + .ThenBy(x => x.ParkedUntil) .ThenBy(x => x.RecentFailure) .ThenBy(x => x.Score) .ThenBy(x => x.Index) @@ -313,6 +316,15 @@ public List OrderedNodeIndices(CallClass callClass) } } + /// How long the node stays parked for a 429, 0 when it is not. + public long RateLimitedForMs(int nodeIndex) + { + lock (_lock) + { + return Math.Max(0, _health[nodeIndex].RateLimitedUntilMs - NowMs); + } + } + /// /// Admission at attempt time, because the ordering a call holds was taken /// when the call started and can be stale by the time it reaches this node: @@ -322,7 +334,18 @@ public List OrderedNodeIndices(CallClass callClass) /// rule yields when no other node could take the attempt. Pair with /// . /// - public bool TryBeginAttempt(int nodeIndex) + public bool TryBeginAttempt(int nodeIndex) => Admit(nodeIndex, allowRateLimitParked: true) == Admission.Admitted; + + public enum Admission { Admitted, RateLimitParked, Refused } + + /// + /// plus, when + /// is false, a node parked for a 429 is not admitted (RateLimitParked), decided + /// under the same lock so a concurrent park cannot slip in between. A node that + /// is failure-parked is Refused first, even if it is also rate-limit parked: an + /// outage outranks throttling. Admitted pairs with . + /// + public Admission Admit(int nodeIndex, bool allowRateLimitParked) { lock (_lock) { @@ -341,10 +364,11 @@ public bool TryBeginAttempt(int nodeIndex) var oBusy = !oParked && o.FailureParkStreak > 0 && o.InFlight > 0; othersAvailable = !oParked && !oBusy; } - if (othersAvailable) return false; + if (othersAvailable) return Admission.Refused; } + if (!allowRateLimitParked && h.RateLimitedUntilMs > now) return Admission.RateLimitParked; h.InFlight++; - return true; + return Admission.Admitted; } }