A Prometheus-driven observability dashboard for the Magma Devs Smart Router — the process that sits in front of raw RPC endpoints and multiplexes, retries, hedges, caches, and cross-validates across them.
A pnpm/TypeScript monorepo (Fastify API + Next.js 16 web + shared package, plus
apps/auth-proxy, a Cloudflare Worker that is the sign-in redirect proxy for
every dashboard — docs/AUTH.md),
built to the engineering standard of ~/projects/lava-connect, with the web UI
built 1:1 against the SR_Dashboard/ design prototype. Everything lives at the
repo root — apps/, packages/, docker-compose*.yml, Makefile.
lava-connect is the shape reference only. We copy its tooling, structure, and conventions (strict TS, Node16 ESM
.jssuffixes, Fastify plugin/route/ service layout, pnpm workspace, vitest, Docker patterns) — NOT its domain. This product has no billing and no users table by default. It reads live metrics from Prometheus and router topology from a mounted config file. Auth is optional:AUTH_MODE=disabled(the default) leaves every route public with no database;AUTH_MODE=enabledadds an Auth.js login, a gate on/api/*,/auth/*routes, and Postgres-backedusers+sessions(packages/db). Sessions are server-side: the token carries asid, the api resolves it to a live session and the live user row on every request, and four cumulative roles (read_only · requester · approver · admin) gate from that row — so revoking a session or demoting someone takes effect on the request in flight, not at their next sign-in. WithAUTH_MODE=enabledeveryone also sets up an authenticator app — seedocs/TWO-FACTOR.md, which needsTOTP_ENCRYPTION_KEY. Seedocs/AUTH.md.
The compose stack is self-contained: bundled Prometheus + an optional
router profile that builds the Smart Router from a checkout.
make up # SELF-CONTAINED stack: router + Prometheus + api + web + logs (Grafana :3001), detached
make ps # what's running
make down # stop everything
make dev # hot-reload stack (api tsx watch · web next dev · shared tsc --watch)
# equivalently, without make:
docker compose --profile router up --build # everything from nothing
docker compose up --build # dashboard + Prometheus only
# (a router already runs on the host's :7779)UI → http://localhost:3000 · API → http://localhost:8000 · Prometheus → http://localhost:9090 · router ETH1 jsonrpc → http://localhost:3360
# Host dev (Node 26 + pnpm 12) — needs a Prometheus at PROMETHEUS_URL
# pnpm once: https://pnpm.io/installation (or `npm install -g pnpm`). It then runs
# the version `packageManager` pins.
pnpm install
pnpm --filter @sr/shared build # api/web read shared's dist
pnpm dev # api :8000, web :3000
pnpm typecheck && pnpm testThe router profile builds from a smart-router checkout (ROUTER_DIR, default
~/projects/smart-router via make / ../../smart-router via compose) because
the published release image ships only the binary — no bundled specs/. The
checkout image bundles specs + example configs, so it boots offline. Override
paths/ports via Makefile/compose vars (ROUTER_DIR, SR_CONFIG_HOST,
SR_SPEC, WEB_PORT, …).
Ask your data implementation: docs/ASK-YOUR-DATA.md
and the delivery/acceptance ledger.
Managed Ask uses server-only MCP/Bedrock adapters, PostgreSQL personal history
and durable runs, and shared customer budget admission. The customer feature
flag, managed accounts and current session gate both the UI and paid routes.
An admin turns Ask off for everyone at once, and back on, from the Team page
(POST /api/ask/switch, audited as ask.turned_off / ask.turned_on).
┌──────────────┐ REST ┌─────────────────────┐ PromQL ┌────────────┐
│ apps/web │───────▶│ apps/api │─────────▶│ Prometheus │
│ Next.js 16 │ │ Fastify 5 (:8000) │ │ (:9090, │
│ (:3000) │ │ stateless proxy │ │ bundled) │
│ SWR · @sr/* │ │ optional auth/DB │ └─────┬──────┘
└──────┬───────┘ └──────────┬──────────┘ scrapes :7779
│ GET /api/config │ reads ┌─────┴──────┐
│ (runtime api url) └─ values file ──────▶│ smart-router│
└─ POST /api/routers/relay (Live test) ──────────▶│ (profile) │
— the api sends it from inside; the browser │ │
POSTs to :3360 with ROUTER_RELAY_ENABLED=false └─────┬──────┘
POST /api/upstreams/relay │
api ─────────────────────────────────────────────▶ upstream RPC
(Try-me "Direct to upstream" — router left out) (vendor endpoint)
The api's outbound paths besides Prometheus are that relay and Loki. The
relay is the Try-me drawer's "Direct to upstream" mode. The browser can't make
that call itself -
node urls are masked to scheme+host before they leave the api, because that is
where API keys live — so the api dials the upstream and hands back only the
answer. See docs/UPSTREAM-DIRECT-TEST.md.
The drawer's Via router leg goes through the api too:
POST /api/routers/relay sends it to the router's listener inside the
deployment, so a tenant that admits only listed source addresses at its public
hostnames still works from any browser. It is on in both auth modes, so with
accounts off anyone who can reach the api can send through the routers;
ROUTER_RELAY_ENABLED=false turns the routes off and the browser sends it. See
docs/ROUTER-RELAY.md.
Loki (LOKI_URL, optional) feeds the Transactions tab, the
Errors tab's request list and the Metrics page's Failed requests card. Prometheus holds totals, never one request, so
each transaction or failed request is rebuilt from the router's own log lines,
joined by the request GUID (services/transactions.ts and
services/error-requests.ts list the lines they read; what each try at each
upstream did is triesOf in services/router-log.ts, shared by both). That wording is the
router's, not an interface: a reworded line empties the tab, and the tests pin
it with captured lines. A router on smart-router #543 or later ends each
request in one relay_end event instead (services/relay-end.ts; contract:
smart-router's docs/RELAY-END-EVENT.md), written at every log level with the
chain, the method, the outcome and every try: a request that has one is read
from it alone, and each tab finds requests by it as well as by the old lines,
so a window across an upgrade reads both. Order them by Loki's nanosecond timestamp, never by
arrival: the router writes several lines of one request in the same
millisecond at different levels, and each level is its own Loki stream. A transaction
is a request the spec marks stateful:"1" or a transaction method by name
(HYPERLIQUID's spec doesn't flag eth_sendRawTransaction). On Cosmos SDK
chains a refused transaction still gets a normal reply, which the router
doesn't log, so there a reply without a node-error line is unknown, never
accepted. A transaction the router gave up on after sending it to a
provider is unknown too (a provider may still have passed it on, the error
rulebook's R-L); failed is kept for one sent nowhere. The tab words them by
the send, never by the chain: Sent, Refused, Outcome unknown, Not sent. A write the router itself can't settle ("write outcome unknown", or
write_unknown on relay_end) is unknown too, in its words; the Errors tab
lists the same request as write-unknown, drawn as the same grey "Outcome unknown"
with the same words (WRITE_UNKNOWN_NOTE in @sr/shared), and the Failed
requests card still counts it: it is a server error by the alert's definition. On relay_end a Cosmos refusal is read: the
router puts the reply's code in tx_code, so only a gRPC write is unknown
for it; and a transaction submitted over a WebSocket subscription (Substrate's
submit-and-watch) is a row, which the old lines never logged. Credentials work as the Prometheus ones do:
LOKI_USERNAME + LOKI_PASSWORD for basic auth (both or nothing),
LOKI_ORG_ID for X-Scope-OrgID.
The Transactions tab's chart (services/transactions-over-time.ts) counts the
same relay_end lines over the page window, a bar per stretch of the clock
(bucketGrid), each split by result. It reads the store first: the fleet's
Loki ruler records smartrouter_transactions:count1m in each tenant's org
(labels cluster, chain = the spec lowercased, service_name =
<tenant>-<router id lower-cased>, api_interface, outcome, tx_status, tx_refused;
the rule's line filter is TX_EVENT_FILTER, the list's own). A series' result
is txResultOf, the mapping the list's rows use too, so the two can't drift;
a subscription request a node refused on a try is the one case the list reads
as rejected and the counts can't. The recorded counts lag about two minutes
([1m] offset 30s, then the ruler's delay): the newest minutes are counted
from the logs, from where the ruler's newest count ends (read off a sample's
timestamp, since it evaluates at a second of its own), and the bars say so
(partialFrom) when the logs don't answer. No transactions recorded for the
scope is none sent where the store has the fleet's ruler, which records
smartrouter_final_requests:count1m from the same rules file for every tenant
whose routers log (RULER_FAMILY, checked over the window - 15 minutes at
least, a day at most - and kept 5 minutes): the whole window is never counted
from Loki there, since sparing that read is what the rules are for. Only a
store without the ruler - a standalone install - has the whole window counted
from the logs; a store that doesn't answer the check answers unreachable
rather than guess. A config router is read through its chain; on a chain other
routers serve too, the recorded counts split it by service_name, and the
logs, which can't, answer shared-chain. A router before smart-router v1.6.1
writes no relay_end, so its transactions are in the list, not the chart.
Later routers add optional relay_end fields (smart-router's
docs/RELAY-END-EVENT.md; schema 1 still, each absent when unknown, so an
older router's events read as before): the transaction's tx_hash, its
tx_status and tx_error where the send reply reports execution (Sui), the
caller's customer (project id) and request_id / task_id / tx_id,
request_bytes / reply_bytes, requested_block / seen_block, and each
try's node_code. callFactsOf (relay-end.ts) reads the caller's fields
onto both tabs' rows, a value not in its field's form left out. A row with
tx_status: "failure" is failed-on-chain, a failure in the cards and the
success rate. Both tabs filter by customer; the Transactions tab links the
hash to the chain's explorer where a transaction page is known
(explorerTxUrl, docs/CHAINS.md). A look-up takes the request ID, the
transaction hash or the caller's request id (LOOKUP_ID, plain characters,
up to 128), and matches only the event's own fields; a value several requests
carry (a transaction sent again keeps its hash) answers with the newest and
matches.
What a log read may cost. A line filter doesn't make a Loki read cheaper:
every chunk of the selected streams is opened, and a filter with few matches
can't stop early. So one read scans at most LOG_READ_BUDGET_BYTES (4 GB,
services/read-range.ts), weighed first from Loki's index (index/stats,
under a second for a month): a range within it is read whole, a heavier one
from its newest part, and the rest is the next "Load older". On a busy
deployment (gigabytes of router lines an hour) that is about half an hour per
read; on a small one a month reads whole. The Failed requests card reads the counts
the fleet Loki's ruler records once a minute into the metrics store
(smartrouter_final_{requests,failures}:count1m, RECORDED_OUTCOMES), which
cost the same at any window, and counts the lines only where those are
missing or stale, and only within the budget. A 14-day read of the raw lines
can pin a shared Loki and time out every tenant's alert rules.
Reading one chain or one router. Where the log agent labels the
router's streams by chain (the spec lower-cased) and service_name
(<tenant>-<router id lower-cased>) - the fleet's does, the labels the ruler's recorded
counts carry - both lists narrow their read to those streams
(services/stream-scope.ts: the values come from Loki's label index, kept 10
minutes; a router by the one service_name ending in -<id>, else its chain).
It is exact, and Loki opens no other chain's chunks, so the same budget covers
far more of the window. Narrowing by the upstreams' names, the fallback where
the streams carry no such label, fails on a busy deployment: a vendor's name is
on every chain it serves, and one chain's errors at it filled the read's line
limit in two seconds, leaving another chain's list empty for 12 hours
(2026-10-29).
Reading only relay_end lines. The fleet's log agent also labels a
router's relay_end lines relay_end="1", about a third of a busy router's
bytes. The relay_end reads - the finder of both lists, the Failed requests
card's line count and the Transactions chart's log counts - select that stream
(StreamScope.relayEnd) where Loki's series index has labelled streams with
lines in the five minutes before the read's start and in its last five, kept a
minute. The label index can't answer that: its recent answers come from every
stream in memory, whatever the range asked. Each of those reads comes after the
recorded counts it backs (the card's and the chart's), as before. A line
written before the label existed carries none, so a read that reaches back
past it, or a deployment whose agent sets no such label, keeps the plain
selector. The old-shape finders and the per-GUID follow-ups read every line,
as they must.
Naming one router. service_name carries the router id lower-cased: the
chart labels a router's pods app.smart-router-id: {{ $router.id | lower }}
and the fleet's collector builds service_name from that label, on the log
streams and the scraped series alike, while the values file the dashboard reads
keeps the id as written (the chart's own default ids are Ethereum and
CosmosHub). Every reader that picks a router by service_name - these lists,
the Transactions chart, the Failed requests card, the Availability view's
served row - names it through the serviceName* helpers in
services/stream-scope.ts: the id lower-cased, and regex-escaped where it is
matched by its end (serviceNameMatcher).
A request's chain is the one its lines name (chain_id on an error line, or
the listener on the line that ends it), else its router's: the log agent
labels a router's stream chain (its pod's app.smart-router-chain, the
spec lower-cased), and the Loki client keeps a stream's labels on its lines,
so a request still in flight names its chain too. Only without that label is
it the only chain serving every upstream it used - its tries and the pool
the router chose from (validAddresses). One node name serves many chains,
so a name alone never decides it; with several candidates spec is null and
specs lists them, and the row shows under each.
The list opens grouped (lib/error-groups.ts): one line per chain, deciding error (the failed try whose answer went back, else the last failed try, else the request's own code), cause (request for a code the catalogue files under the request or the chain, or an undetermined USER_ one - a CHAIN_ code can be a provider's, every-provider for two or more providers with that error, all-failed for two or more with different ones - pinned first - else the provider; the cache is not a provider) and whether the client got it, a request with no end logged apart. Without a code the error is its message with ids, hashes and numbers blanked (blankIds, an HTTP status kept). It groups the rows loaded and states the times those reads cover (coveredSpan: from where they begin, the window's start once nothing older is left, to the end of the read); the bars share that span. A request is on the Errors tab's list when a try failed, when its relay
policy decided to retry it ([StateMachine] policy.Decide, action: retry),
or when the router gave up. It gives up with one of two lines: failed getting responses from RPC endpoints when nothing came back (it returns
before "relay finished"), failed processing responses from RPC endpoints
when nothing usable did - either makes the request failed. A router on #543
writes neither line: its failed requests are relay_end events with an
outcome of no_answer, write_unknown, rejected_before_dispatch or
router_error, the server-errors alert's set. Such a request is listed when a
try or the request failed - what its finder reads, so the list does not change
with the log level. A request the router couldn't parse and a subscription
request write the event too, and are neither listed nor counted, as the alert
counts neither. A try the router called off (context canceled - another try had answered, or the client stopped waiting) is not a
failure. Each try carries the router's own words: the node's error message,
the router's retryable verdict on it, or why it passed an upstream over
(lag blocks behind the head) and whether it then sent to it anyway (the
stale fallback, when no other upstream is left); the request carries why the
router stopped (stop_reason). The list exists because the retry counters
can't say any of it, and because the router records a retry only once two
of a request's tries have come back: one it wanted to retry with no upstream
left, or whose other try never answered, is in no counter - so the list can
show failures the "Still failed" card doesn't count, and the card says so
rather than showing a quiet 0 - counted over the rows the list has loaded,
while it covers the cards' window. It reads at most 300 requests at a time,
newest first. nextBefore is just past the newest line of the first request
a read didn't keep (or of the oldest line, when the read hit its line limit),
and the next read includes it: a request whose lines straddle two reads comes
back in both, and the list keeps it once. Ending at the oldest kept line
instead would skip every request with lines between a kept one's first and
last. Once an older read is loaded, the list continues from its first read as
it was then and stops polling it.
Both lists read through services/log-list.ts. A read costs Loki the whole
span it covers - it opens every chunk of the router's streams in it, whatever
the filters match - so a list on the page window (no before) keeps its last
read on the api process, and its next poll reads only what is new: the
finders from LATE_MS (a minute) before where that read ended, merged by
GUID with the lines it held, each finder's newest lines kept up to its limit;
and the rest of a request's lines only for one that is new, or whose lines
can still come (afterMs after a line that found it, then LATE_MS for them
to reach Loki). Rows, more and nextBefore come out as a read of the whole
window gives them (log-list.test.ts). The window is read whole on first
use, once the last whole read is 10 minutes old (HEAD_FRESH_MS), when the
values file or the queries changed, and when the merge can't tell. A line
Loki holds more than LATE_MS after its own time is missed by polls until
then. Each list keeps one read per key in flight and its answer: a live
list's 15 s, a range that ended over LATE_MS ago 5 minutes, a read Loki
didn't answer, in whole or in part, 30 s. The web reads a live list every
30 s, and after a read the logs couldn't answer 60 s, doubling to 5 minutes
(hooks/use-log-reads.ts).
ONE values file drives both the router and the dashboard (the v1 pattern):
SR_CONFIG_HOST (default ./dev-config/values.yml) is mounted as the router's
config and as the api's helm-values, so the Upstreams page always
reflects the running topology with no duplicated config.
packages/shared/ @sr/shared — domain types, metric catalog, PromQL builders
src/
constants/metrics.ts GROUND-TRUTH metric names + OPTIONAL_METRICS (see "Metrics")
constants/chains.ts buildChainMetaByIndex(spec) — keyed by Lava spec index
constants/explorers.ts explorersFor / explorerUrl — the chain's block
explorer + deep links; explorerTxUrl — a
transaction's page, from the curated
explorer-tx.json (docs/CHAINS.md)
constants/windows.ts WINDOWS — 13-window catalog (5m..30d) → PromQL range + step;
alignedBounds — a range read's window, on step boundaries
promql/builders.ts typed query builders shared by api (+ docs)
constants/roles.ts ROLES + roleAtLeast — four cumulative roles
constants/audit-events.ts the audit log's verb set (see "Audit log")
constants/error-codes.ts every router error code → source, meaning, what to do,
retries, may have gone through (docs/ERROR-CODES.md)
audit/format.ts how a value is written into an audit row —
redaction, (none)/(new)/(deleted), yes/no, lists
types/domain.ts DashboardData, HeroSummary, ChainSeries, DeploymentPulse,
ProviderDetail, ErrorsReport, RouterTopology, …
packages/db/ @sr/db — Drizzle + Postgres (AUTH_MODE=enabled only)
src/
schema.ts users · sessions
schema-audit.ts audit_events · audit_event_changes (append-only)
audit.ts createAuditWriter — the writer every task emits through
testing.ts createTestDb() — pglite, a real Postgres in-process
apps/api/ @sr/api — Fastify 5 (:8000)
src/
routes/ health · version · metrics · config · transactions ·
error-requests
plugins/ error-handler · swagger · prometheus (decorates services) ·
loki (the transaction + error-request services)
services/ prometheus-client · metrics · metrics-detail ·
metrics-dashboard · configuration (values-file loader) ·
loki-client · router-log (parsing the router's lines) ·
transactions · error-requests (rows from the router's logs) ·
log-list (how both lists read and poll them) ·
transactions-over-time (the Transactions tab's chart) ·
snapshot (the metrics routes' shared answers) ·
read-health (the reads the store refused, per run)
config.ts single source of truth for env defaults
apps/web/ @sr/web — Next.js 16 App Router (:3000)
src/
app/(app)/ metrics · upstreams · team · audit · account
(Shell layout; the dashboard opens on /metrics,
HOME_PATH in lib/home-path.ts)
app/standalone/ chrome-less Metrics page (sharing/embedding)
app/api/config/ runtime-config route (DASHBOARD_API_URL → browser)
components/
gateway/ Shell · Sidebar/Topbar · ChainDrawer (the Metrics
page's chains, beside the sidebar) · RouterHeader ·
FiltersProvider · WindowSelect · ChainSelect ·
RouterFilterSelect · HealthTag · charts · SortTable ·
Modal · SideSheet · DialogLayer (what every dialog
renders through: portaled to <body>, since the
page's `.fade-in` wrapper traps `position: fixed`;
scroll lock, focus trap, Escape) · icons
metrics/ MetricsView (5 tabs) · HeroPanel · RouterOverview ·
ChainDetail (its Availability view is
AvailabilityBreakdown: availability in blocks, all
the router's providers and each one) ·
TrafficOverTime (the Overview's total
traffic, one line for every chain) ·
ChainTrafficByProvider (which upstream
took a picked chain's traffic) · ChainAvailability
(the same blocks for a picked chain, a router picker
when two or more serve it) · ErrorsBreakdown (the Errors tab: count
cards + ErrorIncidents, the timeline of bursts - a
line opens its requests - + ErrorRequests, the
request list) ·
TransactionLog · TransactionsChart (its bars over
time) · request-log (the two log tables'
shared chips) · request-breakdown (an opened row:
request, tries, response, each error
explained from constants/error-codes.ts) · upstream/ (the
Upstreams tab: PMRoster · PMBody - errors over time
(a bar opens the Errors tab on the requests
that failed at its upstream),
volume, latency, latest block)
upstreams/ UpstreamsView (3 groupings) · RouterGroups · catalog
endpoints/ endpoint row model + IfaceTag + detail sheet — the
bits the "By router" grouping renders
team/ InviteModal · ChangeRoleModal · bits
hooks/use-api.ts SWR wrapper: each window polls at its own pace, every
poll through the idle gate (see "Polling")
hooks/use-log-reads.ts the two log lists' 30 s poll and "Load older" paging
lib/poll.ts the poll cadence per window + the idle gate's rules (pure)
lib/idle-store.ts the idle gate's clock: page activity → SWR's isPaused
lib/api-client.ts base URL resolved ONCE per session from /api/config
lib/datetime.ts every date and time shown: one format, in the reader's
zone (`<LocalTime>` renders one), and in UTC where a time
is matched with an email; CSV + API stay ISO UTC
styles/globals.css design tokens + gw-* classes, 1:1 from the prototype
Fonts are self-hosted at build time via next/font (Inter + JetBrains Mono),
matching the prototype's two families — no runtime Google Fonts fetch.
smartrouter_* / rpc_endpoint_* / rpc_optimizer_*,
NOT lava_rpcsmartrouter_* as the ../SR_Dashboard/*.md docs claim. Always verify
against a live scrape (docker exec smart-router-router-1 wget -qO- localhost:7779/metrics).
The catalog lives in packages/shared/src/constants/metrics.ts. See
docs/METRICS-MAPPING.md.
The dashboard never invents data. Every populated value maps to a real
Prometheus series; anything unbacked comes back as null / empty plus an
explicit emitted: false (or families.* / classTotals.emitted.*) flag,
and the UI renders the design's own empty states.
Absent-until-fired families (OPTIONAL_METRICS) are probed for presence
(qPresence = count({__name__="…"})) on every read — panels light up
automatically the first time the router registers a family. No code change,
no redeploy.
| Panel value | On this build |
|---|---|
| Requests / success / read totals, latency histogram, latest block, overall health, consistency, csm, total relays | Real (smartrouter_*) |
| Per-endpoint health/block/latency/in-flight/relays, per-provider p95 | Real (rpc_endpoint_*) |
| QoS / selection score (availability/latency/sync/stake/composite) | Real, and available WITHOUT traffic — read rpc_optimizer_selection_score first, rpc_endpoint_selection_score as fallback. See "Two QoS gauges" below. The design doc wrongly called this "no metric" |
Per-endpoint latest-block polls (rpc_endpoint_fetch_latest_{success,fails}) |
Real, and traffic-independent — the chain tracker polls every configured upstream, backups included |
| Errors (total, trend, per-chain/method/provider) | Real, derived — round(clamp_min(total − success, 0)) = failed attempts (an upstream's JSON-RPC error reply counts as transport SUCCESS); node/protocol classes from smartrouter_{node,protocol}_errors_total once they fire. A protocol error is also a failed attempt, so the class splits show transport as failed − protocol (MAG-3847) |
| Cache, retries, hedge, cross-validation, node/protocol error counters, write/batch, websocket | Absent until the feature fires → nulls + emitted:false, then real. Cross-validation reads …cross_validation_{requests,success,failed,failures}_total (no bare …_total exists); ws totals are lifetime (counter-birth). See docs/METRICS-MAPPING.md → "Counter semantics" for relay-vs-client scoping (requests are CLIENT-scoped via the latency-histogram _count). |
| Compute-unit quota, RPS cap, regions, team members | Magma Cloud concepts — not metered here; pinned null (UI shows "not tracked") |
The web shows no scores. No screen draws a QoS or selection score: an operator can't act on them. The api still reads and returns them, as described here.
The router publishes one set of selection scores through two gauges.
They are not two measurements: a single iteration of the optimizer's
CalculateProviderScores fills both, from the same locals, so
score_type="availability" is the identical number on either. What differs is
only when each is written and who it covers:
rpc_endpoint_selection_score |
rpc_optimizer_selection_score |
|
|---|---|---|
| Written | at provider selection — only when a relay is routed | every --optimizer-qos-sampling-interval tick (default 1s) |
| Covers | the candidates of that one selection; backups live in a separate pool consulted only on fallback, so they are usually absent | every registered upstream, backups included |
| Labels | spec, apiInterface, endpoint_id, score_type |
spec, endpoint_id, score_type — one optimizer per chain, so no interface |
The scores stay current with no traffic because the router's probe loop
(--probe-loop-interval, default 5s) feeds the same optimizer that relays feed.
Probe samples carry a lighter weight than relay samples, so a busy hour moves
the score quickly while a quiet upstream stays scored rather than going blank.
So /api/metrics/upstreams reads the optimizer gauge first and falls back to
the endpoint gauge, per row (scoreSource names which). Two consequences
worth keeping straight:
- A fallback score on a row with zero requests can be arbitrarily old — it
is whatever the last routed selection wrote. The UI marks it rather than
hiding it: "we measured this a while ago" is information,
—is not. - Dropping to chain scope is more correct for the roster, not less. Rows are
keyed by
endpoint_idalone, so with the per-interface gauge an upstream serving two interfaces had one interface's score silently overwrite the other's.
The matching liveness signal is rpc_endpoint_fetch_latest_{success,fails}:
the per-endpoint chain tracker polls every configured upstream on the
chain's own cadence, whatever the traffic. ⚠ A poll gate suppresses polls that
served traffic — or a peer pod's poll — already made redundant, so both
counters at zero means "not polled in this window", never "healthy".
smartrouter_csm_provider_blocked, the router's own per-provider state, cannot
fill this gap: it says only whether the router took the provider out, so an
untouched backup with every url up reads serving there whatever its urls answer.
Chains are keyed by Lava spec index (the spec label: ETH1, BASE, …),
not a human chain id — resolve display metadata via buildChainMetaByIndex.
Three committed files are generated from the lava-specs repo — the chain map,
the Try-it method catalog, and the roll-call of surfaces with no runnable
default (apps/web/scripts/data/no-runnable-defaults.generated.json). CI's
Chain catalogs ↔ lava-specs drift job regenerates all three and fails when
any is stale, so a resync means running both generators and committing the
result, never hand-editing.
The part that needs judgement is what happens after: the Try-it drawer opens
only on commands that can be sent AS-IS, so a chain family nobody has curated
hints for arrives with an empty default list. When the drift gate is red, run
/chain-resync — the skill maps every
line the gate prints to the exact steps (regenerate, icons, explorers, roll-calls,
release, PR). .claude/rules/chain-resync.md is
the reasoning behind them: when hints are needed, and the rule that a curated
example must be fired against a real endpoint before it ships.
The router's own config yaml is bind-mounted into the api at
/app/helm-values/core/values.yml:ro (override the dir with HELM_VALUES_DIR).
ConfigurationService detects and parses either supported format into
RouterTopology[] (GET /api/config/routers):
- Helm-chart values —
routers:[{id, network, nodes:[{name, is_backup, endpoints:[{url, interface, addons}]}], custom_url_prefix?, pathBased?}], withpathBasedresolved per-router against the globalmiscellaneous.gateway.pathBased.enableddefault (chart semantics). Only this format can mark backup nodes, and only it yieldspublicUrls(below). - Raw smart-router SR_CONFIG — the YAML the router itself runs
(
endpoints:+direct-rpc:). Providers are grouped by chain-id into one router per chain; theendpoints:listen ports becomelocalPorts, keyed per api-interface (one chain can expose several interfaces on different ports, e.g. LAVA rest:3360 + tendermintrpc:3361).
Detection is by key: routers ⇒ helm; direct-rpc ⇒ sr-config; anything else
yields an empty topology. Node URLs are masked to scheme+host — upstream
provider URLs routinely embed API keys in the path.
An endpoint's dialable address depends on which format is mounted, and the
Upstreams / Try-me surfaces resolve it in this order — public
gateway URL → local listen port → nothing ("—", never a fabricated host):
- Helm values describe a k8s deployment with no listen ports at all, so
localPortsis empty andpublicUrls(api-interface → URL) carries the address. It mirrors the HTTPRoute / GRPCRoute hostname scheme those values describe, exactly:<custom_url_prefix | id-lowered>+.<iface>.(the default) or-<iface>.(miscellaneous.gateway.hostStructure: chain-interface) +<base_domain>, on the scheme/port of the Gateway's TLS listener (HTTP listener when there is no TLS one; non-default ports kept in the URL). Empty when the values publish nothing routable —gateway.enabled: false, nobase_domain, or a listener list with nothing HTTP(S) on it. - SR_CONFIG describes listen ports but nothing about ingress, so
publicUrlsis empty andlocalPortscarrieshttp://localhost:<port>.
Websockets ride the same address as the base interface, path-scoped
(/ws for jsonrpc, /websocket for tendermintrpc) — a bare host handshake is
rejected 405. The values set no appProtocol on non-grpc ports, so the gateway
serves the HTTP/1.1 upgrade on the interface's own hostname.
Both listeners register those routes unconditionally (smart-router
protocol/chainlib/{jsonRPC,tendermintRPC}.go), so ws availability is a
property of the INTERFACE, never of the mounted values: ifaceServesWs in
components/endpoints/bits.tsx is what the ws capability chip, the WSS url
block and the Try-me transport toggle all read. A wss:// upstream in the
values is a separate fact — the leg subscriptions ride. With none
configured the router installs its NoOp subscription manager and answers every
*_subscribe with an error (plain calls over the socket still relay), which
the drawer flags as no ws upstream on the method.
Several routers may serve one chain (a staging + production pair on the
same network, distinguished by id / custom_url_prefix). Topology handles
that natively — separate cards, separate hostnames, and the router-grouped
card header appends the router id whenever a spec is duplicated. Metrics need the
router scope below, because the router labels its series with the chain, not
with itself.
"Router" means two things here, and the UI has one control for both:
?router= (scope) |
?routerId= (config) |
|
|---|---|---|
| Identity | a value of ROUTER_SCOPE_LABEL — the collector's per-target label |
an id from GET /api/config/routers |
| Comes from | Prometheus target labels | the mounted values file |
| Narrows | the PromQL, so chain-level series split per router | rows — which upstreams a response lists |
| Available | only when the collector labels targets per router (often not) | always, whenever a values file is mounted |
| Read by | every /api/metrics/* route |
/api/metrics/{upstreams,errors,block-heights} |
Anything keyed per UPSTREAM can be attributed, because the config says which
router declares a node: the roster (routerIds on UpstreamMetrics — a LIST,
since two routers declaring one node name share one series, which the UI marks
rather than splitting) and the error hotspots (?routerId= on
/api/metrics/errors, which filters the (chain × upstream) pairs and leaves the
pivots alone) and the upstream tips on /api/metrics/block-heights. Anything
that aggregates BY CHAIN can't be: no series says which router served a request
— smartrouter_latest_block included, which is why that endpoint's routers
rows can only ever be split by the scope axis. So a router selection also sets the chain — a config
router serves exactly one — which narrows those panels as far as the data
honestly allows, and the UI states that a second router on the same chain is
counted in with it.
Web side, useRouterFilter() (hooks/use-router-options.ts) is the only place
a router selection is made: it sets the config id and, when that router maps to
a scrape target the collector actually reports, the scope too. The list is
narrowed by the chain filter, and useChainFilter() clears a router the new
chain excludes — the pair stays consistent without an effect watching for it.
<RouterFilterSelect> renders it next to <ChainSelect>, and only for a chain
that two or more routers serve: with one router per chain, picking the router
is picking the chain. Beside the Metrics page's chains drawer it isn't drawn:
such a chain lists its routers under it there (?chain=ETH1&router=eth-prod).
smartrouter_* carries spec (the chain) and no router identity, so two
routers on one chain sum into a single set of numbers. What does separate
them is the collector: each router is its own scrape target, so Prometheus
attaches a per-target label — router from the fleet's collector and the
chart's ServiceMonitor (6.20.0+), copied from the pod label
app.smart-router-id; service under a bare Prometheus Operator, whose value
is the router's Service name (<router-id-lowered>-router).
ROUTER_SCOPE_LABEL names that label. Unset (the default), the api resolves
it on first use: the first of router, service the store reports values
for, remembered once found, asked again on every use until then, never at
boot. Set job for a scrape config that names jobs per router.
GET /api/metrics/routers→{ label, routers[] }— the distinct values actually present. Empty means the collector attaches no such label (one static target, or a mislabelledROUTER_SCOPE_LABEL): "can't split", never "no routers" — the config still knows the routers, which is why the filter is built on the config list and treats a scrape value as a bonus.- Every
/api/metrics/*route takes?router=<value>, including the raw/querypassthrough. An absent or malformed value reads cluster-wide rather than silently becoming a different query. - The scope is injected into the finished PromQL by
applyScope(packages/shared/src/promql/scope.ts) rather than threaded through ~40 builders: every vector selector gains the matcher. It is a small PromQL walker, not a regex — the naive version corrupts metric names quoted inside{__name__="…"}(the presence probes) and selectors that already carry labels. Names inside a matcher list or aby/without/on/ignoring/group_left/group_rightlist are labels and are copied as written, socache_tiernever takes the deployment scope as acache_*metric. The walker lexes as PromQL does: tabs, line breaks and#comments are blanks (a comment is copied as written, its quotes and braces open nothing), keywords match in any case, and a{afterand/or/unless/atan2/bool/group_left/group_rightopens a nameless selector that takes the scope.cache_*is deliberately left cluster-wide: the relay cache is a separate sidecar shared by every router, so it carries no router's label and scoping it would report a zeroed cache rather than an unattributable one. - Web side: the scope lives in
FiltersProvidernext to the chain and the time window, in two lifetimes — the window persists (sr:window, a viewing preference; a window from a link,linkWindow, is shown on that page only and never saved), the chain and the router belong to the page that set them (in-memory, stamped with the pathname, gone when you navigate — a narrowing that outlives its screen is a trap). Every metrics URL appendsscopeQ/withScope(url). A selection that disappears from the list resets to "All routers" instead of silently filtering every panel to nothing. - The Metrics page picks them in its chains drawer (
ChainDrawer, beside the sidebar): one row per chain with its health, requests and error rate for the page's window, problems first, and a search. Beside it the sidebar folds to a 64 px strip of icons (gw-side--compact), so the page doesn't carry two lists side by side: each icon names itself on hover, "Expand menu" at the top opens the full menu for that visit, and every arrival on the page starts folded (menuCollapsedonChainDrawerProvider). Other pages keep the full menu. A row IS the chain filter (useChainFilter), so every tab follows it; a chain two or more routers serve lists them under it once picked. The page also writes both into its URL with the tab (?chain=ETH1&router=eth-prod&tab=upstreams,useScopeInUrl): a link opens them, a chain or router change is a history entry (Back returns to the previous one, tab included) while a tab change alone rewrites the current entry, and another page's URL has none, so the per-page rule above still holds. The rest of the view rides with them (lib/view-in-url.ts, written by the same hook, so a copied URL or a reload opens the same view):windowalways (the sender's, not the viewer's saved one - opening a link never saves it); on Overviewexpand=<router id>andtile=<tile key>(the Routers table's open row and its chart,ChainDetail's own tile keys); on Upstreamsupstream=<node name>(the deep-dive;upstreamChain=<spec>only when no chain is picked); on Errorsupstream(the list's filter) andfrom/to(unix ms - an errors-over-time bar writes all three). A change to them rewrites the current entry, picking another tab drops the old tab's, and a new chain or router drops the Upstreams tab's upstream. What a link asks for that no longer exists opens the nearest view with a one-line notice (LinkNotice): an upstream or router the config no longer has (the first upstream / no open row), a tile the row doesn't draw, times that ended over 30 days ago (the page window), started before then (cut to 30 days ago) or can't be read, an unknown window. A malformed value reads as none; an upstream name with://is refused, so no node URL reaches the URL. The two log tabs addrequest=<id>(lib/request-in-url.ts): opening a row or finding a request by ID writes it, closing clears it, picking another tab drops it, and a link with it opens that tab's look-up on the request (a v1.6.1 ID is read in its own minutes, whatever the page's window). It rewrites the current entry rather than adding one. Each opened row also links to its own lines on the Grafana logs board (the GUID as the search, a minute either side of the request). The drawer reads the whole deployment, never the router scope (the one exceptionrouter-scope.test.tsallows). Clicking Metrics, or the logo, while on it goes back to every chain, with the menu folded again.
/api/config/routers is per deployment by construction (it reads the mounted
values file); the metrics routes are not — they read whatever the store holds.
One dashboard per zone against a shared Prometheus therefore shows every
zone's routers. METRICS_SCOPE_LABEL + METRICS_SCOPE_VALUE pin the
deployment to one label value:
- The pair becomes a base scope on the ONE
PrometheusClientthe plugin builds (plugins/prometheus.ts), so every query carries it —cache_*included (the deployment owns its cache, unlike a router), thecount by (label)behindGET /api/metrics/routers(the filter then lists only this deployment's routers), and the raw/querypassthrough. The per-request?router=scope stacks on top: each selector ends up with both matchers. - Same
applyScopewalker, run twice ({ cache: true }for the base pass). Only the catalog + prefix families are reached, so a passthrough over some foreign metric name stays unscoped — the label is not a query rewrite. - Half a pair, or a label/value that cannot sit in a matcher, throws at
boot (
readMetricsScope()inconfig.ts). Ignoring it would read the whole store under a scoped name — the exact failure the pair exists to prevent. Unset = no matcher, byte-identical to before. - Failed Prometheus calls (non-2xx, unreachable,
status: "error") are logged at warn by the client, one line per distinct failure per minute. The result is still[]— the panels degrade as before — but a bad URL or a 401 now shows in the api log instead of reading like a quiet router. - The readiness probe (
vector(1)) has no selector and stays unscoped: a scope that matches nothing is an empty dashboard, not a NotReady pod. What catches the typo instead is a one-shotonReadyprobe —count(smartrouter_overall_health)through the scoped client, a gauge every running router exports whether or not it has traffic — that warns when it counts zero. Advisory only: a zone still provisioning is also zero. METRICS_SCOPE_LABELequal toROUTER_SCOPE_LABEL(or, with that unset, to either label it could resolve to) is refused at boot: the router scope would put a second matcher on the same label — redundant for the same value, an empty result for any other.
Two things every chain- or health-aware surface must go through, so the same state can't be worded or sourced two ways:
useChainOptions()(hooks/use-chain-options.ts) is the chain picker's only list: the UNION of the chains the mounted config declares and the chains the metrics report traffic for, each row flaggedinConfig/hasTraffic. A page dims what it can't populate viawithMutedRows(Metrics greys "no traffic yet", Upstreams greys "not in config") rather than hiding it, which would read as "not configured". The selection itself ischainonFiltersProvider, never page state.useRouterFilter()(hooks/use-router-options.ts) is the router filter's only entry point — one selection, both router axes (see "Two router axes"), chain-narrowed list,routerIdonFiltersProvider(sr:routerId).lib/health.tsowns the words and colours forHealthState(operational | unhealthy | unknown | untracked) — Operational / Unhealthy / Unknown / No block height — and<HealthTag>/<HealthDot>are how they reach the screen.unknownmeans "no current health evidence", so it renders as a warning with a reason.untrackedis a provider row only, never a router or a chain: the router tracks no block height on it by design (rpc_endpoint_url_block_tracking= 0), so it renders neutral, with a note instead of an alert, and the pulse counts it as neither unhealthy nor unknown. A row reads it only when every interface of it is untracked; an interface with poll outcomes decides the row. Configured endpoints remain in the roster without metrics. Current health uses live checks and block-poll windows sized to three expected blocks (5 / 15 / 30 / 60 minutes, 30-minute fallback for an unmeasurable rate). A reset healthy gauge alone cannot establish recovery without a recent successful block event; an expired/empty window is a warning with a reason. Request-history filters do not change current health. Every state comes with its reason on the page, not in a tooltip: one plain sentence from the api (healthReason; a "block check" is the router asking a provider for its latest block; no store or scrape is named, the reader can check neither), the same as a word (healthCause:ok/blocked/checks-failing/no-checks/no-data), and for an unhealthy provider since when (healthSince,readHealthSinceinservices/upstream-health.ts: two range reads over the last day, narrowed to the unhealthy providers' names, none while every provider is fine). The roster writes it under the status word, the provider's page in a notice and, for an unhealthy one, what its failed requests said in the last hour from the router's logs. The notice is the latest status whatever window the page is on, and names no next step: there isn't always one. An OPERATIONAL provider says what its status leaves out about its block (upstreamCaveat): one that stopped moving, or 30 s or more behind the chain. Failed block checks are not said for a provider that still serves. The roster says the block part under each provider's block instead (blockBehind: "latest", or how many blocks behind the chain's highest and how long that is), and drops its Chain column on a page narrowed to one chain. The pulse (GET /api/metrics/pulse) carries the unhealthy/unknown counts and the providers behind them (attention), and the top bar draws them only when there is something to look at: no "operational" and no throughput figure there - a pill ("2 providers unhealthy · 3 to check") that lists which, why and since when, each a link to its page. Nothing invents its own health vocabulary: four surfaces used to (the roster said "healthy / degraded", the deep-dive "Live · up", the drawer the raw wire word), and one upstream read three different ways depending on the panel.
A Kubernetes deployment runs the api as the …/backend image and the web as
…/frontend. The contract it has to configure:
| Value | |
|---|---|
| Backend liveness / readiness | /health · /health/ready (not /api/health — that's the retired v1 path). Readiness pings Prometheus, and under AUTH_MODE=enabled the database (3 s), so give it a timeout ≥5s and a failureThreshold >1, or a blip of either evicts the only replica |
| Backend env | PROMETHEUS_URL, CORS_ORIGINS (comma list or JSON array), HELM_VALUES_DIR (default /app/helm-values, matching the values mount), LOG_LEVEL, RATE_LIMIT_MAX. Optional: INCIDENTS_ENABLED + INCIDENT_WEBHOOK_URL (a secretKeyRef — the URL is the credential). No basic auth: AUTH_USERNAME / AUTH_PASSWORD / DEBUG / CORS_ALLOW_CREDENTIALS / AUTH_GATEWAY_* are v1-only and unread here |
| Frontend runtime env | DASHBOARD_API_URL (browser-facing api origin) and DASHBOARD_GRAFANA_URL, both read per-request by GET /api/config so one image serves any host. Optional: INCIDENTS_ENABLED (same as the backend's). NEXT_PUBLIC_* are build-time and can't vary per deployment |
| Frontend liveness / readiness | /api/config (/ also answers — it 307s to /metrics) |
| Values mount | <HELM_VALUES_DIR>/core/values.yml, the rendered values. Drives publicUrls above, so the pod must roll when they change |
| Backend termination | SIGTERM or SIGINT starts the stop sequence (apps/api/src/shutdown.ts): the listener closes at once, so /health/ready is refused from the signal on (a request on an open keep-alive connection gets Fastify's 503), the Ask worker claims no more runs, in-flight requests finish and keep-alive connections close as they go idle, running Ask answers get the rest of the drain window and are then interrupted (ASK_INTERRUPTED, which ends their leases), the database pool ends, and the process exits 0. The drain window is SHUTDOWN_TIMEOUT_MS (20 s) less 8 s; at its end open connections are closed. A second signal, a failed close or the full SHUTDOWN_TIMEOUT_MS exits 1. The api is PID 1 in its image, so these handlers are what make it stop at all. The pod's terminationGracePeriodSeconds (Kubernetes' 30 s when unset), less any preStop, must exceed SHUTDOWN_TIMEOUT_MS, and the database tunnel sidecar must outlive the backend container: the drain reads and writes the database to the end |
AUTH_MODE=enabled only — the default mode has no database, so the audit
surfaces render the usual honest empty state naming the reason. MAG-2770 owns
the log; the accounts, 2FA and config-approval tasks only emit into it.
- The verb set is a typed catalog, not a convention:
packages/shared/src/constants/audit-events.tsholds every event with its group, whether it carries a diff, and whether it may carry access context. Four tickets write these strings, so a typo is a typecheck failure rather than an unfilterable row — and the same constant generates the published event list the ticket requires. - One writer,
createAuditWriter(db)(packages/db/src/audit.ts). It lives in@sr/db, not the api, because the recovery commands run from a shell on the host with no request anywhere. It resolves the group and the access-context rule from the catalog rather than trusting the caller.write(event, tx?)— pass the caller's transaction and the row commits or rolls back with the mutation it records. Failure behaviour is asymmetric on purpose: standalone it swallows and reports (a sign-in must not 500 because the log is unwell); inside a transaction it propagates, because the failed insert has already aborted the caller's transaction and catching it would turn an atomicity guarantee into a silent maybe. The rows that record getting into an account go in the change's transaction: a reset link generated or used, an invitation redeemed, and everything a removal or role change writes, including revoking what a removed or demoted admin handed out. A refused sign-in's row goes in a transaction of its own (recordRefusalinroutes/auth.ts), so a failed write answers 500; the attempt it spent has already committed and stays counted. A lockout'ssignin.blockedshares the counter's transaction.occurredAtstamps a row noticed after the fact with the time it happened (invite.expiredcarries the expiry). - Redaction happens on the way in.
audit/format.tsis the only way values reach a row:(none)·(new)·(deleted)·yes/no· stable comma-joined lists ·(changed, ends a91f). There is no un-redacted copy in the table, which makes "no secret or node URL appears in the log, the export, or the API" a property of the schema rather than a rule three read paths have to remember. MAG-2731's approve screen does show full values — that reads the pending-change record, a different table, and must never be pointed here. - Names are snapshots, never joins.
actor_name/target_namerecord what the thing was called at the time. A removed person keeps their name in the log permanently, and a rename cannot rewrite history. - The export is the same query as a file (
GET /api/audit/export.csv), parsed by the same function as the feed so a download can never answer a question the screen would have refused. Flat by design — one row per changed field — because the person opening it wants to sort and filter, not parse. The formula guard lives in@sr/shared'sescapeCsvField, shared with the member-list export, and covers tab and CR as well as= + - @. - The pull API has its own principal — a read-only token
(
srdash_audit_…,packages/db/src/audit-tokens.ts). The customer requirement is tooling that pulls on a schedule with nobody clicking, and their fourth vendor rule is "API key best practices": a token that could also edit routing fails that review. So it is not a user, not a role and not a session, and what it may reach is a method plus a path prefix decided in one function (auditTokenMayReach) rather than by each handler remembering —GET/HEADunder/api/audit/, with/api/audit/tokensexcluded so a token can never mint another. Anything else is 403, not 401: the credential is fine and retrying will not help. Rate limited per token rather than per IP (a customer behind one NAT would otherwise share a bucket with everyone there), with the limit and reset in the usualx-ratelimit-*headers. Its use is a column, not an event —last_used_aton the row. A row per pull would make the log mostly a record of itself: a five-minute schedule adds ~300 rows a day saying only that it still runs. The token's lifecycle is audited, asapikey.created/apikey.deleted. - Reading it is one query, two directions (
packages/db/src/audit-read.ts). The viewer asks fororder=desc; a customer's tooling takes the default and pulls oldest-first on a schedule. Deliberately the same code path — a screen that could disagree with what a security team pulls is worse than no screen. - A session is a reference on every read surface.
toRecord(audit-read.ts) servescontext.session, and thetarget.idof asessiontarget, asauditSessionRef(id): the first 12 hex characters of the id's SHA-256. The page, the export and the pull API never carry the id a session token addresses, and the rows of one sign-in still share a value.target_idtakes the reference (sha256()in SQL); a session id there matches nothing. - The cursor is gap-free by construction, not by timing.
seqis handed out atINSERT, not atCOMMIT, so two writers can take 100 and 101 and commit in the other order; a reader trustingseqalone serves 101, the puller stores it, and 100 surfaces afterwards behind the cursor and is lost for good. A wall-clock watermark does not fix this —now()is transaction start time, so the slow writer gets an old timestamp and a high sequence, exactly backwards. Instead every row records itsxact_id(xid8), and a row is served only once it sits belowpg_snapshot_xmin(pg_current_snapshot())— the oldest transaction still open. The cursor carries that horizon, and the next read also picks up whatever was withheld last time. A late-committing row is therefore delivered late rather than never, and never twice. The cost, stated plainly: across pages the sequence is not strictly monotonic. Within a page it always is. - Append-only in the database, not just the product. A
BEFORE UPDATE OR DELETEtrigger on both tables raises. The one legitimate writer is retention, which opens the gate withSET LOCAL audit.purge = 'on'inside its own transaction. This is a product boundary, not tamper-evidence — hash chaining is deliberately out of scope.
packages/shared/src/constants/windows.ts defines the 13-window catalog
(5m 15m 30m 1h 3h 6h 12h 1d 3d 7d 14d 21d 30d), each with a PromQL range and
a step targeting ~150–200 range points (clamped to ≥15s, the scrape interval).
The step is how often a chart draws, not what it reads. A rate needs two
samples and a 15-second range holds one scrape, so a rate line reads the step
or a minute, whichever is longer (rateRange in promql/builders.ts). A count
per point (errors, volume) reads m steps and one scrape (countRangeSec: 60 s
at a 15 s step, 75 s at 30 s, step + 15 s from a minute up), times the step:
each counter step lands in exactly m points at 1/m each, at every phase of the
scrape clock, so the points add up to the counter's delta. Points are rounded
only where m is 1. The error bar still filling is a single read (m = 1).
Charts that need to be dense rather than cheap sample on their own grid:
chartSampling(window) - ~300 points, each averaging a 24th of the window (≥4
steps, and ≥5 minutes once the window holds six), so light traffic reads as a
line rather than a zigzag. Volume averages short rateWindow rates over what
is THERE (avg_over_time of a subquery), never one long rate(): that
divides by the whole lookback whatever part of it has data, so around any gap
in the scrapes - a router restart, a laptop asleep - its line slid to zero and
climbed back for a whole lookback. Latency and volume are also cut where the
upstream wasn't scraped, so a gap is a gap. Errors come in
errorBuckets(window) - the clock's own intervals, ten minutes at least, ≤48
bars (six hours is a bar per 10 minutes, a day a bar per 30) - laid on the
clock by bucketGrid: whole bars from a range read, then the bar still
filling from one instant increase over the seconds it has run (a range read
can't: it would end in the future, which Mimir refuses past 10 minutes).
The range reads behind the charts end on a step boundary: alignedBounds(range, step, now) puts the end on the last multiple of the step at or before now and
the start one window before it, at the step the chart draws on
(chartSampling's for the Upstreams deep-dive). Two reasons. Every poll until
the next boundary asks for the same window, so the api's read cache can answer
it: once its newest point has settled (its end three minutes old), for up to a
step (see PROMETHEUS_CACHE_TTL_MS). And Mimir's results cache keeps a range
read only when both ends are multiples of its step, then recomputes just its
newest 10 minutes: about 67% of a 30-minute read comes from cache, 94% at
3 hours, 97% at 6 hours. The cost: a chart's newest point is up to one step
old - 15 s on the 30-minute default, 10 minutes at a day, 4 hours at 30 days.
The error bars sit on their own clock (bucketGrid), and the Transactions
chart's recorded read on its bars' ends shifted 30 seconds
(SAMPLE_SHIFT_SEC): both move once a bar.
Every window= query param accepts those keys plus the 24h alias (= 1d);
anything else falls back to the default 30m. The page-level <select> shows
the design's 12 options (WINDOW_OPTIONS — everything except 1h, which the
api accepts and no page offers).
Every panel reads through useApi (hooks/use-api.ts), which polls with
SWR. A metrics read over a window (/api/metrics/…?window=) polls no faster
than its window can use (pollMsForKey, lib/poll.ts); the caller's own
interval wins when it is longer, and a key that doesn't poll (0, the request
look-ups) never starts.
| Window | Polls every |
|---|---|
| 5m · 15m · 30m · 1h | 15 s |
| 3h · 6h · 12h | 1 minute |
| 1d · 3d | 5 minutes |
| 7d · 14d · 21d · 30d | 15 minutes |
A poll is never further apart than the window's chart step, and from 30m up
it slides the window by under 1% of its length; from 3h the api reads the
store's recorded series where it has them, which move once a minute. Keys
without a window (the topbar pulse, block heights, specs) and the log routes
(/api/error-requests, /api/transactions, /api/requests) poll at the
caller's interval: the two log lists every 30 s, longer while the logs
don't answer (hooks/use-log-reads.ts).
The idle gate (lib/idle-store.ts; its rules are pure functions in
lib/poll.ts) holds every useApi poll to whether someone is at the page:
a pointer move or press, a key, the wheel, a touch, focus, Back or Forward,
or the tab coming back into view. Ten minutes with none of these make every
interval four times longer; an hour pauses every poll through SWR's
isPaused, so nothing revalidates, a mutate() included. While paused, the
Refresh icon turns amber and a "● Paused" pill sits beside it wherever the
header has room for the whole word; its tooltip and screen-reader text say
"Polling paused after an hour without activity · move the mouse to resume".
The pill is never cut: it takes only the header's free space, and where the
word doesn't fit it isn't drawn and
the amber icon says it alone. The first activity after either phase re-reads
every key that polls, once (a global SWR mutate that leaves the numbers on
screen while they reload, never a look-up, which doesn't poll), and re-arms
each poll's timer at its normal cadence. The phases run on the wall clock,
so a laptop that slept through the hour wakes up paused instead of polling
first. A hidden tab doesn't poll at all (SWR's default). The standalone
page is exempt (idleGateApplies): it is for shared and wall screens that
nobody touches, so it never slows or pauses. The Account page's sessions
call useSWR directly, outside the gate.
All endpoints return application/json. With AUTH_MODE=disabled (default)
every route is public; with AUTH_MODE=enabled the /api/* routes require a
valid Bearer JWT (health/version and /auth/* stay public). See docs/AUTH.md.
Every /api/metrics/* route also accepts router? — the router scope
(see "Router scope" above); omitted = cluster-wide. Every one but /query and
/reads answers from a per-process snapshot and says how old the answer is in
Age (see "Response snapshot" below).
| Endpoint | Params | Returns |
|---|---|---|
GET /docs · GET /docs/json |
— | Swagger UI explorer + OpenAPI 3.1 spec. Registered outside production only. |
GET /auth/bootstrap |
— | { needsSetup, mode } — whether this deployment still needs its first admin (derived from "no active users", never a flag), and which shape it is. Never reveals the setup token. Public |
POST /auth/setup |
— | Creates the first admin on a fresh install: { token, email, password, name? } → { user }. Opens no session — the web signs in straight afterwards on the ordinary credentials path. 403 on a wrong token, 409 once claimed. Public |
POST /auth/invite/preview |
— | { token } → { email, role, expiresAt } — what an invitation link is for. Public; the token travels in the body, never a URL. 410 for every dead reason, including one that never existed |
POST /auth/invite/accept |
— | Redeem: { token, password } → { user }, or { token, oauthProvider, oauthToken } → { user, sessionId } for any configured provider (google/github). The account is created with the invited address and the provider id is linked as it inserts. Only the OAuth path opens a session — it holds a one-shot token and has no second sign-in to fall back on; the password path lets the credentials sign-in do it. The OAuth path takes the browser's address from the web's forwarded X-Forwarded-Client-Ip / -Ua headers (with X-Internal-Auth) and writes signin.succeeded after invite.redeemed. 403 on an address mismatch, 410 on a dead link |
GET /api/team/invites |
— | Invitations not yet redeemed, each with state (pending/expired/revoked). Admin |
POST /api/team/invites |
— | { email, role } → the invitation, with delivery saying where the link went. url (shown once) comes back on-prem, and on managed only when the email was not sent (deliveryFallback: true). 409 if already a member or already invited. Admin |
POST /api/team/invites/:id/resend · DELETE …/:id |
— | New link (invalidating the old) / revoke. 410 once redeemed. Admin |
POST /auth/password/forgot |
— | { email } → managed with a mail transport: 202 for every address, answered before the lookup so timing says nothing; emails a 1-hour link when the address belongs to an account with a password, at most one per account per 5 minutes (SELF_SERVE_RESET_COOLDOWN_MS). The password.reset_requested audit note records whether it went. On-prem, or managed with AWS_REGION unset: 404 for every address, writing nothing — a link nobody receives would still kill the one the member holds. Public |
POST /auth/password/reset/preview |
— | { token } → { email } — the address a reset link changes, without spending it. 410 with one message for every dead reason. Public |
POST /auth/password/reset |
— | { token, password } → in one transaction: sets the password, revokes every session, clears the lockout. Does not sign in. After the commit, managed only, emails the owner that the password changed (no link; the outcome goes on password.reset_completed's note). Public |
POST /api/team/members/:id/reset-link |
— | { url, expiresAt }, shown once. An admin generates a link; only the holder chooses the value. Not for your own account (409 — your own password changes on the Account page). Admin |
GET /api/team/members · GET /api/team/members.csv |
— | { members[], adminCount, soleAdmin }, admins first · the same list as CSV with formula leads neutralised. Every role — the access review is for everyone |
PATCH /api/team/members/:id · DELETE …/:id |
— | { role } → change a role (revokes nothing; the gate reads the row) · remove (state change, one transaction: sessions, cutoff, provider ids, pending invite). 409 on your own row, 404 on someone not active, 403 if you stopped being an admin mid-request. Admin |
POST /api/account/password |
— | { current, next } — signs out your other devices, keeps this one. Tests a credential, so: sign-in's per-IP limit (10/min) and the account's lockout budget (423 once spent). After the commit, managed only, emails the owner that the password changed (no link; the outcome is password.changed's note) |
GET /api/account/me |
— | The caller from the live account row — id, email, name, avatar, role, the sign-in providers it is linked to (linkedProviders), its 2FA state. What the web's useMe() polls, so a role change reaches the sidebar badge and the Team page without a new sign-in |
GET /api/account/sessions · DELETE …/:id · DELETE … |
— | Your live sessions · sign out one device · sign out everywhere |
GET /health |
— | Liveness — { health: "ok" } |
GET /health/ready |
— | Readiness — runs vector(1) against the store (not -/ready, which Mimir and a query-only proxy don't serve) with the configured credential; 503 + components.prometheus:"ping_failed" on failure, including a 401. Under AUTH_MODE=enabled it also runs select 1 on the database, within 3 s: components.database is ok, not_connected (the lazy connect has not succeeded — Postgres unreachable, the credential refused, or migrations still running), query_failed or timeout, and anything but ok is a 503, so a pod whose database does not answer never becomes Ready and a surge-first rollout keeps the old pods serving. Absent from the body with auth off. From a stop signal on the listener is closed and the probe is refused (see "Deploying to Kubernetes") |
GET /version |
— | Build provenance — { commit, version, env, startedAt, uptimeSec } |
GET /api/metrics/routers |
— | { label, routers: string[] } — router deployments the metrics can be scoped to (distinct values of ROUTER_SCOPE_LABEL). [] when the collector can't tell routers apart. See "Router scope" |
GET /api/metrics/specs |
router? |
{ specs: string[] } — distinct chains present on the requests counter |
GET /api/metrics/dashboard-summary |
window |
HeroSummary - the hero cards as Kpi {value, prior} pairs (requestsServed - the "Requests answered" card's answered count, beside the failed count from GET /api/error-requests/count; successRate and effectiveReadP95Ms - returned, not shown: the success rate counts tries and rounds a few thousand failures in hundreds of millions away - staleCaught, retriesRecovered (counted with increaseFromBirth, as the Errors tab's cards are), cacheOffloadPct) + providerCount / chainCount / health + emitted: {retries, cache} |
GET /api/metrics/pulse |
spec?, router?, routerId? |
DeploymentPulse — the topbar's health, upstreamHealthCounts, the providers behind those counts (attention: which, why in a sentence and a word, since when for an unhealthy one; unhealthy first, at most 30) and current throughputRps (5m client rate; the top bar does not draw it) in seven reads, no window (MAG-4296), up to two more while a provider is unhealthy. spec narrows all three to the chain; allChains ({ health, throughputRps }) is always the whole router's, every chain, read apart under spec (nine reads) - the topbar shows its health, so on a chain's page only its provider counts follow the chain (topbarFigures) |
GET /api/metrics/dashboard |
window, spec? |
DashboardData — no web consumer (the Dashboard page that read it is removed); kept as a documented read surface: kpis (successRate, p95Ms, errors, rps, errorsHandled=null), series (throughput, errors, errorRate, successRate, latency p50/95/99, perChain, perChainSuccessRate, perChainLatency, providerMix, perProviderLatencyP95), chains (multiselect options — the series filter is client-side; spec accepted for symmetry). Unbacked families (scu, regions, failoverRatio, internalAvailability, cacheHitRate, errorClasses, errorsHandledBreakdown, contribution, providerAvailability, scorecard) are null, trouble is [] |
GET /api/metrics/routers-rollup |
window |
{ routers: RouterMetrics[] } — the Routers table: one row per CONFIG router, not per chain. ChainMetrics plus routerId, upstreamCount (from the values file, so always the router's own) and attribution: own when the collector reports a target label for it (its chain-level numbers come from the read grouped by that label) or when it is alone on its chain, shared otherwise — in which case sharedWith names the siblings reading the same series, and the rows deliberately carry identical figures. Falls back to one row per chain when no values file is mounted |
GET /api/metrics/chains |
window |
{ chains: ChainMetrics[] } — per-chain rollup (requests, availability, errorRate, p95, composite QoS, health, latestBlock, providerCount) for the Routers table |
GET /api/metrics/upstreams |
window, spec?, routerId? |
{ upstreams: UpstreamMetrics[] } — roster with requests, uptime, p95, errorRate, selection scores, health with its reason (healthReason, healthCause, and healthSince / healthSinceOrEarlier for an unhealthy one), latestBlock, blockLag, behindSec (that lag ÷ the chain's block rate — the comparable form) + stale (tip frozen 15m while the chain produced blocks), role (primary/backup from helm is_backup; null for SR_CONFIG), apiInterface, inFlight, routerIds (the config routers declaring the upstream — several when they share a node name), plus the two signals that need NO traffic: scoreSource (optimizer = the sampler's live score, refreshed for every upstream on a timer; endpoint = the routing path's, frozen at the last selection, so possibly old on an idle row; null = no score) and polls ({ok, failed} latest-block polls the chain tracker made — null when the family is absent, {0,0} when the poll gate suppressed them, which is "we did not ask", never "it answered fine"). routerId keeps only one router's rows; it filters against the values file and does NOT narrow the PromQL (that's router — see "Two router axes") |
GET /api/metrics/block-heights |
spec?, router?, routerId? |
BlockHeights — { routerLabel, chains: ChainTips[] }. Per chain: blocksPerSec (from deriv on the endpoint gauge), bestBlock (highest upstream tip — the reference), routers[] (smartrouter_latest_block per scope value × api interface, each with behindBlocks / behindSec / refreshSec) and upstreams[] (rpc_endpoint_latest_block per endpoint × interface, with stale). Instant only — gauges, so no window. Lags are given in seconds as well as blocks because a block count isn't comparable across chains. ⚠ The router gauge advances on accepted tip observations, not every poll, so it trails by ~one refreshSec however healthy the router is; judge it against that cadence, never a wall-clock threshold |
GET /api/metrics/rps |
window, spec? |
TimeSeries — { label, points: {t, v}[] }: client requests per second over the window (the latency histogram's _count, so a retried request counts once), one range read. The Overview tab's Traffic card, with every chain in view |
GET /api/metrics/traffic |
window |
Aggregate rpsNow + series + per-chain rows (rpsNow, requests, share, trend sparkline). No web consumer; kept as a documented read surface |
GET /api/metrics/methods |
window, spec? |
{ methods: MethodUsage[], classTotals: MethodClassTotals } — per-method CLIENT requests/class/errorRate + real p95Ms (the histogram's method label is named function); classTotals: read real, write/batch null + emitted flags, unclassified remainder. No web consumer; kept as a documented read surface |
GET /api/metrics/chain-series |
spec (required), window |
ChainSeries — the ChainDetail metric-switcher bundle: availability / p95 / errorRate / rps series + qos (optimizer-scope score, endpoint-scope fallback; null when never emitted) + backupShare (only when the config marks backups and the selector actually matched — an unmatched selector is null, never a 0% series). 400 without spec |
GET /api/metrics/upstream-mix |
spec (required), window |
UpstreamMix — { spec, upstreams: { upstream, points }[] }: requests per second each upstream took on the chain, biggest first - relay-scoped, so a retried request counts at every upstream it reached; Cached is the relay cache answering with no upstream. One range read through qPerUpstreamRpsExpr (the per-upstream read, recorded series on long windows), kept apart from chain-series so the Metrics tab's "Traffic by provider" card, shown whenever a chain is picked, doesn't pull the row bundle's other reads. 400 without spec |
GET /api/metrics/upstream-timeline |
spec (required), window, router?, routerId? |
UpstreamTimeline - the Availability blocks (a router row's Availability view and the Metrics tab's Availability card): every upstream of one chain, a cell per stretch of the clock (bucketGrid, the errors-over-time bars' grid - 30 minutes on 12 hours; grid holds the cells' ends, the last still filling up to asOf): rps and failedRps (tries by provider_address), share of the chain's tries (the relay cache's counted in, as qBackupShareExpr divides), pollsOk / pollsFailed (rpc_endpoint_fetch_latest_* by endpoint_id), and state (upstreamCellState: unhealthy at half the tries failed or every poll failed, unknown when scraped but neither tried nor polled, null when nothing was scraped - a gap, never a health). No health-over-time series exists per upstream; smartrouter_csm_provider_blocked is not read (it says only whether the router took the provider out). Four range reads whatever the count; the stretch still filling is one more read of each at now. Recorded series for the tries from 12h. served: per cell, the clients' requests and the ones the router couldn't serve - the Failed requests card's recorded counts (RECORDED_OUTCOMES, chain and a router's service_name=~".+-<id lower-cased>"), null where the store has none or the router can't be split; the top row, Requests served, reads it. Rows: the config's nodes on the chain (one router's with routerId), matched to series case-insensitively, role from helm is_backup, primaries then backups; without routerId, upstreams only the metrics name too (inConfig: false); Cached gets no row. available:false + failed when a read was refused. 400 without spec. See docs/METRICS-MAPPING.md |
GET /api/metrics/upstream-detail |
endpointId + spec (both required), window |
UpstreamDetail - the Upstreams deep-dive for ONE upstream on ONE chain (vendors reuse a node name across chains, so every selector carries spec too: upstreamEndpointSelector / upstreamProviderSelector): health, availability, requests, rpsNow, p50/95/99, errorRate, blockLag, inFlight, score gauges + per-score-type series (not shown), latency/volume/block-lag series (volume.read real; write/batch null), errorsOverTime (failed tries + node error replies per bar, on the clock (bucketGrid) - a bar at t covers the stepSec before it, the last one still filling up to asOf; clicking a bar opens the Errors tab on the requests whose attempt at that upstream failed over exactly that span, the list's upstream filter); errorsByCode/recentErrors empty + emitted flags. 400 without endpointId or spec |
GET /api/metrics/upstream-peers |
spec (required), window |
UpstreamPeers - every upstream of one chain side by side: latencyP95, rps and latestBlock series per upstream, from three range queries whatever the count, sampled on grid (chartSampling: ~300 points, each averaging a 24th of the window - volume as an average of short rates over what is there, see "Time windows"). The deep-dive draws the selected upstream bold against these and lays points out by time on the grid; latency and volume are cut where the upstream wasn't scraped, so missing data is a gap. No requests at a point ⇒ no latency there (v: null), never a zero. 400 without spec |
GET /api/metrics/error-incidents |
window, spec?, routerId? |
ErrorIncidentsReport - the Errors tab's timeline (MAG-5263): errors batched by when they arrived, from failed tries and error replies per (chain × provider) and cross-validation failures per (chain × method) - disagreed: requests the router answered with no result because the providers' answers didn't match (`smartrouter_cross_validation_failures_total{reason=~"no-agreement |
GET /api/metrics/downtime-avoided |
window, spec?, routerId? |
DowntimeAvoidedReport - the Overview's "Downtime avoided" card: seconds a provider was failing while its chain kept answering, notAvoidedSeconds where it did not, incidents, chains, stepSec, strict. A stretch of a chain counts when a provider was in a burst of failed tries on it (the Errors timeline's bursts, detectErrorIncidents, kind failed; error replies are left out) AND at least 99.9% of the chain's client requests in the stretch were answered (DOWNTIME_AVOIDED_RULES.minAnswered), from the log store's recorded outcomes (RECORDED_OUTCOMES summed per chain, read without the router scope: they carry chain and service_name, not the router's label); a stretch with no client request counts neither way; once per chain, however many providers failed. Read at a 1-minute step up to 3h and 5 minutes beyond, a window past a week in pieces of a week at most, one after the other (downtimeAvoidedRead: 30 days is five reads of the Errors tab's 7-day size, about 10 s on a large deployment, kept as a window's answer is) - never at the timeline's 30-minute step, where a 5-minute burst would count as 30. strict: false where the store records no request outcomes (no log ruler) or a router can't be told from another on its chain: seconds is then the time a provider was failing, whatever its chain did, and the card is titled "Provider trouble time". available:false when the store refused the failed-tries read |
GET /api/metrics/errors |
window, spec? |
ErrorsReport — derived total + trend, (chain × provider) hotspots (trend sparklines for the top 5), chain/method pivots; category/code/retryability pivots stay [] until labelled error counters exist (families presence flags) |
GET /api/metrics/retries |
window, spec? |
RetriesReport - the Errors tab's retry cards: retried / recovered / failed from smartrouter_retries_{success,failed}_total (retried = recovered + failed, so the cards add up), recoveryRate, retryRate (÷ client requests), avgExtraAttempts (the retry_attempts histogram). Null + emitted:false until the first retry. ⚠ "Recovered" = the router returned a reply, which can be an upstream error reply; and the router records a retry only once two of the request's tries have come back, so a request it couldn't retry (no upstream left, or a try that never answered) is in no counter - GET /api/error-requests lists those. Counts go through increaseFromBirth: plain increase() drops the first value of a counter born inside the window |
GET /api/metrics/unavailable |
— | { unavailable: UnavailableChain[] } — chains whose every backing endpoint reports down (sinceSeconds null for now) |
GET /api/metrics/cross-validation |
window |
CrossValidationReport - emitted:false + nulls until cross_validation_* fires; consistency (total/caught) is real either way, but no web consumer: MAG-2527 removed the strip that rendered consistency (consistency checks are head-freshness verification, not cross-validation), and the Traffic tab that rendered the rest is gone. caught still surfaces as the hero's staleCaught |
GET /api/metrics/websocket |
window |
WebSocketReport - emitted:false + nulls until ws_* fires (first subscription). No web consumer; kept as a documented read surface |
GET /api/metrics/query |
query (required) |
Raw instant PromQL passthrough — { result }. 400 without query |
GET /api/config/routers |
— | { routers: RouterTopology[] } — live topology from the mounted values file (either format), node URLs masked to scheme+host. Each endpoint also carries index (the handle the relay below resolves) + directable |
GET /api/error-requests |
window or from + to (unix ms, in the past, ≤30 days; 400 otherwise), before?, spec?, routerId?, upstream? |
ErrorRequestsReport - the Errors tab's request list, from the router's logs in Loki (not Prometheus): every request that hit an error, newest first - attempts[] in order (upstream, batch (tries sent together share one), outcome ∈ ok/failed/skipped/cancelled/no-result, replied, the router's code and retryable verdict, the node's message word for word, the router's note, atMs / endMs), result ∈ recovered/error-reply/failed/write-unknown/unknown (write-unknown: a write the router couldn't settle, or a transaction it gave up on after sending it to a provider - the Transactions tab's unknown; unknown: the logs show no end), resolvedBy, retried, stopReason (the router's own), exhausted, totalMs, error (what the client got, for failed and write-unknown), errorCode (the request's own code from relay_end, e.g. NODE_GATEWAY_TIMEOUT on a write-unknown; null on the old lines), the caller's fields where the router wrote them (customer, requestId, taskId, txId, requestBytes, replyBytes, requestedBlock, seenBlock) and a try's nodeCode, quorum on a request that failed cross-validation (PROTOCOL_HASH_CONSENSUS_ERROR: the rule it failed - needed, answered, nodeErrors, reason, and agreed / asked where the router wrote them - from the line the router writes beside the relay_end, the one other line the list reads of a request it found by its relay_end; absent when that line isn't in the logs read), spec (null + specs when its upstreams serve several chains). At most 300 requests per read, and at most LOG_READ_BUDGET_BYTES (4 GB) of logs, newest first: more + nextBefore say where to read on (before=). A chain or router narrows the read to its upstreams' names; upstream (an errors-over-time bar's) narrows it to that one and keeps the requests whose try there failed. Node urls in messages are cut to scheme+host. available:false + reason (unconfigured / unreachable) without LOKI_URL or when Loki doesn't answer. One read per key in flight on a process, its answer kept 15 s (a range that ended over a minute ago 5 minutes, a read Loki didn't answer 30 s); a poll of a page window reads only what is new since the last (see the Loki section) |
GET /api/error-requests/count |
window, spec?, routerId? |
FailedRequests - { available, reason?, value, since? }: client requests the router could not serve (nothing, or nothing usable, came back from the upstreams, so the router returned its own error, typically "insufficient results") in the window. Read from the counts the fleet Loki's ruler records once a minute into the tenant's metrics store (smartrouter_final_failures:count1m, the server-errors alert's count) while they are fresh (newest under 5 min; looked at once a minute): any window, one cheap read; a chain is chain="<spec lower-cased>", a config router service_name=~".+-<id lower-cased>", so a router on a shared chain has its own count unless another router id of the chain ends in its, compared lower-cased (shared-chain). When the recorded counts start inside the window, since (ISO) says where. Without them it counts the lines in Loki: the line the router ends each such request with (message = "failed getting responses from RPC endpoints" when nothing came back, "failed processing responses from RPC endpoints" when nothing usable did; its own relays log "[-] failed sending init relay" instead), plus each failed relay_end on a router on smart-router #543 or later (parsed, not a subscription, outcome no_answer / write_unknown / rejected_before_dispatch / router_error); a chain narrows it by the listener that logged it (<spec><interface>), or by the event's chain; a router on a shared chain answers shared-chain; a window heavier than LOG_READ_BUDGET_BYTES answers too-large - the count reads the whole window at once. A chain the values file doesn't serve is 0 without a read. Kept 30 s per window, chain and router, a failed read too, one read in flight per key. No metric has this number: smartrouter_requests_{total,success,failed}_total move once per TRY, and the one per-request series, the end-to-end latency histogram, is only observed on success. The Metrics page's "Failed requests" card |
GET /api/requests/:guid |
window or from + to |
RequestLookup - one request by its ID (the GUID the router puts in its errors), its transaction hash or the caller's request id (tx_hash / request_id on its relay_end), from its logs: the same row the Errors list shows, for ANY request - result: "ok" when nothing failed on the way - and, when it is a transaction, transaction: the Transactions tab's row for it (send outcome, hash, status), built from the same lines, so one read answers both. matches when several requests carry the value; row is the newest. row: null = not in the logs read. An ID from smart-router v1.6.1 on carries the second it was minted (guidMintedSecond in @sr/shared: the top 32 bits, taken when they fall from 30 days back to 5 minutes ahead): its lines are read from a minute before that second to 5 minutes after (MINTED_SPAN_MS, the router's longest default processing budget with room to spare), whatever the range, and that read answers once it holds the request's relay_end. Otherwise the range is read too, except a 30-day one: about 0.06% of older routers' random GUIDs decode to a plausible second, and the range finds those (linesOfLookup in services/router-log.ts). A transaction hash, a caller's request id or any other ID reads every line in the range, so the web offers it a 30-day read on purpose rather than by default; a v1.6.1 ID gets none, the look-up having read the logs where it was minted. 400 on a value that isn't plain characters (LOOKUP_ID: letters, digits, _ - . : + = @, up to 128) |
GET /api/transactions |
window or from + to (unix ms, in the past, ≤30 days; 400 otherwise), before?, spec?, routerId? |
TransactionsReport - the Transactions tab, from the router's logs in Loki (not Prometheus): rows (newest first: time, chain, method, attempts - every upstream it went to and what each answered, the same shape as a retried request's tries - answeredBy, replyMs, outcome ∈ accepted/rejected/failed/failed-on-chain/unknown, error, note, and where the router wrote them txHash, txStatus, txError and the caller's fields - customer, requestId, taskId, txId, requestBytes, replyBytes, requestedBlock, seenBlock; a try's nodeCode), totals by result, with failedOnChain (no success rate: a refusal is usually the client's own mistake, so a rate would count it against the router). At most 500 transactions per read, and at most LOG_READ_BUDGET_BYTES (4 GB) of logs, and the numbers cover those: more + nextBefore say where to read on (before=), the same paging as /api/error-requests. available:false without LOKI_URL or when Loki doesn't answer. Value and finality are not here: the logs cut long bodies short, and finality needs the chain. Kept and polled as /api/error-requests is |
GET /api/transactions/over-time |
window, spec?, routerId? |
TransactionsOverTime - the Transactions tab's chart: grid (the bars' end times, bucketGrid), counts (one count per bar for each result in the window: accepted/rejected/failed/unknown, and failed-on-chain where the send reply says the chain ran it and it failed), asOf, source (recorded: the store's smartrouter_transactions:count1m, the newest minutes from the logs; logs: counted from the router's logs, on a store without the fleet's ruler - no smartrouter_final_requests:count1m in the window; with the ruler, no series is no transactions), partialFrom (unix s from which the newest bars may be short: the logs didn't answer for the minutes the store doesn't hold yet). available:false + reason (unconfigured / unreachable - also when the store doesn't answer whether it has the ruler - / shared-chain: a router whose lines can't be told from another router's on its chain). Kept 30 s per window, chain and router, one read in flight per key |
GET /api/transactions/:guid |
window or from + to |
TransactionLookup - one transaction by its request ID, its hash or the caller's request id, the same row the Transactions tab shows, read as GET /api/requests/:guid reads it (a v1.6.1 ID in its own minutes first); matches when several requests carry the value (a resent transaction keeps its hash), row the newest. found with row: null = the ID is a request that isn't a transaction (the Errors tab's look-up shows it). 400 on a value that isn't plain characters (LOOKUP_ID) |
POST /api/upstreams/relay |
body: {routerId, node, endpointIndex, transport?, httpMethod?, path?, body?} |
Fires ONE request straight at a configured upstream, router excluded — {httpStatus, latencyMs, body, truncated, transport}. The target is resolved from the values file, never taken from the caller; the resolved url is never returned and is scrubbed out of the upstream's own body. Upstream 4xx/5xx come back 200 with their status inside; 502/504 mean our hop failed. Off with UPSTREAM_RELAY_ENABLED=false. See docs/UPSTREAM-DIRECT-TEST.md |
POST /api/routers/relay |
body: {routerId, iface, transport?, httpMethod?, path?, body?, selectProvider?, forceCacheRefresh?} |
Sends ONE request through a router from inside the deployment — {httpStatus, latencyMs, body, truncated, transport, servedBy, retries, cvStatus, cvAgreeing, cvDisagreeing}. Both auth modes: any signed-in role with accounts on, anyone who reaches the api with them off. The address is resolved from the values file (helm: the <id>-router Service on the chart's 300<N> port; SR_CONFIG: ROUTER_RELAY_HOST + listen port), never taken from the caller; the path and query go on as written; only lava-select-provider / lava-force-cache-refresh are forwarded (HTTP only). Router 4xx/5xx come back 200 with the status inside; 502/504 mean our hop failed; 429 past the per-minute limit or with two relays already in flight, 503 with ROUTER_RELAY_MAX_IN_FLIGHT in flight. 404 with ROUTER_RELAY_ENABLED=false. See docs/ROUTER-RELAY.md |
POST /api/routers/ws-probe |
body: {routerId, iface, path?} |
{online} — whether the router listener's WebSocket upgrade opened from the api within 6 s. The drawer's ws · online tag. Same callers and the same switch as the relay |
POST /api/incidents |
body: {id, severity, title, description?, chain?, routerId?, reporter?} |
A member reports an incident to our on-call system → {id, severity, sentAt}, only after IRM answered 2xx (IRM queues; routing and the call follow). severity ∈ critical/high/medium/low; id is a UUID the form mints, reused on retry. AUTH_MODE=disabled: reporter {name, email, phone?} required, recorded as typed; enabled: the signed-in user, any role, reporter ignored, audited as incident.reported. A chain / routerId the values file doesn't declare is 400. 404 while INCIDENTS_ENABLED is off, 503 without a usable webhook, 429 past either limit, 502 when IRM refused or didn't answer. See docs/INCIDENTS.md |
GET /api/usage/config |
— | Usage data (MAG-5373, MAG-5402): what the web starts Mixpanel's browser SDK with. { enabled: false } unless accounts are on (AUTH_MODE=enabled), the deployment's switch is on, it holds MIXPANEL_TOKEN and a signed-in user is on the request; then { enabled: true, token, apiHost, tenant, deploymentMode, version, viewer: { id, staff, role, email?, created, twoFactor, signIn } }, viewer.id being the first 32 hex characters of sha256(<tenant>:<user id>); email for staff only, never a customer's address; created the account's month; signIn the session's first factor. Cache-Control: no-store. The browser loads the SDK only after the signed-in person's Accept, kept per account and consent version (sr:usage-consent:2:<viewer.id>), and sends to apiHost itself; signing out resets the SDK; the 2FA enrolment is never in a session replay. The api never talks to Mixpanel. See docs/USAGE-DATA.md |
GET /api/usage/viewers/:id |
admin | Usage data (MAG-5413): the member a usage id (viewer.id, Mixpanel's distinct id) belongs to, removed members included: { member: { id, email, name, role, status } } or { member: null }; 400 for anything but 32 hex characters. Cache-Control: no-store. The Team page reads it at /team?usage=<id>. See docs/USAGE-DATA.md |
POST /auth/2fa/verify |
body: {challenge, code} |
Second sign-in step. /auth/sign-in returns a challenge and no session for an enrolled account; only this opens one. Wrong code, dead challenge and unknown challenge all answer the same 401 |
POST /auth/oauth/:provider |
body: {token} |
Google/GitHub sign-in. An account without an authenticator gets { user, sessionId }; an enrolled one gets { twoFactorRequired, challenge, expiresAt, email } and no session — the web parks the challenge in the sr_2fa handoff cookie for the code screen, and the session opens at /auth/2fa/verify as <provider>+totp |
POST /api/account/2fa/begin · /confirm |
— · {code} |
Enrolment. begin returns the QR (server-rendered SVG) and the secret as text, once; confirm proves a code and turns 2FA on. Refused 409 for an already-enrolled account — an admin reset is the only way back |
POST /api/team/members/:id/2fa/reset |
— | Admin only, and not for your own account (409). Destroys the secret, retires live challenges, signs them out everywhere, in one transaction with 2fa.reset (naming both people) and a session.revoked per ended session. Then, on managed, emails the member, naming who reset it and when, and records the outcome as 2fa.reset_notice; a failed send never undoes the reset. notified: "email" when it was sent, else "on_next_signin" (always on-prem). See docs/TWO-FACTOR.md |
GET /api/audit/events |
from?, to?, actor?, action? (repeatable), group? (repeatable), target_type?, target_id?, order?, per_page?, after?, before? |
AuditEventsResponse — { items, cursor, has_more, start_cursor, has_previous }. AUTH_MODE=enabled only; any role, no gate beyond a live session. Oldest first by default and resumable — feed cursor back as after; start_cursor as before reads the page ahead of this one (newer rows under order=desc, how the Audit log page steps back). A misspelled action/group, an actor that is neither a UUID nor an address, an unparseable time, after with before, and a cursor that is malformed, past the largest xid8, or from a different filter set or direction are all 400, never an empty page or a 500 |
GET /api/audit/export.csv |
same filters as /api/audit/events (no after/before/per_page) |
The same events as a streamed CSV — one row per changed field sharing an event_id, events with nothing to diff getting one row with the field columns empty. Each row carries the event's ip, client and session reference, empty on events with no access context. UTF-8 BOM (Excel ignores the charset header on a downloaded file), CRLF per RFC 4180, and every field run through escapeCsvField so a name someone typed as =HYPERLINK(…) opens as text. Paged internally, so the whole matching history is served without holding it in memory |
GET /api/audit/tokens |
— | { tokens } — admin only. Never returns a hash; a token is identified by name + last four characters, with lastUsedAt / lastUsedIp |
POST /api/audit/tokens |
body { name } |
admin only. Mints a read-only pull token and returns { token, secret } — the only time the value exists. Stored as SHA-256; lost means revoke and re-issue |
DELETE /api/audit/tokens/:id |
— | admin only. Revokes; the token stops working on the next request. 404 when already revoked or unknown — the two are one answer so an id can't be confirmed by guessing |
Every /api/metrics/* route that reads the store answers from a snapshot: one
answer per route and query, shared by every caller of the process
(services/snapshot.ts; the TTLs are snapshotTtlMs in routes/metrics.ts).
Without it every viewer re-runs its page's whole read set on every poll,
N viewers N times that, and neither Mimir (its results cache covers range
queries only) nor the client's 10 s answer cache, which sits under the 15 s
poll, shares them. /api/metrics/query (the caller's own PromQL) and
/api/metrics/reads (process state) always answer live.
- The key is the route and the parameters it reads, as parsed: the window
after
toMetricWindow(24hand1dshare an answer),spec,router,routerId,endpointId. Parameter order, and parameters the route doesn't read, change nothing. - Younger than its TTL, an answer is served as is. Up to twice its TTL old it is still served while one refresh runs in the background, so no request waits on a refresh; older, or never read, the request waits for the read, and every request that arrives meanwhile shares it. A viewer alone on a page whose polls are as far apart as the TTL (15 s on the short windows) therefore sees the answer its previous poll read.
- A run that throws, or one during which the store refused a read, gives no
good answer, and the key is read again 5 s later at the earliest, never on
every request. A refused read (non-2xx, an error envelope, a timeout or a
dropped connection) comes back as empty fields rather than an error (the
honesty contract), so the client notes it against the run that issued it
(
services/read-health.ts, called fromfetchOnce). Such a degraded answer never replaces a good one still under twice its TTL: that one keeps being served, itsAgerunning on. With no servable good answer, the degraded answer goes to the callers of its run and is kept for those 5 s only; after a throw they get the error. A read that joined one already in flight counts only for the run that issued it, and a refused read counts even when the client answers it from its last good read. - At most 256 answers; a new key past that evicts the least recently refreshed one. Per process: each replica keeps its own, so a key costs each replica one read set per TTL. A values-file edit reaches the answers within twice their TTL.
Agesays how old an answer is, in seconds since its read started, andAccess-Control-Expose-Headerslets the browser read it. The payloads are unchanged.- No answer depends on the caller: no metrics route reads the session, and
under
AUTH_MODE=enabledthe gate is anonRequesthook, so a snapshot is only served past it.
| Answer | Routes (/api/metrics/…) |
5m–1h | 3h–12h | 1d–3d | 7d–30d |
|---|---|---|---|---|---|
| Figures over the window | rps · traffic · methods · chain-series · upstream-timeline · upstream-peers · cross-validation · downtime-avoided |
15 s | 60 s | 5 min | 15 min |
| Figures about now too (health, latest block, in-flight, a current rate), and the Errors tab | dashboard-summary · dashboard · routers-rollup · chains · upstreams · upstream-detail · websocket · errors · error-incidents · retries |
15 s | 60 s | 60 s | 60 s |
| No window | routers · specs · block-heights · unavailable |
15 s | |||
| The topbar's pulse, polled every 30 s | pulse |
30 s |
The 15 s is METRICS_SNAPSHOT_TTL_MS. No TTL is shorter, so a larger value
raises the others to it, and 0 turns the snapshot off. A window's answer is
kept at most one chart point of the window (chartSampling: 15 s up to 1h,
1–5 min from 3h, 5–15 min from 1d, an hour and more from 7d), and from 3h the
window reads recorded series that move once a minute. A figure about now is
kept a minute at most. The Errors tab is read during an incident, beside the
request list, which reads the logs live. websocket ignores its window: its
figures are lifetime totals and the live connection gauge.
API (apps/api/src/config.ts is the source of truth):
| Variable | Default | Notes |
|---|---|---|
API_PORT |
8000 |
|
API_HOST |
0.0.0.0 |
|
PROMETHEUS_URL |
http://localhost:9090 |
compose sets http://prometheus:9090. A path prefix (Mimir's /prometheus) and a query string are both kept on every call |
PROMETHEUS_TIMEOUT_MS |
10000 |
per-query abort |
METRICS_RECORDED_FROM |
3h |
the narrowest window read from the store's recorded series (promql/recorded.ts: the fleet Mimir ruler's two-minute rates, summed per chain and router) instead of the raw histograms and counters; narrower windows stay raw and exact; chart series switch only from 12h (RECORDED_CHART_FLOOR). never holds every window on raw. Only while the series are fresh — see the next row |
METRICS_RECORDED_STALE_MS |
300000 |
the api asks the store once a minute (METRICS_RECORDED_PROBE_MS) how old the newest recorded sample is, how far back the oldest one reaches (looked for 30 days 12 hours back on an hourly grid - past a 30-day read's first stretch, inside the fleet store's 31-day limit on one read's span), and how far apart the raw router samples are (the rules' 2m15s window is exact for a 15-second scrape only); older than this, absent, on another scrape interval, or with less history than the window asked for, and the builder reads raw — slow, never wrong. GET /api/metrics/reads reports the state; the Metrics page's notice reads it. Transitions are logged once |
PROMETHEUS_CACHE_TTL_MS |
10000 |
how long a successful answer is reused for an identical read (same path, params, scope and credential) — under the fastest panel poll (15 s), so two tabs or two panels asking the same instant read in an interval cost the store one query (the store is per process, each replica keeps its own). A range read ends on a step boundary (see "Time windows"), so it asks for the same window until the next one. An answer read while the window's end is under three minutes old (RANGE_SETTLE_MS: raw samples land late, and the ruler writes recorded series a minute or two after their timestamps) is reused for this value only, so a chart's newest point and a just-closed error bar are read again until they settle; once settled, for the read's step, five minutes at most and never less than this value. 0 keeps every read live, range reads included. Identical reads in flight at the same moment share one request whatever the value. A refused refresh (429, timeout, error) is answered from the last good read for up to 60 s (60 s past its reuse, for a range read) and retried next time; failures themselves and the readiness probe are never kept |
METRICS_SNAPSHOT_TTL_MS |
15000 |
the base TTL of the metrics routes' response snapshot (see "Response snapshot"): windows up to 1h and the window-less routes keep an answer this long, and no answer is kept shorter. 0 turns the snapshot off: every request reads live and carries no Age. Read at boot |
PROMETHEUS_USERNAME / PROMETHEUS_PASSWORD |
unset | Basic auth on every Prometheus call — for a per-tenant read proxy or Mimir behind an auth gateway. Both or neither: one half alone sends no header |
PROMETHEUS_ORG_ID |
unset | Sent as X-Scope-OrgID, for a multi-tenant store that takes the org from the client. The fleet's read proxy pins the org from the credential and ignores this |
ROUTER_SCOPE_LABEL |
unset | Target label carrying the router identity for ?router=. Unset: resolved on first use — router (the fleet's collector and the chart's ServiceMonitor from 6.20.0 stamp it from the pod label app.smart-router-id), else service (the Prometheus Operator's automatic label, the router's Service name); never probed at boot, remembered once found. Set job for a scrape config that names jobs per router. Parsed at import — a change needs a restart |
METRICS_SCOPE_LABEL / METRICS_SCOPE_VALUE |
unset | Deployment scope: a label="value" matcher EVERY metrics query carries (cache_*, router discovery and the /query passthrough included), for one dashboard per zone / tenant against a shared store. Both or neither — half a pair, a value that cannot sit in a matcher, or a label equal to ROUTER_SCOPE_LABEL refuses the boot. A scope that selects no router series warns at boot. Unset = the whole store, as before. See "The deployment scope" |
CORS_ORIGINS |
all | comma list or JSON array |
RATE_LIMIT_MAX |
300 |
per caller per minute. With AUTH_MODE=enabled a second, fixed limit of 100 (ACCOUNTS_RATE_LIMIT_MAX in plugins/auth.ts) counts the same requests, so 100 is the one met. Both key on the connection's address, except a call the web vouches for (X-Internal-Auth), which spends the reader's session, else the forwarded browser address (clientRateLimitKey) — the layouts' per-page-load /api/account/me read would otherwise put every signed-in person in the web pod's bucket |
TRUST_PROXY |
1 |
how far X-Forwarded-For is believed when deriving request.ip (hop count, proxy IP/CIDR list, or false). Not true — this api is public, and trusting every hop lets any caller choose their apparent address |
HELM_VALUES_DIR |
/app/helm-values |
reads <dir>/core/values.yml (either format) |
UPSTREAM_RELAY_ENABLED |
true |
false 404s POST /api/upstreams/relay. With AUTH_MODE=disabled anyone who can reach the api can spend the operator's upstream quota through it, using credentials only the api holds — turn it off where that isn't acceptable |
UPSTREAM_RELAY_TIMEOUT_MS |
10000 |
deadline on the api→upstream call |
UPSTREAM_RELAY_MAX_BODY_BYTES |
262144 |
upstream responses past this come back truncated: true |
UPSTREAM_RELAY_RATE_LIMIT_MAX |
20 |
per IP per minute, tighter than RATE_LIMIT_MAX |
ROUTER_RELAY_ENABLED |
true |
the api sends Try-me's router leg (POST /api/routers/relay, POST /api/routers/ws-probe), in both auth modes. Exactly false 404s both routes and the drawer sends from the browser. With AUTH_MODE=disabled anyone who can reach the api can send through the routers, past an address list at their edge — turn it off where that is not acceptable |
ROUTER_RELAY_HOST |
localhost |
where an SR_CONFIG mount's routers listen, for POST /api/routers/relay (router in the compose stacks). Unused for a helm mount, which dials each router's <id>-router Service |
ROUTER_RELAY_TIMEOUT_MS |
30000 |
deadline on the api→router call, body included; a WebSocket send stops at 15 s |
ROUTER_RELAY_MAX_BODY_BYTES |
4194304 |
router answers past this come back truncated: true |
ROUTER_RELAY_RATE_LIMIT_MAX |
60 |
per caller per minute (the signed-in user, or the address with accounts off); the relay and the ws probe each count their own |
ROUTER_RELAY_MAX_IN_FLIGHT |
8 |
relays in flight across all callers; one caller holds two at most |
ASK_DATA_ENABLED |
off | exactly true, with AUTH_MODE=enabled and DEPLOYMENT_MODE=managed, turns on Ask your data. It also needs ASK_DATA_CUSTOMER_ID, ASK_DATA_MCP_TOKEN, AWS_BEARER_TOKEN_BEDROCK, ASK_DATA_BEDROCK_MODEL, ASK_DATA_PRICING_JSON and ASK_DATA_TOKEN_COUNTER; the full list, defaults and the admins' off switch are in docs/ASK-YOUR-DATA.md |
INCIDENTS_ENABLED |
off | exactly true turns on POST /api/incidents; anything else 404s it. With AUTH_MODE=disabled anyone who can reach the api may send a report, Critical included — opt-in per deployment. See docs/INCIDENTS.md |
INCIDENT_WEBHOOK_URL |
unset | the deployment's inbound webhook in our on-call system (Grafana IRM formatted_webhook). The URL is the credential — deliver it from a Secret, never a plain chart value. https only (http for a loopback mock). On with no usable URL logs an error at boot and every report answers 503; the boot is NOT refused |
INCIDENT_WEBHOOK_TIMEOUT_MS |
10000 |
deadline on the api→IRM call |
INCIDENT_RATE_LIMIT_MAX |
3 |
reports per caller per 10 minutes, keyed on cf-connecting-ip (the fleet sits behind Cloudflare) and falling back to the connection |
INCIDENT_POD_MAX |
10 |
reports per api process per 5 minutes, every caller together — keeps a flood far below IRM's organisation budget (900 / 5 min), which fleet alerts share |
LOKI_URL |
unset | Loki holding the router's logs, for the Transactions tab, the Errors tab's request list and the Failed requests card. Unset ⇒ they say they can't read them (available:false). Compose sets http://loki:3100 (the logs profile). Read from the live env, so tests can set it |
LOKI_TIMEOUT_MS |
60000 |
per-query abort — a day of router lines on a shared Loki takes seconds per read; keep it under the edge's cut (Cloudflare: 100 s) |
LOKI_ROUTER_SELECTOR |
{component="router"} |
LogQL stream selector for the router's lines - the label the fleet's log agent and the compose promtail both put on them; set it only where the router's streams carry other labels. smart-router v1.6.1 and later write relay_end at every log level; an older router must log at info |
LOKI_USERNAME / LOKI_PASSWORD |
unset | basic auth for Loki, sent only when both are set - e.g. a per-tenant read path that pins the org from the credential |
LOKI_ORG_ID |
unset | sent as X-Scope-OrgID, for a Loki that takes the org from the client; unset sends no header |
USAGE_ANALYTICS |
managed: on · onprem: off | usage data (MAG-5373): on / off. Only with accounts on (AUTH_MODE=enabled): with them off it is off whatever this says. On, GET /api/usage/config hands every signed-in browser what it starts Mixpanel's browser SDK with, the project token included; the browser starts the SDK only after the consent banner's Accept. Off without MIXPANEL_TOKEN. See docs/USAGE-DATA.md |
MIXPANEL_TOKEN |
unset | the Mixpanel project's token, from a Secret; handed to a signed-in browser only while usage data is on, since the browser SDK sends with it |
MIXPANEL_API_HOST |
https://api-eu.mixpanel.com |
the one host the browser SDK sends events, profiles and session replays to (the project keeps its data in the EU); https only, http for a loopback mock |
USAGE_TENANT |
TENANT_ID |
the tenant every usage event and profile carries, so Mixpanel splits reports per client |
USAGE_STAFF_DOMAINS |
magmadevs.com |
a user whose email is at one of these (anyone @magmadevs.com) is marked staff: true (with their role), so our own use can be left out; a staff member's profile carries their address, a customer's never does |
LOG_LEVEL |
info |
|
SHUTDOWN_TIMEOUT_MS |
20000 |
from SIGTERM to a forced exit 1. In-flight requests and running Ask answers get all but the last 8 s of it (SHUTDOWN_CLOSE_RESERVE_MS), which is left for interrupted runs' terminal writes and the pool's 5 s end. Keep it under the pod's grace period less any preStop. See "Deploying to Kubernetes" |
TENANT_ID |
— | set by the chart, not read for tenancy (read only as the usage data's tenant label, USAGE_TENANT). The multi-tenant store pins X-Scope-OrgID from the credential that authenticated, so the api never names its own org — a config field that did would move the tenancy boundary into a values file |
GIT_COMMIT / APP_VERSION |
unknown / 0.0.0 |
surfaced by /version; build-and-push.yml sets both on every published image (the commit is github.sha) |
NODE_ENV |
production |
non-prod enables /docs + pretty logs |
Auth (only read when AUTH_MODE=enabled; the metrics path never touches the DB):
| Variable | Default | Notes |
|---|---|---|
AUTH_MODE |
disabled |
enabled turns on the session gate + /auth/* + Postgres |
AUTH_SECRET |
(unset) | HS256 signing secret shared with the web (must match). 32 characters or more: a shorter one, or one still a __NAME__ placeholder, refuses the boot, as an unset one does (authSecretProblem in plugins/auth.ts) |
DATABASE_URL |
(unset) | Postgres connection string for users + sessions |
DB_POOL_MAX |
20 |
Connections each api process holds open to Postgres. Every authenticated request takes one for the session join, so this bounds a backend's concurrency and, summed over a deployment's backends, what its instance must admit — the fleet sets it per backend from a shared instance's connection budget. Anything but a whole number ≥ 1 refuses the boot |
DB_IDLE_TIMEOUT_S |
30 |
Seconds a pooled connection sits idle before it is closed; the next request pays for a new one (TCP, TLS, three SCRAM legs). 0 keeps idle connections for the life of the process. Anything but a whole number ≥ 0 refuses the boot |
DB_TLS_SERVERNAME |
(unset) | The name the Postgres server's TLS certificate must carry, when DATABASE_URL points at a local proxy rather than at the database — the fleet's backends dial a cloudflared sidecar on 127.0.0.1:5432 while the TLS session ends on RDS, whose certificate names the endpoint; for an IP in the URL Node checks the certificate against localhost, so sslmode=verify-full alone refuses every connection there. Set, TLS is always on and the certificate must match this name whatever the URL's sslmode says (verify-full with the name supplied; the chain still needs the CA, NODE_EXTRA_CA_CERTS). Unset, the URL decides. Anything but a DNS name refuses the boot |
ADMIN_EMAIL / ADMIN_PASSWORD |
(unset) | idempotent admin seed on first boot, development only — refused under NODE_ENV=production, where first-run setup with the installer's SETUP_TOKEN is the only way an account comes into existence |
GOOGLE_CLIENT_ID |
(unset) | validates the aud claim of Google ID tokens server-side |
INTERNAL_AUTH_SECRET |
(unset) | shared with the web; gates whether the forwarded browser IP / User-Agent (X-Forwarded-Client-Ip / -Ua headers) are trusted on the routes that open a session (/auth/sign-in, /auth/2fa/verify, /auth/oauth/:provider, /auth/invite/accept), and whether the per-IP limiter keys on them (a vouched call with a session keys on the session). Required under AUTH_MODE=enabled — the api refuses to boot without it |
DEPLOYMENT_MODE |
onprem |
managed (we host) / onprem (customer hosts, no mail server). Forks invite + reset delivery (managed emails them, on-prem hands the admin a link), sets their lifetimes, and marks the first account as Magma's on managed. Read by the web at runtime via /api/config |
SETUP_TOKEN |
(generated) | First-run token, required to create the first admin. Must be ≥ 16 characters; unset (or shorter) ⇒ generated once at boot, on an install that still needs setting up, and logged at warn |
SETUP_TOKEN_FILE |
(unset) | Path to write a generated token to (mode 0600), so an init container or mounted volume can surface it |
PASSWORD_BREACH_CHECK |
hibp |
off disables the HaveIBeenPwned check — the honest setting for an air-gapped install, rather than relying on a silent timeout |
TOTP_ENCRYPTION_KEY |
(unset) | Required. 32 bytes (base64 or hex) encrypting every enrolled TOTP secret at rest. The api refuses to boot without it: the 2FA gate shuts the dashboard to anyone unenrolled, enrolment is the only way through, and enrolment needs this key — so missing it locks out every account at once. Deliberately NOT derived from AUTH_SECRET, whose rotation is routine and would otherwise invalidate every enrolled phone. openssl rand -base64 32 |
TOTP_ISSUER |
Smart Router |
What an authenticator app shows as the issuer. Override it so somebody administering two dashboards can tell the entries apart |
PUBLIC_WEB_ORIGIN |
(unset) | browser-facing origin of the web app, used to build invitation and password-reset links. Routes that need it fail loudly when it is unset rather than guessing a host — POST /api/team/invites 500s. Both compose files default it to the web's AUTH_URL |
CUSTOMER_NAME |
Smart Router |
Who the deployment belongs to, as the emails name the dashboard; the invitation subject is "{inviter} invited you to the Smart Router dashboard for {customer}". The fleet sets the tenant's name |
AWS_REGION |
(unset) | Enables email. Unset ⇒ nothing is sent; a warn line names the recipient, and only under NODE_ENV=development carries the body (it holds a live link). On-prem that is correct. On managed it means the admin carries invitation links, and self-serve reset answers 404 rather than issue a link nobody receives |
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY |
(unset) | Optional. Both set ⇒ the SES client signs with this pair: the fleet's managed deployments get one per tenant from a Secret (the chart's mail.accessKeySecret), scoped to sending as the no-reply address through that tenant's configuration set. Absent ⇒ the SDK resolves credentials from the environment (IRSA / instance role). ses-credentials.test.ts pins that the pair alone signs the send |
EMAIL_FROM |
Smart Router <noreply@smart-router.local> |
Sender. An unmonitored no-reply |
EMAIL_REPLY_TO |
(unset) | Monitored inbox, so a reply to a reset email reaches somebody |
EMAIL_CONFIGURATION_SET |
(unset) | SES configuration set. Keeps each environment's bounce/complaint reputation separate on a shared identity |
SES_ENDPOINT |
(unset) | Points SES at a local mock for development — make accounts-managed runs one and serves its inbox on :8005 |
Web — build-time vs. runtime:
| Variable | Default | Notes |
|---|---|---|
NEXT_PUBLIC_API_URL |
http://localhost:8000 |
baked into the bundle at build time |
NEXT_PUBLIC_LOCAL_MODE |
false |
build-time default for the localMode flag |
DASHBOARD_API_URL |
(unset) | runtime override — read from the container env per-request by GET /api/config, so one published image serves any host |
DASHBOARD_LOCAL_MODE |
(unset) | runtime override of localMode, same mechanism |
DASHBOARD_GRAFANA_URL |
(unset) | Grafana base URL the "View full logs" button links to — runtime override via /api/config, same mechanism (falls back to NEXT_PUBLIC_GRAFANA_URL). Unset hides the button; the logs compose profile's Grafana is http://localhost:3001 |
DASHBOARD_GRAFANA_DASHBOARD_URL |
(unset) | Exact customer reports URL for Advanced → Logs & Metrics, read per request; invalid or unset hides the link. See docs/GRAFANA-LINK.md |
DASHBOARD_GRAFANA_CUSTOMER_USAGE_DASHBOARD_URL |
(unset) | Exact customer usage URL for Advanced → Customer Usage, independent of the reports link; invalid or unset hides the link |
INCIDENTS_ENABLED |
(unset) | true (any case) shows the top bar's Report incident button. Read per request by the (app) layout, not asked of the api, so the button still shows when the api is down. Set it with the api's |
AUTH_MODE / AUTH_SECRET |
disabled / (unset) |
must match the api; enabled renders the login page + edge gate |
DEPLOYMENT_MODE |
onprem |
must match the api. Surfaced to the browser by GET /api/config, so one image serves both shapes |
INTERNAL_AUTH_SECRET |
(unset) | must match the api (which requires it under AUTH_MODE=enabled); lets the web forward the browser's real IP / User-Agent on sign-in and on the server-rendered previews, and vouch for the layouts' enrolment read so it spends the reader's allowance, not the web pod's |
TRUST_PROXY_HOPS |
1 (compose: 0) |
how many proxies sit in front of the web; 0 when it is published directly, which forwards no address (Next leaves a browser's own X-Forwarded-For intact, so nothing in it can be believed). The browser's entry is that many back from the right of X-Forwarded-For; the left-most is caller-supplied and never used |
INTERNAL_API_BASE_URL |
(falls back to api url) | server-side api URL for Auth.js callbacks (compose sets http://api:8000) |
{GOOGLE,GITHUB}_CLIENT_{ID,SECRET} |
(unset) | each provider's button appears only when its id+secret pair is set |
AUTH_REDIRECT_PROXY_URL |
(unset) | Auth.js's redirect proxy: the base URL of an Auth.js instance holding the same AUTH_SECRET (the fleet's apps/auth-proxy at https://auth.magmadevs.com/api/auth). Set, each provider's redirect_uri is <it>/callback/<provider> and this dashboard's own callback rides in the signed state, so the provider's client lists one callback for every dashboard. Read by next-auth itself; nothing in auth.config.ts names it |
The browser resolves its api base once per session from /api/config
(DASHBOARD_API_URL → NEXT_PUBLIC_API_URL → http://localhost:8000),
falling back to the build-time value if the route is unreachable
(lib/api-client.ts).
Compose / Makefile knobs:
| Variable | Default | Notes |
|---|---|---|
SR_CONFIG_HOST |
./dev-config/values.yml |
the values file — mounted into the router as its config AND into the api as helm-values |
ROUTER_DIR |
~/projects/smart-router (make) / ../../smart-router (compose) |
router-profile build context |
SR_SPEC |
specs/ |
--use-static-spec dir inside the router image |
SR_LOG_LEVEL / SR_LOG_FORMAT |
info / json |
router logging |
BUILDER / API_IMAGE / WEB_IMAGE / API_PORT / WEB_PORT / API_URL |
see Makefile | make build image names + printed URLs |
- Self-contained compose:
deploy/prometheus.ymlships two static scrape jobs — the bundledrouter:7779andhost.docker.internal:7779(an already-running host router); a down target is harmless since every query aggregates withsum()/max(). Distinct compose project names (smart-router-dashboard/smart-router-dashboard-dev) avoid collisions with a sibling agent's smart-router stack. - The router profile boots with
--cors-headers "*"(the browser Live-test panel preflights cross-origin POSTs) and--skip-websocket-verification(http-only upstreams boot cleanly). - GHCR publishing: the
build-and-pushjob in.github/workflows/build-and-push.ymlpublishes the api asghcr.io/magma-devs/smart-router-dashboard/backendand the web as…/frontend(tags:VERSION,major.minor,lateston main; other branches get a-<branch>suffix, with any character a tag can't hold,/among them, replaced by-). Each image is pushed by digest and tagged only aftersmoke-arm64boots it (thepublishjob); on main,tag-releasethen cuts the git tag and pointslatestandmajor.minorat the highestv*release tag, so overlapping main runs cannot move them backwards. Those image names are the ones the smart-router helm chart consumes, so the build target (apps/api/apps/web) maps onto them in the workflow matrix.make buildreproduces the same images locally on an isolated buildx builder (srdash-builder) — on a Docker daemon shared with sibling projects, BuildKit's shared cache can serve the wrong project'sapps/api/package.json(ERR_PNPM_OUTDATED_LOCKFILEmentioning@info/shared), so themake build*targets always pass--builder srdash-builder. - One build stage for both architectures: each Dockerfile builds on
$BUILDPLATFORM(plain-JS output; the api has no native module, and the web never loads sharp, whichimages.unoptimizedinnext.config.mjspins and the web Dockerfile removes from the standalone output) and keeps its runtime stage free ofRUN, so alinux/amd64,linux/arm64build compiles once and the workflow sets up no QEMU. Layers go lockfile + package manifests →pnpm install→ sources, so a code-only commit reuses the install layer. The layer cache lives on GHCR (type=registry): main writes…/<image>:buildcache, a branch writes…/<image>:buildcache-<branch>and reads both, and a failed cache export never fails a build. The api runtime image is apnpm deploy --legacy --prodtree underapps/api/: thefilesfield of each package manifest decides what ships, and it carries no devDependencies, soNODE_ENV=development(the dev-onlypino-prettytransport) does not boot it. Asmoke-arm64job pulls each image by digest on anubuntu-24.04-armrunner and waits for its health endpoint (and the web's first page); no tag exists until it passes, so a failed smoke leaves the version unpublished and reusable.
- A branch is brought up to date by a rebase, never a merge commit.
git fetch origin && git rebase origin/main, then push with--force-with-lease.git merge origin/main,git pullwithout--rebaseand GitHub's "Update branch" (merge) are out; "Update with rebase" is fine.git rev-list --merges origin/main..HEADprints nothing on a branch that is ready. Two things enforce it: the "linear history" ruleset refuses a push that carries a merge commit, on every branch, and the quality gate's No merge commits job fails a pull request whose branch holds one. maintakes squash merges only, one commit per pull request, titled as the pull request is.- A pull request that ships sets
VERSIONto the next number aftermain's: the patch for a fix, the minor for a feature. An open pull request reserves no number: when another one merges first, rebase and take the next. The build onmainrefuses aVERSIONat or below the latestv*tag and publishes nothing for it, so a stale number is a release that never happens. The pull request's title ends with the version, andCHANGELOG.mdhas a## [<VERSION>]section above the previous release's. - A pull request's evidence lives in its body and its Jira ticket, never in
the repository: no per-ticket validation folders, dated test logs, recorded
provider receipts or screenshots of the change. Screenshots go into the body
with
gh pr create/gh pr edit --attach. Docs describe how the product works now and point at the tests that prove it.
| Trap | Reality |
|---|---|
ESM .js suffixes |
apps/api + packages/shared use Node16 resolution — relative imports need .js suffixes even though source is .ts. apps/web uses bundler resolution (no suffixes). |
shared dist |
api/web read @sr/shared from dist/ — run pnpm --filter @sr/shared build after editing it (the docker dev builder service does this on a tsc --watch). |
| Metric names | NOT lava_rpcsmartrouter_* — see Metrics above. The ../SR_Dashboard/ prototype is authoritative for pixels, not for metric names. |
| Polling | A poll belongs in useApi: the per-window cadence and the idle gate live there, and a direct useSWR poll gets neither. While the gate has polling paused, isPaused refuses every revalidation, a mutate() included. A click or a key resumes polling before its handler runs, so a refresh a person asks for works; one fired by a timer does nothing until someone comes back. See "Polling" |
| Window params | 24h is a wire alias of 1d; unknown values silently fall back to DEFAULT_WINDOW = 30m (never a 400). The web opens on the same constant, and a window the user picks persists to localStorage under sr:window — so a changed default only reaches someone who has never picked one. The Metrics page's ?window= beats both and is never saved. 1h is in the catalog but not in the page-level select. |
Provider role |
Only the helm values format marks backups (is_backup); with a raw SR_CONFIG mount, role is null and backup-share panels stay empty — that's honest, not a bug. |
| Endpoint URLs | localhost:<port> comes from SR_CONFIG's listen ports, gateway hostnames from helm values' publicUrls — a mount never has both. Anything that renders or dials an endpoint address must resolve public → local → — (epHttpUrl / epWsUrl in components/endpoints/bits.tsx), never hardcode localhost. |
| Health words | HealthState has exactly four states and exactly one wording — lib/health.ts / <HealthTag>. A panel that maps health to its own labels/colours is a bug, even when the words look nicer locally: the same upstream is read across panels. |
| BuildKit cache | make build* targets use the isolated srdash-builder (see Docker / images / isolation). Plain docker compose up --build is fine for the stack itself. |
RUN in a runtime stage |
CI builds the arm64 half of each image without QEMU, so a RUN in a Dockerfile's runtime stage fails there with exec format error. Do the work in the build stage and COPY --from=builder. A runtime break on arm64 (a dependency that loads a native binding at boot) shows up in the smoke-arm64 job instead. |
| Pinned versions | Every version is exact: package.json, overrides in pnpm-workspace.yaml, actions by commit SHA, and images by tag plus digest. pnpm is pinned by packageManager (CI's pnpm/setup reads it; the lockfile's first document records each platform binary's sha512) and by the ghcr.io/pnpm/pnpm stage in the three Dockerfiles. A Docker build fails when those two differ (pnpm_config_pm_on_fail=error), so move them together. The quality gate's "pins agree" step (apps/web/scripts/check-pins.mjs) fails when .nvmrc or packageManager disagrees with any Dockerfile FROM: Dependabot moves only the Dockerfiles (one PR per image across all three), so its Node or pnpm PR goes green once the same PR moves .nvmrc or packageManager. It proposes no major of Node, the pnpm image or @types/node (ignore in .github/dependabot.yml); those are migrations done by hand. No corepack: Node 26 does not ship it, and pnpm does not use it. pnpm only reads its settings from pnpm-workspace.yaml (the pnpm field in package.json and non-auth .npmrc keys are ignored), and a package with an install script that is not listed in allowBuilds fails the install. There is no minimum release age (minimumReleaseAge: 0; Dependabot has no cooldown). pnpm install refuses a release published with weaker evidence than the package's earlier releases (ERR_PNPM_TRUST_DOWNGRADE). Don't get around that with a ^ range or a --config flag: add the package to trustPolicyExclude in pnpm-workspace.yaml with its reason. A new override or dependency goes in as an exact version, and a new uses: or image as a SHA or digest. See README → Testing & CI. |
| Database round trips | Every query is a named prepared statement (preparing in packages/db/src/client.ts): drizzle sends queries through sql.unsafe, which postgres-js leaves unprepared, and an unprepared query with parameters costs two round trips and holds back the queries after it. A fleet API reaches RDS across regions through a tunnel, so a round trip is about 100 ms. Named statements need a direct connection: never put a transaction pooler in front of the database. In a transaction, statements that do not wait on each other's results can be sent together (inOrder in the Ask store, sent in the Ask budget) and share a round trip. |
Image files whitelist |
The api image ships only what each package's files lists (apps/api: dist; packages/db: dist + migrations; packages/shared: dist). A runtime asset anywhere else (a template, a file read with fs) works in dev and fails only in the published image — put it under dist or add it to files. |