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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>`/`TryGetValue<string>` or `ToJsonString` on such data. Suggesting a switch back to the strict System.Text.Json APIs reintroduces production 500s.

Expand Down
133 changes: 132 additions & 1 deletion dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ private sealed class StubNode : IAsyncDisposable
/// answer with a well-formed account whose posting_json_metadata is empty.</summary>
public bool ServesMetadata = true;

/// <summary>Headers added to every response.</summary>
public Dictionary<string, string> 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 =>
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -448,6 +462,123 @@ public async Task RateLimits_DoNotCountTowardFailureParking()
Assert.Equal(0, view["parked_for_ms"]!.GetValue<long>());
}

[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<string>();
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<string>();
var client = new HiveRpcClient(new[] { hung.Url }, timeoutMs: 200, failoverThreshold: 1,
clock: null, traceClock: () => unixMs, traceLog: lines.Add);

await Assert.ThrowsAnyAsync<Exception>(() => 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<string>();
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<string>();
var client = new HiveRpcClient(new[] { blocked.Url }, timeoutMs: 500, failoverThreshold: 1,
clock: null, traceClock: () => unixMs, traceLog: lines.Add);

await Assert.ThrowsAnyAsync<Exception>(() => 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<string>();
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()
{
Expand Down
Loading
Loading