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
11 changes: 11 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ METRICS_ENABLED=false
# always present but returns nulls until enabled). Cheap: 2 extra RPC calls per poll.
# FINALITY_ENABLED=false

# API only. On a deployment with NO finality data, /ready, /coverage, `_coverage` and
# the ensv2_coverage_stale gauge report stale=true once any indexed protocol has gone
# this many seconds without committing a batch, or when nothing has synced at all.
# Ignored when finality data is present (the safe-head comparison wins).
# Off by default (0 / off). The shipped docker-compose files set 3600.
# - Must exceed your longest healthy batch: bulk-sync batches have taken 10-44 min.
# - --backfill and END_BLOCK-pinned deployments do not advance the head and WILL read
# stale; set 0 for those.
# - Compares the indexer host's clock with the API host's; keep both NTP-synced.
# COVERAGE_STALE_AFTER_SECONDS=3600

# Query-time Resolution (all OFF by default — served values are byte-identical
# until explicitly enabled). See docs/tasks/04-06.
# Dedicated resolution RPC endpoint (defaults to RPC_URL when unset):
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ services:
- API_PORT=5655
- GRAPHQL_MAX_DEPTH=10
- GRAPHQL_MAX_COST=${GRAPHQL_MAX_COST:-10000}
# Without finality data, report stale=true once a protocol has gone this long
# without committing a batch (see .env.example). Above the longest healthy
# batch; set 0 for a --backfill or an END_BLOCK-pinned deployment.
- COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600}
- WEBHOOKS_ENABLED=${WEBHOOKS_ENABLED:-false}
- WEBHOOK_DB_PATH=/app/webhooks/webhooks.db
- WEBHOOK_ADMIN_USERNAME=${WEBHOOK_ADMIN_USERNAME:-}
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ services:
# throttle, so setting it only there left the API on the code default (15/s)
# and capped the public surface without anyone choosing that number.
- RATE_LIMIT_PER_SECOND=${API_RATE_LIMIT_PER_SECOND:-25}
# Without finality data, report stale=true once a protocol has gone this long
# without committing a batch (see .env.example). Above the longest healthy
# batch; set 0 for a --backfill or an END_BLOCK-pinned deployment.
- COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600}
- GRAPHQL_MAX_DEPTH=10
- GRAPHQL_MAX_COST=${GRAPHQL_MAX_COST:-10000}
# Live resolution (ENSIP-10 Universal Resolver fallback) for single-name
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ services:
# throttle, so setting it only there left the API on the code default (15/s)
# and capped the public surface without anyone choosing that number.
- RATE_LIMIT_PER_SECOND=${API_RATE_LIMIT_PER_SECOND:-25}
# Without finality data, report stale=true once a protocol has gone this long
# without committing a batch (see .env.example). Above the longest healthy
# batch; set 0 for a --backfill or an END_BLOCK-pinned deployment.
- COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600}
# Number of trusted reverse-proxy hops. MUST be non-zero behind a proxy:
# at 0 the limiter keys on the direct TCP peer, which is the proxy, so every
# client on earth shares one bucket. Count the real chain (CDN -> ingress ->
Expand Down
8 changes: 5 additions & 3 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,10 @@ type Query {

"""
What this deployment indexes (ensv2 extension): chain id, per-protocol indexed
head + last-sync time, and a staleness flag. `stale` is false when finality data
is absent (default deployments); `_finality.isStale` is the conservative variant.
head + last-sync time, and a staleness flag. Without finality data `stale` can
fall back to how long each protocol has gone without committing a batch (opt-in,
`COVERAGE_STALE_AFTER_SECONDS`); `_finality.isStale` remains the conservative
variant (true whenever no safe data).
"""
_coverage: Coverage!
}
Expand All @@ -141,7 +143,7 @@ type Query {
type Coverage {
"""EVM chain id this deployment indexes."""
chainId: Int!
"""True only when finality data shows the indexed head behind the chain's safe point."""
"""True when the indexed head is behind the chain's safe point. Without finality data it is false unless the deployment sets `COVERAGE_STALE_AFTER_SECONDS`, in which case it is true when any indexed protocol has gone that long without committing a batch, or when nothing has synced yet."""
stale: Boolean!
"""Per-protocol indexed positions."""
protocols: [ProtocolCoverage!]!
Expand Down
67 changes: 40 additions & 27 deletions src/api/api_endpoints.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const models = @import("../types/models.zig");
const Address = @import("../types/address.zig").Address;
const Hash = @import("../types/hash.zig").Hash;
const graphql = @import("handler.zig");
const api_common = @import("common.zig");
const parser = @import("../lib/graphql/parser.zig");
const json_utils = @import("../utils/json.zig");
const url_utils = @import("../utils/url.zig");
Expand Down Expand Up @@ -467,49 +468,46 @@ pub fn handleHealthCheck(self: *Server, conn: http_util.Conn) !void {

/// Readiness: can this node actually serve queries? Acquires a pool session and does a
/// trivial read; returns 503 when the DB is unreachable so a load balancer routes traffic
/// away. Staleness (indexed head behind the safe head) is surfaced as a `stale` flag, not
/// a 503, so a node that is merely a little behind keeps serving instead of flapping out
/// of rotation.
/// away. Staleness is surfaced as a `stale` flag (api/common.coverageStale), not a 503,
/// so a node that is merely a little behind keeps serving instead of flapping out of
/// rotation.
pub fn handleReadiness(self: *Server, conn: http_util.Conn) !void {
const database = self.pool.acquire() catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unavailable\"}");
defer self.pool.release(database);

const v1 = (database.getSyncState(.v1) catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}")) orelse 0;
const v2 = (database.getSyncState(.v2) catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}")) orelse 0;
const head: u64 = if (v1 > v2) v1 else v2;
const v1 = database.getSyncStateFull(.v1) catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}");
const v2 = database.getSyncStateFull(.v2) catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}");
const head = api_common.indexedHead(v1, v2);

const safe = database.getFinality(database.chain_id, .safe) catch null;
const safe_num: u64 = if (safe) |sp| sp.number else 0;
const stale = safe != null and head < safe_num;
const safe_num: ?u64 = if (safe) |sp| sp.number else null;
const stale = api_common.coverageStale(v1, v2, safe_num, database.stale_after_seconds, zsys.timestamp());

const body = try std.fmt.allocPrint(self.allocator, "{{\"status\":\"ready\",\"indexed_head\":{d},\"safe\":{d},\"stale\":{s}}}", .{ head, safe_num, if (stale) "true" else "false" });
const body = try std.fmt.allocPrint(self.allocator, "{{\"status\":\"ready\",\"indexed_head\":{d},\"safe\":{d},\"stale\":{s}}}", .{ head, safe_num orelse 0, if (stale) "true" else "false" });
defer self.allocator.free(body);
try self.sendJsonResponse(conn, 200, body);
}

/// Coverage declaration: chain id, per-protocol indexed head + last-sync time, and a
/// staleness flag (same semantics as /ready's `stale`: false when no finality data).
/// The GraphQL `_coverage` field serves the same data with field selection.
/// staleness flag (api/common.coverageStale, the same flag /ready reports). The
/// GraphQL `_coverage` field serves the same data with field selection.
pub fn handleCoverage(self: *Server, conn: http_util.Conn) !void {
const database = self.pool.acquire() catch
return self.sendJsonResponse(conn, 503, "{\"status\":\"unavailable\",\"reason\":\"db_unavailable\"}");
defer self.pool.release(database);

const v1 = database.getSyncStateFull(.v1) catch null;
const v2 = database.getSyncStateFull(.v2) catch null;
const v1_block: u64 = if (v1) |s| s.block else 0;
const v2_block: u64 = if (v2) |s| s.block else 0;
const head: u64 = if (v1_block > v2_block) v1_block else v2_block;
const safe = database.getFinality(database.chain_id, .safe) catch null;
const stale = if (safe) |sp| head < sp.number else false;
const stale = api_common.coverageStale(v1, v2, if (safe) |sp| sp.number else null, database.stale_after_seconds, zsys.timestamp());

const body = try std.fmt.allocPrint(
self.allocator,
"{{\"chainId\":{d},\"stale\":{s},\"protocols\":[{{\"protocol\":\"v1\",\"indexedHead\":{d},\"lastSyncedAt\":{?d}}},{{\"protocol\":\"v2\",\"indexedHead\":{d},\"lastSyncedAt\":{?d}}}]}}",
.{ database.chain_id, if (stale) "true" else "false", v1_block, if (v1) |s| s.at else null, v2_block, if (v2) |s| s.at else null },
.{ database.chain_id, if (stale) "true" else "false", if (v1) |s| s.block else 0, if (v1) |s| s.at else null, if (v2) |s| s.block else 0, if (v2) |s| s.at else null },
);
defer self.allocator.free(body);
try self.sendJsonResponse(conn, 200, body);
Expand Down Expand Up @@ -544,22 +542,27 @@ pub fn handleMetrics(self: *Server, conn: http_util.Conn) !void {
}

/// Append Prometheus finality gauges (Task 09): indexed head, safe/finalized positions,
/// safe lag, and a stale flag. Reads a pool session; 0/stale when finality is unpopulated.
/// safe lag, and both stale flags. Reads a pool session; 0/stale when finality is unpopulated.
fn appendFinalityMetrics(self: *Server, out: *std.Io.Writer.Allocating) !void {
const database = try self.pool.acquire();
defer self.pool.release(database);
const v1 = (try database.getSyncState(.v1)) orelse 0;
const v2 = (try database.getSyncState(.v2)) orelse 0;
const head: u64 = if (v1 > v2) v1 else v2;
const safe = try database.getFinality(database.chain_id, .safe);
const v1 = try database.getSyncStateFull(.v1);
const v2 = try database.getSyncStateFull(.v2);
const safe: ?u64 = if (try database.getFinality(database.chain_id, .safe)) |s| s.number else null;
const finalized = try database.getFinality(database.chain_id, .finalized);
try writeFinalityGauges(&out.writer, head, if (safe) |s| s.number else null, if (finalized) |f| f.number else null);
const coverage_stale = api_common.coverageStale(v1, v2, safe, database.stale_after_seconds, zsys.timestamp());
try writeFinalityGauges(&out.writer, api_common.indexedHead(v1, v2), safe, if (finalized) |f| f.number else null, coverage_stale);
}

/// Pure Prometheus-gauge formatter for the finality metrics (Task 09). Split out of the
/// DB-coupled fetch so the gauge SET and the lag math are unit-testable. `safe`/`finalized`
/// are the block numbers of the chain's safe/finalized heads (null = not yet observed).
fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64) !void {
///
/// Two stale gauges, deliberately different: `ensv2_indexing_stale` is the conservative
/// `_finality.isStale` (1 whenever there is no safe head to trust);
/// `ensv2_coverage_stale` is the `stale` flag /ready, /coverage and `_coverage` report,
/// including the COVERAGE_STALE_AFTER_SECONDS fallback.
fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64, coverage_stale: bool) !void {
try w.print("# TYPE ensv2_indexed_head gauge\nensv2_indexed_head {d}\n", .{head});
try w.print("# TYPE ensv2_finality_safe gauge\nensv2_finality_safe {d}\n", .{safe orelse 0});
try w.print("# TYPE ensv2_finality_finalized gauge\nensv2_finality_finalized {d}\n", .{finalized orelse 0});
Expand All @@ -570,31 +573,41 @@ fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64
try w.print("# TYPE ensv2_finality_finalized_lag gauge\nensv2_finality_finalized_lag {d}\n", .{finalized_lag});
const stale: u8 = if (safe) |s| (if (head < s) @as(u8, 1) else 0) else 1;
try w.print("# TYPE ensv2_indexing_stale gauge\nensv2_indexing_stale {d}\n", .{stale});
try w.print("# TYPE ensv2_coverage_stale gauge\nensv2_coverage_stale {d}\n", .{@intFromBool(coverage_stale)});
}

test "writeFinalityGauges: emits the full finality gauge set with correct lag" {
const a = std.testing.allocator;
{
var buf: std.Io.Writer.Allocating = .init(a);
defer buf.deinit();
try writeFinalityGauges(&buf.writer, 200, 190, 180); // head=200, safe=190, finalized=180
try writeFinalityGauges(&buf.writer, 200, 190, 180, false); // head=200, safe=190, finalized=180
const o = buf.written();
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexed_head 200\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe 190\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_finalized 180\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe_lag 10\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_finalized_lag 20\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexing_stale 0\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_coverage_stale 0\n") != null);
}
{
// No finality observed yet -> zeros, and stale=1 (we have no safe head to trust).
var buf: std.Io.Writer.Allocating = .init(a);
defer buf.deinit();
try writeFinalityGauges(&buf.writer, 200, null, null);
try writeFinalityGauges(&buf.writer, 200, null, null, false);
const o = buf.written();
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe 0\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe_lag 0\n") != null);
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexing_stale 1\n") != null);
// The coverage flag is whatever /coverage computed, not the conservative one.
try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_coverage_stale 0\n") != null);
}
{
var buf: std.Io.Writer.Allocating = .init(a);
defer buf.deinit();
try writeFinalityGauges(&buf.writer, 200, null, null, true);
try std.testing.expect(std.mem.indexOf(u8, buf.written(), "ensv2_coverage_stale 1\n") != null);
}
}

Expand Down
Loading
Loading