diff --git a/.changeset/admission-overload.md b/.changeset/admission-overload.md new file mode 100644 index 000000000..1bef122dc --- /dev/null +++ b/.changeset/admission-overload.md @@ -0,0 +1,33 @@ +--- +default: minor +--- + +# zingod-grpc, zingod: one adaptive work limit, a load-balancer overload signal, no hardware knobs + +- Work limit (2048) sheds only when the CPU falls behind (ready requests wait > 100 ms for a core, + 15 s); disk, wallet and network waits never count. Linux PSI signals gone +- `/readyz` `down`, reason `overloaded`, while > 10% of wallets are refused or held back by a + congested uplink (60 s average; clears under 2%). Serving continues +- Connections and memory limits come from the host (`Connection cap` at startup; under 256, + zingod refuses to start) +- Per address (an IPv6 /64 = one): `[grpc] work_share_per_ip` of the work limit, default + `0.0625` (`1.0` = none, for load tests) +- Requests take a work slot only once their body has arrived; streams whose wallet stops reading + give theirs up when slots run short +- Index reads on zingod's own threads: `[grpc] read_threads` (32), address-history scans apart in + `[grpc] scan_threads` (4) +- Remove from your config, or zingod refuses to start: `[grpc.overload]`, and under `[grpc]` + `max_connections`, `max_streams_per_connection`, `max_work_streams`, `adaptive_work_streams`, + `max_subscriptions`, `max_point_reads`, `max_range_reads`, `max_scan_reads`, + `silent_timeout_secs` +- `zingod overload` removed; delete `/overload/` if it exists +- Metrics: + - gone: `zingod_grpc_overload_latched` (use `zingod_state_reason{reason="overloaded"}`), + `zingod_grpc_active_subscriptions`, `zingod_grpc_subscriptions_rejected_total` + - renamed: `zingod_grpc_disk_read_wait_seconds{lane}` → `zingod_grpc_read_wait_seconds{pool}` + - new: `zingod_grpc_overload_share{cause}`, `zingod_grpc_adaptive_stream_ceiling`, + `zingod_grpc_adaptive_scheduling_delay_seconds`, `zingod_grpc_parked_bytes`, + `zingod_grpc_parked_evicted_total`, `zingod_grpc_uplink_*`; + `zingod_grpc_admission_rejected_total` gains `reason` +- Logs: `Serving` = `rps`, `conns`, `refused`, `failed`, `evicted`; new `Work limit lowered` / + `restored`, `Uplink congested` / `clear`, `Overload latched` / `cleared` diff --git a/Cargo.lock b/Cargo.lock index 01c429bd2..17fb4e70a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2477,6 +2477,36 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "netlink-packet-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6e2daf9a8c2e21302714706860a0e6be02e03d17294ecc66b354ea7d4059dd" + +[[package]] +name = "netlink-packet-sock-diag" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55169f3ffef150fcfbeda8ab1d9766ce69e02f27f8bc1601555ec3b7a2a84377" +dependencies = [ + "bitflags 2.13.0", + "libc", + "netlink-packet-core", + "smallvec", + "zerocopy", +] + +[[package]] +name = "netlink-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c99d38e00b420df49e940fe0826e667c3dad82ac68eb4c2bbf754c1c14a83a10" +dependencies = [ + "bytes", + "libc", + "log", +] + [[package]] name = "nix" version = "0.31.3" @@ -4211,6 +4241,17 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "tokio-metrics" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01f967a7d11cf59ebeb361546fcc207763de7a885db18176e7042dfc28665f1c" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio-stream", +] + [[package]] name = "tokio-rustls" version = "0.26.6" @@ -5474,6 +5515,7 @@ dependencies = [ "metrics", "metrics-exporter-prometheus", "metrics-process", + "procfs", "psl", "reqwest", "rlimit", @@ -5550,11 +5592,16 @@ dependencies = [ "http", "http-body", "http-body-util", + "hyper", "hyper-util", "ipnet", "metrics", + "netlink-packet-core", + "netlink-packet-sock-diag", + "netlink-sys", "ppp", "prost", + "rayon", "rcgen", "rustls", "serde", @@ -5563,6 +5610,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", + "tokio-metrics", "tokio-rustls", "tokio-util", "tonic", diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 46d3d7b3c..3692e9d2a 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -14,9 +14,10 @@ - [Quick start](operators/quick-start.md) - [Configuration](operators/configuration.md) - [First sync](operators/first-sync.md) +- [Network exposure](operators/network.md) +- [Load and DoS protection](operators/dos-protection.md) - [Monitoring](operators/monitoring.md) - [Maintenance](operators/maintenance.md) -- [Network exposure](operators/network.md) - [Docker](operators/docker.md) - [Migrating from Zaino](operators/migrating-from-zaino.md) diff --git a/book/src/operators/configuration.md b/book/src/operators/configuration.md index 3be508fbd..79b624cc8 100644 --- a/book/src/operators/configuration.md +++ b/book/src/operators/configuration.md @@ -26,7 +26,7 @@ every enabled index, and `p2p.cache_dir` if `[p2p]` is enabled. | `[submission]` | how `SendTransaction` retries relaying | | `[p2p]` | Zingod's own Zcash p2p peers (off by default) | | `[serve]` | gRPC listen address, TLS, gRPC-web, state directory, drain delay | -| `[grpc]` | connection and stream limits, timeouts, trusted proxies, overload thresholds | +| `[grpc]` | [load and DoS protection](dos-protection.md) limits and timeouts, trusted proxies, shutdown grace | | `[metrics]` | admin listener for metrics and probes (off by default) | | `[sync]` | block fetching and finality depth | | `[index.]` | per index: `enabled` and `path` | diff --git a/book/src/operators/dos-protection.md b/book/src/operators/dos-protection.md new file mode 100644 index 000000000..08ee8b9e1 --- /dev/null +++ b/book/src/operators/dos-protection.md @@ -0,0 +1,81 @@ +# Load and DoS protection + +Zingod refuses work it cannot take on at once instead of queueing it, so a wallet can try another +server. The defaults suit most nodes. + +## Settings + +| Setting | Default | What it does | +| ------------------------------- | -------- | ------------------------------------------------------------------ | +| `[grpc] max_connections_per_ip` | `128` | Connections one address may open; more are closed. High because mobile carriers put many wallets behind one address. Behind a proxy, set [`trusted_proxies`](network.md#behind-a-proxy) so this counts wallets, not the proxy. | +| `[grpc] work_share_per_ip` | `0.0625` | Share of the request limit one address may use (1/16: it takes 16 addresses to fill a node). `1.0` turns it off, for load tests from a few addresses. | +| `[grpc] read_threads` | `32` | Index reads at once (blocks, tree states, transactions). | +| `[grpc] scan_threads` | `4` | Transparent-address history reads at once. Kept apart so a flood of them never slows block reads. | +| `[grpc] unread_timeout_secs` | `300` | A connection whose wallet stops reading for this long is closed. | +| `[serve] max_address_rows` | `100000` | Transparent receives one address request may walk; more is refused with `RESOURCE_EXHAUSTED`. | + +An IPv6 /64 counts as one address. The thread defaults suit NVMe; for other disks: + +| Disk | `read_threads` | `scan_threads` | +| ---------------------- | -------------- | -------------- | +| NVMe (default) | 32 | 4 | +| SATA SSD, cloud volume | 16 | 2 | +| HDD | 4 | 1 | + +## Limits + +Fixed, or sized from the host at startup: + +| Limit | Value | Over it | +| -------------------------------------- | ----------------------------------------------------- | -------------------------------- | +| connections | open-file limit − 1024, or half of memory at 128 KiB each, whichever is lower | closed | +| streams per connection | 100 | refused | +| requests in progress | 2048, lowered while the CPU falls behind (down to 128) | `UNAVAILABLE` | +| request size | 64 KiB, `SendTransaction` 2 MB | `RESOURCE_EXHAUSTED` | +| request upload time | 30 s | `DEADLINE_EXCEEDED` | +| responses waiting to be read, requests still uploading | a quarter of memory | the heaviest address's fullest connection closed | +| `/readyz`, `/status` | 10 at once, then 1 per second, per connection | `429` | + +- Startup logs the connection limit as `Connection cap`. Under 256, Zingod refuses to start: raise + the hard open-file limit (systemd `LimitNOFILE=`, docker `--ulimit nofile=`) or give it more + memory. +- A refusal ends a wallet's sync: pepper-sync and librustzcash do not retry. + +## Browser origins + +With [gRPC-web](network.md#browser-clients-grpc-web) on, any website can have browsers call your +server. Policies take effect within a second and survive restarts; the most specific one wins: + +| Command | Effect | +| ------------------------------ | --------------------------------------------------------- | +| `zingod origin block ` | refuse it and its subdomains with `PERMISSION_DENIED` | +| `zingod origin allow ` | serve it even when a parent domain is blocked | +| `zingod origin reset ` | remove its policy | +| `zingod origin` | list the policies | + +An allowed origin still gets the same limits as everyone else. + +## Overload + +`/readyz` reports `overloaded` (`503`) once 10% or more of connections, averaged over a minute, +are refused at the request limit or held back by a congested uplink. It clears under 2%. Zingod +keeps serving the whole time; only `/readyz` changes. Refusals past `work_share_per_ip` never +count. `zingod_grpc_overload_share` shows the share by `cause`. + +The uplink counts as congested when, for 30 seconds, the median of at least 10 sending +connections queues 50 ms or more, or 2% or more of bytes are resent. Connections through a trusted +proxy are not checked. + +## Troubleshooting + +| You see | Cause | Do this | +| --------------------------------------------------------- | ------------------------------ | ----------------------------- | +| refusals, `adaptive_stream_limit` under 2048 | CPU | more cores or nodes | +| refusals, limit at 2048, `read_wait_seconds{pool="read"}` high | disk | faster disk, more RAM | +| refusals, limit at 2048, `read_wait_seconds{pool="read"}` low | too many wallets | more nodes | +| `overload_share{cause="network"}` | uplink | more bandwidth or nodes | +| `connections_rejected_total` rising | connection limits | check `trusted_proxies` | +| `admission_rejected_total{reason="client_share"}` rising | one address sending too much | nothing: refused for you | +| `parked_evicted_total` rising | clients not reading or uploading slowly | nothing: closed for you | + +Metric names are prefixed `zingod_grpc_`. diff --git a/book/src/operators/maintenance.md b/book/src/operators/maintenance.md index cad4d46c2..833ee0e5f 100644 --- a/book/src/operators/maintenance.md +++ b/book/src/operators/maintenance.md @@ -29,30 +29,6 @@ so dashboards can tell planned maintenance from a crash. Both commands are idempotent. -## Overload - -A node that is persistently short of capacity reports `down` with reason `overloaded`, so load -balancers move traffic away from it. Thresholds are set under `[grpc.overload]` (0 disables a -cause). A cause is raised after its signal stays above the threshold for the enter time, and -cleared after it stays below half the threshold for the exit time. - -| Cause | Signal, per minute | Enter / exit | -| ---------------------------- | ------------------------------------------------------------- | ------------ | -| `CPU pressure`, `IO pressure` | share of time Zingod's cgroup waited (Linux PSI) | 2 / 3 min | -| `refusing work` | at least 10% of requests refused, at 1/s or more (exit: < 2%) | 5 / 5 min | - -Override the detector on a running node, without a restart: - -```sh -zingod overload off # never report overloaded -zingod overload on # back to automatic -zingod overload set # override a threshold, e.g. cpu_pressure_percent 40 -zingod overload unset # back to the config's value -``` - -Overrides are stored in `state_dir` and persist across restarts. Zingod applies them within a -second and logs a warning while any is in effect. - ## systemd ```ini diff --git a/book/src/operators/monitoring.md b/book/src/operators/monitoring.md index 36b960ce6..96906a890 100644 --- a/book/src/operators/monitoring.md +++ b/book/src/operators/monitoring.md @@ -8,7 +8,7 @@ Zingod reports a single state. The same value appears in `/readyz`, `/status`, t | State | Meaning | `/readyz` | | -------------- | ----------------------------------------------------------------------------------------- | --------- | | `held` | an operator ran [`zingod hold`](maintenance.md#operator-hold) | `503` | -| `down` | cannot serve: the server is stalled or [overloaded](maintenance.md#overload), startup is waiting for a validator, or the tip is unverified and stale | `503` | +| `down` | cannot serve: the server is stalled, startup is waiting for a validator, or the tip is unverified and stale; or [overloaded](dos-protection.md#overload): still serving, new wallets belong elsewhere | `503` | | `provisioning` | starting up, or installing an [index snapshot](first-sync.md#index-snapshot) | `503` | | `degraded` | serving a recent tip that no trusted validator has confirmed (p2p peers supplied it) | `200` | | `syncing` | serving, but behind the best block; or no validator's mempool is available yet | `503` | @@ -31,8 +31,8 @@ Zingod reports a single state. The same value appears in `/readyz`, `/status`, t | `serving` | `{start, mbps}`: gRPC egress over the last full 10-minute UTC window | | `degraded`, `down`, `held` | `{reason, message}` | -`reason` is one of `no_validator_reachable`, `tip_unvouched`, `tip_stale`, `runtime_stalled`, -`overloaded`, `goaway_pending` or `goaway_sent`. +`reason` is one of `no_validator_reachable`, `tip_unvouched`, `runtime_stalled`, `overloaded`, +`goaway_pending` or `goaway_sent`. ## Endpoints @@ -107,13 +107,17 @@ ts=… level=info target=zingod::telemetry::progress message="Syncing blocks" he ### The `Serving` line -Once a minute, the gRPC server logs a `Serving` summary: `rps` (streams completed per second) and -`conns` (open connections). It is logged at WARN if, during that minute, any request failed or -was refused, took more than a second to its first response (`slow`), stalled (`stalled`), or a -connection was refused at a limit (`conns_refused`). These fields appear only when non-zero. +Once a minute, the gRPC server logs a `Serving` summary: `rps` (requests completed per second) +and `conns` (open connections). If any request was refused (`UNAVAILABLE`, `RESOURCE_EXHAUSTED`) +or failed (`INTERNAL`, `UNKNOWN`, `DATA_LOSS`), or a connection was +[evicted](dos-protection.md#limits) that minute, it is logged at WARN with `refused`, `failed` +and `evicted` counts. The first failure of each minute is also logged as `Request failed` (ERROR) +with its message. Everything else is in the [metrics](#metrics). -- `INTERNAL`, `UNKNOWN` and `DATA_LOSS` count as failures. `UNAVAILABLE` and - `RESOURCE_EXHAUSTED` count as refusals. Other codes are client errors, counted in - `zingod_grpc_requests_total{code}`. -- The first failure of each minute is also logged as `Request failed` (ERROR), and the first - refusal not caused by capacity as `Request unavailable` (WARN). +Load events, each logged once as it starts and ends (see [Load and DoS protection](dos-protection.md)): + +| Starts (WARN) | Ends (INFO) | Fields | +| --------------------------------------------- | ---------------------- | --------------------------------------- | +| `Work limit lowered`: the CPU fell behind | `Work limit restored` | `limit`, `cpu_wait_ms` | +| `Uplink congested` | `Uplink clear` | `queue_delay_ms`, `retransmitted_percent` | +| `Overload latched`: `/readyz` 503 | `Overload cleared` | `refused_percent`, `network_percent`, `connections` | diff --git a/book/src/operators/network.md b/book/src/operators/network.md index e65efa997..d3df3c1f5 100644 --- a/book/src/operators/network.md +++ b/book/src/operators/network.md @@ -10,9 +10,8 @@ Zingod has two listeners: Connections to validators are plain HTTP JSON-RPC. -Limits on connections, streams and reads are set under `[grpc]`; see the -[reference](configuration.md#reference). When a limit is reached, the request is refused, not -queued. +Limits on connections, requests and reads are set under `[grpc]`; see +[Load and DoS protection](dos-protection.md). ## TLS @@ -46,36 +45,12 @@ after changing the listen address, delete `cert.pem`. allowing any origin. Native gRPC is unaffected. Enabling it makes the server usable from any website. A popular site embedding it can send load -proportional to its own traffic. - -`zingod origin` manages per-origin policy. Changes apply within a second and persist until -changed: - -| Command | Effect | -| ------------------------------- | -------------------------------------------------------------- | -| `zingod origin block ` | refuse requests from the origin with `PERMISSION_DENIED` | -| `zingod origin allow ` | serve the origin even when a parent domain is blocked | -| `zingod origin reset ` | remove the origin's policy | -| `zingod origin` | list the policies in effect | - -- Policies apply to the registrable domain and its subdomains. The most specific policy wins, so - `allow app.example.com` can override `block example.com`. -- Every origin that is not blocked meets the same limits as any other client. Clients can set any - `Origin` header, so an origin never lifts a limit. -- `zingod_grpc_origin_requests_total{verdict}` counts browser requests by policy. To find an - abusive origin, check your proxy or edge logs. +proportional to its own traffic. To refuse a site, see [Browser +origins](dos-protection.md#browser-origins). Over HTTP/1.1, browsers open one connection per in-flight stream, each counting against `max_connections_per_ip`. Serve over TLS so browsers use HTTP/2. -## Stream timeouts - -Streams have no total time limit. Two settings close streams that stop making progress: - -- `unread_timeout_secs`: the client stopped reading. The connection is closed. -- `silent_timeout_secs`: the server has had nothing to send. The stream ends with `UNAVAILABLE`. - `GetMempoolStream` is exempt. - ## Behind a proxy Behind a proxy, every connection comes from the proxy's address, so `max_connections_per_ip` would @@ -113,10 +88,4 @@ stream { For HAProxy, use `server zingod 127.0.0.1:8137 send-proxy-v2` in a `mode tcp` backend. If your proxy cannot send the header, leave `trusted_proxies` empty and raise -`max_connections_per_ip` to `max_connections`. - -## Open files - -Each connection uses a file descriptor. At startup, Zingod raises its soft `RLIMIT_NOFILE` to the -hard limit and refuses to start if `max_connections` plus 1024 does not fit. Raise the hard limit -(`LimitNOFILE=` in systemd, `--ulimit nofile=` in Docker) or lower `max_connections`. +`max_connections_per_ip` past the connection limit Zingod logs at startup (`Connection cap`). diff --git a/book/src/operators/zingod.toml b/book/src/operators/zingod.toml index 60297aab1..e8c77e5ee 100644 --- a/book/src/operators/zingod.toml +++ b/book/src/operators/zingod.toml @@ -106,34 +106,24 @@ hold_goaway_delay_secs = 0 # client that pins it connects) # tls = { cert_path = "/etc/zingod/fullchain.pem", key_path = "/etc/zingod/key.pem" } -# Serving caps (defaults shown); every cap refuses rather than queues, except the read lanes +# Serving caps (defaults shown); every cap refuses rather than queues. Total connections and work +# are sized from the host (open-file limit, memory) and zingod's own speed, never set here +# - https://zingolabs.github.io/zingod/operators/dos-protection.html [grpc] -# excess accepts closed; + 1024 must fit the open-file limit or boot fails -max_connections = 4096 # per client: the peer, or the address a trusted proxy's PROXY header names max_connections_per_ip = 128 -# HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS: every stream on one connection, of any method (as -# lightwalletd's grpc-max-concurrent-streams) -max_streams_per_connection = 100 -# work streams (every method but GetMempoolStream) across all connections; excess = UNAVAILABLE + -# retry hint -max_work_streams = 2048 -# work streams admitted at once follow measured latency, max_work_streams the ceiling: a saturated -# node refuses new work within seconds (UNAVAILABLE + retry hint); false = always max_work_streams -adaptive_work_streams = true -# GetMempoolStream subscriptions (idle until the next block), counted apart from max_work_streams -max_subscriptions = 4096 -# index reads in flight on the blocking pool, per lane; excess waits in its own lane -# - point: one block / tree state / root list; range: one GetBlockRange window; scan: one address -# history -max_point_reads = 64 -max_range_reads = 32 -max_scan_reads = 4 -# no-progress bounds, never a cap on a stream's length (the client's grpc-timeout is its deadline) -# data its client does not read for this long closes its connection +# share of the work limit one address (an IPv6 /64) may hold: 1/16 takes 16 to fill the node; +# 1.0 = none (a load test from a few addresses) +work_share_per_ip = 0.0625 +# threads reading index files for wallets, oldest read first: the disk under the indexes' useful +# parallelism +# - https://zingolabs.github.io/zingod/operators/dos-protection.html#settings +read_threads = 32 +# threads for transparent-address history reads, apart so a flood of them never slows block reads +scan_threads = 4 +# data its client does not read for this long closes its connection (no cap on a stream's length: +# the client's grpc-timeout is its deadline) unread_timeout_secs = 300 -# a stream with nothing to send for this long ends UNAVAILABLE (GetMempoolStream exempt) -silent_timeout_secs = 300 # GOAWAY after this long (±10% per connection): the client reconnects and re-resolves DNS, so a # load balancer or a replaced node moves long-held wallet connections; 0 = never max_connection_age_secs = 1800 @@ -149,12 +139,6 @@ trusted_proxies = [] # - https://zingolabs.github.io/zingod/operators/maintenance.html#operator-hold shutdown_grace_secs = 10 -# When /readyz reports `Overloaded: ` (0 = that cause off; `zingod overload` overrides live) -[grpc.overload] -# share of each minute zingod's cgroup waited (Linux PSI) -cpu_pressure_percent = 25 -io_pressure_percent = 25 - # One block-fetch pipeline, shared by every index (defaults shown; all non-zero) [sync] # Blocks below the tip kept reorg-able (in memory, served, written once buried); >= 1000 off regtest diff --git a/book/src/wallets/connecting.md b/book/src/wallets/connecting.md index b7ace9c8a..642e19c39 100644 --- a/book/src/wallets/connecting.md +++ b/book/src/wallets/connecting.md @@ -48,7 +48,6 @@ Defaults are shown; operators can change them. | idle connection | closed after 30 minutes | | in-flight streams after a GOAWAY | 10 minutes to finish | | client not reading a stream | connection closed after 5 minutes | -| stream with nothing to send | ends `UNAVAILABLE` after 5 minutes (except `GetMempoolStream`) | Streams have no total time limit, so a full-chain `GetBlockRange` runs for as long as the client keeps reading. gRPC libraries reconnect after a GOAWAY on their own. A server being taken out of diff --git a/book/src/wallets/status-codes.md b/book/src/wallets/status-codes.md index cd8142ac9..3b1dab74f 100644 --- a/book/src/wallets/status-codes.md +++ b/book/src/wallets/status-codes.md @@ -5,7 +5,7 @@ status; it is reported in the response ([details](methods.md#transactions)). | Code | When | Client action | | -------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------- | -| `UNAVAILABLE` | the server is starting, at capacity, or cannot reach its data sources; a stream had nothing to send for 5 minutes | retry with backoff | +| `UNAVAILABLE` | the server is starting, at capacity, or cannot reach its data sources | retry with backoff | | `NOT_FOUND` | the height, hash or txid is not in the chain, or is above the index's tip | do not retry the same request | | `OUT_OF_RANGE` | `GetBlockRange` reached the tip, after sending every block up to it | retry once the tip advances | | `INVALID_ARGUMENT` | malformed request, height above the protocol maximum, invalid or wrong-network address, invalid `poolTypes` | fix the request | diff --git a/packages/zingod-grpc/Cargo.toml b/packages/zingod-grpc/Cargo.toml index c88da099a..32a8aa7f0 100644 --- a/packages/zingod-grpc/Cargo.toml +++ b/packages/zingod-grpc/Cargo.toml @@ -59,6 +59,12 @@ rcgen.workspace = true aws-lc-rs = "1.19.0" tonic-web = "0.14" tower-http = { version = "0.6", features = ["cors"] } +rayon.workspace = true +netlink-packet-sock-diag = { version = "0.5", features = ["rich_nlas"] } +netlink-sys = "0.9" +netlink-packet-core = "0.9" +tokio-metrics = { version = "0.5.2", default-features = false } +hyper.workspace = true [dev-dependencies] tempfile = { workspace = true } diff --git a/packages/zingod-grpc/src/adaptive.rs b/packages/zingod-grpc/src/adaptive.rs index 2fba48e28..2aa4c18d0 100644 --- a/packages/zingod-grpc/src/adaptive.rs +++ b/packages/zingod-grpc/src/adaptive.rs @@ -1,96 +1,86 @@ -//! Adaptive work-stream limit: Netflix concurrency-limits' Gradient2 over server time per message +//! Adaptive work-stream limit: Netflix concurrency-limits' Gradient2 over sustained CPU queueing //! -//! - sample = time the server spent producing one message (admission → first DATA frame, then -//! each poll → the next) -//! - client backpressure never counts (hyper stops polling) -//! - per window: `limit × clamp(TOLERANCE × long / short, 0.5, 1) + √limit`, smoothed, in -//! `floor..=ceiling` (`max_work_streams`) -//! - window whose peak in flight < limit / 2 = app-limited: no change (a quiet node never inflates) -//! - refusal unchanged: `UNAVAILABLE` + pushback (`admission.rs`) - -use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering::Relaxed}; +//! - [`WORK_CEILING`] until the CPU falls behind; the limit = a shed, never a guess at capacity +//! - sample = the gRPC tasks' scheduling delay: woken (ready) → polled, i.e. waiting for a core +//! (`tokio_metrics::TaskMonitor`); a task waiting on a disk read, a client or the network is +//! not ready, so none of those count (shedding cannot speed them up) +//! - decision = median of 10 windows, so a block rush (≤ 2 s) moves ≤ 4 of them +//! - rules + their measured basis: `usage.md` "Serve stack", adaptive limit + +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; use std::sync::Mutex; use std::time::Duration; -use tokio::time::Instant; +use tokio::time::MissedTickBehavior; +use tokio_metrics::TaskMonitor; +use tokio_util::sync::CancellationToken; +use tracing::{info, warn}; + +use crate::metrics; /// Fixed-point scale of the estimated limit and the gradient (integer Gradient2) -const MILLI: usize = 1000; +const MILLI: u64 = 1000; -/// Short-term RTT may reach this × the long-term baseline before the limit shrinks (‰) -const TOLERANCE_MILLI: u64 = 1500; +/// Median scheduling delay over this = the CPU is falling behind +/// - bench (2 cores, 12k wallets): delay 7 → 158 ms with load; never shedding failed 6k sessions +/// (tip p99 1.2 s), a 20 ms budget 21k (refusals end syncs): shed only where waits hurt +const BUDGET: Duration = Duration::from_millis(100); -/// Gradient bounds (‰) -const GRADIENT_MILLI: std::ops::RangeInclusive = 500..=1000; +/// Decisions over budget in a row before the first shrink (15 s: a rush never lasts it) +const SUSTAIN: u32 = 3; -/// Weight of each window's new limit = 1 / SMOOTHING_PARTS -const SMOOTHING_PARTS: usize = 5; +/// Largest single shrink (‰ of the limit), then smoothed: weight of a step = 1 / SMOOTHING_PARTS +const MIN_GRADIENT_MILLI: u64 = 500; +const SMOOTHING_PARTS: u64 = 5; -/// Windows the long-term RTT averages over (5 min at [`WINDOW`]) -const LONG_WINDOWS: u64 = 600; +/// Healthy decision → limit × this (‰): floor to ceiling in ~2.5 min +const GROWTH_MILLI: u64 = 1100; -/// A window closes once both this long and [`WINDOW_SAMPLES`] in +/// One window = this long, counted once ≥ [`WINDOW_WAKES`] (an idle node decides nothing); a +/// decision = [`DECISION_WINDOWS`] of them const WINDOW: Duration = Duration::from_millis(500); -const WINDOW_SAMPLES: u32 = 10; +const WINDOW_WAKES: u64 = 10; +const DECISION_WINDOWS: usize = 10; -/// Lowest adaptive limit (clamped to the ceiling) -const FLOOR: usize = 32; +/// Lowest limit while shedding (clamped to the ceiling) +const FLOOR: usize = 128; -/// Starting limit (clamped to `FLOOR..=ceiling`): growth needs load, so a cold start admits a burst -const INITIAL: usize = 256; +/// Limit while the CPU keeps up (a full disk fills it → refusals → overload: the disk's signal) +pub(crate) const WORK_CEILING: usize = 2048; -/// `adaptive` off = the limit stays the ceiling -/// -/// - `sample` = relaxed atomics only; the one sample that closes a window takes `gradient` +/// The limit, moved only by [`Limiter::window`]'s decisions #[derive(Debug)] pub(crate) struct Limiter { limit: AtomicUsize, floor: usize, ceiling: usize, - adaptive: bool, - window: OpenWindow, gradient: Mutex, } -/// Samples since the last close (`opened_us` = that close, since `epoch`) -/// -/// - a sample racing the close may land in either window (±1 of ≥ [`WINDOW_SAMPLES`]) +/// `windows` = this decision's window delays; `over` = decisions over budget in a row #[derive(Debug)] -struct OpenWindow { - epoch: Instant, - opened_us: AtomicU64, - sum_us: AtomicU64, - samples: AtomicU32, - peak: AtomicUsize, +struct Gradient { + estimated_milli: u64, + windows: Vec, + over: u32, } -/// `long_ns` = baseline RTT (`None` before the first window) -#[derive(Debug)] -struct Gradient { - estimated_milli: usize, - long_ns: Option, +/// One decision's outcome (its limit + the median delay it weighed) +struct Decision { + limit: u64, + delay_ns: u64, } impl Limiter { - pub(crate) fn new(ceiling: usize, adaptive: bool) -> Self { - let floor = FLOOR.min(ceiling); - let initial = if adaptive { INITIAL.clamp(floor, ceiling) } else { ceiling }; - let window = OpenWindow { - epoch: Instant::now(), - opened_us: AtomicU64::new(0), - sum_us: AtomicU64::new(0), - samples: AtomicU32::new(0), - peak: AtomicUsize::new(0), - }; + pub(crate) fn new(ceiling: usize) -> Self { Self { - limit: AtomicUsize::new(initial), - floor, + limit: AtomicUsize::new(ceiling), + floor: FLOOR.min(ceiling), ceiling, - adaptive, - window, gradient: Mutex::new(Gradient { - estimated_milli: initial.saturating_mul(MILLI), - long_ns: None, + estimated_milli: wide(ceiling).saturating_mul(MILLI), + windows: Vec::with_capacity(DECISION_WINDOWS), + over: 0, }), } } @@ -99,63 +89,76 @@ impl Limiter { self.limit.load(Relaxed) } - /// One message's production time, `in_flight` work streams as it landed - pub(crate) fn sample(&self, took: Duration, in_flight: usize) { - if !self.adaptive { - return; - } - let window = &self.window; - let micros = |duration: Duration| u64::try_from(duration.as_micros()).unwrap_or(u64::MAX); - window.sum_us.fetch_add(micros(took), Relaxed); - let samples = window.samples.fetch_add(1, Relaxed) + 1; - window.peak.fetch_max(in_flight, Relaxed); - let (now, opened) = (micros(window.epoch.elapsed()), window.opened_us.load(Relaxed)); - // saturating: a racing closer may have stamped a later `now` than ours - if now.saturating_sub(opened) < micros(WINDOW) || samples < WINDOW_SAMPLES { - return; - } - // one closer per window - if window.opened_us.compare_exchange(opened, now, Relaxed, Relaxed).is_err() { - return; + /// Until `cancel`: every [`WINDOW`], `tasks`' mean scheduling delay (idle windows skipped) + pub(crate) async fn follow(&self, tasks: &TaskMonitor, cancel: &CancellationToken) { + let mut intervals = tasks.intervals(); + let mut ticks = tokio::time::interval(WINDOW); + ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = cancel.cancelled() => return, + _ = ticks.tick() => {} + } + let Some(window) = intervals.next() else { return }; + if window.total_scheduled_count >= WINDOW_WAKES { + self.window(window.mean_scheduled_duration()); + } } - let sum_ns = window.sum_us.swap(0, Relaxed).saturating_mul(1000); - let (samples, peak) = (window.samples.swap(0, Relaxed), window.peak.swap(0, Relaxed)); + } + + /// One window's mean scheduling delay; every [`DECISION_WINDOWS`]th decides + fn window(&self, delay: Duration) { + let delay_ns = u64::try_from(delay.as_nanos()).unwrap_or(u64::MAX); let mut gradient = self.gradient.lock().expect("adaptive limiter poisoned"); - let limit = - gradient.update(sum_ns / u64::from(samples.max(1)), peak, self.floor, self.ceiling); - self.limit.store(limit, Relaxed); + let range = + wide(self.floor).saturating_mul(MILLI)..=wide(self.ceiling).saturating_mul(MILLI); + if let Some(decided) = gradient.window(delay_ns, range) { + let limit = usize::try_from(decided.limit).expect("limit <= ceiling, a usize"); + let was = self.limit.swap(limit, Relaxed); + let delay = Duration::from_nanos(decided.delay_ns); + let cpu_wait_ms = delay.as_millis(); + match (was == self.ceiling, limit == self.ceiling) { + (true, false) => warn!(limit, cpu_wait_ms, "Work limit lowered"), + (false, true) => info!(limit, cpu_wait_ms, "Work limit restored"), + _ => {} + } + metrics::adaptive_decided(limit, self.ceiling, delay); + } } } +fn wide(value: usize) -> u64 { + u64::try_from(value).expect("usize fits u64") +} + impl Gradient { - /// Gradient2's update, one closed window (`short_ns` = its mean RTT, `peak` = most in flight) - fn update(&mut self, short_ns: u64, peak: usize, floor: usize, ceiling: usize) -> usize { - // a zero-time window carries no signal (and would divide by zero) - let short = short_ns.max(1); - let long = self.long_ns.get_or_insert(short); - match short >= *long { - true => *long += (short - *long) / LONG_WINDOWS, - false => *long -= (*long - short) / LONG_WINDOWS, - } - // load gone: the baseline follows the faster RTT down - if *long > short.saturating_mul(2) { - *long -= *long / 20; + /// One window's delay; every [`DECISION_WINDOWS`]th decides (`range` = floor..=ceiling, ‰) + fn window(&mut self, delay_ns: u64, range: std::ops::RangeInclusive) -> Option { + self.windows.push(delay_ns); + if self.windows.len() < DECISION_WINDOWS { + return None; } + // upper median: ≥ 6 of 10 windows slow before a decision is + let (_, &mut median, _) = self.windows.select_nth_unstable(DECISION_WINDOWS / 2); + self.windows.clear(); + let delay = median.max(1); + let budget = u64::try_from(BUDGET.as_nanos()).expect("budget fits u64"); + let over = delay > budget; + self.over = if over { self.over.saturating_add(1) } else { 0 }; let estimated = self.estimated_milli; - if peak.saturating_mul(2 * MILLI) < estimated { - return estimated / MILLI; - } - let gradient = TOLERANCE_MILLI.saturating_mul(*long) / short; - let gradient = gradient.clamp(*GRADIENT_MILLI.start(), *GRADIENT_MILLI.end()); - let gradient = usize::from(u16::try_from(gradient).expect("clamped to <= 1000")); - // √(e / MILLI) × MILLI = √(e × MILLI) - let next = - estimated.saturating_mul(gradient) / MILLI + estimated.saturating_mul(MILLI).isqrt(); - let smoothed = - estimated.saturating_mul(SMOOTHING_PARTS - 1).saturating_add(next) / SMOOTHING_PARTS; - self.estimated_milli = - smoothed.clamp(floor.saturating_mul(MILLI), ceiling.saturating_mul(MILLI)); - self.estimated_milli / MILLI + let next = match over { + false => estimated.saturating_mul(GROWTH_MILLI) / MILLI, + true if self.over < SUSTAIN => estimated, + true => { + // how far over the budget = how hard to shrink (at most halved, smoothed 1/5) + let gradient = + (budget.saturating_mul(MILLI) / delay).clamp(MIN_GRADIENT_MILLI, MILLI); + let shrunk = estimated.saturating_mul(gradient) / MILLI; + (estimated.saturating_mul(SMOOTHING_PARTS - 1) + shrunk) / SMOOTHING_PARTS + } + }; + self.estimated_milli = next.clamp(*range.start(), *range.end()); + Some(Decision { limit: self.estimated_milli / MILLI, delay_ns: delay }) } } @@ -164,71 +167,61 @@ mod tests { use super::*; const CEILING: usize = 2048; - /// In flight past any limit here: every window loaded - const LOADED: usize = 2 * CEILING; - - /// `count` windows passed (paused clock), each filled with `rtt` samples at `in_flight`: the - /// limit after each - async fn windows(limiter: &Limiter, count: usize, rtt_ms: u64, in_flight: usize) -> Vec { - let mut limits = Vec::with_capacity(count); - for _ in 0..count { - tokio::time::advance(WINDOW).await; - for _ in 0..WINDOW_SAMPLES { - limiter.sample(Duration::from_millis(rtt_ms), in_flight); - } - limits.push(limiter.limit()); - } - limits + const QUICK: Duration = Duration::from_micros(200); + const SLOW: Duration = Duration::from_millis(300); + + /// `count` windows, each at `delay`: the limit after each + fn windows(limiter: &Limiter, count: usize, delay: Duration) -> Vec { + (0..count) + .map(|_| { + limiter.window(delay); + limiter.limit() + }) + .collect() } - /// ≈ +√limit / 5 per window - #[tokio::test(start_paused = true)] - async fn a_loaded_limiter_at_a_steady_rtt_grows_from_initial() { - let limiter = Limiter::new(CEILING, true); - assert_eq!(limiter.limit(), INITIAL, "cold start"); - - let grown = windows(&limiter, 20, 10, LOADED).await; + /// A node's day of block rushes: 2 s at 300 ms (3× the budget), every 75 s, for 30 min + #[test] + fn block_rushes_never_move_the_limit_off_its_ceiling() { + let limiter = Limiter::new(CEILING); + let mut seen = Vec::new(); - let shrank = grown.windows(2).find(|pair| pair[1] < pair[0]); - assert_eq!(shrank, None, "steady 10 ms RTT never shrinks: {grown:?}"); - let last = *grown.last().expect("20 windows"); - assert!(last > INITIAL + 40, "20 windows from {INITIAL}: {grown:?}"); - } + for _ in 0..24 { + seen.extend(windows(&limiter, 4, SLOW)); + seen.extend(windows(&limiter, 146, QUICK)); + } - /// Baseline 10 ms; floor = `FLOOR` - #[tokio::test(start_paused = true)] - async fn rtt_past_the_tolerance_shrinks_the_limit_to_the_floor_and_recovery_grows_it() { - let limiter = Limiter::new(CEILING, true); - let before = *windows(&limiter, 20, 10, LOADED).await.last().expect("20 windows"); - - let shrunk = windows(&limiter, 10, 40, LOADED).await; - let floored = windows(&limiter, 200, 400, LOADED).await; - let recovered = windows(&limiter, 20, 10, LOADED).await; - - let after = *shrunk.last().expect("10 windows"); - assert!(after < before / 2, "5 s at 4× the RTT: {before} → {shrunk:?}"); - assert_eq!(floored.last(), Some(&FLOOR), "100 s at 40× the RTT"); - let regrown = *recovered.last().expect("20 windows"); - assert!(regrown > FLOOR, "RTT back to 10 ms: grows from {FLOOR}: {recovered:?}"); + assert!(seen.iter().all(|&limit| limit == CEILING), "a rush shed work: {seen:?}"); } - /// Peak in flight < limit / 2: a quiet node never inflates or deflates - #[tokio::test(start_paused = true)] - async fn an_app_limited_limiter_holds_its_limit_as_rtt_rises() { - let limiter = Limiter::new(CEILING, true); - let quiet = windows(&limiter, 1, 10, 1).await; - - let slow = windows(&limiter, 20, 400, 1).await; - - assert_eq!(slow, vec![quiet[0]; 20], "1 in flight under {}", quiet[0]); + /// 200 µs, then 300 ms sustained (3× the 100 ms budget), then back + #[test] + fn sustained_cpu_queueing_sheds_after_fifteen_seconds_to_the_floor_and_recovery_regrows() { + let limiter = Limiter::new(CEILING); + windows(&limiter, 60, QUICK); + + let first_two_decisions = windows(&limiter, 20, SLOW); + let third = windows(&limiter, 10, SLOW); + let sustained = windows(&limiter, 400, SLOW); + let recovered = windows(&limiter, 400, QUICK); + + let (shed, settled) = (third[9], *sustained.last().expect("400 windows")); + assert!(first_two_decisions.iter().all(|&limit| limit == CEILING), "10 s: no shed yet"); + // halving (gradient floor 0.5) smoothed 1/5: × 0.9 + assert_eq!(shed, CEILING * 9 / 10, "15 s: one smoothed step"); + assert_eq!(settled, FLOOR, "sustained 3× the budget: down to the floor"); + assert!(sustained.iter().all(|&limit| limit >= FLOOR), "never under the floor"); + assert_eq!(recovered.last(), Some(&CEILING), "200 s back at 200 µs: the ceiling again"); } - #[tokio::test(start_paused = true)] - async fn a_fixed_limiter_stays_at_its_ceiling() { - let fixed = Limiter::new(CEILING, false); + /// Any delay up to the budget, sustained: never a shed + #[test] + fn queueing_up_to_the_budget_never_sheds() { + let limiter = Limiter::new(CEILING); - let limits = windows(&fixed, 20, 400, LOADED).await; + let busy = windows(&limiter, 600, Duration::from_millis(50)); + let at_budget = windows(&limiter, 600, BUDGET); - assert_eq!(limits, vec![CEILING; 20], "adaptive off, 40× RTT under load"); + assert!(busy.iter().chain(&at_budget).all(|&limit| limit == CEILING), "{busy:?}"); } } diff --git a/packages/zingod-grpc/src/admission.rs b/packages/zingod-grpc/src/admission.rs index 12ceda573..a27ca2711 100644 --- a/packages/zingod-grpc/src/admission.rs +++ b/packages/zingod-grpc/src/admission.rs @@ -1,23 +1,29 @@ -//! Stream admission: a [`Slot`], or `UNAVAILABLE` + pushback, never a queue +//! Work-stream admission: a [`Slot`] under the adaptive limit, or `UNAVAILABLE` + pushback //! -//! - Slot owned by the response *body* (`guard.rs`), not the handler (released at handler return -//! = unbounded streams) -//! - Two pools by [`Class`]: a subscription idles for a block, so it never holds a work slot (one -//! mempool stream per wallet would otherwise fill `max_work_streams` with idlers) -//! - Work held exactly to the adaptive limit (`adaptive.rs`), fed each message's production time - -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; +//! - slot held for the stream's life (bounds work in progress), except one whose client has not +//! read for [`GRACE`](crate::stall::GRACE) while slots run short: reclaimed (`stall.rs`) +//! - reclaimed, then read on: takes a slot back even past the limit (never refused mid-stream; +//! newcomers refused until it drains, and the limit sheds if the overshoot queues the CPU) +//! - `GetMempoolStream` takes none (idle until the next block: bounded by the connection caps) +//! - the limit follows the gRPC tasks' CPU queueing (`tasks`, `adaptive.rs`) +//! - one client (IPv4 address, IPv6 /64) holds at most its [`WorkShare`] of it (default 1/16): +//! filling it takes a crowd; a client refused over its share = its own doing, no overload + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use http::{HeaderValue, Response}; -use tokio::time::Instant; +use tokio_metrics::TaskMonitor; +use tokio_util::sync::CancellationToken; use tonic::Status; use crate::adaptive::Limiter; +use crate::limits::WorkShare; use crate::metrics; -use crate::overload::{Overload, OverloadCause, Signals}; -use crate::OverloadLimits; +use crate::overload::{Overload, Wallet}; +use crate::stall::Client; /// Refusal retry hint, ms (held streams = wallet syncs: a slot frees well under a second) const PUSHBACK_MS: &str = "250"; @@ -25,42 +31,73 @@ const PUSHBACK_MS: &str = "250"; /// gRPC's own "come back later" header (grpc-core) const PUSHBACK_HEADER: &str = "grpc-retry-pushback-ms"; -/// Cap a request counts against (each method's in [`Method::route`](crate::service::Method::route), -/// unknown path = `Work`) -/// -/// - `Work` = unary, ranges, scans -/// - `Subscription` = open until the next block, idle between arrivals -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Class { - Work, - Subscription, -} - -/// The two admission pools, the adaptive work limit and their outcomes, shared by every connection +/// Work streams holding a slot, the adaptive limit and its outcomes, shared by every connection /// ([`GrpcService::admission`](crate::GrpcService::admission) = its readiness view) +/// +/// - `refused` = a newcomer refused since the last reclaim sweep looked +/// - `tasks` = every connection's and stream's task, timed woken → polled (the limiter's input) +/// - `clients` = live work streams per client, reclaimed or not (entry gone at 0) #[derive(Debug)] pub struct AdmissionState { - work: AtomicUsize, - subscriptions: AtomicUsize, - max_subscriptions: usize, + held: AtomicUsize, + clients: Mutex>, + share: WorkShare, limiter: Limiter, overload: Overload, + refused: AtomicBool, + tasks: TaskMonitor, } impl AdmissionState { - pub(crate) fn new(limits: &crate::GrpcLimits) -> Self { + /// `ceiling` = [`WORK_CEILING`](crate::adaptive::WORK_CEILING) (tests: smaller, to refuse) + pub(crate) fn new(ceiling: usize, share: WorkShare) -> Self { Self { - work: AtomicUsize::new(0), - subscriptions: AtomicUsize::new(0), - max_subscriptions: limits.max_subscriptions.get(), - limiter: Limiter::new(limits.max_work_streams.get(), limits.adaptive_work_streams), - overload: Overload::new(limits.overload.clone()), + held: AtomicUsize::new(0), + clients: Mutex::new(HashMap::new()), + share, + limiter: Limiter::new(ceiling), + overload: Overload::default(), + refused: AtomicBool::new(false), + tasks: TaskMonitor::new(), + } + } + + /// Where gRPC's tasks are spawned instrumented (`transport.rs`: connections, hyper's streams) + pub(crate) fn tasks(&self) -> &TaskMonitor { + &self.tasks + } + + /// Until `cancel`: the limit follows the tasks' CPU queueing (`adaptive.rs`) + pub(crate) async fn adapt(&self, cancel: &CancellationToken) { + self.limiter.follow(&self.tasks, cancel).await; + } + + /// Worth a reclaim sweep: a newcomer refused since the last, or within 1/16 of the limit + pub(crate) fn pressed(&self) -> bool { + let limit = self.limiter.limit(); + let held = self.held.load(Ordering::Relaxed); + self.refused.swap(false, Ordering::Relaxed) || held.saturating_add(limit / 16) >= limit + } + + fn release(&self) { + self.held.fetch_sub(1, Ordering::Relaxed); + metrics::stream_released(); + } + + /// A stream of `client`'s ended (its share counts live streams, reclaimed or not) + fn ended(&self, client: Client) { + let mut clients = self.clients.lock().expect("client shares mutex poisoned"); + if let Some(live) = clients.get_mut(&client) { + *live -= 1; + if *live == 0 { + clients.remove(&client); + } } } - /// First latched cause as of the last serving summary (rules: `overload.rs`) - pub fn overload(&self) -> Option { - self.overload.cause() + /// Hurting wallets persistently, as of the last overload window (rules: `overload.rs`) + pub fn overloaded(&self) -> bool { + self.overload.latched() } #[cfg(test)] @@ -68,84 +105,125 @@ impl AdmissionState { self.limiter.limit() } - /// The operator's overload thresholds + whether a latched cause is reported (next window on) - pub fn set_overload(&self, limits: OverloadLimits, detection: bool) { - self.overload.set(limits, detection); + /// One overload tick (`elapsed` long, `connections` open now) + pub(crate) fn tick(&self, elapsed: Duration, connections: usize) { + self.overload.tick(elapsed, connections); } - /// Closes a serving summary's window (`elapsed` long, on its `signals`): its refusals, every - /// class - pub(crate) fn tick(&self, elapsed: Duration, signals: Signals) -> u64 { - metrics::adaptive_stream_limit(self.limiter.limit()); - self.overload.tick(elapsed, signals) + /// A connection accepted (the overload share's denominator) + pub(crate) fn connected(&self) { + self.overload.connected(); } - /// `class`'s pool + its limit now (work: the adaptive one) - fn pool(&self, class: Class) -> (&AtomicUsize, usize) { - match class { - Class::Work => (&self.work, self.limiter.limit()), - Class::Subscription => (&self.subscriptions, self.max_subscriptions), - } + /// Mean connections a congested uplink holds back now, 0 = clear (uplink sampler) + pub(crate) fn network_waiting(&self, connections: f64) { + self.overload.network_waiting(connections); } - /// Streams of `class` held now - pub(crate) fn held(&self, class: Class) -> usize { - self.pool(class).0.load(Ordering::Relaxed) + #[cfg(test)] + pub(crate) fn held(&self) -> usize { + self.held.load(Ordering::Relaxed) } - /// A slot, or `None` = refused at once at the class's limit - pub(crate) fn admit(self: &Arc, class: Class) -> Option { - let (held, limit) = self.pool(class); + /// A slot, or refused at once: `client` at its share (live streams), or the limit full + pub(crate) fn admit( + self: &Arc, + wallet: &Wallet, + client: Client, + ) -> Result { + let limit = self.limiter.limit(); + let mut clients = self.clients.lock().expect("client shares mutex poisoned"); + if clients.get(&client).is_some_and(|&live| live >= self.share.of(limit)) { + metrics::stream_rejected(Refusal::ClientShare); + return Err(Refusal::ClientShare); + } let taken = |held: usize| (held < limit).then_some(held + 1); - if held.fetch_update(Ordering::Relaxed, Ordering::Relaxed, taken).is_err() { - self.overload.refused(class); - return None; + if self.held.fetch_update(Ordering::Relaxed, Ordering::Relaxed, taken).is_err() { + self.refused.store(true, Ordering::Relaxed); + self.overload.refused(wallet); + metrics::stream_rejected(Refusal::Limit); + return Err(Refusal::Limit); } - self.overload.admitted(class); - metrics::stream_admitted(class); - Some(Slot { class, admission: Arc::clone(self), busy_since: Some(Instant::now()) }) + *clients.entry(client).or_insert(0) += 1; + metrics::stream_admitted(); + let claim = Claim { held: AtomicBool::new(true), admission: Arc::clone(self) }; + Ok(Slot { claim: Arc::new(claim), client }) } } -/// One admitted stream's place in its pool, back on drop +/// Why a work stream was refused +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Refusal { + Limit, + ClientShare, +} + +impl Refusal { + pub(crate) const fn label(self) -> &'static str { + match self { + Self::Limit => "limit", + Self::ClientShare => "client_share", + } + } + + /// `UNAVAILABLE` + pushback hint, before any handler runs + pub(crate) fn response(self) -> Response { + let message = match self { + Self::Limit => "work stream limit reached", + Self::ClientShare => "per-client work stream share reached", + }; + let mut response = Status::unavailable(message).into_http(); + response.headers_mut().insert(PUSHBACK_HEADER, HeaderValue::from_static(PUSHBACK_MS)); + response + } +} + +/// A stream's slot, shared with the reclaim sweep (`held` = false: reclaimed) /// -/// - `busy_since` = producing its next message since (`None` = handed one, not polled since) +/// - each release is a `held` swap: the sweep and the stream's end never both release #[derive(Debug)] -pub(crate) struct Slot { - class: Class, +pub(crate) struct Claim { + held: AtomicBool, admission: Arc, - busy_since: Option, +} + +impl Claim { + /// Its slot back to the pool (`false` = already) + pub(crate) fn reclaim(&self) -> bool { + let held = self.held.swap(false, Ordering::AcqRel); + if held { + self.admission.release(); + } + held + } +} + +/// One admitted stream's hold on work, for its whole life (its client's share: until it ends, +/// reclaimed or not, so reclaim-then-reopen never grows a share) +#[derive(Debug)] +pub(crate) struct Slot { + claim: Arc, + client: Client, } impl Slot { - pub(crate) fn polled(&mut self) { - self.busy_since.get_or_insert_with(Instant::now); + /// What the reclaim sweep may take back while its client is not reading + pub(crate) fn claim(&self) -> Arc { + Arc::clone(&self.claim) } - /// A data frame out: one work message's production time to the limiter - pub(crate) fn handed(&mut self) { - let since = self.busy_since.take(); - if let (Class::Work, Some(since)) = (self.class, since) { - let in_flight = self.admission.held(Class::Work); - self.admission.limiter.sample(since.elapsed(), in_flight); + /// Polled again: a reclaimed slot taken back, past the limit if need be + pub(crate) fn resume(&self) { + if !self.claim.held.swap(true, Ordering::AcqRel) { + self.claim.admission.held.fetch_add(1, Ordering::Relaxed); + metrics::stream_admitted(); } } } impl Drop for Slot { fn drop(&mut self) { - self.admission.pool(self.class).0.fetch_sub(1, Ordering::Relaxed); - metrics::stream_released(self.class); + self.claim.reclaim(); + self.claim.admission.ended(self.client); } } - -/// `UNAVAILABLE` + pushback hint, before any handler runs -pub(crate) fn refused(class: Class) -> Response { - let message = match class { - Class::Work => "work stream limit reached", - Class::Subscription => "subscription limit reached", - }; - let mut response = Status::unavailable(message).into_http(); - response.headers_mut().insert(PUSHBACK_HEADER, HeaderValue::from_static(PUSHBACK_MS)); - response -} diff --git a/packages/zingod-grpc/src/connections.rs b/packages/zingod-grpc/src/connections.rs index 936cdc92f..c9c1602bb 100644 --- a/packages/zingod-grpc/src/connections.rs +++ b/packages/zingod-grpc/src/connections.rs @@ -6,11 +6,12 @@ use std::collections::HashMap; use std::net::IpAddr; +use std::num::NonZeroUsize; use std::sync::{Arc, Mutex}; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; -use crate::{metrics, GrpcLimits}; +use crate::metrics; #[derive(Debug)] pub(crate) struct ConnectionCaps { @@ -27,13 +28,12 @@ pub(crate) struct Reserved { } impl ConnectionCaps { - pub(crate) fn new(limits: &GrpcLimits) -> Self { - let total_max = limits.max_connections.get(); + pub(crate) fn new(total_max: NonZeroUsize, per_client_max: NonZeroUsize) -> Self { Self { - total: Arc::new(Semaphore::new(total_max)), - total_max, + total: Arc::new(Semaphore::new(total_max.get())), + total_max: total_max.get(), per_client: Arc::new(Mutex::new(HashMap::new())), - per_client_max: limits.max_connections_per_ip.get(), + per_client_max: per_client_max.get(), } } @@ -42,7 +42,7 @@ impl ConnectionCaps { self.total_max.saturating_sub(self.total.available_permits()) } - /// `None` = at `max_connections` (caller drops the socket) + /// `None` = at `total_max` (caller drops the socket) pub(crate) fn reserve(&self) -> Option { match Arc::clone(&self.total).try_acquire_owned() { Ok(permit) => Some(Reserved { _slot: permit }), @@ -95,22 +95,12 @@ impl Drop for ConnectionGuard { #[cfg(test)] mod tests { - use std::num::NonZeroUsize; - use super::*; - fn caps(max_connections: usize, max_connections_per_ip: usize) -> ConnectionCaps { - let non_zero = |cap| NonZeroUsize::new(cap).expect("non-zero cap"); - ConnectionCaps::new(&GrpcLimits { - max_connections: non_zero(max_connections), - max_connections_per_ip: non_zero(max_connections_per_ip), - ..GrpcLimits::default() - }) - } - #[test] fn connections_are_admitted_up_to_both_caps_and_every_slot_returns_on_close() { - let caps = caps(3, 2); + let non_zero = |cap| NonZeroUsize::new(cap).expect("non-zero cap"); + let caps = ConnectionCaps::new(non_zero(3), non_zero(2)); let (alice, bob): (IpAddr, IpAddr) = ([203, 0, 113, 1].into(), [203, 0, 113, 2].into()); let admit = |client| caps.reserve().and_then(|reserved| caps.admit(reserved, client)); @@ -126,7 +116,7 @@ mod tests { ); assert!(bobs.is_some(), "bob counted apart from alice: {bobs:?}"); assert_eq!(caps.held(), 3, "a refused client's reservation returned"); - assert!(past_total.is_none(), "4th connection over max_connections 3: {past_total:?}"); + assert!(past_total.is_none(), "4th connection over the total 3: {past_total:?}"); alices.remove(0); assert!(admit(alice).is_some(), "one of alice's closed: her next admitted"); diff --git a/packages/zingod-grpc/src/deadline.rs b/packages/zingod-grpc/src/deadline.rs index adcc0eb33..7f727b25d 100644 --- a/packages/zingod-grpc/src/deadline.rs +++ b/packages/zingod-grpc/src/deadline.rs @@ -1,12 +1,8 @@ -//! Time bounds on one request: the client's `grpc-timeout`, and a silence bound, never a total cap +//! Client's `grpc-timeout` = a request's only time bound (never a total cap) //! -//! - deadline = `grpc-timeout` at arrival: past it, a pending handler = `DEADLINE_EXCEEDED`, a -//! stream ends in `DEADLINE_EXCEEDED` trailers -//! - silence = nothing to send for `silent_timeout` while hyper waits on the handler or the body -//! → `UNAVAILABLE` (retry) -//! - client-side twin = `stall.rs` (`unread_timeout` → connection closed) -//! - `GetMempoolStream` exempt (silent until the next block by design) -//! - a long stream that keeps delivering lives as long as the client wants (Z#1537) +//! - past it: pending handler = `DEADLINE_EXCEEDED`, a stream ends in `DEADLINE_EXCEEDED` trailers +//! - a stream that keeps delivering lives as long as the client wants (Z#1537) +//! - client stopped reading = `stall.rs` (`unread_timeout` → connection closed) use std::future::Future; use std::pin::Pin; @@ -42,80 +38,36 @@ fn requested(headers: &HeaderMap) -> Option { } } -/// One request's bounds, fixed at arrival (`silent_limit` = `None`: never cut for silence) -#[derive(Clone, Copy, Debug)] -pub(crate) struct Bounds { - deadline: Option, - silent_limit: Option, +/// `headers`' deadline, fixed at arrival +pub(crate) fn of(headers: &HeaderMap) -> Option { + requested(headers).map(|timeout| Instant::now() + timeout) } -impl Bounds { - pub(crate) fn of(headers: &HeaderMap, silent_limit: Option) -> Self { - Self { deadline: requested(headers).map(|timeout| Instant::now() + timeout), silent_limit } - } - - /// `answer` cut at the first bound - /// - /// - stream's body (status in trailers) bounded the same - pub(crate) async fn apply( - self, - answer: impl Future>, - ) -> Response { - let first_message = self.silent_limit.map(|limit| Instant::now() + limit); - let cut = match (self.deadline, first_message) { - (Some(deadline), Some(silent)) => Some(deadline.min(silent)), - (deadline, silent) => deadline.or(silent), - }; - let response = match cut { - Some(at) => match tokio::time::timeout_at(at, answer).await { - Ok(response) => response, - Err(_) => return self.cut_at(at).into_http(), - }, - None => answer.await, - }; - // grpc-status in the headers = complete (unary or a refusal): nothing left to bound - if response.headers().contains_key("grpc-status") { - return response; - } - let deadline = self.deadline.map(|at| Box::pin(tokio::time::sleep_until(at))); - let (silent_limit, silent_timer) = (self.silent_limit, None); - response.map(|inner| { - Body::new(Bounded { inner: Some(inner), deadline, silent_limit, silent_timer }) - }) - } - - /// Why a cut at `at` ended the request - fn cut_at(&self, at: Instant) -> Status { - match (self.deadline == Some(at), self.silent_limit) { - (false, Some(limit)) => silenced(limit), - _ => expired(), - } +/// `answer` cut at `deadline`, its stream body too (`None` = never cut) +pub(crate) async fn apply( + deadline: Option, + answer: impl Future>, +) -> Response { + let Some(deadline) = deadline else { return answer.await }; + let Ok(response) = tokio::time::timeout_at(deadline, answer).await else { + return expired().into_http(); + }; + // grpc-status in the headers = complete (unary or a refusal): nothing left to bound + if response.headers().contains_key("grpc-status") { + return response; } + let deadline = Box::pin(tokio::time::sleep_until(deadline)); + response.map(|inner| Body::new(Bounded { inner: Some(inner), deadline })) } fn expired() -> Status { Status::deadline_exceeded("grpc-timeout passed") } -fn silenced(silent: Duration) -> Status { - Status::unavailable(format!("nothing to send for {silent:?}")) -} - -/// A stream body under its [`Bounds`] (`inner` dropped at a cut: its reads and permits go with it) -/// -/// - `silent_timer` runs from the first `Pending` since the last frame, never while hyper holds one +/// Stream body under its deadline (`inner` dropped at the cut: its slot goes with it) struct Bounded { inner: Option, - deadline: Option>>, - silent_limit: Option, - silent_timer: Option>>, -} - -impl Bounded { - fn cut(&mut self, status: Status) -> Poll, Status>>> { - self.inner = None; - Poll::Ready(Some(Ok(Frame::trailers(trailers(&status))))) - } + deadline: Pin>, } impl http_body::Body for Bounded { @@ -128,36 +80,22 @@ impl http_body::Body for Bounded { ) -> Poll, Status>>> { let this = self.get_mut(); let Some(inner) = this.inner.as_mut() else { return Poll::Ready(None) }; - if this.deadline.as_ref().is_some_and(|deadline| deadline.is_elapsed()) { - return this.cut(expired()); - } - match Pin::new(inner).poll_frame(cx) { - Poll::Ready(Some(Ok(frame))) => { - this.silent_timer = None; - if frame.is_trailers() { - this.inner = None; - } + let polled = match this.deadline.is_elapsed() { + true => None, + false => Some(Pin::new(inner).poll_frame(cx)), + }; + match polled { + Some(Poll::Ready(Some(Ok(frame)))) if !frame.is_trailers() => { Poll::Ready(Some(Ok(frame))) } - Poll::Ready(other) => { + Some(Poll::Ready(done)) => { this.inner = None; - Poll::Ready(other) + Poll::Ready(done) } - Poll::Pending => { - if let Some(deadline) = this.deadline.as_mut() { - if deadline.as_mut().poll(cx).is_ready() { - return this.cut(expired()); - } - } - if let Some(limit) = this.silent_limit { - let timer = this - .silent_timer - .get_or_insert_with(|| Box::pin(tokio::time::sleep(limit))); - if timer.as_mut().poll(cx).is_ready() { - return this.cut(silenced(limit)); - } - } - Poll::Pending + Some(Poll::Pending) if this.deadline.as_mut().poll(cx).is_pending() => Poll::Pending, + None | Some(Poll::Pending) => { + this.inner = None; + Poll::Ready(Some(Ok(Frame::trailers(trailers(&expired()))))) } } } @@ -174,7 +112,7 @@ mod tests { use tokio::time::Instant; use tonic::{body::Body, Status}; - use super::{requested, Bounds}; + use super::requested; use crate::wire::trailers; fn timeout(value: &'static str) -> HeaderMap { @@ -229,17 +167,17 @@ mod tests { frames } - /// `Stream`: `count` records, one every `period`, then `OK` trailers (`silent` = pending) + /// `Stream`: `count` records, one every `period`, then `OK` trailers #[derive(Clone, Copy, Debug)] enum Handler { Pending, - Stream { count: u64, period: Duration, silent: bool }, + Stream { count: u64, period: Duration }, } async fn handle(handler: Handler) -> Response { use std::cmp::Ordering::{Equal, Greater, Less}; - let Handler::Stream { count, period, silent } = handler else { + let Handler::Stream { count, period } = handler else { return std::future::pending().await; }; let frames = futures::stream::unfold(0, move |sent: u64| async move { @@ -248,7 +186,6 @@ mod tests { tokio::time::sleep(period).await; Frame::data(Bytes::from_static(b"\0\0\0\0\0")) } - Equal if silent => return std::future::pending().await, Equal => Frame::trailers(trailers(&Status::ok(""))), Greater => return None, }; @@ -257,38 +194,31 @@ mod tests { Response::new(Body::new(StreamBody::new(Box::pin(frames)))) } - /// Z#1537 (paused clock): no total cap, only the client's deadline or the silence bound + /// Z#1537 (paused clock): no total cap, no silence cap, only the client's deadline #[tokio::test(start_paused = true)] - async fn a_stream_lives_while_it_delivers_until_the_clients_deadline_or_a_silence_bound() { - const SILENT: Option = Some(Duration::from_secs(300)); + async fn a_stream_lives_while_it_delivers_until_the_clients_deadline() { let s100 = Duration::from_secs(100); let data = |at: u64| (at, "data".to_owned()); let ended = |at: u64, code: &str| (at, code.to_owned()); let every_100s_for_1000s: Vec<_> = (1..=10).map(|n| data(n * 100)).collect(); - let delivering = Handler::Stream { count: 10, period: s100, silent: false }; + let delivering = Handler::Stream { count: 10, period: s100 }; - // case, grpc-timeout, silence bound, handler, frames as (second, data / status) + // case, grpc-timeout, handler, frames as (second, data / status) #[rustfmt::skip] let cases = [ - ("delivering 1,000 s", HeaderMap::new(), SILENT, delivering, + ("delivering 1,000 s", HeaderMap::new(), delivering, [every_100s_for_1000s, vec![ended(1_000, "Ok")]].concat()), - ("client deadline 250 s", timeout("250S"), SILENT, delivering, + ("client deadline 250 s", timeout("250S"), delivering, vec![data(100), data(200), ended(250, "DeadlineExceeded")]), - ("silent after one record", HeaderMap::new(), SILENT, Handler::Stream { count: 1, period: s100, silent: true }, - vec![data(100), ended(400, "Unavailable")]), - ("subscription, 1,000 s gaps", HeaderMap::new(), None, Handler::Stream { count: 2, period: s100 * 10, silent: false }, + ("1,000 s gaps, no deadline", HeaderMap::new(), Handler::Stream { count: 2, period: s100 * 10 }, vec![data(1_000), data(2_000), ended(2_000, "Ok")]), - ("handler pending, 2 s deadline", timeout("2S"), SILENT, Handler::Pending, + ("handler pending, 2 s deadline", timeout("2S"), Handler::Pending, vec![ended(2, "DeadlineExceeded")]), - ("handler pending, no deadline", HeaderMap::new(), SILENT, Handler::Pending, - vec![ended(300, "Unavailable")]), - ("handler pending, 1 h deadline", timeout("1H"), SILENT, Handler::Pending, - vec![ended(300, "Unavailable")]), ]; - for (case, headers, silent, handler, expected) in cases { + for (case, headers, handler, expected) in cases { let start = Instant::now(); - let response = Bounds::of(&headers, silent).apply(handle(handler)).await; + let response = super::apply(super::of(&headers), handle(handler)).await; assert_eq!(drained(start, response).await, expected, "{case}: {handler:?}"); } diff --git a/packages/zingod-grpc/src/guard.rs b/packages/zingod-grpc/src/guard.rs index d281aa416..5b809920c 100644 --- a/packages/zingod-grpc/src/guard.rs +++ b/packages/zingod-grpc/src/guard.rs @@ -1,6 +1,10 @@ //! Per-stream guard: admission slot, stall ticket, connection activity + close-out metrics, all //! owned by the response body //! +//! - request body whole before admission (a bodiless or trickled request holds no slot; its +//! arriving bytes charged to the unread budget: `stall::Arriving`) +//! - slot held for the stream's life, reclaimable while its client has not read for a grace +//! (`admission.rs`, `stall.rs`) //! - body dropped = stream over, however it ended (stream end, client gone: hyper drops it either //! way) → slot back, close-out measured //! - refusal measured as the request it was (counted, never logged one by one) @@ -8,22 +12,25 @@ use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; -use std::time::{Duration, Instant}; +use std::time::Instant; -use bytes::Bytes; +use bytes::{Buf as _, Bytes}; use futures::future::BoxFuture; use http::{HeaderMap, Request, Response}; use http_body::{Body, Frame, SizeHint}; +use http_body_util::{BodyExt as _, Full}; use tonic::{Code, Status}; use tower::ServiceExt as _; -use crate::admission::{self, AdmissionState, Class, Slot}; +use crate::admission::{AdmissionState, Slot}; use crate::lifetime::{Activity, Open}; use crate::origin::{OriginGate, OriginVerdict}; +use crate::overload::Wallet; use crate::service::Method; use crate::stall::{self, Ticket}; -use crate::{metrics, summary}; +use crate::{metrics, summary, wire}; +/// One per connection (cloned per request): `wallet` = this connection's overload mark #[derive(Clone, Debug)] pub(crate) struct Guard { inner: Inner, @@ -31,6 +38,7 @@ pub(crate) struct Guard { stalls: Arc, activity: Arc, gate: Arc, + wallet: Arc, } impl Guard { @@ -41,7 +49,7 @@ impl Guard { activity: Arc, gate: Arc, ) -> Self { - Self { inner, admission, stalls, activity, gate } + Self { inner, admission, stalls, activity, gate, wallet: Arc::default() } } } @@ -64,13 +72,15 @@ fn status_of(headers: &HeaderMap) -> Option<(Code, Option)> { /// Never pushes back itself: `inner` readied inside the call (`oneshot`) impl tower::Service> for Guard where - Inner: tower::Service, Response = Response> + Inner: tower::Service>, Response = Response> + Clone + Send + 'static, Inner::Error: Send + 'static, Inner::Future: Send + 'static, - ReqBody: Send + 'static, + ReqBody: Body + Send + 'static, + ReqBody::Data: Send, + ReqBody::Error: std::fmt::Display, { type Response = Response>; type Error = Inner::Error; @@ -82,15 +92,13 @@ where fn call(&mut self, request: Request) -> Self::Future { let method = Method::of_request(&request); - let class = method.map_or(Class::Work, |method| method.route().class); let mut close = CloseOut { method, started: Instant::now(), - first_message: None, + answered: false, sent: 0, code: None, message: None, - at_capacity: false, ended: false, _open: self.activity.opened(), }; @@ -105,34 +113,56 @@ where None => OriginVerdict::Default, }; if verdict == OriginVerdict::Blocked { - close.code = Some(Code::PermissionDenied); let refusal = Status::permission_denied("origin blocked").into_http(); - let refusal = refusal.map(|inner| Guarded { inner, slot: None, ticket, close }); - return Box::pin(std::future::ready(Ok(refusal))); + return Box::pin(std::future::ready(Ok(refused(refusal, ticket, close)))); } - // every unblocked origin = one admission path (Origin client-settable, never lifts a cap) - let slot = match self.admission.admit(class) { - Some(slot) => slot, - None => { - (close.code, close.at_capacity) = (Some(Code::Unavailable), true); - let refusal = admission::refused(class); - let refusal = refusal.map(|inner| Guarded { inner, slot: None, ticket, close }); - return Box::pin(std::future::ready(Ok(refusal))); - } - }; - - let inner = self.inner.clone(); + let (inner, admission, wallet) = + (self.inner.clone(), Arc::clone(&self.admission), Arc::clone(&self.wallet)); + let mut arriving = stall::Arriving::of(&self.stalls); + let client = self.stalls.client(); Box::pin(async move { - let response = inner.oneshot(request).await?; + let (parts, body) = request.into_parts(); + let body = body.map_frame(|frame| { + if let Some(data) = frame.data_ref() { + arriving.add(data.remaining()); + } + frame + }); + let body = match wire::collect_request(body, method).await { + Ok(body) => body, + Err(status) => return Ok(refused(status.into_http(), ticket, close)), + }; + // every unblocked origin = one admission path (Origin client-settable, never lifts a cap) + let slot = if method.is_some_and(Method::is_subscription) { + None + } else { + match admission.admit(&wallet, client) { + Ok(slot) => Some(slot), + Err(refusal) => return Ok(refused(refusal.response(), ticket, close)), + } + }; + drop(arriving); + + let response = inner.oneshot(Request::from_parts(parts, Full::new(body))).await?; // header-carried `grpc-status` = unary answer or error, already complete let (code, message) = status_of(response.headers()).unzip(); (close.code, close.message) = (code, message.flatten()); - Ok(response.map(|inner| Guarded { inner, slot: Some(slot), ticket, close })) + Ok(response.map(|inner| Guarded { inner, slot, ticket, close })) }) } } -/// Response body owning its stream's guards (`slot` = `None` on a refusal or once ended) +/// A refusal before any handler ran, measured as the request it was (`code` = its `grpc-status`) +fn refused( + refusal: Response, + ticket: Ticket, + mut close: CloseOut, +) -> Response> { + close.code = status_of(refusal.headers()).map(|(code, _)| code); + refusal.map(|inner| Guarded { inner, slot: None, ticket, close }) +} + +/// Response body owning its stream's guards (`slot` = `None`: a subscription, a refusal, or ended) #[derive(Debug)] pub(crate) struct Guarded { inner: B, @@ -143,17 +173,16 @@ pub(crate) struct Guarded { /// One stream's measurement to its end, recorded on drop /// -/// - `first_message` = admission → first DATA frame +/// - `answered` = first DATA frame sent (its time = `first_message_seconds`) /// - `message` = non-`Ok` status message #[derive(Debug)] struct CloseOut { method: Option, started: Instant, - first_message: Option, + answered: bool, sent: u64, code: Option, message: Option, - at_capacity: bool, ended: bool, _open: Open, } @@ -167,23 +196,21 @@ impl + Unpin> Body for Guarded { cx: &mut Context<'_>, ) -> Poll, Self::Error>>> { let this = &mut *self; + // hyper polling = the client took the last frame; off the owing list first (the reclaim + // sweep reclaims only what is on it, under its lock) this.ticket.pulled(); - if let Some(slot) = this.slot.as_mut() { - slot.polled(); + if let Some(slot) = &this.slot { + slot.resume(); } let polled = Pin::new(&mut this.inner).poll_frame(cx); let close = &mut this.close; match &polled { Poll::Ready(Some(Ok(frame))) => match frame.data_ref() { Some(chunk) => { - this.ticket.handed(); - if let Some(slot) = this.slot.as_mut() { - slot.handed(); - } - if close.first_message.is_none() { - let elapsed = close.started.elapsed(); - close.first_message = Some(elapsed); - metrics::first_message(close.method, elapsed); + this.ticket.handed(chunk.len(), this.slot.as_ref().map(Slot::claim)); + if !close.answered { + close.answered = true; + metrics::first_message(close.method, close.started.elapsed()); } close.sent += u64::try_from(chunk.len()).expect("usize fits u64"); } @@ -220,33 +247,26 @@ impl Drop for CloseOut { true => Code::Ok, false => Code::Cancelled, }); - let elapsed = self.started.elapsed(); - // answered work request's latency = its client's wait for the first message - let subscription = self.method.is_some_and(|method| method.route().is_subscription()); - let latency = - (code == Code::Ok && !subscription).then(|| self.first_message.unwrap_or(elapsed)); - - metrics::stream_finished(self.method, code, elapsed, latency, self.sent); - if code != Code::Ok && !self.at_capacity { - summary::answered_badly(self.method, code, self.message.as_deref().unwrap_or_default()); - } + metrics::stream_finished(self.method, code, self.started.elapsed(), self.sent); + summary::finished(self.method, code, self.message.as_deref().unwrap_or_default()); } } #[cfg(test)] mod tests { use std::convert::Infallible; - use std::num::NonZeroUsize; use http::HeaderValue; use http_body_util::{BodyExt as _, Full, StreamBody}; use tower::Service as _; use super::*; - use crate::overload::Signals; + use crate::adaptive::WORK_CEILING; + use crate::limits::WorkShare; /// - `/open` + `GetMempoolStream` never end /// - `/data` = one frame then waits + /// - `/many` = a frame at every poll, never done (a range sync) /// - `/short` = one frame, done #[derive(Clone)] struct Answers; @@ -276,6 +296,10 @@ mod tests { then, ))) } + "/many" => { + let frame = || Ok::<_, Status>(Frame::data(Bytes::from_static(b"\0\0\0\0\0"))); + tonic::body::Body::new(StreamBody::new(futures::stream::repeat_with(frame))) + } _ => tonic::body::Body::new(Full::new(Bytes::from_static(b"\0\0\0\0\0"))), }; @@ -300,16 +324,45 @@ mod tests { request } + /// Body whole before a slot: headers + part of a body, the rest withheld, hold none (pool of + /// 1); its arriving bytes are charged, so past the budget its connection is the one evicted + #[tokio::test] + async fn a_request_takes_a_slot_only_once_its_body_has_arrived() { + use futures::{FutureExt as _, StreamExt as _}; + + let state = Arc::new(AdmissionState::new(1, WorkShare::default())); + let parked = Arc::new(stall::Parked::new(16 * 1024)); + let trickler_watch = parked.watch([203, 0, 113, 1].into()); + let guard = |watch| { + Guard::new(Answers, Arc::clone(&state), watch, Arc::default(), OriginGate::new()) + }; + let (mut trickler, mut wallet) = + (guard(Arc::clone(&trickler_watch)), guard(parked.watch([203, 0, 113, 2].into()))); + let part = Ok::<_, Infallible>(Frame::data(Bytes::from(vec![0; 20 * 1024]))); + let withheld = + StreamBody::new(futures::stream::iter([part]).chain(futures::stream::pending())); + let mut trickled = + Request::builder().uri("http://localhost/open").body(withheld).expect("request"); + Method::resolve(&mut trickled); + + let mut trickling = trickler.call(trickled); + let still_collecting = (&mut trickling).now_or_never().is_none(); + let held_while_trickling = state.held(); + let evicted = trickler_watch.evicted().now_or_never().is_some(); + let admitted = wallet.call(request("/open")).await.expect("infallible"); + + assert!(still_collecting, "body incomplete: no response yet"); + assert_eq!(held_while_trickling, 0, "an incomplete body holds no work slot"); + assert!(evicted, "20 KiB arriving past a 16 KiB budget: the trickler's connection picked"); + assert_eq!(status_of(admitted.headers()), None, "another client's whole request admitted"); + assert_eq!(state.held(), 1, "the one slot = the complete request's"); + } + /// With one work slot full: blocked = `PermissionDenied` before admission; a carve-out under /// the block or an unmarked origin = refused at the limit like any client #[tokio::test] async fn the_origin_gate_blocks_and_otherwise_defers_to_the_limit() { - let limits = crate::GrpcLimits { - max_work_streams: NonZeroUsize::MIN, - adaptive_work_streams: false, - ..crate::GrpcLimits::default() - }; - let state = Arc::new(AdmissionState::new(&limits)); + let state = Arc::new(AdmissionState::new(1, WorkShare::default())); let gate = OriginGate::new(); gate.set(["evil.com".to_owned()].into(), ["good.evil.com".to_owned()].into()); let mut guard = @@ -318,7 +371,7 @@ mod tests { // fill the one work slot (held open, never ends) let held = guard.call(request("/open")).await.expect("infallible"); let _held = std::pin::pin!(held.into_body()); - assert_eq!(state.held(Class::Work), 1, "slot taken"); + assert_eq!(state.held(), 1, "slot taken"); let verdict = |response: &Response>| { status_of(response.headers()).map(|(code, _)| code) @@ -332,14 +385,14 @@ mod tests { assert_eq!(verdict(&blocked), Some(Code::PermissionDenied), "blocked origin refused"); assert_eq!(verdict(&allowed), Some(Code::Unavailable), "carve-out refused at the limit"); assert_eq!(verdict(&other), Some(Code::Unavailable), "default origin refused at the limit"); - assert_eq!(state.held(Class::Work), 1, "no refusal took a slot"); + assert_eq!(state.held(), 1, "no refusal took a slot"); } /// Guard → ticket wiring (stall timing itself: `stall.rs`) #[tokio::test(start_paused = true)] async fn a_stream_owes_from_a_handed_data_frame_until_its_next_poll() { let stalls = Arc::new(stall::Watch::default()); - let admission = Arc::new(AdmissionState::new(&crate::GrpcLimits::default())); + let admission = Arc::new(AdmissionState::new(WORK_CEILING, WorkShare::default())); let mut guard = Guard::new(Answers, admission, Arc::clone(&stalls), Arc::default(), OriginGate::new()); @@ -368,7 +421,7 @@ mod tests { /// The body's drop = the only signal a client walked away mid-stream #[tokio::test] async fn a_stream_slot_lives_as_long_as_its_body() { - let state = Arc::new(AdmissionState::new(&crate::GrpcLimits::default())); + let state = Arc::new(AdmissionState::new(WORK_CEILING, WorkShare::default())); let mut guard = Guard::new( Answers, Arc::clone(&state), @@ -376,7 +429,7 @@ mod tests { Arc::default(), OriginGate::new(), ); - let in_flight = || state.held(Class::Work); + let in_flight = || state.held(); let open = guard.call(request("/open")).await.expect("infallible"); assert_eq!(in_flight(), 1, "handler returned, stream still open"); @@ -390,15 +443,64 @@ mod tests { assert_eq!(in_flight(), 0, "read to its end: returned before the drop"); } - #[tokio::test] - async fn subscriptions_have_their_own_pool_beside_work() { - let one = NonZeroUsize::MIN; - let limits = crate::GrpcLimits { - max_work_streams: one, - max_subscriptions: one, - ..Default::default() + /// Konclave report: never-read streams held every slot + /// - a client reading keeps its slot; not reading past the grace, the sweep reclaims it + /// - reclaimed, it still counts toward its client's share (limit 1 → share 1): reclaim + /// then reopen never grows a client past its share + /// - reading on after a reclaim: back past the limit (never refused mid-stream), newcomers + /// refused until it drains; a reclaimed then dropped stream releases nothing twice + #[tokio::test(start_paused = true)] + async fn a_stream_whose_client_stops_reading_loses_its_slot_and_reading_on_takes_one_back() { + use crate::stall::{Parked, GRACE}; + + let state = Arc::new(AdmissionState::new(1, WorkShare::default())); + let parked = Arc::new(Parked::default()); + let client = |last: u8| { + let watch = parked.watch([203, 0, 113, last].into()); + Guard::new(Answers, Arc::clone(&state), watch, Arc::default(), OriginGate::new()) }; - let state = Arc::new(AdmissionState::new(&limits)); + let (mut a_client, mut b_client, mut c_client) = (client(1), client(2), client(3)); + let refusal = |response: &Response<_>| status_of(response.headers()); + let at_limit = Some((Code::Unavailable, Some("work stream limit reached".to_owned()))); + let at_share = + Some((Code::Unavailable, Some("per-client work stream share reached".to_owned()))); + + // A: one message sent, its client not reading yet: within the grace it keeps the slot + let a = a_client.call(request("/many")).await.expect("infallible"); + let mut a = Box::pin(a.into_body()); + a.frame().await.expect("a frame").expect("in-band"); + let b = b_client.call(request("/short")).await.expect("infallible"); + assert_eq!(refusal(&b), at_limit, "A within the grace: pool of 1 full"); + + // A still not reading past the grace: reclaimed; A's client still at its share, B admitted + tokio::time::advance(GRACE).await; + assert_eq!(parked.reclaim(GRACE), 1, "A's slot reclaimed"); + let again = a_client.call(request("/many")).await.expect("infallible"); + assert_eq!(refusal(&again), at_share, "reclaimed A still counts for its client"); + let b = b_client.call(request("/many")).await.expect("infallible"); + assert_eq!(refusal(&b), None, "B admitted in A's place"); + let mut b = Box::pin(b.into_body()); + b.frame().await.expect("a frame").expect("in-band"); + + // A's client reads on with B holding the slot: A goes on, past the limit; C refused + a.frame().await.expect("A reads on").expect("in-band"); + assert_eq!(state.held(), 2, "A took a slot back past the limit of 1"); + let c = c_client.call(request("/short")).await.expect("infallible"); + assert_eq!(refusal(&c), at_limit, "C refused until held drains"); + + // B reclaimed then gone (one release, by the sweep); A ends: every slot + share back + tokio::time::advance(GRACE).await; + assert_eq!(parked.reclaim(GRACE), 2, "A and B both idle past the grace"); + drop((b, a)); + assert_eq!(state.held(), 0, "nothing released twice, nothing leaked"); + let d = a_client.call(request("/short")).await.expect("infallible"); + assert_eq!(refusal(&d), None, "D admitted: A's client's share back too"); + } + + /// `GetMempoolStream` idles until the next block: never takes or waits on a work slot + #[tokio::test] + async fn subscriptions_open_with_every_work_slot_taken() { + let state = Arc::new(AdmissionState::new(1, WorkShare::default())); let mut guard = Guard::new( Answers, Arc::clone(&state), @@ -407,59 +509,70 @@ mod tests { OriginGate::new(), ); let mempool = &Method::GetMempoolStream.path(); - fn refusal(response: &Response) -> Option { - Status::from_header_map(response.headers()) - } - let _work = guard.call(request("/open")).await.expect("infallible"); + let code = |response: &Response<_>| status_of(response.headers()).map(|(code, _)| code); - let subscribed = guard.call(request(mempool)).await.expect("infallible"); - assert_eq!( - refusal(&subscribed).map(|s| s.code()), - None, - "work pool full: subscription admitted" - ); - let second = guard.call(request(mempool)).await.expect("infallible"); - let refused = refusal(&second).map(|status| (status.code(), status.message().to_owned())); - let full = Some((Code::Unavailable, "subscription limit reached".to_owned())); - assert_eq!(refused, full, "second subscription over max_subscriptions 1"); - drop(subscribed); - let third = guard.call(request(mempool)).await.expect("infallible"); - assert_eq!(refusal(&third).map(|s| s.code()), None, "slot back on disconnect"); + let _work = guard.call(request("/open")).await.expect("infallible"); + let refused = guard.call(request("/open")).await.expect("infallible"); + let subscribed: Vec<_> = + futures::future::join_all((0..3).map(|_| guard.call(request(mempool)))) + .await + .into_iter() + .map(|response| code(&response.expect("infallible"))) + .collect(); + + assert_eq!(code(&refused), Some(Code::Unavailable), "work pool of 1 full"); + assert_eq!(subscribed, vec![None; 3], "every subscription opened"); + assert_eq!(state.held(), 1, "subscriptions hold no work slot"); } - /// Default limits (`max_work_streams` 2048, adaptive from 256): + /// The limit = [`WORK_CEILING`] (2048) until zingod falls behind; one client (IPv6 /64 here) + /// holds at most 1/16 of it /// - /// - 257th open work stream refused at once (a queue would hang a wallet behind the open - /// streams), below the ceiling, `UNAVAILABLE` + pushback, taking no slot - /// - counted once the window closes + /// - a client past its 128: refused, its own doing (no pool pressure → no overload) + /// - 16 clients fill it; the next refused at once (a queue would hang a wallet behind the + /// open streams), `UNAVAILABLE` + pushback, taking no slot #[tokio::test] - async fn work_past_the_adaptive_limit_is_refused_at_once_below_the_ceiling() { + async fn one_client_stops_at_its_share_and_only_a_crowd_fills_the_limit() { use futures::FutureExt as _; - let state = Arc::new(AdmissionState::new(&crate::GrpcLimits::default())); - let mut guard = Guard::new( - Answers, - Arc::clone(&state), - Arc::default(), - Arc::default(), - OriginGate::new(), - ); + let state = Arc::new(AdmissionState::new(WORK_CEILING, WorkShare::default())); + let parked = Arc::new(stall::Parked::default()); + let guard = |client: &str| { + let watch = parked.watch(client.parse().expect("address")); + Guard::new(Answers, Arc::clone(&state), watch, Arc::default(), OriginGate::new()) + }; + let refusal = |response: Response>| { + let status = Status::from_header_map(response.headers()).expect("Trailers-Only"); + let pushback = response.headers().get("grpc-retry-pushback-ms").cloned(); + (status.code(), status.message().to_owned(), pushback) + }; + let retry_after = Some(HeaderValue::from_static("250")); + let refused = |message: &str| (Code::Unavailable, message.to_owned(), retry_after.clone()); + let (at_limit, at_share) = + (refused("work stream limit reached"), refused("per-client work stream share reached")); let mut open = Vec::new(); - for _ in 0..256 { - open.push(guard.call(request("/open")).await.expect("infallible")); + + let mut greedy = guard("2001:db8::1"); + for _ in 0..128 { + open.push(greedy.call(request("/open")).await.expect("infallible")); + } + let over_share = greedy.call(request("/open")).await.expect("infallible"); + let sibling = guard("2001:db8::ffff").call(request("/open")).await.expect("infallible"); + let pressed_by_one = state.pressed(); + for crowd in 1..16 { + let mut guard = guard(&format!("2001:db8:0:{crowd}::1")); + for _ in 0..128 { + open.push(guard.call(request("/open")).await.expect("infallible")); + } } - let refused = - guard.call(request("/open")).now_or_never().expect("refused at once, never queued"); - let refused = refused.expect("infallible"); - let status = Status::from_header_map(refused.headers()).expect("Trailers-Only refusal"); - let pushback = refused.headers().get("grpc-retry-pushback-ms"); - let refusal = (status.code(), status.message(), pushback); - let retry_after = HeaderValue::from_static("250"); - assert_eq!(refusal, (Code::Unavailable, "work stream limit reached", Some(&retry_after))); - - let refusals = state.tick(Duration::from_secs(1), Signals::default()); - assert_eq!(refusals, 1, "the window's one refusal"); - let work = (state.work_limit(), state.held(Class::Work)); - assert_eq!(work, (256, 256), "refused below the 2048 ceiling, no slot of its own"); + let newcomer = guard("2001:db8:0:16::1").call(request("/open")).now_or_never(); + + assert_eq!(refusal(over_share), at_share, "129th from one client refused"); + assert_eq!(refusal(sibling), at_share, "same /64 = same client"); + assert!(!pressed_by_one, "one client at its share: no pressure, no overload"); + let newcomer = newcomer.expect("refused at once, never queued").expect("infallible"); + assert_eq!(refusal(newcomer), at_limit, "16 clients × 128 = the limit"); + let work = (state.work_limit(), state.held()); + assert_eq!(work, (2048, 2048), "at the ceiling, refusals took no slot"); } } diff --git a/packages/zingod-grpc/src/lib.rs b/packages/zingod-grpc/src/lib.rs index 82ea86cdb..a8d10c745 100644 --- a/packages/zingod-grpc/src/lib.rs +++ b/packages/zingod-grpc/src/lib.rs @@ -20,13 +20,13 @@ mod memo; mod metrics; mod origin; mod overload; -mod pressure; mod proxy_protocol; -mod read_lanes; +mod read_pool; mod routes; mod service; mod stall; mod summary; +mod tcp_info; #[cfg(test)] mod testing; mod tls; @@ -37,9 +37,8 @@ pub use crate::metrics::{sent_bytes_total, METRICS}; pub use admission::AdmissionState; pub use health::Health; pub use lifetime::{Hold, Retire}; -pub use limits::{GrpcLimits, OverloadLimits}; +pub use limits::{GrpcLimits, HostCapacity, WorkShare}; pub use origin::{OriginGate, OriginVerdict}; -pub use overload::OverloadCause; pub use proxy_protocol::TrustedProxies; pub use service::{RouteDeps, Routing}; diff --git a/packages/zingod-grpc/src/limits.rs b/packages/zingod-grpc/src/limits.rs index e3a33362c..efd323b1b 100644 --- a/packages/zingod-grpc/src/limits.rs +++ b/packages/zingod-grpc/src/limits.rs @@ -1,9 +1,8 @@ //! [`GrpcLimits`]: serving caps (zingod's `[grpc]`) //! -//! - Every cap refuses, never queues, except the read lanes (`read_lanes.rs`: a page-faulting -//! read waits for its lane's permit, at most `max_work_streams` waiting) +//! - every cap refuses, never queues -use std::num::{NonZeroU32, NonZeroUsize}; +use std::num::NonZeroUsize; use std::time::Duration; use serde::{Deserialize, Serialize}; @@ -11,51 +10,78 @@ use zingod_primitives::serde_secs; use crate::proxy_protocol::TrustedProxies; +/// What the host holds, never configured (zingod derives both from its open-file limit + memory) +/// +/// - `parked_bytes` = budget for streams waiting on their clients (`stall::Parked`) +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HostCapacity { + pub connections: NonZeroUsize, + pub parked_bytes: u64, +} + +/// Share of the work limit one client (IPv4 address / IPv6 /64) may hold: in (0, 1], 1 = none +/// (a load test's few generator addresses) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(try_from = "f64", into = "f64")] +pub struct WorkShare(f64); + +/// Parsed in (0, 1]: never NaN +impl Eq for WorkShare {} + +impl Default for WorkShare { + /// 1/16: 128 slots at the 2048 ceiling, filling a node takes 16 clients + fn default() -> Self { + Self(1.0 / 16.0) + } +} + +impl TryFrom for WorkShare { + type Error = String; + + fn try_from(share: f64) -> Result { + match share > 0.0 && share <= 1.0 { + true => Ok(Self(share)), + false => Err(format!("work_share_per_ip = {share}: must be over 0 and at most 1")), + } + } +} + +impl From for f64 { + fn from(share: WorkShare) -> Self { + share.0 + } +} + +impl WorkShare { + /// Streams one client may hold at `limit` (≥ 1) + pub(crate) fn of(self, limit: usize) -> usize { + ((limit as f64 * self.0) as usize).max(1) + } +} + /// What one zingod serves at once + which peers name their client (zingod's `[grpc]`) /// /// - each field's contract: usage.md "Serve stack" -/// - `max_streams_per_connection` = every h2 stream, `max_work_streams` = admitted work only -/// - `unread_timeout` (client stopped reading) != `silent_timeout` (server has nothing to send) +/// - hardware-sized caps = [`HostCapacity`], never set here; work = +/// [`WORK_CEILING`](crate::adaptive::WORK_CEILING), lowered by Gradient2 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields, default)] pub struct GrpcLimits { - pub max_connections: NonZeroUsize, pub max_connections_per_ip: NonZeroUsize, - pub max_streams_per_connection: NonZeroU32, - pub max_work_streams: NonZeroUsize, - pub max_subscriptions: NonZeroUsize, - pub max_point_reads: NonZeroUsize, - pub max_range_reads: NonZeroUsize, - pub max_scan_reads: NonZeroUsize, + pub work_share_per_ip: WorkShare, + pub read_threads: NonZeroUsize, + pub scan_threads: NonZeroUsize, #[serde(rename = "unread_timeout_secs", with = "serde_secs::nonzero")] pub unread_timeout: Duration, - #[serde(rename = "silent_timeout_secs", with = "serde_secs::nonzero")] - pub silent_timeout: Duration, #[serde(rename = "max_connection_age_secs", with = "serde_secs::zero_is_never")] pub max_connection_age: Option, #[serde(rename = "max_connection_age_grace_secs", with = "serde_secs::any")] pub max_connection_age_grace: Duration, #[serde(rename = "max_connection_idle_secs", with = "serde_secs::zero_is_never")] pub max_connection_idle: Option, - pub adaptive_work_streams: bool, pub trusted_proxies: TrustedProxies, #[serde(rename = "shutdown_grace_secs", with = "serde_secs::any")] pub drain_timeout: Duration, - pub overload: OverloadLimits, -} - -/// When `/readyz` reports `Overloaded` (zingod's `[grpc.overload]`, usage.md "Overload"; 0 = off) -#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -#[serde(deny_unknown_fields, default)] -pub struct OverloadLimits { - pub cpu_pressure_percent: u8, - pub io_pressure_percent: u8, -} - -impl Default for OverloadLimits { - fn default() -> Self { - Self { cpu_pressure_percent: 25, io_pressure_percent: 25 } - } } impl Default for GrpcLimits { @@ -64,32 +90,48 @@ impl Default for GrpcLimits { NonZeroUsize::new(value).expect("a literal default is non-zero") } Self { - max_connections: const { non_zero(4096) }, // CGNAT: many wallets behind one carrier address max_connections_per_ip: const { non_zero(128) }, - // lightwalletd's `grpc-max-concurrent-streams` (clients tuned against it) - max_streams_per_connection: const { NonZeroU32::new(100).expect("100 is non-zero") }, - max_work_streams: const { non_zero(2048) }, - // one mempool stream per connected wallet - max_subscriptions: const { non_zero(4096) }, - // µs, warm: CPU-bound, so ~cores in parallel is the useful ceiling - max_point_reads: const { non_zero(64) }, - // 1 MiB windows: device queue depth - max_range_reads: const { non_zero(32) }, - // whole address histories, capped per request by rows (few in flight, never many) - max_scan_reads: const { non_zero(4) }, + work_share_per_ip: WorkShare::default(), + // an NVMe's useful parallelism (SATA SSD 16, HDD 4: operators' DoS protection page) + read_threads: const { non_zero(32) }, + // address-history scans apart: a flood of them never queues a block read + scan_threads: const { non_zero(4) }, // past pepper-sync's longest legitimate backpressure (scanning a fetched batch) unread_timeout: Duration::from_secs(300), - silent_timeout: Duration::from_secs(300), // long-held wallet connections re-resolve DNS (gRPC A9) max_connection_age: Some(Duration::from_secs(30 * 60)), // a whole `GetBlockRange` sync max_connection_age_grace: Duration::from_secs(600), max_connection_idle: Some(Duration::from_secs(30 * 60)), - adaptive_work_streams: true, trusted_proxies: TrustedProxies::default(), drain_timeout: Duration::from_secs(10), - overload: OverloadLimits::default(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// In (0, 1] or refused; a client's streams = its share of the limit now, at least 1 + #[test] + fn a_work_share_parses_in_zero_to_one_and_sizes_a_client_by_the_limit() { + // case: share, streams at the 2048 ceiling, at the 128 floor (None = refused) + #[rustfmt::skip] + let cases = [ + ("default 1/16", WorkShare::default().0, Some((128, 8))), + ("load test", 1.0, Some((2048, 128))), + ("tiny", 0.0001, Some((1, 1))), + ("none", 0.0, None), + ("over all", 1.5, None), + ("not a number", f64::NAN, None), + ]; + for (case, share, want) in cases { + let sized = + WorkShare::try_from(share).ok().map(|share| (share.of(2048), share.of(128))); + + assert_eq!(sized, want, "{case}"); } } } diff --git a/packages/zingod-grpc/src/memo.rs b/packages/zingod-grpc/src/memo.rs index 40fcd7096..97374d413 100644 --- a/packages/zingod-grpc/src/memo.rs +++ b/packages/zingod-grpc/src/memo.rs @@ -7,8 +7,12 @@ //! - one publication held: a request pinned on an older one replaces it (brief, at publication) use std::collections::HashMap; +use std::future::Future; use std::hash::Hash; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex}; + +use tokio::sync::OnceCell; +use tonic::Status; pub(crate) struct PerView { last: Mutex>>, @@ -16,7 +20,7 @@ pub(crate) struct PerView { struct Memo { view: Arc, - answers: HashMap>>, + answers: HashMap>>, } impl Default for PerView { @@ -26,7 +30,7 @@ impl Default for PerView { } impl PerView { - /// Already computed for `view`: the inline path (no hop, no permit) + /// Already computed for `view`: the inline path (no hop, no read thread) pub(crate) fn cached(&self, view: &Arc, key: &K) -> Option { let last = self.last.lock().expect("per-view memo poisoned"); let memo = last.as_ref().filter(|memo| Arc::ptr_eq(&memo.view, view))?; @@ -35,11 +39,15 @@ impl PerView { /// `compute` at most once per `(view, key)` /// - /// - concurrent askers of one key block on the first (single flight: the herd after a block - /// costs one computation) - /// - other keys proceed - /// - blocking: call off the async workers when `compute` reads pages - pub(crate) fn get_or_compute(&self, view: &Arc, key: K, compute: impl FnOnce() -> T) -> T { + /// - concurrent askers of one key await the first (the herd after a block = one computation, + /// one read thread; the rest hold no thread) + /// - `Err` (shutdown) not kept: the next asker computes + pub(crate) async fn get_or_compute( + &self, + view: &Arc, + key: K, + compute: impl Future>, + ) -> Result { let cell = { let mut last = self.last.lock().expect("per-view memo poisoned"); let memo = match last.as_mut().filter(|memo| Arc::ptr_eq(&memo.view, view)) { @@ -48,53 +56,55 @@ impl PerView { }; Arc::clone(memo.answers.entry(key).or_default()) }; - cell.get_or_init(compute).clone() + cell.get_or_try_init(|| compute).await.cloned() } } #[cfg(test)] mod tests { - use super::*; + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; - #[test] - fn concurrent_askers_of_one_key_share_one_computation() { - use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use super::*; + /// Eight askers while the first computes: one computation, every asker answered, then inline + #[tokio::test] + async fn concurrent_askers_of_one_key_share_one_computation_and_a_failure_is_not_kept() { let memo: PerView = PerView::default(); let view = Arc::new(1u32); let computed = AtomicUsize::new(0); - let compute = || { + let (release, held) = tokio::sync::watch::channel(false); + let compute = || async { computed.fetch_add(1, SeqCst); - // held open while the other askers arrive - std::thread::sleep(std::time::Duration::from_millis(20)); - 10 + // held open until every asker is waiting + held.clone().wait_for(|&go| go).await.expect("release sender alive"); + Ok(10) }; - assert_eq!(memo.cached(&view, &"tip"), None, "nothing computed yet"); + let failed = memo.get_or_compute(&view, "tip", async { Err(Status::unavailable("x")) }); + assert_eq!(failed.await.map_err(|status| status.code()), Err(tonic::Code::Unavailable)); + assert_eq!(memo.cached(&view, &"tip"), None, "a failure is not an answer"); - let herd: Vec = std::thread::scope(|scope| { - let askers: Vec<_> = (0..8) - .map(|_| scope.spawn(|| memo.get_or_compute(&view, "tip", compute))) - .collect(); - askers.into_iter().map(|asker| asker.join().expect("asker")).collect() - }); + let askers = + futures::future::join_all((0..8).map(|_| memo.get_or_compute(&view, "tip", compute()))); + let herd = futures::future::join(askers, async { release.send(true) }).await.0; + let herd: Vec = herd.into_iter().map(|answer| answer.expect("answered")).collect(); assert_eq!(herd, [10; 8], "every asker answered"); assert_eq!(computed.load(SeqCst), 1, "eight concurrent askers, one computation"); assert_eq!(memo.cached(&view, &"tip"), Some(10), "then served inline"); assert_eq!(memo.cached(&view, &"roots"), None, "another key = its own computation"); } - #[test] - fn a_new_view_starts_empty_and_drops_the_older_one() { + #[tokio::test] + async fn a_new_view_starts_empty_and_drops_the_older_one() { let memo: PerView = PerView::default(); let (first, second) = (Arc::new(1u32), Arc::new(2u32)); - memo.get_or_compute(&first, "tip", || 10); + memo.get_or_compute(&first, "tip", async { Ok(10) }).await.expect("computed"); let fresh = memo.cached(&second, &"tip"); - let computed = memo.get_or_compute(&second, "tip", || 20); + let computed = memo.get_or_compute(&second, "tip", async { Ok(20) }).await; assert_eq!(fresh, None, "a new publication knows nothing"); - assert_eq!(computed, 20, "computed for the new publication"); + assert_eq!(computed.expect("computed"), 20, "computed for the new publication"); assert_eq!(memo.cached(&first, &"tip"), None, "the older publication dropped"); } } diff --git a/packages/zingod-grpc/src/metrics.rs b/packages/zingod-grpc/src/metrics.rs index f71d11663..6841e3f00 100644 --- a/packages/zingod-grpc/src/metrics.rs +++ b/packages/zingod-grpc/src/metrics.rs @@ -7,13 +7,10 @@ use metrics::Unit; use tonic::Code; use zingod_primitives::metric::Metric; -use crate::admission::Class; +use crate::admission::Refusal; use crate::lifetime::RetireReason; use crate::origin::OriginVerdict; -use crate::overload::OverloadCause; -use crate::read_lanes::Lane; use crate::service::{Method, Reply}; -use crate::summary; const REQUESTS_TOTAL: &str = "zingod.grpc.requests_total"; const FIRST_MESSAGE_SECONDS: &str = "zingod.grpc.first_message_seconds"; @@ -21,16 +18,22 @@ const DURATION_SECONDS: &str = "zingod.grpc.duration_seconds"; const SENT_BYTES_TOTAL: &str = "zingod.grpc.sent_bytes_total"; const ACTIVE_STREAMS: &str = "zingod.grpc.active_streams"; const ADMISSION_REJECTED_TOTAL: &str = "zingod.grpc.admission_rejected_total"; -const ACTIVE_SUBSCRIPTIONS: &str = "zingod.grpc.active_subscriptions"; -const SUBSCRIPTIONS_REJECTED_TOTAL: &str = "zingod.grpc.subscriptions_rejected_total"; const ACCEPT_ERRORS_TOTAL: &str = "zingod.grpc.accept_errors_total"; -const DISK_READ_WAIT_SECONDS: &str = "zingod.grpc.disk_read_wait_seconds"; const CONNECTIONS_ACTIVE: &str = "zingod.grpc.connections_active"; const CONNECTIONS_REJECTED_TOTAL: &str = "zingod.grpc.connections_rejected_total"; const STALLED_CONNECTIONS_TOTAL: &str = "zingod.grpc.stalled_connections_total"; +const PARKED_BYTES: &str = "zingod.grpc.parked_bytes"; +const PARKED_EVICTED_TOTAL: &str = "zingod.grpc.parked_evicted_total"; const RETIRED_CONNECTIONS_TOTAL: &str = "zingod.grpc.retired_connections_total"; const ADAPTIVE_STREAM_LIMIT: &str = "zingod.grpc.adaptive_stream_limit"; -const OVERLOAD_LATCHED: &str = "zingod.grpc.overload_latched"; +const ADAPTIVE_STREAM_CEILING: &str = "zingod.grpc.adaptive_stream_ceiling"; +const ADAPTIVE_SCHEDULING_DELAY_SECONDS: &str = "zingod.grpc.adaptive_scheduling_delay_seconds"; +const READ_WAIT_SECONDS: &str = "zingod.grpc.read_wait_seconds"; +const OVERLOAD_SHARE: &str = "zingod.grpc.overload_share"; +const UPLINK_WAITING_CONNECTIONS: &str = "zingod.grpc.uplink_waiting_connections"; +const UPLINK_QUEUE_DELAY_MEDIAN_SECONDS: &str = "zingod.grpc.uplink_queue_delay_median_seconds"; +const UPLINK_RETRANSMITTED_RATIO: &str = "zingod.grpc.uplink_retransmitted_ratio"; +const UPLINK_CONGESTED: &str = "zingod.grpc.uplink_congested"; const ORIGIN_REQUESTS_TOTAL: &str = "zingod.grpc.origin_requests_total"; /// Σ `SENT_BYTES_TOTAL` over methods, readable without the metrics recorder (zingod's egress) @@ -86,30 +89,36 @@ pub const METRICS: &[Metric] = &[ ) .unit(Unit::Seconds), Metric::counter(SENT_BYTES_TOTAL, "Response body bytes, by method").unit(Unit::Bytes), - Metric::gauge(ACTIVE_STREAMS, "Work streams holding an admission slot"), - Metric::counter( - ADMISSION_REJECTED_TOTAL, - "Work streams refused UNAVAILABLE at the adaptive work-stream limit", + Metric::gauge( + ACTIVE_STREAMS, + "Work streams holding an admission slot (one whose client stopped reading loses it when \ + slots run short)", ), - Metric::gauge(ACTIVE_SUBSCRIPTIONS, "GetMempoolStream subscriptions holding a slot"), Metric::counter( - SUBSCRIPTIONS_REJECTED_TOTAL, - "Subscriptions refused UNAVAILABLE at max_subscriptions", + ADMISSION_REJECTED_TOTAL, + "Work streams refused UNAVAILABLE, by reason: limit (the adaptive work-stream limit full), \ + client_share (one address or /64 holding 1/16 of it)", ), Metric::counter( ACCEPT_ERRORS_TOTAL, "accept() failures the listener backed off from (EMFILE, ENFILE, ENOBUFS, ...)", ), - Metric::histogram( - DISK_READ_WAIT_SECONDS, - "Wait for an index-read permit, by lane (point, range, scan)", - ) - .unit(Unit::Seconds), Metric::gauge(CONNECTIONS_ACTIVE, "Open client connections"), Metric::counter( STALLED_CONNECTIONS_TOTAL, "Connections closed for holding data their client did not read within unread_timeout", ), + Metric::gauge( + PARKED_BYTES, + "Bytes held for streams waiting on their clients to read (estimate: 4 KiB + 2 messages \ + each) and request bodies still arriving; over the host's budget the heaviest client's \ + heaviest connection closes", + ) + .unit(Unit::Bytes), + Metric::counter( + PARKED_EVICTED_TOTAL, + "Connections closed to bring parked_bytes back under the host's budget", + ), Metric::counter(CONNECTIONS_REJECTED_TOTAL, "Connections refused by the accept-time caps"), Metric::counter( RETIRED_CONNECTIONS_TOTAL, @@ -117,12 +126,45 @@ pub const METRICS: &[Metric] = &[ ), Metric::gauge( ADAPTIVE_STREAM_LIMIT, - "Work streams admitted at once now (latency-adaptive; max_work_streams when off)", + "Work streams admitted at once now (the ceiling until the CPU falls behind)", + ), + Metric::gauge(ADAPTIVE_STREAM_CEILING, "The work limit's ceiling (limit below it = shedding)"), + Metric::gauge( + ADAPTIVE_SCHEDULING_DELAY_SECONDS, + "gRPC tasks' wait for a CPU core once ready (woken to polled), median of the adaptive \ + limit's last 5 s decision; disk, client and network waits never count (sheds over 0.1 \ + for 15 s)", + ) + .unit(Unit::Seconds), + Metric::histogram( + READ_WAIT_SECONDS, + "Index reads' wait for a thread, by pool: read (read_threads), scan (scan_threads)", + ) + .unit(Unit::Seconds), + Metric::gauge( + OVERLOAD_SHARE, + "Share of connections hurt, smoothed over 60 s (updated every 10 s), by cause: refused \ + (work refused at the limit) or network (waiting on a congested uplink). Overloaded from \ + >= 0.10 (causes summed) until under 0.02", + ), + Metric::gauge( + UPLINK_WAITING_CONNECTIONS, + "Debug: connections whose sending the network held back, mean over the last 10 s (counts \ + toward overload_share only while uplink_congested)", ), Metric::gauge( - OVERLOAD_LATCHED, - "Overload causes latched, by cause (1 = latched, also while detection is off; /readyz names \ - the first only while on)", + UPLINK_QUEUE_DELAY_MEDIAN_SECONDS, + "Debug: median over sending connections of smoothed RTT above the connection's own \ + lifetime lowest (congested at >= 0.05)", + ) + .unit(Unit::Seconds), + Metric::gauge( + UPLINK_RETRANSMITTED_RATIO, + "Debug: share of TCP bytes resent over the last 10 s (congested at >= 0.02)", + ), + Metric::gauge( + UPLINK_CONGESTED, + "Debug: 1 once queue delay or resends stay over their line for 30 s (>= 10 senders)", ), Metric::counter( ORIGIN_REQUESTS_TOTAL, @@ -134,9 +176,28 @@ pub(crate) fn connection_retired(reason: RetireReason) { metrics::counter!(RETIRED_CONNECTIONS_TOTAL, "reason" => reason.label()).increment(1); } -/// Set at each serving summary -pub(crate) fn adaptive_stream_limit(limit: usize) { +/// One adaptive-limit decision: its limit + ceiling, and the median scheduling delay it weighed +pub(crate) fn adaptive_decided(limit: usize, ceiling: usize, delay: Duration) { metrics::gauge!(ADAPTIVE_STREAM_LIMIT).set(limit as f64); + metrics::gauge!(ADAPTIVE_STREAM_CEILING).set(ceiling as f64); + metrics::gauge!(ADAPTIVE_SCHEDULING_DELAY_SECONDS).set(delay.as_secs_f64()); +} + +/// One uplink window: the congestion gate's inputs (waiting, median delay, resent ‰) + verdict +pub(crate) fn uplink_window( + waiting: f64, + median: Duration, + resent_per_mille: u64, + congested: bool, +) { + metrics::gauge!(UPLINK_WAITING_CONNECTIONS).set(waiting); + metrics::gauge!(UPLINK_QUEUE_DELAY_MEDIAN_SECONDS).set(median.as_secs_f64()); + metrics::gauge!(UPLINK_RETRANSMITTED_RATIO).set(resent_per_mille as f64 / 1000.0); + metrics::gauge!(UPLINK_CONGESTED).set(f64::from(u8::from(congested))); +} + +pub(crate) fn read_waited(pool: &'static str, waited: Duration) { + metrics::histogram!(READ_WAIT_SECONDS, "pool" => pool).record(waited); } pub(crate) fn connection_opened() { @@ -150,7 +211,14 @@ pub(crate) fn connection_closed() { /// A connection closed for holding data unread past `unread_timeout` pub(crate) fn connection_stalled() { metrics::counter!(STALLED_CONNECTIONS_TOTAL).increment(1); - summary::connection_stalled(); +} + +pub(crate) fn parked_bytes(total: u64) { + metrics::gauge!(PARKED_BYTES).set(total as f64); +} + +pub(crate) fn parked_evicted() { + metrics::counter!(PARKED_EVICTED_TOTAL).increment(1); } pub(crate) fn accept_failed() { @@ -159,29 +227,18 @@ pub(crate) fn accept_failed() { pub(crate) fn connection_rejected() { metrics::counter!(CONNECTIONS_REJECTED_TOTAL).increment(1); - summary::connection_refused(); -} - -fn active(class: Class) -> &'static str { - match class { - Class::Work => ACTIVE_STREAMS, - Class::Subscription => ACTIVE_SUBSCRIPTIONS, - } } -pub(crate) fn stream_admitted(class: Class) { - metrics::gauge!(active(class)).increment(1.0); +pub(crate) fn stream_admitted() { + metrics::gauge!(ACTIVE_STREAMS).increment(1.0); } -pub(crate) fn stream_released(class: Class) { - metrics::gauge!(active(class)).decrement(1.0); +pub(crate) fn stream_released() { + metrics::gauge!(ACTIVE_STREAMS).decrement(1.0); } -pub(crate) fn stream_rejected(class: Class) { - match class { - Class::Work => metrics::counter!(ADMISSION_REJECTED_TOTAL).increment(1), - Class::Subscription => metrics::counter!(SUBSCRIPTIONS_REJECTED_TOTAL).increment(1), - } +pub(crate) fn stream_rejected(refusal: Refusal) { + metrics::counter!(ADMISSION_REJECTED_TOTAL, "reason" => refusal.label()).increment(1); } fn verdict_label(verdict: OriginVerdict) -> &'static str { @@ -197,14 +254,10 @@ pub(crate) fn origin_request(verdict: OriginVerdict) { metrics::counter!(ORIGIN_REQUESTS_TOTAL, "verdict" => verdict_label(verdict)).increment(1); } -/// Set at each overload window -pub(crate) fn overload_latched(cause: OverloadCause, held: bool) { - metrics::gauge!(OVERLOAD_LATCHED, "cause" => cause.label()).set(f64::from(u8::from(held))); -} - -pub(crate) fn disk_read_waited(lane: Lane, waited: Duration) { - metrics::histogram!(DISK_READ_WAIT_SECONDS, "lane" => lane.label()) - .record(waited.as_secs_f64()); +/// One overload window: wallets hurt by cause, over `open` connections (the latch = readiness) +pub(crate) fn overload_shares(refused: f64, network: f64) { + metrics::gauge!(OVERLOAD_SHARE, "cause" => "refused").set(refused); + metrics::gauge!(OVERLOAD_SHARE, "cause" => "network").set(network); } /// A stream's first message (a one-reply RPC's = its whole answer: [`stream_finished`] times it) @@ -216,16 +269,7 @@ pub(crate) fn first_message(method: Option, elapsed: Duration) { } /// One stream's close-out (recorded where the body drops) -/// -/// - `latency` = time to its first message, for an answered work request -pub(crate) fn stream_finished( - method: Option, - code: Code, - elapsed: Duration, - latency: Option, - sent: u64, -) { - summary::finished(code, latency); +pub(crate) fn stream_finished(method: Option, code: Code, elapsed: Duration, sent: u64) { let name = method_label(method); metrics::counter!(REQUESTS_TOTAL, "method" => name, "code" => code_label(code)).increment(1); // answers only (refusal = µs of no work) diff --git a/packages/zingod-grpc/src/overload.rs b/packages/zingod-grpc/src/overload.rs index bc82a0d01..a7cb355c0 100644 --- a/packages/zingod-grpc/src/overload.rs +++ b/packages/zingod-grpc/src/overload.rs @@ -1,182 +1,118 @@ -//! Overload latch per summary window (`summary::INTERVAL`) → readiness +//! Overload latch: share of wallets hurt, smoothed, over 10 % → readiness `overloaded`, back under 2 % //! -//! - one latch per [`OverloadCause`]: over its threshold for its `enter` → latched, under half of -//! it (refusals: under 2 %) for its `exit` → cleared; reported = the first latched -//! - signals: admission refusals (counted here), CPU / IO pressure (`pressure.rs`) -//! - operator settings live (`set`): while detection is off the latches still step, none reported +//! - hurt = refused work (each connection once a tick) or held back by a congested uplink +//! - each [`TICK`]'s share of its connections, smoothed over [`TIME_CONSTANT`] (an EWMA, as the +//! kernel's PSI averages): a trip takes hurt that lasts, never one bad tick +//! - no minimum count: each input needs a crowd already (refusal = limit ≥ 128 full; network = +//! ≥ 10 senders congested 30 s) -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Mutex; use std::time::Duration; use tracing::{info, warn}; -use crate::admission::Class; use crate::metrics; -use crate::OverloadLimits; -/// Refusals: >= ENTER_PERCENT of work (at >= 1 refusal/s) / < EXIT_PERCENT -const ENTER_PERCENT: u64 = 10; -const EXIT_PERCENT: u64 = 2; +pub(crate) const TICK: Duration = Duration::from_secs(10); -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OverloadCause { - CpuPressure, - IoPressure, - RefusingWork, -} - -impl OverloadCause { - const ALL: [Self; 3] = [Self::CpuPressure, Self::IoPressure, Self::RefusingWork]; - - /// Readiness `detail.message` - pub const fn detail(self) -> &'static str { - match self { - Self::CpuPressure => "Overloaded: CPU pressure", - Self::IoPressure => "Overloaded: IO pressure", - Self::RefusingWork => "Overloaded: refusing work", - } - } - - /// `zingod_grpc_overload_latched{cause}` - pub(crate) const fn label(self) -> &'static str { - match self { - Self::CpuPressure => "cpu_pressure", - Self::IoPressure => "io_pressure", - Self::RefusingWork => "refusing_work", - } - } - - /// (enter, exit) - fn rule(self) -> (Duration, Duration) { - let minutes = |m: u64| Duration::from_secs(m * 60); - match self { - Self::CpuPressure | Self::IoPressure => (minutes(2), minutes(3)), - // admission already sheds within seconds: only a persistent shortfall counts - Self::RefusingWork => (minutes(5), minutes(5)), - } - } -} - -/// One window's signals (`None` = not measured here) -#[derive(Clone, Copy, Debug, Default)] -pub(crate) struct Signals { - pub(crate) cpu: Option, - pub(crate) io: Option, -} +/// 60 s: one tick trips only at ≥ 65 % hurt; 37 % hurt trips in 20 s; release ≈ 2-3 min +const TIME_CONSTANT: Duration = Duration::from_secs(60); -/// One cause's state (`flipping_for` = how long the opposite condition has held) -#[derive(Clone, Copy, Debug, Default)] -struct Latch { - held: bool, - flipping_for: Duration, -} +/// Smoothed share: >= ENTER latches, < EXIT clears (the gap = no flapping) +const ENTER: f64 = 0.10; +const EXIT: f64 = 0.02; -/// `value` against `limit` (0 = off): (over, under half) -fn against(value: Option, limit: f64) -> (bool, bool) { - match value { - Some(value) if limit > 0.0 => (value >= limit, value < limit / 2.0), - _ => (false, true), - } +/// One connection's mark: the tick it was last counted refused in (+1; 0 = never) +#[derive(Debug, Default)] +pub(crate) struct Wallet { + refused_in: AtomicU64, } -#[derive(Debug)] +/// - `network_milli` = connections held back by a congested uplink now (× 1000; the uplink +/// sampler's latest dump, a level: its dumps and these ticks never align) +/// - share of the tick's connections: open at its start (`open_before`) + `opened` in it +#[derive(Debug, Default)] pub(crate) struct Overload { - admitted_work: AtomicU64, - refused_work: AtomicU64, - refused_subscriptions: AtomicU64, - closed: Mutex, + tick: AtomicU64, + refused: AtomicU64, + network_milli: AtomicU64, + open_before: AtomicU64, + opened: AtomicU64, + smoothed: Mutex, + latched: AtomicBool, } -/// As of the last closed window + the operator's settings -#[derive(Debug)] -struct Closed { - limits: OverloadLimits, - detection: bool, - latches: [Latch; OverloadCause::ALL.len()], +/// Smoothed share hurt, by cause (their sum = the latch's input) +#[derive(Debug, Default, Clone, Copy)] +struct Shares { + refused: f64, + network: f64, } impl Overload { - pub(crate) fn new(limits: OverloadLimits) -> Self { - let closed = Closed { limits, detection: true, latches: Default::default() }; - Self { - admitted_work: AtomicU64::new(0), - refused_work: AtomicU64::new(0), - refused_subscriptions: AtomicU64::new(0), - closed: Mutex::new(closed), + /// Refused work; a wallet counts once per tick however often it is refused + pub(crate) fn refused(&self, wallet: &Wallet) { + let mark = self.tick.load(Ordering::Relaxed) + 1; + if wallet.refused_in.swap(mark, Ordering::Relaxed) != mark { + self.refused.fetch_add(1, Ordering::Relaxed); } } - pub(crate) fn set(&self, limits: OverloadLimits, detection: bool) { - let mut closed = self.closed.lock().expect("overload latch poisoned"); - (closed.limits, closed.detection) = (limits, detection); - } - - pub(crate) fn admitted(&self, class: Class) { - if class == Class::Work { - self.admitted_work.fetch_add(1, Ordering::Relaxed); - } - } - - pub(crate) fn refused(&self, class: Class) { - metrics::stream_rejected(class); - let refused = match class { - Class::Work => &self.refused_work, - Class::Subscription => &self.refused_subscriptions, + /// Mean connections the network holds back now (0 = uplink clear; `tcp_info.rs`) + pub(crate) fn network_waiting(&self, connections: f64) { + let milli = (connections.max(0.0) * 1000.0) as u64; + self.network_milli.store(milli, Ordering::Relaxed); + } + + /// A connection accepted (counted into the tick it opens in) + pub(crate) fn connected(&self) { + self.opened.fetch_add(1, Ordering::Relaxed); + } + + /// Folds the tick (`elapsed` long, `connections` open now) into the smoothed share + pub(crate) fn tick(&self, elapsed: Duration, connections: usize) { + self.tick.fetch_add(1, Ordering::Relaxed); + let refused = self.refused.swap(0, Ordering::Relaxed); + let network = self.network_milli.load(Ordering::Relaxed) as f64 / 1000.0; + // every connection the tick had (not just those open at its end: refused wallets reconnect) + let open_now = u64::try_from(connections).unwrap_or(u64::MAX); + let had = self.open_before.swap(open_now, Ordering::Relaxed); + let opened = self.opened.swap(0, Ordering::Relaxed); + let had = had.saturating_add(opened).max(open_now).max(1) as f64; + let instant = + Shares { refused: (refused as f64).min(had) / had, network: network.min(had) / had }; + // elapsed-weighted: a late tick weighs as long as it ran + let weight = 1.0 - (-elapsed.as_secs_f64() / TIME_CONSTANT.as_secs_f64()).exp(); + let shares = { + let mut smoothed = self.smoothed.lock().expect("overload shares mutex poisoned"); + smoothed.refused += weight * (instant.refused - smoothed.refused); + smoothed.network += weight * (instant.network - smoothed.network); + *smoothed }; - refused.fetch_add(1, Ordering::Relaxed); - } - - /// Closes the window (`elapsed` long) on its `signals`: its refusals, every class - pub(crate) fn tick(&self, elapsed: Duration, signals: Signals) -> u64 { - let take = |counter: &AtomicU64| counter.swap(0, Ordering::Relaxed); - let (admitted, refused) = (take(&self.admitted_work), take(&self.refused_work)); - let attempts = admitted.saturating_add(refused); - let percent_of_attempts = |percent: u64| attempts.saturating_mul(percent); - let refused_percent = refused.saturating_mul(100); - let refusing = refused_percent >= percent_of_attempts(ENTER_PERCENT) - && Duration::from_secs(refused) >= elapsed; - let quiet = refused == 0 || refused_percent < percent_of_attempts(EXIT_PERCENT); - - let mut closed = self.closed.lock().expect("overload latch poisoned"); - let limits = &closed.limits; - let percent = |p: u8| f64::from(p) / 100.0; - let conditions = OverloadCause::ALL.map(|cause| match cause { - OverloadCause::CpuPressure => { - against(signals.cpu, percent(limits.cpu_pressure_percent)) + let hurt = shares.refused + shares.network; + let was = self.latched.load(Ordering::Relaxed); + let now = match was { + false => hurt >= ENTER, + true => hurt >= EXIT, + }; + self.latched.store(now, Ordering::Relaxed); + let percent = |share: f64| (share * 1000.0).round() / 10.0; + let (refused_percent, network_percent) = (percent(shares.refused), percent(shares.network)); + match (was, now) { + (false, true) => { + warn!(refused_percent, network_percent, connections, "Overload latched") } - OverloadCause::IoPressure => against(signals.io, percent(limits.io_pressure_percent)), - OverloadCause::RefusingWork => (refusing, quiet), - }); - let detection = closed.detection; - let causes = OverloadCause::ALL.into_iter().zip(conditions); - for ((cause, (over, under)), latch) in causes.zip(&mut closed.latches) { - let (enter, exit) = cause.rule(); - let (flipping, needed) = if latch.held { (under, exit) } else { (over, enter) }; - latch.flipping_for = - if flipping { latch.flipping_for + elapsed } else { Duration::ZERO }; - if latch.flipping_for >= needed { - (latch.held, latch.flipping_for) = (!latch.held, Duration::ZERO); - let cause = cause.detail(); - match latch.held { - true => { - warn!(cause, detection, ?signals, refused, attempts, "Overload latched") - } - false => info!(cause, ?signals, refused, attempts, "Overload cleared"), - } + (true, false) => { + info!(refused_percent, network_percent, connections, "Overload cleared") } - metrics::overload_latched(cause, latch.held); + _ => {} } - - refused.saturating_add(take(&self.refused_subscriptions)) + metrics::overload_shares(shares.refused, shares.network); } - /// The first latched cause (`None` while detection is off) - pub(crate) fn cause(&self) -> Option { - let closed = self.closed.lock().expect("overload latch poisoned"); - let mut latched = OverloadCause::ALL.into_iter().zip(&closed.latches); - let first = latched.find_map(|(cause, latch)| latch.held.then_some(cause)); - first.filter(|_| closed.detection) + pub(crate) fn latched(&self) -> bool { + self.latched.load(Ordering::Relaxed) } } @@ -184,121 +120,81 @@ impl Overload { mod tests { use super::*; - const MINUTE: Duration = Duration::from_secs(60); - - /// One minute of `per_second` work admissions, `refused_percent` of them refused → the cause - fn refusal_minute( - overload: &Overload, - per_second: u64, - refused_percent: u64, - ) -> Option { - let total = per_second * 60; - for _ in 0..total * (100 - refused_percent) / 100 { - overload.admitted(Class::Work); - } - for _ in 0..total * refused_percent / 100 { - overload.refused(Class::Work); - } - overload.tick(MINUTE, Signals::default()); - overload.cause() - } - - /// Enter: >= 10 % refused at >= 1 refusal/s for 5 min; exit: < 2 % for 5 min + /// Smoothed over 60 s: hurt that lasts trips it, one bad tick (< 65 %) never; under 2 % = back #[test] - fn refusing_work_latches_after_five_sustained_minutes_and_clears_after_five_quiet() { - let (none, refusing) = (None, Some(OverloadCause::RefusingWork)); - let latched_5 = [vec![none; 4], vec![refusing]].concat(); - // case, work admissions/s, % refused each minute, cause after each minute + fn the_latch_trips_on_lasting_hurt_over_ten_percent_and_releases_under_two() { + // case, runs of ticks: (refused, held by the network, ticks) of 1000 connections, + // ticks (1-based) where the latch flips #[rustfmt::skip] let cases = [ - ("9 % for 10 min", 100, vec![9; 10], vec![none; 10]), - ("10 % for 5 min", 100, vec![10; 5], latched_5.clone()), - ("30 %, one minute at 25 %", 100, vec![30, 30, 25, 30, 30], latched_5.clone()), - ("50 % of 1/s = 0.5 refusals/s", 1, vec![50; 10], vec![none; 10]), - ("latched, then 2 % for 5 min", 100, [vec![10; 5], vec![2; 5]].concat(), [latched_5.clone(), vec![refusing; 5]].concat()), - ("latched, then 1 % for 5 min", 100, [vec![10; 5], vec![1; 5]].concat(), [latched_5.clone(), vec![refusing; 4], vec![none]].concat()), + ("9 % refused, 5 min", vec![(90, 0, 30)], vec![]), + ("15 % refused", vec![(150, 0, 12)], vec![7]), + ("one tick 60 %", vec![(600, 0, 1), (0, 0, 30)], vec![]), + ("one tick 70 %, then healthy", vec![(700, 0, 1), (0, 0, 30)], vec![1, 12]), + ("37 % network 1 min, then clear", vec![(0, 370, 6), (0, 0, 20)], vec![2, 21]), + ("6 % refused + 6 % network", vec![(60, 60, 30)], vec![11]), + ("tripped, then 5 % holds it", vec![(1000, 0, 1), (50, 0, 40)], vec![1]), ]; - for (case, per_second, refused_percent, causes) in cases { - let overload = Overload::new(OverloadLimits::default()); + for (case, runs, want) in cases { + let overload = Overload::default(); - let latched: Vec<_> = - refused_percent.iter().map(|&p| refusal_minute(&overload, per_second, p)).collect(); + let mut flips = Vec::new(); + let ticks = runs.iter().flat_map(|&(refused, network, ticks)| { + std::iter::repeat_n((refused, network), ticks) + }); + for (tick, (refused, network)) in (1..).zip(ticks) { + let was = overload.latched(); + for _ in 0..refused { + overload.refused(&Wallet::default()); + } + overload.network_waiting(f64::from(network)); + overload.tick(TICK, 1_000); + if overload.latched() != was { + flips.push(tick); + } + } - assert_eq!(latched, causes, "{case}: cause after each minute"); + assert_eq!(flips, want, "{case}: ticks where the latch flipped"); } } + /// Wallets refused then reconnecting: the share is of every connection the tick had, ≤ 100 % #[test] - fn a_window_counts_every_refusal_of_every_class() { - let overload = Overload::new(OverloadLimits::default()); - for _ in 0..120 { - overload.refused(Class::Work); - } - overload.refused(Class::Subscription); - - let refused = overload.tick(MINUTE, Signals::default()); + fn the_share_counts_every_connection_of_the_tick_not_just_those_left_open() { + let overload = Overload::default(); + overload.tick(TICK, 1_000); - assert_eq!(refused, 121, "120 work + 1 subscription refused"); - assert_eq!(overload.tick(MINUTE, Signals::default()), 0, "next window starts at zero"); - } + // 1000 open at the start, 2000 more opened, 3000 refused, 900 left open at the end + for _ in 0..2_000 { + overload.connected(); + } + for _ in 0..3_000 { + overload.refused(&Wallet::default()); + } + overload.tick(TICK, 900); - /// One minute's pressure shares (`None` = unmeasured) - fn signals(cpu: Option, io: Option) -> Signals { - Signals { cpu, io } + let smoothed = overload.smoothed.lock().expect("shares").refused; + let one_tick = 1.0 - (-1.0f64 / 6.0).exp(); + assert!((smoothed - one_tick).abs() < 1e-9, "3000 of 3000 hurt = 100 %: {smoothed}"); + let open_before = overload.open_before.load(Ordering::Relaxed); + assert_eq!(open_before, 900, "the next tick starts from those still open"); } - /// CPU / IO 25 %: enter over the limit for 2 min, exit under half of it for 3 + /// One wallet refused all tick = one wallet hurt; counted again in the next tick #[test] - fn each_pressure_cause_latches_over_its_limit_and_clears_under_half_of_it() { - let (none, cpu, io) = - (None, Some(OverloadCause::CpuPressure), Some(OverloadCause::IoPressure)); - let limits = OverloadLimits::default(); - #[rustfmt::skip] - let cases = [ - ("CPU 30 %; 15 % (not under 12.5) holds; unmeasured 3 min clears", - [signals(Some(0.3), None), signals(Some(0.3), None), signals(Some(0.15), None), - signals(None, None), signals(None, None), signals(None, None)], - [none, cpu, cpu, cpu, cpu, none]), - ("IO 25 % exactly latches; 20 % holds; 10 % for 3 min clears", - [signals(None, Some(0.25)), signals(None, Some(0.25)), signals(None, Some(0.2)), - signals(None, Some(0.1)), signals(None, Some(0.1)), signals(None, Some(0.1))], - [none, io, io, io, io, none]), - ("CPU + IO both latch: CPU named first, then IO", - [signals(Some(0.3), Some(0.3)), signals(Some(0.3), Some(0.3)), signals(Some(0.15), Some(0.3)), - signals(Some(0.1), Some(0.3)), signals(Some(0.1), Some(0.3)), signals(Some(0.1), Some(0.3))], - [none, cpu, cpu, cpu, cpu, io]), - ]; - for (case, minutes, causes) in cases { - let overload = Overload::new(limits.clone()); - - let latched = minutes.map(|minute| { - overload.tick(MINUTE, minute); - overload.cause() - }); - - assert_eq!(latched, causes, "{case}: cause after each minute"); - } - } + fn a_wallet_refused_many_times_counts_once_a_tick() { + let overload = Overload::default(); + let wallet = Wallet::default(); + let count = |overload: &Overload| overload.refused.load(Ordering::Relaxed); - #[test] - fn operator_settings_apply_to_a_latched_cause_live() { - let cpu = Some(OverloadCause::CpuPressure); - let limits = OverloadLimits { cpu_pressure_percent: 25, ..OverloadLimits::default() }; - let overload = Overload::new(limits.clone()); - for _ in 0..2 { - overload.tick(MINUTE, signals(Some(0.3), None)); + for _ in 0..500 { + overload.refused(&wallet); } - assert_eq!(overload.cause(), cpu, "CPU 30 % for 2 min: latched"); - - overload.set(limits.clone(), false); - let detection_off = overload.cause(); - overload.set(OverloadLimits { cpu_pressure_percent: 0, ..limits }, true); - let limit_off = [0; 3].map(|_| { - overload.tick(MINUTE, signals(Some(1.0), None)); - overload.cause() - }); + assert_eq!(count(&overload), 1, "500 refusals, one wallet"); - assert_eq!(detection_off, None, "detection off: latched, never reported"); - assert_eq!(limit_off, [cpu, cpu, None], "CPU limit 0 = off: clears by its 3 min exit"); + overload.tick(TICK, 20); + overload.refused(&wallet); + overload.refused(&Wallet::default()); + assert_eq!(count(&overload), 2, "next tick: the same wallet again + another"); } } diff --git a/packages/zingod-grpc/src/pressure.rs b/packages/zingod-grpc/src/pressure.rs deleted file mode 100644 index ca5e33bd6..000000000 --- a/packages/zingod-grpc/src/pressure.rs +++ /dev/null @@ -1,95 +0,0 @@ -//! CPU / IO pressure (Linux PSI): share of a window this process's cgroup waited, else unmeasured -//! -//! - share = Δ `some total=` µs / window (exact, not the kernel's 10 s / 60 s averages) -//! - never `/proc/pressure` (other processes' stalls would latch zingod's overload) - -use std::path::PathBuf; -use std::time::Duration; - -/// `some … total=<µs>` of a PSI file -fn some_total_us(psi: &str) -> Option { - let some = psi.lines().find(|line| line.starts_with("some "))?; - some.split_whitespace().find_map(|field| field.strip_prefix("total="))?.parse().ok() -} - -#[derive(Debug, Clone, Copy)] -pub(crate) enum Resource { - Cpu, - Io, -} - -impl Resource { - /// PSI file name, under `/proc/pressure` and as `.pressure` in a cgroup - fn name(self) -> &'static str { - match self { - Self::Cpu => "cpu", - Self::Io => "io", - } - } -} - -/// One resource's PSI file + its total at the last window -#[derive(Debug)] -pub(crate) struct Pressure { - file: Option, - last_us: Option, -} - -impl Pressure { - pub(crate) fn new(resource: Resource) -> Self { - let resource = resource.name(); - // cgroup v2: `0::/system.slice/zingod.service` - let cgroup = std::fs::read_to_string("/proc/self/cgroup").ok().and_then(|text| { - let path = text.lines().find_map(|line| line.strip_prefix("0::"))?.to_owned(); - Some(PathBuf::from("/sys/fs/cgroup").join(path.trim_start_matches('/'))) - }); - let file = - cgroup.map(|dir| dir.join(format!("{resource}.pressure"))).filter(|file| file.exists()); - let mut pressure = Self { file, last_us: None }; - pressure.last_us = pressure.read(); - pressure - } - - fn read(&self) -> Option { - some_total_us(&std::fs::read_to_string(self.file.as_ref()?).ok()?) - } - - /// Stalled share since the last call (`elapsed` long) - pub(crate) fn share(&mut self, elapsed: Duration) -> Option { - let now = self.read()?; - let stalled = now.checked_sub(self.last_us.replace(now)?)?; - let window = elapsed.max(Duration::from_micros(1)); - Some(Duration::from_micros(stalled).div_duration_f64(window).min(1.0)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn psi(some_total_us: u64) -> String { - format!("some avg10=1.00 total={some_total_us}\nfull avg10=0.00 total=9\n") - } - - /// Window = Δ `some` total (never `full`'s) / its length, capped at 1; no PSI file or no - /// `some` line = unmeasured - #[test] - fn a_window_is_the_stalled_share_of_its_length() { - let dir = tempfile::tempdir().expect("tempdir"); - let file = dir.path().join("cpu.pressure"); - let mut cpu = Pressure { file: Some(file.clone()), last_us: Some(1_000_000) }; - let minute = Duration::from_secs(60); - - std::fs::write(&file, psi(16_000_000)).expect("write"); - let quarter = cpu.share(minute); - std::fs::write(&file, psi(136_000_000)).expect("write"); - let over = cpu.share(minute); - std::fs::write(&file, "full avg10=0.00 total=1\n").expect("write"); - let no_some_line = cpu.share(minute); - - assert_eq!(quarter, Some(0.25), "15 s stalled of 60 s"); - assert_eq!(over, Some(1.0), "120 s stalled of 60 s: capped"); - assert_eq!(no_some_line, None, "no `some` line"); - assert_eq!(Pressure { file: None, last_us: None }.share(minute), None, "no PSI file"); - } -} diff --git a/packages/zingod-grpc/src/read_lanes.rs b/packages/zingod-grpc/src/read_lanes.rs deleted file mode 100644 index 16907816f..000000000 --- a/packages/zingod-grpc/src/read_lanes.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Index read lanes: semaphore gate around `spawn_blocking` disk reads -//! -//! - the one bounded wait in the serve path (a page-faulting read waits for its lane's permit) - -use std::num::NonZeroUsize; -use std::sync::Arc; -use std::time::Instant; - -use tokio::sync::Semaphore; - -use crate::limits::GrpcLimits; -use crate::metrics; - -/// Index read kind, own permit pool each (heavy never queues light): `Point` = one record / tree -/// state (µs warm), `Range` = one `GetBlockRange` window (<= 1 MiB), `Scan` = an address history -/// (bounded by the row budget) -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Lane { - Point, - Range, - Scan, -} - -impl Lane { - pub(crate) fn label(self) -> &'static str { - match self { - Self::Point => "point", - Self::Range => "range", - Self::Scan => "scan", - } - } -} - -/// Process-wide (clone = share) -#[derive(Clone, Debug)] -pub(crate) struct ReadLanes { - point: Arc, - range: Arc, - scan: Arc, -} - -impl ReadLanes { - pub(crate) fn new(limits: &GrpcLimits) -> Self { - let lane = |max: NonZeroUsize| Arc::new(Semaphore::new(max.get())); - Self { - point: lane(limits.max_point_reads), - range: lane(limits.max_range_reads), - scan: lane(limits.max_scan_reads), - } - } - - /// `read` on the blocking pool under a `lane` permit (faults mmapped pages: never on a runtime - /// worker, shared by metrics + other RPCs) - /// - /// - a panic in `read` resumes here (a broken invariant: zingod aborts) - /// - runtime shutting down → `unavailable` - pub(crate) async fn read( - &self, - lane: Lane, - read: impl FnOnce() -> T + Send + 'static, - ) -> Result { - let pool = match lane { - Lane::Point => &self.point, - Lane::Range => &self.range, - Lane::Scan => &self.scan, - }; - let waiting = Instant::now(); - let _permit = pool.acquire().await.expect("read lanes are never closed"); - metrics::disk_read_waited(lane, waiting.elapsed()); - tokio::task::spawn_blocking(read).await.map_err(|join| match join.try_into_panic() { - Ok(panic) => std::panic::resume_unwind(panic), - Err(_) => tonic::Status::unavailable("shutting down"), - }) - } -} diff --git a/packages/zingod-grpc/src/read_pool.rs b/packages/zingod-grpc/src/read_pool.rs new file mode 100644 index 000000000..85254c323 --- /dev/null +++ b/packages/zingod-grpc/src/read_pool.rs @@ -0,0 +1,154 @@ +//! Index reads on their own threads: `read_threads` in flight at most, never tokio's blocking pool +//! +//! - address-history scans apart (`scan_threads`): a flood of them never queues a block read +//! - tokio's pool = sync's index writes + `/metrics`: a wallet read never queues ahead of them +//! - wait for a thread = disk pressure (`read_wait_seconds`) +//! - a read whose request is gone before a thread takes it = skipped (a cancel never leaks a read) +//! - a request awaiting its read is not runnable: the adaptive limit (CPU queueing) never sees a +//! slow disk + +use std::num::NonZeroUsize; +use std::panic::{self, AssertUnwindSafe}; +use std::sync::Arc; +use std::time::Instant; + +use tonic::Status; + +use crate::metrics; + +/// Process-wide (clone = share) +#[derive(Clone, Debug)] +pub(crate) struct ReadPool { + reads: Arc, + scans: Arc, +} + +impl ReadPool { + pub(crate) fn new( + reads: NonZeroUsize, + scans: NonZeroUsize, + ) -> Result { + let pool = |threads: NonZeroUsize, name: &'static str| { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads.get()) + .thread_name(move |index| format!("zingod-{name}-{index}")) + .build()?; + Ok(Arc::new(pool)) + }; + Ok(Self { reads: pool(reads, "read")?, scans: pool(scans, "scan")? }) + } + + /// `read` on a read thread, oldest first + pub(crate) async fn read( + &self, + read: impl FnOnce() -> T + Send + 'static, + ) -> Result { + run(&self.reads, "read", read).await + } + + /// An address-history scan on a scan thread, oldest first + pub(crate) async fn scan( + &self, + scan: impl FnOnce() -> T + Send + 'static, + ) -> Result { + run(&self.scans, "scan", scan).await + } +} + +/// `read` on one of `pool`'s threads (`label` = its `read_wait_seconds` pool) +/// +/// - panic in `read` resumes here (broken invariant: zingod aborts) +/// - pool gone (shutdown) → `UNAVAILABLE` +async fn run( + pool: &rayon::ThreadPool, + label: &'static str, + read: impl FnOnce() -> T + Send + 'static, +) -> Result { + let (done, outcome) = tokio::sync::oneshot::channel(); + let queued = Instant::now(); + pool.spawn_fifo(move || { + if done.is_closed() { + return; + } + metrics::read_waited(label, queued.elapsed()); + // receiver gone mid-read: nothing left to deliver to + let _ = done.send(panic::catch_unwind(AssertUnwindSafe(read))); + }); + match outcome.await { + Ok(Ok(value)) => Ok(value), + Ok(Err(payload)) => panic::resume_unwind(payload), + Err(_) => Err(Status::unavailable("shutting down")), + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use std::time::Duration; + + use super::*; + + /// One thread held by a slow read: the next waits its turn, a dropped one never runs + #[tokio::test] + async fn reads_queue_for_a_thread_and_a_dropped_one_never_runs() { + let pool = ReadPool::new(NonZeroUsize::MIN, NonZeroUsize::MIN).expect("one of each"); + let ran = Arc::new(AtomicUsize::new(0)); + let (release, hold) = std::sync::mpsc::channel::<()>(); + + let slow = tokio::spawn({ + let pool = pool.clone(); + async move { pool.read(move || hold.recv().is_ok()).await } + }); + let dropped = { + let (pool, ran) = (pool.clone(), Arc::clone(&ran)); + tokio::spawn(async move { pool.read(move || ran.fetch_add(1, SeqCst)).await }) + }; + let queued = tokio::spawn({ + let (pool, ran) = (pool.clone(), Arc::clone(&ran)); + async move { pool.read(move || ran.fetch_add(1, SeqCst)).await } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + dropped.abort(); + // its future gone before the thread frees (else the abort races the released read) + let aborted = dropped.await.expect_err("aborted while queued"); + assert!(aborted.is_cancelled(), "dropped read's task cancelled: {aborted:?}"); + assert!(!queued.is_finished(), "one thread, held: the next read waits"); + release.send(()).expect("slow read listening"); + + let slow = slow.await.expect("slow task").expect("slow read"); + let queued = queued.await.expect("queued task").expect("queued read"); + assert!(slow, "held read answered once released"); + assert_eq!((queued, ran.load(SeqCst)), (0, 1), "only the read still wanted ran"); + } + + /// Scan threads apart: with the one scan thread held, a read completes at once and the next + /// scan waits its turn + #[tokio::test] + async fn a_held_scan_thread_never_delays_a_read_and_scans_queue_behind_it() { + let pool = ReadPool::new(NonZeroUsize::MIN, NonZeroUsize::MIN).expect("one of each"); + let (release, hold) = std::sync::mpsc::channel::<()>(); + let scan = |pool: &ReadPool, scan: Box bool + Send>| { + let pool = pool.clone(); + tokio::spawn(async move { pool.scan(scan).await }) + }; + + let held = scan(&pool, Box::new(move || hold.recv().is_ok())); + let next = scan(&pool, Box::new(|| true)); + tokio::time::sleep(Duration::from_millis(50)).await; + let read = tokio::time::timeout(Duration::from_secs(1), pool.read(|| 7)).await; + let next_waited = !next.is_finished(); + release.send(()).expect("held scan listening"); + + assert_eq!(read.ok().map(|read| read.ok()), Some(Some(7)), "read beside a held scan"); + assert!(next_waited, "one scan thread, held: the next scan waits"); + let scans = (held.await.expect("held task"), next.await.expect("next task")); + assert_eq!((scans.0.ok(), scans.1.ok()), (Some(true), Some(true)), "both scans answered"); + } + + #[tokio::test] + #[should_panic(expected = "index invariant")] + async fn a_panicking_read_resumes_in_its_caller() { + let pool = ReadPool::new(NonZeroUsize::MIN, NonZeroUsize::MIN).expect("one of each"); + let _ = pool.read(|| panic!("index invariant")).await; + } +} diff --git a/packages/zingod-grpc/src/routes.rs b/packages/zingod-grpc/src/routes.rs index c3d12a1b8..2c94d337a 100644 --- a/packages/zingod-grpc/src/routes.rs +++ b/packages/zingod-grpc/src/routes.rs @@ -1,4 +1,5 @@ -//! One module per route group, its handlers (registry + dispatch: [`crate::service`]) +//! One module per route group, its handlers (registry + dispatch: [`crate::service`]; index reads +//! on [`crate::read_pool`]) mod args; pub(super) mod blocks; diff --git a/packages/zingod-grpc/src/routes/blocks.rs b/packages/zingod-grpc/src/routes/blocks.rs index 6f8ea89cb..5718a22db 100644 --- a/packages/zingod-grpc/src/routes/blocks.rs +++ b/packages/zingod-grpc/src/routes/blocks.rs @@ -12,13 +12,14 @@ use zingod_persistence::{OverlayView, PinnedView}; use zingod_sync::IndexKind; use super::args; -use crate::read_lanes::{Lane, ReadLanes}; +use crate::read_pool::ReadPool; use crate::wire::{self, unary_response}; use zingod_proto::proto::service; pub(crate) struct CompactBlocks<'a, V> { pub(crate) served: &'a IndexesAtBlock, pub(crate) reader: CompactBlockReader>, + pub(crate) reads: ReadPool, } /// `GetLatestBlock` answers a `BlockID`, not a block: the served tip (no read at all) @@ -37,14 +38,13 @@ pub(crate) fn get_latest_block(served: &IndexesAtBlock) -> Response pub(crate) async fn get_block( compact_blocks: CompactBlocks<'_, V>, block_id: service::BlockId, - reads: &ReadLanes, ) -> Result, Status> { let block = if block_id.hash.is_empty() { let height = args::height(block_id.height, "height")?; - compact_blocks.read_by_height(height, reads).await? + compact_blocks.read_by_height(height).await? } else { let (height, hash) = compact_blocks.locate(&block_id.hash, "GetBlock")?; - compact_blocks.read_by_hash(height, hash, reads).await? + compact_blocks.read_by_hash(height, hash).await? }; Ok(unary_response(block)) } @@ -53,11 +53,10 @@ pub(crate) async fn get_block( pub(crate) fn get_block_range( compact_blocks: CompactBlocks<'_, V>, range: service::BlockRange, - reads: ReadLanes, ) -> Result, Status> { let pools = args::pools(&range.pool_types)?; let blocks = compact_blocks.open_range(&range, pools)?; - Ok(blocks.into_response(reads, std::convert::identity)) + Ok(blocks.into_response(std::convert::identity)) } impl CompactBlocks<'_, V> { @@ -71,8 +70,8 @@ impl CompactBlocks<'_, V> { args::locate(self.served, self.served_through(), hash, method) } - /// NFS layer (pepper-sync's reorg check at the tip) = RAM, answered inline; else the point lane - async fn read_by_height(self, height: BlockHeight, reads: &ReadLanes) -> Result { + /// NFS layer (pepper-sync's reorg check at the tip) = RAM, answered inline; else a read thread + async fn read_by_height(self, height: BlockHeight) -> Result { if height > self.served_through() { return Err(serve_error_status(ServeError::NotFound { height })); } @@ -84,21 +83,16 @@ impl CompactBlocks<'_, V> { let held = reader.block(height); held.unwrap_or_else(|| panic!("compact-block view holds {height} <= answers_through")) }; - reads.read(Lane::Point, read).await + self.reads.read(read).await } /// Only where this index holds that same block (a located height can lag a reorg) - async fn read_by_hash( - self, - height: BlockHeight, - hash: [u8; 32], - reads: &ReadLanes, - ) -> Result { + async fn read_by_hash(self, height: BlockHeight, hash: [u8; 32]) -> Result { let reader = self.reader; let read = move || { reader.block_at(height, &zcash_protocol::BlockHash(hash)).map_err(serve_error_status) }; - reads.read(Lane::Point, read).await? + self.reads.read(read).await? } /// Walk order up to the first height past [`Self::served_through`] @@ -129,7 +123,7 @@ impl CompactBlocks<'_, V> { let cursor = RangeCursor::new(self.reader, start, end, through, pools) .expect("compact-block view's tip >= answers_through >= start"); - Ok(BlockStream { cursor, past_tip }) + Ok(BlockStream { cursor, past_tip, reads: self.reads }) } } @@ -141,18 +135,15 @@ impl CompactBlocks<'_, V> { pub(super) struct BlockStream { cursor: RangeCursor, past_tip: Option, + reads: ReadPool, } impl BlockStream { /// Server-streaming response, cursor chunk by chunk /// /// - `reproject` = per-chunk rewrite (`identity` for `GetBlockRange`: records stay slices) - pub(super) fn into_response( - self, - reads: ReadLanes, - reproject: fn(Bytes) -> Bytes, - ) -> Response { - let BlockStream { cursor, past_tip } = self; + pub(super) fn into_response(self, reproject: fn(Bytes) -> Bytes) -> Response { + let BlockStream { cursor, past_tip, reads } = self; let chunks = futures::stream::try_unfold((cursor, reads), move |(cursor, reads)| async move { let (cursor, chunk) = next_chunk(cursor, &reads).await?; @@ -165,19 +156,19 @@ impl BlockStream { /// Cursor's next chunk (`None` = spent) /// -/// - disk step = blocking pool, range lane per step not per request (cold mmap refill ~11.7 ms -/// would stall the worker; layer reads never queue) +/// - disk step = a read thread, per step not per request (cold mmap refill ~11.7 ms would stall +/// the worker; layer reads never queue) /// - in-memory step = inline (else a task per block on the highest-volume RPC) async fn next_chunk( mut cursor: RangeCursor, - reads: &ReadLanes, + reads: &ReadPool, ) -> Result<(RangeCursor, Option), Status> { if !cursor.next_touches_disk() { let chunk = cursor.next_chunk(); return Ok((cursor, chunk)); } reads - .read(Lane::Range, move || { + .read(move || { let chunk = cursor.next_chunk(); (cursor, chunk) }) diff --git a/packages/zingod-grpc/src/routes/deprecated_nullifiers.rs b/packages/zingod-grpc/src/routes/deprecated_nullifiers.rs index e81a4668f..a5810de6f 100644 --- a/packages/zingod-grpc/src/routes/deprecated_nullifiers.rs +++ b/packages/zingod-grpc/src/routes/deprecated_nullifiers.rs @@ -18,7 +18,6 @@ use zingod_proto::proto::service; use super::args; use super::blocks::CompactBlocks; -use crate::read_lanes::ReadLanes; use crate::wire; /// `GetBlockRangeNullifiers` @@ -28,13 +27,12 @@ use crate::wire; pub(crate) fn get_block_range_nullifiers( compact_blocks: CompactBlocks<'_, V>, mut range: service::BlockRange, - reads: ReadLanes, ) -> Result, Status> { range.pool_types.retain(|&pool| pool != i32::from(service::PoolType::Transparent)); let pools = args::pools(&range.pool_types)?; let blocks = compact_blocks.open_range(&range, pools)?; - Ok(blocks.into_response(reads, nullifiers_only_chunk)) + Ok(blocks.into_response(nullifiers_only_chunk)) } /// Framed records → framed nullifier-only records, one frame per block diff --git a/packages/zingod-grpc/src/routes/transactions.rs b/packages/zingod-grpc/src/routes/transactions.rs index e84fcb439..c1c16802c 100644 --- a/packages/zingod-grpc/src/routes/transactions.rs +++ b/packages/zingod-grpc/src/routes/transactions.rs @@ -14,7 +14,7 @@ use zingod_source::{ChainDataSource, GetTransactionError, QueryError}; use zingod_traffic::TrafficBalancer; use super::mempool::unmined; -use crate::read_lanes::{Lane, ReadLanes}; +use crate::read_pool::ReadPool; use crate::wire::{frame, unary_response}; /// `SendTransaction`, answered as lightwalletd does (a rejection = a reply, only unreachable = a @@ -47,7 +47,7 @@ pub(crate) async fn send_transaction( pub(crate) async fn get_transaction( validators: &TrafficBalancer, grpc_snapshot: &GrpcSnapshot, - reads: &ReadLanes, + reads: &ReadPool, tx_filter: service::TxFilter, ) -> Result, Status> { let txid: [u8; 32] = tx_filter @@ -68,7 +68,7 @@ pub(crate) async fn get_transaction( pub(super) async fn fetch_raw_transaction( validators: &TrafficBalancer, grpc_snapshot: &GrpcSnapshot, - reads: &ReadLanes, + reads: &ReadPool, txid: TxId, ) -> Result { let found = validators.lookup(move |source| async move { source.get_transaction(txid).await }); @@ -106,7 +106,7 @@ fn raw_transaction_message(found: zingod_source::TransactionResponse) -> RawTran async fn fetch_without_validators( validators: &TrafficBalancer, grpc_snapshot: &GrpcSnapshot, - reads: &ReadLanes, + reads: &ReadPool, txid: TxId, ) -> Result, Status> { if let Some(entry) = grpc_snapshot.mempool().ok().and_then(|mempool| mempool.get(&txid)) { @@ -116,7 +116,7 @@ async fn fetch_without_validators( else { return Ok(None); }; - let Some(mined) = reads.read(Lane::Point, move || index.mined(&txid)).await? else { + let Some(mined) = reads.read(move || index.mined(&txid)).await? else { return Ok(None); }; let Some(raw) = validators.peer_block_bytes(mined.block.hash).await else { return Ok(None) }; @@ -227,7 +227,8 @@ mod tests { let ours = [(txid, bytes::Bytes::from(raw.clone()))]; let held = fixed_snapshots(&chain, tip, Vec::new(), TrustedValidatorSet::at([0]), &ours); let held = held.load(); - let reads = ReadLanes::new(&crate::GrpcLimits::default()); + let one = std::num::NonZeroUsize::MIN; + let reads = crate::read_pool::ReadPool::new(one, one).expect("1 thread each"); let served = fetch_raw_transaction(&routes.validators, &held, &reads, txid).await; let unheld = TxId::from_bytes([9; 32]); diff --git a/packages/zingod-grpc/src/routes/transparent_address.rs b/packages/zingod-grpc/src/routes/transparent_address.rs index 7c11a8281..5d469e331 100644 --- a/packages/zingod-grpc/src/routes/transparent_address.rs +++ b/packages/zingod-grpc/src/routes/transparent_address.rs @@ -22,7 +22,7 @@ use tonic::{body::Body, Status}; use super::args; use super::info::chain_name; -use crate::read_lanes::{Lane, ReadLanes}; +use crate::read_pool::ReadPool; use crate::wire::{self, frame, streamed_response, unary_response}; /// One request's transparent-address index: the reader (as of the served tip, row-capped) + the @@ -30,15 +30,15 @@ use crate::wire::{self, frame, streamed_response, unary_response}; pub(crate) struct AddressIndex { pub(crate) reader: TransparentAddressReader>, pub(crate) network: NetworkType, + pub(crate) reads: ReadPool, } /// `GetAddressUtxos`: every utxo in one list message pub(crate) async fn get_address_utxos( address_index: AddressIndex, request: service::GetAddressUtxosArg, - reads: &ReadLanes, ) -> Result, Status> { - let address_utxos = address_utxos(address_index, &request, reads).await?; + let address_utxos = address_utxos(address_index, &request).await?; let reply = service::GetAddressUtxosReplyList { address_utxos }; Ok(unary_response(wire::frame(&reply))) } @@ -47,9 +47,8 @@ pub(crate) async fn get_address_utxos( pub(crate) async fn get_address_utxos_stream( address_index: AddressIndex, request: service::GetAddressUtxosArg, - reads: &ReadLanes, ) -> Result, Status> { - let address_utxos = address_utxos(address_index, &request, reads).await?; + let address_utxos = address_utxos(address_index, &request).await?; Ok(streamed_response(address_utxos.iter().map(wire::frame).collect())) } @@ -57,9 +56,8 @@ pub(crate) async fn get_address_utxos_stream( pub(crate) async fn get_taddress_balance( address_index: AddressIndex, address_list: service::AddressList, - reads: &ReadLanes, ) -> Result, Status> { - let balance = total_balance(address_index, &address_list.addresses, reads).await?; + let balance = total_balance(address_index, &address_list.addresses).await?; Ok(unary_response(wire::frame(&balance))) } @@ -67,11 +65,10 @@ pub(crate) async fn get_taddress_balance( pub(crate) async fn get_taddress_balance_stream( address_index: AddressIndex, streamed: Vec, - reads: &ReadLanes, ) -> Result, Status> { let addresses: Vec = streamed.into_iter().map(|one| one.address).collect(); - let balance = total_balance(address_index, &addresses, reads).await?; + let balance = total_balance(address_index, &addresses).await?; Ok(unary_response(wire::frame(&balance))) } @@ -82,10 +79,10 @@ pub(crate) async fn get_taddress_transactions validators: TrafficBalancer, grpc_snapshot: Arc>, filter: service::TransparentAddressBlockFilter, - reads: &ReadLanes, ) -> Result, Status> { - let txids = address_txids(address_index, filter, reads).await?; - Ok(streamed_raw_transactions(txids, validators, grpc_snapshot, reads.clone())) + let reads = address_index.reads.clone(); + let txids = address_txids(address_index, filter).await?; + Ok(streamed_raw_transactions(txids, validators, grpc_snapshot, reads)) } /// Utxos of every requested address at or above `startHeight`, height order, capped at @@ -93,7 +90,6 @@ pub(crate) async fn get_taddress_transactions async fn address_utxos( address_index: AddressIndex, request: &service::GetAddressUtxosArg, - reads: &ReadLanes, ) -> Result, Status> { let from = args::height(request.start_height, "startHeight")?; let addresses = request @@ -103,8 +99,9 @@ async fn address_utxos( .collect::, _>>()?; let reader = address_index.reader; - let (addresses, utxos_per_address) = reads - .read(Lane::Scan, move || { + let (addresses, utxos_per_address) = address_index + .reads + .scan(move || { let utxos = reader.utxos_of(&addresses, from); (addresses, utxos) }) @@ -137,7 +134,6 @@ async fn address_utxos( async fn total_balance( address_index: AddressIndex, addresses: &[String], - reads: &ReadLanes, ) -> Result { let distinct: Vec = addresses .iter() @@ -147,7 +143,7 @@ async fn total_balance( .collect(); let reader = address_index.reader; - let balances = reads.read(Lane::Scan, move || reader.balances(&distinct)).await?; + let balances = address_index.reads.scan(move || reader.balances(&distinct)).await?; let total = balances.map_err(serve_error_status)?.into_iter().sum::>(); let total = total.ok_or_else(|| { Status::failed_precondition("these addresses' unspent total exceeds the money supply") @@ -159,7 +155,6 @@ async fn total_balance( async fn address_txids( address_index: AddressIndex, filter: service::TransparentAddressBlockFilter, - reads: &ReadLanes, ) -> Result, Status> { let address = parse_transparent_address(&filter.address, address_index.network)?; let range = filter.range.ok_or_else(|| Status::invalid_argument("range is required"))?; @@ -171,7 +166,7 @@ async fn address_txids( let (start, end) = args::ordered(bound(range.start, "start")?, bound(range.end, "end")?)?; let reader = address_index.reader; - let touching = reads.read(Lane::Scan, move || reader.transactions(&address, start, end)); + let touching = address_index.reads.scan(move || reader.transactions(&address, start, end)); touching.await?.map_err(serve_error_status) } @@ -183,7 +178,7 @@ fn streamed_raw_transactions( txids: Vec, validators: TrafficBalancer, grpc_snapshot: Arc>, - reads: ReadLanes, + reads: ReadPool, ) -> Response { let transactions = futures::stream::iter(txids).then(move |txid| { let (validators, grpc_snapshot) = (validators.clone(), Arc::clone(&grpc_snapshot)); diff --git a/packages/zingod-grpc/src/routes/tree_state.rs b/packages/zingod-grpc/src/routes/tree_state.rs index 4cc33ef4d..636c30d22 100644 --- a/packages/zingod-grpc/src/routes/tree_state.rs +++ b/packages/zingod-grpc/src/routes/tree_state.rs @@ -20,7 +20,7 @@ use zingod_sync::IndexKind; use super::args; use super::info::chain_name; use crate::memo::PerView; -use crate::read_lanes::{Lane, ReadLanes}; +use crate::read_pool::ReadPool; use crate::wire::{self, streamed_response, unary_response}; /// Framed answers per NFS publish: the layer heights every synced wallet asks (the tip among @@ -45,8 +45,8 @@ impl Default for Memos { pub(crate) struct TreeStateReads { pub(crate) indexed: Arc>, pub(crate) reader: TreeStateReader>, - pub(crate) reads: ReadLanes, pub(crate) memos: Arc>, + pub(crate) reads: ReadPool, } impl TreeStateReads { @@ -66,12 +66,12 @@ impl TreeStateReads { self.memoized(|memos| &memos.tree_states, height, frame).await? } - /// Framed tree state at `height`, read on the point lane (not memoized) + /// Framed tree state at `height`, read on a read thread (not memoized) async fn read_tree_state(&self, height: BlockHeight) -> Result { let (reader, through, params) = (self.reader.clone(), self.served_through(), self.served().params()); let read = move || framed_tree_state(&reader, height, through, params); - self.reads.read(Lane::Point, read).await? + self.reads.read(read).await? } /// Framed tree state at `height` only if this index holds `hash` there (a located height can @@ -91,7 +91,7 @@ impl TreeStateReads { } Ok(tree_state_message(&tree_state, params)) }; - self.reads.read(Lane::Point, read).await? + self.reads.read(read).await? } /// Every root of `pool` completed at or below the served tip, framed once per NFS publish @@ -105,8 +105,8 @@ impl TreeStateReads { self.memoized(|memos| &memos.subtree_roots, pool, frame).await } - /// `compute` on first ask per NFS publish, on the point lane (single flight), then the cached - /// answer inline + /// `compute` on first ask per NFS publish, on a read thread (single flight: the herd awaits it, + /// holding no thread), then the cached answer inline async fn memoized( &self, memo: fn(&Memos) -> &Memo, @@ -120,10 +120,9 @@ impl TreeStateReads { if let Some(hit) = memo(&self.memos).cached(&self.indexed, &key) { return Ok(hit); } - let (memos, indexed, reader) = - (Arc::clone(&self.memos), Arc::clone(&self.indexed), self.reader.clone()); - let compute = move || memo(&memos).get_or_compute(&indexed, key, || compute(&reader)); - self.reads.read(Lane::Point, compute).await + let (reads, reader) = (self.reads.clone(), self.reader.clone()); + let computed = async move { reads.read(move || compute(&reader)).await }; + memo(&self.memos).get_or_compute(&self.indexed, key, computed).await } } diff --git a/packages/zingod-grpc/src/service.rs b/packages/zingod-grpc/src/service.rs index 4cbec7bf5..be79a6763 100644 --- a/packages/zingod-grpc/src/service.rs +++ b/packages/zingod-grpc/src/service.rs @@ -13,7 +13,6 @@ use std::{ num::NonZeroUsize, sync::{Arc, OnceLock}, task::{Context, Poll}, - time::Duration, }; use futures::future::BoxFuture; @@ -27,14 +26,12 @@ use zingod_source::ChainDataSource; use zingod_sync::IndexKind; use zingod_traffic::TrafficBalancer; -use crate::admission::Class; -use crate::deadline::Bounds; -use crate::read_lanes::ReadLanes; +use crate::deadline; +use crate::read_pool::ReadPool; use crate::routes::{ blocks, deprecated_nullifiers, info, mempool, transactions, transparent_address, tree_state, }; use crate::wire; -use crate::GrpcLimits; /// Every method's path prefix (`/{service}/{method}`) const SERVICE: &str = "/cash.z.wallet.sdk.rpc.CompactTxStreamer/"; @@ -67,11 +64,10 @@ pub(crate) enum Method { GetStandardFee, } -/// One method's policy: admission pool, reply shape (its latency metric), the index whose view -/// its handler reads (`None` = reads none: always served) +/// One method's policy: reply shape (its latency metric), the index whose view its handler reads +/// (`None` = reads none: always served) #[derive(Clone, Copy, Debug)] pub(crate) struct Route { - pub(crate) class: Class, pub(crate) reply: Reply, pub(crate) index: Option, } @@ -87,40 +83,38 @@ pub(crate) enum Reply { impl Method { /// The registry's policy columns: one arm per method pub(crate) const fn route(self) -> Route { - use Class::{Subscription, Work}; use IndexKind::{CompactBlock, TransparentAddress, TreeState}; use Method::*; use Reply::{One, Stream}; - let (class, reply, index) = match self { - GetLatestBlock => (Work, One, None), - GetBlock => (Work, One, Some(CompactBlock)), - GetBlockRange => (Work, Stream, Some(CompactBlock)), + let (reply, index) = match self { + GetLatestBlock => (One, None), + GetBlock => (One, Some(CompactBlock)), + GetBlockRange => (Stream, Some(CompactBlock)), // TODO: REMOVE — deprecated alias of `GetBlockRange` (pepper-sync still calls it) - GetBlockRangeNullifiers => (Work, Stream, Some(CompactBlock)), - GetTreeState => (Work, One, Some(TreeState)), - GetLatestTreeState => (Work, One, Some(TreeState)), - GetSubtreeRoots => (Work, Stream, Some(TreeState)), - GetAddressUtxos => (Work, One, Some(TransparentAddress)), - GetAddressUtxosStream => (Work, Stream, Some(TransparentAddress)), - GetTaddressBalance => (Work, One, Some(TransparentAddress)), - GetTaddressBalanceStream => (Work, One, Some(TransparentAddress)), + GetBlockRangeNullifiers => (Stream, Some(CompactBlock)), + GetTreeState => (One, Some(TreeState)), + GetLatestTreeState => (One, Some(TreeState)), + GetSubtreeRoots => (Stream, Some(TreeState)), + GetAddressUtxos => (One, Some(TransparentAddress)), + GetAddressUtxosStream => (Stream, Some(TransparentAddress)), + GetTaddressBalance => (One, Some(TransparentAddress)), + GetTaddressBalanceStream => (One, Some(TransparentAddress)), // index names the txs, a validator holds the bytes // (`book/src/contributors/architecture.md` §1) - GetTaddressTransactions => (Work, Stream, Some(TransparentAddress)), + GetTaddressTransactions => (Stream, Some(TransparentAddress)), // TODO: REMOVE — deprecated alias of `GetTaddressTransactions` (pepper-sync calls it) - GetTaddressTxids => (Work, Stream, Some(TransparentAddress)), + GetTaddressTxids => (Stream, Some(TransparentAddress)), // one random entry per attempt, watched until it spreads // (`book/src/contributors/architecture.md` §6) - SendTransaction => (Work, One, None), - GetMempoolTx => (Work, Stream, None), - // open until the served tip moves, silent between arrivals - GetMempoolStream => (Subscription, Stream, None), - GetTransaction => (Work, One, None), - GetLightdInfo => (Work, One, None), - GetStandardFee => (Work, One, None), + SendTransaction => (One, None), + GetMempoolTx => (Stream, None), + GetMempoolStream => (Stream, None), + GetTransaction => (One, None), + GetLightdInfo => (One, None), + GetStandardFee => (One, None), }; - Route { class, reply, index } + Route { reply, index } } /// Wire name (= the `method` metric label) @@ -145,19 +139,17 @@ impl Method { request.extensions().get::().copied() } + /// Open until the served tip moves, idle between arrivals: no work slot, no latency to time + pub(crate) fn is_subscription(self) -> bool { + matches!(self, Self::GetMempoolStream) + } + #[cfg(test)] pub(crate) fn path(self) -> String { format!("{SERVICE}{}", self.name()) } } -impl Route { - /// Open until the next block, silent between arrivals: never idles out, no latency to time - pub(crate) fn is_subscription(self) -> bool { - self.class == Class::Subscription - } -} - /// What one `GrpcService` answers from /// /// - `grpc_snapshots` = every read (chain, indexes, mempool, validator facts) @@ -183,12 +175,11 @@ pub(crate) const STARTING: &str = "starting: not routed yet"; /// [`RouteDeps`] + what every request shares, one `Arc` (a request clones one pointer) /// /// - `routes` set once, after bind (empty = every method `UNAVAILABLE` [`STARTING`]) -/// - `reads` process-wide (every index read on the blocking pool under its lane's permit) +/// - `reads` process-wide (every index read on a read thread: `read_pool.rs`) struct Wired { routes: OnceLock>, - reads: ReadLanes, tree_states: Arc>, - silent_timeout: Duration, + reads: ReadPool, } /// Every `CompactTxStreamer` method, dispatched by path (the tower service each connection runs; @@ -202,10 +193,8 @@ impl Clone for Dispatch { } impl Dispatch { - pub(crate) fn new(limits: &GrpcLimits) -> Self { - let (reads, silent_timeout) = (ReadLanes::new(limits), limits.silent_timeout); - let routes = OnceLock::new(); - Self(Arc::new(Wired { routes, reads, tree_states: Arc::default(), silent_timeout })) + pub(crate) fn new(reads: ReadPool) -> Self { + Self(Arc::new(Wired { routes: OnceLock::new(), tree_states: Arc::default(), reads })) } pub(crate) fn routing(&self) -> Routing { @@ -266,14 +255,13 @@ impl Wired { use wire::{decode, decode_each}; use Method::*; - let request = wire::collect_request(body, method).await?; - let reads = self.reads.clone(); + let request = wire::collect_request(body, Some(method)).await?; let grpc_snapshot = routes.grpc_snapshots.load(); let served = || grpc_snapshot.served().map_err(wire::unavailable); let compact_blocks = || { let served = served()?; let reader = view(served.views().compact_block(), method); - Ok::<_, Status>(blocks::CompactBlocks { served, reader }) + Ok::<_, Status>(blocks::CompactBlocks { served, reader, reads: self.reads.clone() }) }; let tree_states = || { // the NFS publish itself: memo identity (`served()` = its served tip) @@ -281,25 +269,24 @@ impl Wired { let indexed = grpc_snapshot.indexed().ok_or_else(nothing)?; let reader = view(indexed.served().views().tree_state(), method); let (indexed, memos) = (Arc::clone(indexed), Arc::clone(&self.tree_states)); - let reads = reads.clone(); - Ok::<_, Status>(tree_state::TreeStateReads { indexed, reader, reads, memos }) + let reads = self.reads.clone(); + Ok::<_, Status>(tree_state::TreeStateReads { indexed, reader, memos, reads }) }; let address_index = || { let served = served()?; let reader = view(served.views().transparent_address(), method); let reader = reader.as_of(served.tip().height).with_max_rows(routes.max_address_rows); - let network = served.params().network; - Ok::<_, Status>(transparent_address::AddressIndex { reader, network }) + let (network, reads) = (served.params().network, self.reads.clone()); + Ok::<_, Status>(transparent_address::AddressIndex { reader, network, reads }) }; match method { GetLatestBlock => Ok(blocks::get_latest_block(served()?)), - GetBlock => blocks::get_block(compact_blocks()?, decode(&request)?, &reads).await, - GetBlockRange => blocks::get_block_range(compact_blocks()?, decode(&request)?, reads), + GetBlock => blocks::get_block(compact_blocks()?, decode(&request)?).await, + GetBlockRange => blocks::get_block_range(compact_blocks()?, decode(&request)?), GetBlockRangeNullifiers => deprecated_nullifiers::get_block_range_nullifiers( compact_blocks()?, decode(&request)?, - reads, ), GetTreeState => tree_state::get_tree_state(&tree_states()?, decode(&request)?).await, GetLatestTreeState => tree_state::get_latest_tree_state(&tree_states()?).await, @@ -308,20 +295,19 @@ impl Wired { } GetAddressUtxos => { let index = address_index()?; - transparent_address::get_address_utxos(index, decode(&request)?, &reads).await + transparent_address::get_address_utxos(index, decode(&request)?).await } GetAddressUtxosStream => { let index = address_index()?; - transparent_address::get_address_utxos_stream(index, decode(&request)?, &reads) - .await + transparent_address::get_address_utxos_stream(index, decode(&request)?).await } GetTaddressBalance => { let index = address_index()?; - transparent_address::get_taddress_balance(index, decode(&request)?, &reads).await + transparent_address::get_taddress_balance(index, decode(&request)?).await } GetTaddressBalanceStream => { let (index, request) = (address_index()?, decode_each(&request)?); - transparent_address::get_taddress_balance_stream(index, request, &reads).await + transparent_address::get_taddress_balance_stream(index, request).await } GetTaddressTransactions | GetTaddressTxids => { transparent_address::get_taddress_transactions( @@ -329,7 +315,6 @@ impl Wired { routes.validators.clone(), Arc::clone(&grpc_snapshot), decode(&request)?, - &reads, ) .await } @@ -341,7 +326,7 @@ impl Wired { GetTransaction => { let validators = &routes.validators; let filter = decode(&request)?; - transactions::get_transaction(validators, &grpc_snapshot, &reads, filter).await + transactions::get_transaction(validators, &grpc_snapshot, &self.reads, filter).await } GetLightdInfo => info::get_lightd_info(&grpc_snapshot, routes.network, routes.version), GetStandardFee => info::get_standard_fee(&grpc_snapshot, routes.network), @@ -383,11 +368,10 @@ where let wired = Arc::clone(&self.0); let path = request.uri().path().to_owned(); let method = Method::of_request(&request); - let bounded = method.is_none_or(|method| !method.route().is_subscription()); - let bounds = Bounds::of(request.headers(), bounded.then_some(wired.silent_timeout)); - Box::pin( - async move { Ok(bounds.apply(wired.answer(method, &path, request.into_body())).await) }, - ) + let deadline = deadline::of(request.headers()); + Box::pin(async move { + Ok(deadline::apply(deadline, wired.answer(method, &path, request.into_body())).await) + }) } } diff --git a/packages/zingod-grpc/src/stall.rs b/packages/zingod-grpc/src/stall.rs index 354e70f20..ac08fb4db 100644 --- a/packages/zingod-grpc/src/stall.rs +++ b/packages/zingod-grpc/src/stall.rs @@ -1,33 +1,238 @@ -//! Streams whose client stopped reading +//! Streams whose client stopped reading: per connection past `unread_timeout`, node-wide past the +//! [`Parked`] memory budget //! //! - flow control stalls hyper on `poll_capacity`: it stops polling the body, so a stream cannot -//! notice from inside, and a live peer that never reads keeps every permit it holds +//! notice from inside, only its connection can close //! - owing = a body handed hyper a data frame and has not been polled since (a `Pending` body = //! idle or waiting on a read, never owing) -//! - the connection's watchdog closes it once any stream has owed for `unread_timeout` +//! - owing past [`GRACE`] with the work pool nearly full: its work slot reclaimed +//! ([`reclaim_idle`]; a client reading on keeps its slot, as one never reading cannot hold it) +//! - the connection's watchdog closes it once any stream has owed for `unread_timeout`, or once +//! [`Parked`] picks it to bring the node's owed bytes back under budget use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; -use tokio::time::Instant; +use tokio::sync::Notify; +use tokio::time::{Instant, MissedTickBehavior}; +use tokio_util::sync::CancellationToken; -/// One connection's owing streams, by ticket id → since when -#[derive(Debug, Default)] +use crate::admission::{AdmissionState, Claim}; +use crate::{metrics, summary}; + +/// Owing this long = its client is not reading (a syncing wallet takes the next message well +/// within it): the work slot is reclaimable +pub(crate) const GRACE: Duration = Duration::from_secs(1); + +/// Reclaim sweep cadence while the pool is pressed (a refused newcomer waits at most this) +const SWEEP: Duration = Duration::from_millis(250); + +/// Per owing stream beyond its messages: h2 stream state + the route's cursor +const OVERHEAD: u64 = 4 * 1024; + +/// One owing stream holds ≈ 2 messages: one in h2's send buffer, one hyper waits to send +const MESSAGES_HELD: u64 = 2; + +/// Over budget, an eviction pass at most this often (each scans every connection; the evicted +/// take a moment to close, so passes per frame would rescan a flood at its peak) +const EVICT_EVERY: Duration = Duration::from_millis(100); + +/// Bytes the node holds for owing streams, by client, against one budget (the host's: zingod +/// derives it from memory) +/// +/// - over budget → the heaviest client's heaviest connection closes, until the rest fit (one +/// hoarding address evicts itself; a wallet with one waiting stream goes last) +/// - `clients` = each client's live connections (IPv4 address, IPv6 /64: one subscriber's prefix) +#[derive(Debug)] +pub(crate) struct Parked { + budget: u64, + total: AtomicU64, + clients: Mutex>>>, + evicted_at: Mutex>, +} + +impl Default for Parked { + fn default() -> Self { + Self::new(u64::MAX) + } +} + +impl Parked { + pub(crate) fn new(budget: u64) -> Self { + let (total, clients) = (AtomicU64::new(0), Mutex::new(HashMap::new())); + Self { budget, total, clients, evicted_at: Mutex::new(None) } + } + + /// A connection's watch, counted under its client until dropped + pub(crate) fn watch(self: &Arc, client: IpAddr) -> Arc { + let client = Client::of(client); + let watch = Arc::new(Watch::under(Arc::clone(self), client)); + let mut clients = self.clients.lock().expect("parked clients mutex poisoned"); + clients.entry(client).or_default().push(Arc::downgrade(&watch)); + watch + } + + fn charge(&self, bytes: u64) { + let total = self.total.fetch_add(bytes, Ordering::Relaxed).saturating_add(bytes); + metrics::parked_bytes(total); + if total > self.budget && self.eviction_due() { + self.evict(); + } + } + + fn eviction_due(&self) -> bool { + let mut evicted_at = self.evicted_at.lock().expect("eviction time mutex poisoned"); + if evicted_at.is_some_and(|at| at.elapsed() < EVICT_EVERY) { + return false; + } + *evicted_at = Some(Instant::now()); + true + } + + fn release(&self, bytes: u64) { + let total = self.total.fetch_sub(bytes, Ordering::Relaxed).saturating_sub(bytes); + metrics::parked_bytes(total); + } + + /// Marks connections to close, the heaviest client's heaviest first, until the bytes not + /// already leaving fit the budget + fn evict(&self) { + let clients = self.clients.lock().expect("parked clients mutex poisoned"); + let live: Vec>> = clients + .values() + .map(|watches| watches.iter().filter_map(Weak::upgrade).collect()) + .collect(); + drop(clients); + let staying = |watch: &&Arc| !watch.evicted.load(Ordering::Relaxed); + let owed = |watch: &Arc| watch.owed.load(Ordering::Relaxed); + let leaving: u64 = live.iter().flatten().filter(|watch| !staying(watch)).map(owed).sum(); + let mut held = self.total.load(Ordering::Relaxed).saturating_sub(leaving); + while held > self.budget { + let heaviest = live + .iter() + .max_by_key(|watches| watches.iter().filter(staying).map(owed).sum::()); + let Some(watch) = heaviest + .and_then(|watches| watches.iter().filter(staying).max_by_key(|watch| owed(watch))) + else { + return; + }; + if owed(watch) == 0 { + return; + } + held = held.saturating_sub(owed(watch)); + watch.evicted.store(true, Ordering::Relaxed); + watch.evict.notify_one(); + metrics::parked_evicted(); + summary::evicted(); + } + } + + /// Work slots of streams owing for `grace` or longer, back to the pool (count reclaimed) + pub(crate) fn reclaim(&self, grace: Duration) -> usize { + let watches: Vec> = { + let clients = self.clients.lock().expect("parked clients mutex poisoned"); + clients.values().flatten().filter_map(Weak::upgrade).collect() + }; + let mut reclaimed = 0; + for watch in watches { + let owing = watch.owing.lock().expect("stall watch poisoned"); + let idle = owing.values().filter(|owing| owing.since.elapsed() >= grace); + reclaimed += + idle.filter_map(|owing| owing.claim.as_ref()).filter(|c| c.reclaim()).count(); + } + reclaimed + } +} + +/// Until `cancel`: every [`SWEEP`] while the work pool is pressed, idle streams' slots reclaimed +pub(crate) async fn reclaim_idle( + parked: Arc, + admission: Arc, + cancel: CancellationToken, +) { + let mut sweeps = tokio::time::interval(SWEEP); + sweeps.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = cancel.cancelled() => return, + _ = sweeps.tick() => {} + } + if admission.pressed() { + parked.reclaim(GRACE); + } + } +} + +/// Unit of fairness (eviction, work share): an IPv4 address, or an IPv6 /64 (one subscriber's +/// prefix) +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct Client(IpAddr); + +impl Client { + fn of(ip: IpAddr) -> Self { + match ip.to_canonical() { + IpAddr::V6(v6) => { + let [a, b, c, d, ..] = v6.segments(); + Self(IpAddr::V6(Ipv6Addr::new(a, b, c, d, 0, 0, 0, 0))) + } + v4 => Self(v4), + } + } +} + +/// One connection's owing streams, by ticket id (`owed` = their charged bytes) +#[derive(Debug)] pub(crate) struct Watch { - owing: Mutex>, + owing: Mutex>, issued: AtomicU64, + owed: AtomicU64, + evicted: AtomicBool, + evict: Notify, + parked: Arc, + client: Client, +} + +/// One owing stream: since when, and its work slot (`None` = a subscription, holding none) +#[derive(Debug)] +struct Owing { + since: Instant, + claim: Option>, +} + +/// Unbudgeted, unregistered (tests) +impl Default for Watch { + fn default() -> Self { + Self::under(Arc::default(), Client(IpAddr::V4(Ipv4Addr::UNSPECIFIED))) + } } impl Watch { + fn under(parked: Arc, client: Client) -> Self { + Self { + owing: Mutex::new(HashMap::new()), + issued: AtomicU64::new(0), + owed: AtomicU64::new(0), + evicted: AtomicBool::new(false), + evict: Notify::new(), + parked, + client, + } + } + + pub(crate) fn client(&self) -> Client { + self.client + } + pub(crate) fn ticket(self: &Arc) -> Ticket { let id = self.issued.fetch_add(1, Ordering::Relaxed); - Ticket { watch: Arc::clone(self), id, owing: false } + Ticket { watch: Arc::clone(self), id, charged: None } } pub(crate) fn oldest(&self) -> Option { - self.owing.lock().expect("stall watch poisoned").values().min().copied() + self.owing.lock().expect("stall watch poisoned").values().map(|owing| owing.since).min() } /// Resolves once some stream has owed for `timeout` (sleeps to the oldest deadline) @@ -43,30 +248,56 @@ impl Watch { tokio::time::sleep_until(deadline).await; } } + + /// Resolves once [`Parked`] picks this connection to close + pub(crate) async fn evicted(&self) { + // notify_one keeps its permit for a waiter that arrives later + if !self.evicted.load(Ordering::Relaxed) { + self.evict.notified().await; + } + } +} + +impl Drop for Watch { + fn drop(&mut self) { + let mut clients = self.parked.clients.lock().expect("parked clients mutex poisoned"); + if let Some(watches) = clients.get_mut(&self.client) { + watches.retain(|watch| watch.strong_count() > 0); + if watches.is_empty() { + clients.remove(&self.client); + } + } + } } -/// One stream's standing with its connection's [`Watch`] (locks only on a transition) +/// One stream's standing with its connection's [`Watch`] (`charged` = its bytes while owing) #[derive(Debug)] pub(crate) struct Ticket { watch: Arc, id: u64, - owing: bool, + charged: Option, } impl Ticket { - /// Handed hyper a data frame: owing until the next poll - pub(crate) fn handed(&mut self) { - if !self.owing { - self.watch.owing.lock().expect("stall watch poisoned").insert(self.id, Instant::now()); - self.owing = true; + /// Handed hyper a `len`-byte data frame: owing until the next poll (`claim` = its work slot) + pub(crate) fn handed(&mut self, len: usize, claim: Option>) { + if self.charged.is_none() { + let len = u64::try_from(len).unwrap_or(u64::MAX); + let bytes = OVERHEAD.saturating_add(len.saturating_mul(MESSAGES_HELD)); + let owing = Owing { since: Instant::now(), claim }; + self.watch.owing.lock().expect("stall watch poisoned").insert(self.id, owing); + self.watch.owed.fetch_add(bytes, Ordering::Relaxed); + self.charged = Some(bytes); + self.watch.parked.charge(bytes); } } /// Polled again: hyper had room for more pub(crate) fn pulled(&mut self) { - if self.owing { + if let Some(bytes) = self.charged.take() { self.watch.owing.lock().expect("stall watch poisoned").remove(&self.id); - self.owing = false; + self.watch.owed.fetch_sub(bytes, Ordering::Relaxed); + self.watch.parked.release(bytes); } } } @@ -77,6 +308,34 @@ impl Drop for Ticket { } } +/// A request body arriving before admission: its bytes charged as the connection's until dropped +/// (a client trickling big bodies = the heaviest, evicted as for unread responses) +#[derive(Debug)] +pub(crate) struct Arriving { + watch: Arc, + bytes: u64, +} + +impl Arriving { + pub(crate) fn of(watch: &Arc) -> Self { + Self { watch: Arc::clone(watch), bytes: 0 } + } + + pub(crate) fn add(&mut self, len: usize) { + let len = u64::try_from(len).unwrap_or(u64::MAX); + self.bytes = self.bytes.saturating_add(len); + self.watch.owed.fetch_add(len, Ordering::Relaxed); + self.watch.parked.charge(len); + } +} + +impl Drop for Arriving { + fn drop(&mut self) { + self.watch.owed.fetch_sub(self.bytes, Ordering::Relaxed); + self.watch.parked.release(self.bytes); + } +} + #[cfg(test)] mod tests { use super::*; @@ -89,8 +348,8 @@ mod tests { let watch = Arc::new(Watch::default()); let (mut reading, mut stuck) = (watch.ticket(), watch.ticket()); let start = Instant::now(); - reading.handed(); - stuck.handed(); + reading.handed(5, None); + stuck.handed(5, None); let stalled = tokio::spawn({ let watch = Arc::clone(&watch); async move { watch.stalled(TIMEOUT).await } @@ -98,7 +357,7 @@ mod tests { tokio::time::sleep(TIMEOUT / 2).await; reading.pulled(); - reading.handed(); + reading.handed(5, None); stalled.await.expect("stalled"); assert_eq!(start.elapsed(), TIMEOUT, "the stuck stream's frame, unpulled for TIMEOUT"); @@ -119,11 +378,67 @@ mod tests { tokio::time::sleep(TIMEOUT * 3).await; let mut late = watch.ticket(); - late.handed(); + late.handed(5, None); stalled.await.expect("stalled"); let tripped_at = start.elapsed(); let window = TIMEOUT * 4..=TIMEOUT * 5; assert!(window.contains(&tripped_at), "quiet 3 × TIMEOUT, tripped at {tripped_at:?}"); } + + /// Over budget: the heaviest client's heaviest connection closes, once, and only as many as + /// the budget needs; a wallet with one waiting stream stays; an IPv6 /64 = one client; one + /// eviction pass per [`EVICT_EVERY`] however many charges land meanwhile + #[tokio::test(start_paused = true)] + async fn over_budget_the_heaviest_clients_heaviest_connection_closes() { + const KIB: usize = 1024; + // each owing stream: 4 KiB + 2 × its frame (16 KiB frame = 36 KiB, 40 KiB frame = 84 KiB) + let parked = Arc::new(Parked::new(400 * 1024)); + let hoarder = |n: u16| IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 1, 0, 0, 0, n)); + let (big, small) = (parked.watch(hoarder(1)), parked.watch(hoarder(2))); + let wallet = parked.watch(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7))); + + // wallet 36 KiB; one /64 over two addresses: big 3 × 84, small 1 × 84 → 372 KiB, fits + let mut tickets = vec![wallet.ticket()]; + tickets[0].handed(16 * KIB, None); + for watch in [&big, &big, &big, &small] { + let mut ticket = watch.ticket(); + ticket.handed(40 * KIB, None); + tickets.push(ticket); + } + let evicted = |watch: &Watch| watch.evicted.load(Ordering::Relaxed); + assert_eq!(parked.total.load(Ordering::Relaxed), 372 * 1024); + assert!(![&wallet, &big, &small].iter().any(|watch| evicted(watch)), "under budget"); + + // small waits once more (456 KiB): the /64 (420) outweighs the wallet; big (252) > small + let mut over = small.ticket(); + over.handed(40 * KIB, None); + let flags: Vec = [&wallet, &big, &small].iter().map(|watch| evicted(watch)).collect(); + assert_eq!( + flags, + [false, true, false], + "the /64 = heaviest client; its heaviest connection" + ); + tokio::time::timeout(Duration::from_secs(1), big.evicted()).await.expect("notified"); + + // big's bytes count as leaving: another small charge evicts nothing more + let mut more = wallet.ticket(); + more.handed(KIB, None); + assert!(!evicted(&small) && !evicted(&wallet), "big leaving brings the rest under budget"); + + // wallet floods 204 KiB: 409 KiB not leaving, over again, but within EVICT_EVERY of the + // last pass: no scan; the first charge after it evicts the wallet (246 KiB > /64's 172) + let mut flood = wallet.ticket(); + flood.handed(100 * KIB, None); + assert!(!evicted(&wallet), "a pass ran under EVICT_EVERY ago: this charge skips it"); + tokio::time::advance(EVICT_EVERY).await; + let mut next = small.ticket(); + next.handed(0, None); + assert!(evicted(&wallet) && !evicted(&small), "next pass: the now-heaviest client"); + + // closing returns every byte; the client table forgets dropped connections + drop((tickets, over, more, flood, next, big, small, wallet)); + assert_eq!(parked.total.load(Ordering::Relaxed), 0, "every charge released"); + assert!(parked.clients.lock().expect("clients").is_empty(), "no dropped watch kept"); + } } diff --git a/packages/zingod-grpc/src/summary.rs b/packages/zingod-grpc/src/summary.rs index 880c03747..2f9797667 100644 --- a/packages/zingod-grpc/src/summary.rs +++ b/packages/zingod-grpc/src/summary.rs @@ -1,11 +1,7 @@ -//! Serving summary every [`INTERVAL`] (per-method latency, bytes, codes = the `zingod.grpc.*` -//! metrics) +//! `Serving` log line every [`INTERVAL`]: rate, connections, refused, failed, evicted (rest = metrics) //! -//! - `Serving`: rate, connections held, then the window's problems by count (silent while nothing -//! served or held) -//! - `Serving` level: WARN once any request failed, was refused, stalled or ran slow, else INFO -//! - first server fault (ERROR `Request failed`) + first unavailable answer (WARN `Request -//! unavailable`) of a window logged as they happen, the rest only counted +//! - WARN once any request was refused or failed or a connection evicted, else INFO; silent idle +//! - first server fault of a window logged as it happens (ERROR `Request failed`), the rest counted use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Duration; @@ -18,156 +14,56 @@ use crate::service::Method; pub(crate) const INTERVAL: Duration = Duration::from_secs(60); -/// Time to first message past this = a slow request -const SLOW: Duration = Duration::from_secs(1); +static REQUESTS: AtomicU64 = AtomicU64::new(0); +static REFUSED: AtomicU64 = AtomicU64::new(0); +static FAILED: AtomicU64 = AtomicU64::new(0); +static EVICTED: AtomicU64 = AtomicU64::new(0); +static FAILURE_LOGGED: AtomicBool = AtomicBool::new(false); -/// Code this server answers for (any other = the client's: bad argument, not found, cancelled) -/// -/// - `Refused` = not now (capacity, nothing served yet, validator down), `Failed` = this server -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Blame { - Refused, - Failed, +/// This server's fault (any other non-`Ok` = the client's or a refusal) +fn is_failure(code: Code) -> bool { + matches!(code, Code::Unknown | Code::Internal | Code::DataLoss) } -fn blame(code: Code) -> Option { - match code { - Code::Unavailable | Code::ResourceExhausted => Some(Blame::Refused), - Code::Unknown | Code::Internal | Code::DataLoss => Some(Blame::Failed), - _ => None, +/// Stream close-out; a window's first failure logged with the message its client got +pub(crate) fn finished(method: Option, code: Code, message: &str) { + REQUESTS.fetch_add(1, Ordering::Relaxed); + if matches!(code, Code::Unavailable | Code::ResourceExhausted) { + REFUSED.fetch_add(1, Ordering::Relaxed); } -} - -/// Everything counted since the last summary (`*_logged` = this window's first already logged) -struct Window { - requests: AtomicU64, - refused: AtomicU64, - failed: AtomicU64, - slow: AtomicU64, - connections_refused: AtomicU64, - stalled: AtomicU64, - failure_logged: AtomicBool, - unavailable_logged: AtomicBool, -} - -#[derive(Debug, Default, PartialEq, Eq)] -struct Counts { - requests: u64, - refused: u64, - failed: u64, - slow: u64, - connections_refused: u64, - stalled: u64, -} - -impl Window { - const fn new() -> Self { - Self { - requests: AtomicU64::new(0), - refused: AtomicU64::new(0), - failed: AtomicU64::new(0), - slow: AtomicU64::new(0), - connections_refused: AtomicU64::new(0), - stalled: AtomicU64::new(0), - failure_logged: AtomicBool::new(false), - unavailable_logged: AtomicBool::new(false), - } - } - - fn finished(&self, code: Code, latency: Option) { - let count = |counter: &AtomicU64| counter.fetch_add(1, Ordering::Relaxed); - count(&self.requests); - match blame(code) { - Some(Blame::Refused) => count(&self.refused), - Some(Blame::Failed) => count(&self.failed), - None => 0, - }; - if latency.is_some_and(|latency| latency > SLOW) { - count(&self.slow); - } - } - - /// Every counter read and zeroed (a request landing mid-swap counts in one window or the next) - fn take(&self) -> Counts { - let take = |counter: &AtomicU64| counter.swap(0, Ordering::Relaxed); - self.failure_logged.store(false, Ordering::Relaxed); - self.unavailable_logged.store(false, Ordering::Relaxed); - Counts { - requests: take(&self.requests), - refused: take(&self.refused), - failed: take(&self.failed), - slow: take(&self.slow), - connections_refused: take(&self.connections_refused), - stalled: take(&self.stalled), + if is_failure(code) { + FAILED.fetch_add(1, Ordering::Relaxed); + if !FAILURE_LOGGED.swap(true, Ordering::Relaxed) { + let (method, code) = (method_label(method), code_label(code)); + error!(method, code, error = message, "Request failed"); } } } -static WINDOW: Window = Window::new(); - -/// Stream close-out (`latency` = time to its first message, for an answered work request) -pub(crate) fn finished(code: Code, latency: Option) { - WINDOW.finished(code, latency); -} - -pub(crate) fn connection_refused() { - WINDOW.connections_refused.fetch_add(1, Ordering::Relaxed); +/// A connection closed for holding the most unread responses past their budget (`stall.rs`) +pub(crate) fn evicted() { + EVICTED.fetch_add(1, Ordering::Relaxed); } -pub(crate) fn connection_stalled() { - WINDOW.stalled.fetch_add(1, Ordering::Relaxed); +/// (requests, refused, failed, evicted) since the last call, zeroed +fn take() -> (u64, u64, u64, u64) { + let take = |counter: &AtomicU64| counter.swap(0, Ordering::Relaxed); + FAILURE_LOGGED.store(false, Ordering::Relaxed); + (take(&REQUESTS), take(&REFUSED), take(&FAILED), take(&EVICTED)) } -/// A server fault or unavailable answer (never an admission refusal): the window's first of each -/// is logged now, with the message the client got -pub(crate) fn answered_badly(method: Option, code: Code, message: &str) { - let first = |logged: &AtomicBool| !logged.swap(true, Ordering::Relaxed); - let method = method_label(method); - match blame(code) { - Some(Blame::Failed) if first(&WINDOW.failure_logged) => { - error!(method, code = code_label(code), error = message, "Request failed"); - } - Some(Blame::Refused) if first(&WINDOW.unavailable_logged) => { - warn!(method, error = message, "Request unavailable"); - } - _ => {} - } -} - -/// Logs the window since the last call (`elapsed` long, `connections` held now, `at_capacity` -/// admission refusals) and starts the next -pub(crate) fn summarise(elapsed: Duration, connections: usize, at_capacity: u64) { - let counts = WINDOW.take(); - let problems = - counts.refused + counts.failed + counts.slow + counts.stalled + counts.connections_refused; - // no connection = no stream held either - if counts.requests == 0 && connections == 0 && problems == 0 { +/// Logs the window since the last call (`elapsed` long, `connections` held now) +pub(crate) fn summarise(elapsed: Duration, connections: usize) { + let (requests, refused, failed, evicted) = take(); + if requests == 0 && connections == 0 { return; } - // requests × 1 s / window = per second - let window = elapsed.max(Duration::from_nanos(1)); - let per_s = Duration::from_secs(counts.requests).div_duration_f64(window); + let per_s = + Duration::from_secs(requests).div_duration_f64(elapsed.max(Duration::from_nanos(1))); let rps = (per_s * 100.0).round() / 100.0; - let nonzero = |count: u64| (count > 0).then_some(count); - - macro_rules! serving { - ($level:ident) => { - $level!( - rps, - conns = connections, - failed = nonzero(counts.failed), - refused = nonzero(counts.refused), - at_capacity = nonzero(at_capacity), - slow = nonzero(counts.slow), - stalled = nonzero(counts.stalled), - conns_refused = nonzero(counts.connections_refused), - "Serving" - ) - }; - } - match problems { - 0 => serving!(info), - _ => serving!(warn), + match refused + failed + evicted { + 0 => info!(rps, conns = connections, "Serving"), + _ => warn!(rps, conns = connections, refused, failed, evicted, "Serving"), } } @@ -175,28 +71,17 @@ pub(crate) fn summarise(elapsed: Duration, connections: usize, at_capacity: u64) mod tests { use super::*; - /// - codes split by who they blame (`NotFound`, `Cancelled` = the client's: uncounted) - /// - slow = past [`SLOW`] to the first message - /// - taken = zeroed + /// Refusals + server faults counted apart; client errors only as requests; taken = zeroed #[test] - fn a_window_counts_refusals_failures_and_slow_requests() { - let window = Window::new(); - window.finished(Code::Ok, Some(SLOW)); - window.finished(Code::Ok, Some(SLOW + Duration::from_millis(1))); - for code in [Code::NotFound, Code::Cancelled, Code::Unavailable, Code::Internal] { - window.finished(code, None); + fn a_window_counts_refusals_and_failures_apart_from_client_errors() { + let codes = [Code::Ok, Code::NotFound, Code::Cancelled, Code::Unavailable, Code::Internal]; + for code in codes { + finished(None, code, ""); } - let taken = window.take(); + evicted(); - let expected = Counts { - requests: 6, - refused: 1, // Unavailable - failed: 1, // Internal - slow: 1, // SLOW + 1 ms (SLOW itself is not) - ..Counts::default() - }; - assert_eq!(taken, expected, "NotFound + Cancelled = the client's, uncounted"); - assert_eq!(window.take(), Counts::default(), "taken = zeroed"); + assert_eq!(take(), (5, 1, 1, 1), "(requests, refused, failed, evicted)"); + assert_eq!(take(), (0, 0, 0, 0), "taken = zeroed"); } } diff --git a/packages/zingod-grpc/src/tcp_info.rs b/packages/zingod-grpc/src/tcp_info.rs new file mode 100644 index 000000000..5d4f515aa --- /dev/null +++ b/packages/zingod-grpc/src/tcp_info.rs @@ -0,0 +1,418 @@ +//! Kernel TCP state of the listener's connections → wallets waiting on this node's uplink +//! +//! - one dump per [`INTERVAL`] (ESTABLISHED, local port = listener's), keyed by socket cookie +//! - waiting = sending held by the network (cwnd), not the wallet's window nor our buffer +//! - queue delay = smoothed RTT above the connection's own lifetime lowest (its queue-free path) +//! - waiting counts toward overload only once most connections queue or lose for 30 s ([`Congestion`]) + +use std::collections::HashMap; +use std::io; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use netlink_packet_core::{ + NetlinkHeader, NetlinkMessage, NetlinkPayload, NLM_F_DUMP, NLM_F_REQUEST, +}; +use netlink_packet_sock_diag::constants::{AF_INET, AF_INET6, IPPROTO_TCP}; +use netlink_packet_sock_diag::inet::nlas::{Nla, TcpInfo}; +use netlink_packet_sock_diag::inet::{ + ExtensionFlags, InetRequest, InetResponse, SocketId, StateFlags, +}; +use netlink_packet_sock_diag::SockDiagMessage; +use netlink_sys::protocols::NETLINK_SOCK_DIAG; +use netlink_sys::{Socket, SocketAddr}; +use tokio::time::MissedTickBehavior; +use tokio_util::sync::CancellationToken; +use tracing::{info, warn}; + +use crate::admission::AdmissionState; +use crate::metrics; +use crate::proxy_protocol::TrustedProxies; + +const INTERVAL: Duration = Duration::from_secs(10); + +/// Shared congestion = median queue delay over sending connections, or resent share +/// - bench: full uplink 200-470 ms, fading to 51-85 ms past ~5 min (new connections' floors hold +/// the queue); healthy 12-20 ms; drops 26 % +/// - 500 wallets at 1 Mbit each reached 88-97 ms once for ~106 s: the two overlap (kept at 50 ms: +/// a long saturation stays seen) +const CONGESTED_QUEUE_DELAY: Duration = Duration::from_millis(50); +const CONGESTED_RETRANSMITTED_PER_MILLE: u64 = 20; +/// Fewer senders = no median worth the name (one slow phone on a quiet node ≠ a full uplink) +const MIN_SENDERS: usize = 10; +/// Congested this long without a break before waiting counts +/// - bench: full uplink 8-12 min unbroken; slow wallets' ~1 s spikes last seconds +const SUSTAINED: Duration = Duration::from_secs(30); + +/// Large enough for one kernel dump chunk (it fills at most the reader's buffer) +const RECEIVE_BUFFER: usize = 64 * 1024; + +/// One socket's cumulative counters (`waiting` = µs held by the network; bytes) +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Totals { + waiting: u64, + sent: u64, + retransmitted: u64, +} + +/// One socket at dump time (`rtt` = smoothed, `min_rtt` = kernel's over the last 300 s; µs) +/// - `cookie` = the kernel's id for the socket, never reused (a 4-tuple is: NAT ports recycle) +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Sample { + cookie: u64, + totals: Totals, + rtt: u32, + min_rtt: u32, +} + +/// Since the previous dump, summed over sockets (`queue_delays` = one per socket that sent) +#[derive(Debug, Default, PartialEq)] +struct Window { + elapsed: Duration, + waiting: Duration, + sent: u64, + retransmitted: u64, + queue_delays: Vec, +} + +impl Window { + /// (median queue delay, retransmitted ‰): the uplink's own symptoms, shared by most connections + fn symptoms(&self) -> (Duration, u64) { + let mut delays = self.queue_delays.clone(); + delays.sort_unstable(); + let median = delays.get(delays.len() / 2).copied().unwrap_or_default(); + let retransmitted = self.retransmitted.saturating_mul(1000) / self.sent.max(1); + (median, retransmitted) + } + + /// This window alone ([`Congestion`] = whether it has lasted) + fn congested(&self) -> bool { + let (median, retransmitted) = self.symptoms(); + self.queue_delays.len() >= MIN_SENDERS + && (median >= CONGESTED_QUEUE_DELAY + || retransmitted >= CONGESTED_RETRANSMITTED_PER_MILLE) + } +} + +/// Start of the current unbroken congested run (`None` = clear at the last dump) +#[derive(Debug, Default)] +struct Congestion { + since: Option, +} + +impl Congestion { + /// Sustained = congested for [`SUSTAINED`] without a clear dump between + fn step(&mut self, at: Instant, congested: bool) -> bool { + self.since = congested.then(|| self.since.unwrap_or(at)); + self.since.is_some_and(|since| at.saturating_duration_since(since) >= SUSTAINED) + } +} + +/// One open socket between dumps: its counters + lifetime lowest RTT (µs) +/// - kernel `min_rtt` windows over `tcp_min_rtt_wlen` (300 s): a standing queue would lift it +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Seen { + totals: Totals, + lowest: u32, +} + +/// Previous dump's time + each open socket by cookie (closed ones drop out; `None` = no dump yet) +#[derive(Debug, Default)] +struct Tracker { + previous: Option<(Instant, HashMap)>, +} + +impl Tracker { + /// `None` on the first dump (totals since each socket opened ≠ this window) + fn step(&mut self, at: Instant, samples: &[Sample]) -> Option { + let previous = self.previous.take(); + let mut window = previous.as_ref().map(|(then, _)| Window { + elapsed: at.saturating_duration_since(*then), + ..Window::default() + }); + let mut current = HashMap::with_capacity(samples.len()); + for sample in samples { + let before = previous.as_ref().and_then(|(_, seen)| seen.get(&sample.cookie)).copied(); + let floor = before.map_or(sample.min_rtt, |seen| seen.lowest.min(sample.min_rtt)); + current.insert(sample.cookie, Seen { totals: sample.totals, lowest: floor }); + let Some(window) = window.as_mut() else { continue }; + // unseen = opened since the last dump: all of its totals fall in this window + let before = before.map(|seen| seen.totals).unwrap_or_default(); + let (now, delta) = (sample.totals, |now: u64, then: u64| now.saturating_sub(then)); + let sent = delta(now.sent, before.sent); + window.waiting += micros(delta(now.waiting, before.waiting)); + window.sent += sent; + window.retransmitted += delta(now.retransmitted, before.retransmitted); + // idle socket's srtt = stale (last measured whenever it last sent) + if sent > 0 { + window.queue_delays.push(micros(u64::from(sample.rtt.saturating_sub(floor)))); + } + } + self.previous = Some((at, current)); + window + } +} + +fn micros(us: u64) -> Duration { + Duration::from_micros(us) +} + +/// Until `cancel`: one dump per [`INTERVAL`] → the overload latch's network part +/// +/// - stops (warned) once the kernel refuses a dump: network part absent, serving unaffected +pub(crate) async fn sample( + port: u16, + proxies: TrustedProxies, + admission: Arc, + cancel: CancellationToken, +) { + let (mut tracker, mut congestion, mut congested) = + (Tracker::default(), Congestion::default(), false); + let mut ticks = tokio::time::interval(INTERVAL); + ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = cancel.cancelled() => return, + _ = ticks.tick() => {} + } + let proxies = proxies.clone(); + let samples = match zingod_sync::blocking(move || dump(port, &proxies)).await { + Ok(samples) => samples, + Err(error) => { + admission.network_waiting(0.0); + return warn!(%error, "Kernel TCP stats unavailable, uplink not watched"); + } + }; + let now = Instant::now(); + let Some(window) = tracker.step(now, &samples) else { continue }; + let sustained = congestion.step(now, window.congested()); + let (median, retransmitted) = window.symptoms(); + let waiting = window.waiting.div_duration_f64(window.elapsed.max(Duration::from_nanos(1))); + admission.network_waiting(if sustained { waiting } else { 0.0 }); + metrics::uplink_window(waiting, median, retransmitted, sustained); + if sustained != congested { + congested = sustained; + let (queue_delay_ms, retransmitted_percent) = + (median.as_millis(), retransmitted as f64 / 10.0); + match congested { + true => warn!(queue_delay_ms, retransmitted_percent, "Uplink congested"), + false => info!(queue_delay_ms, retransmitted_percent, "Uplink clear"), + } + } + } +} + +/// Every ESTABLISHED socket on local `port`, both families (a trusted proxy's = its hop, skipped) +fn dump(port: u16, proxies: &TrustedProxies) -> io::Result> { + let mut socket = Socket::new(NETLINK_SOCK_DIAG)?; + socket.bind_auto()?; + socket.connect(&SocketAddr::new(0, 0))?; + let mut samples = Vec::new(); + for (family, id) in [(AF_INET, SocketId::new_v4()), (AF_INET6, SocketId::new_v6())] { + request(&socket, family, id)?; + receive(&socket, |response| { + let id = &response.header.socket_id; + // canonical = as transport.rs judges the peer (dual-stack v4 = ::ffff:a.b.c.d) + if id.source_port == port && !proxies.trusts(id.destination_address.to_canonical()) { + samples.extend(decode_sample(id.cookie, &response.nlas)); + } + })?; + } + Ok(samples) +} + +fn request(socket: &Socket, family: u8, socket_id: SocketId) -> io::Result<()> { + let mut header = NetlinkHeader::default(); + header.flags = NLM_F_REQUEST | NLM_F_DUMP; + let mut message = NetlinkMessage::new( + header, + SockDiagMessage::InetRequest(InetRequest { + family, + protocol: IPPROTO_TCP, + extensions: ExtensionFlags::INFO, + states: StateFlags::ESTABLISHED, + socket_id, + }) + .into(), + ); + message.finalize(); + let mut bytes = vec![0; message.buffer_len()]; + message.serialize(&mut bytes); + socket.send(&bytes, 0)?; + Ok(()) +} + +/// Each response of one dump to `each`, until the kernel's `Done` +fn receive(socket: &Socket, mut each: impl FnMut(&InetResponse)) -> io::Result<()> { + let mut buffer = vec![0; RECEIVE_BUFFER]; + loop { + let received = socket.recv(&mut &mut buffer[..], 0)?; + let mut chunk = buffer.get(..received).unwrap_or_default(); + while !chunk.is_empty() { + let message = NetlinkMessage::::deserialize(chunk) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + match message.payload { + NetlinkPayload::Done(_) => return Ok(()), + NetlinkPayload::Error(error) if error.code.is_some() => return Err(error.to_io()), + NetlinkPayload::InnerMessage(SockDiagMessage::InetResponse(response)) => { + each(&response); + } + _ => {} + } + let length = usize::try_from(message.header.length).unwrap_or(usize::MAX); + chunk = chunk.get(length.max(1)..).unwrap_or_default(); + } + } +} + +/// `INET_DIAG_INFO` → one sample (`None` = the kernel attached no `tcp_info`) +fn decode_sample(cookie: [u8; 8], nlas: &[Nla]) -> Option { + let info: &TcpInfo = nlas.iter().find_map(|nla| match nla { + Nla::TcpInfo(info) => Some(info), + _ => None, + })?; + Some(Sample { + cookie: u64::from_ne_bytes(cookie), + totals: Totals { + // busy_time = Σ every chrono state (kernel tcp_get_info_chrono_stats): rest = cwnd's + waiting: info + .busy_time + .saturating_sub(info.rwnd_limited) + .saturating_sub(info.sndbuf_limited), + sent: info.bytes_sent, + retransmitted: info.bytes_retrans, + }, + rtt: info.rtt, + min_rtt: info.min_rtt, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Window = per-socket deltas; a new socket counts whole, a closed one drops out + #[test] + fn windows_difference_each_socket_and_count_a_new_one_from_its_open() { + let totals = |waiting, sent, retransmitted| Totals { waiting, sent, retransmitted }; + let sample = |cookie, totals, rtt, min_rtt| Sample { cookie, totals, rtt, min_rtt }; + let start = Instant::now(); + let mut tracker = Tracker::default(); + + let first = [ + sample(1, totals(4_000, 9_000, 0), 40_000, 20_000), + sample(2, totals(0, 100, 0), 30_000, 30_000), + ]; + assert_eq!(tracker.step(start, &first), None, "first dump = baselines only"); + + let second = [ + // 1: +5 ms waiting, +4000 B (+400 retransmitted) + sample(1, totals(9_000, 13_000, 400), 45_000, 20_000), + // 2: sent nothing → no queue delay sample (stale srtt) + sample(2, totals(0, 100, 0), 90_000, 30_000), + // 3: new since the last dump → its totals whole + sample(3, totals(2_000, 600, 0), 12_000, 10_000), + ]; + assert_eq!( + tracker.step(start + INTERVAL, &second), + Some(Window { + elapsed: INTERVAL, + waiting: Duration::from_millis(7), + sent: 4_600, + retransmitted: 400, + queue_delays: vec![Duration::from_millis(25), Duration::from_millis(2)], + }), + ); + + // 1 closed (absent); 3 reopened under a new cookie never inherits 1's totals + let third = [sample(4, totals(1_000, 50, 0), 10_000, 10_000)]; + let window = tracker.step(start + 2 * INTERVAL, &third).expect("after a dump"); + assert_eq!((window.waiting, window.sent), (Duration::from_millis(1), 50)); + } + + /// One window: most of ≥ 10 senders queueing, or losing; slow wallets or a quiet node never + #[test] + fn only_a_queue_or_loss_shared_by_most_of_ten_senders_is_congestion() { + let ms = Duration::from_millis; + // case, queue delays of sending connections, bytes sent, retransmitted, congested + #[rustfmt::skip] + let cases = [ + ("healthy", vec![ms(15); 10], 1_000, 2, false), + ("slow wallets: a high tail", [vec![ms(15); 8], vec![ms(900); 2]].concat(), 1_000, 1, false), + ("uplink full, provider queues", [vec![ms(40); 4], vec![ms(216); 6]].concat(), 1_000, 4, true), + ("uplink full, provider drops", vec![ms(11); 10], 1_000, 260, true), + ("quiet node, one slow phone", vec![ms(900)], 1_000, 1, false), + ("quiet node, three losing", vec![ms(11); 3], 1_000, 260, false), + ("idle: nothing sent", vec![], 0, 0, false), + ]; + for (case, queue_delays, sent, retransmitted, want) in cases { + let window = Window { queue_delays, sent, retransmitted, ..Window::default() }; + + assert_eq!(window.congested(), want, "{case}: {:?}", window.symptoms()); + } + } + + /// Waiting counts from 30 s of unbroken congestion; one clear dump restarts the clock + #[test] + fn congestion_counts_once_unbroken_for_thirty_seconds() { + let start = Instant::now(); + let mut congestion = Congestion::default(); + // dump every 10 s: congested? + let dumps = [true, true, true, true, true, false, true, true, true, true]; + + let sustained: Vec = (0u32..) + .zip(dumps) + .map(|(n, congested)| congestion.step(start + INTERVAL * n, congested)) + .collect(); + + #[rustfmt::skip] + let want = [false, false, false, true, true, false, false, false, false, true]; + assert_eq!(sustained, want, "0-40 s congested, 50 s clear, 60-90 s congested"); + } + + /// A standing queue outlasting the kernel's 300 s window stays measured: the floor = lifetime + #[test] + fn queue_delay_is_measured_against_the_connections_own_lifetime_lowest() { + let (start, ms) = (Instant::now(), |ms: u32| ms * 1_000); + let socket = |cookie, rtt, min_rtt, sent| Sample { + cookie, + totals: Totals { waiting: 0, sent, retransmitted: 0 }, + rtt: ms(rtt), + min_rtt: ms(min_rtt), + }; + let mut tracker = Tracker::default(); + + tracker.step(start, &[socket(1, 20, 20, 0)]); + // 10 min into a 200 ms standing queue: the kernel's min (300 s window) now includes it + let later = start + Duration::from_secs(600); + let window = tracker.step(later, &[socket(1, 220, 210, 1_000), socket(2, 220, 210, 1_000)]); + assert_eq!( + window.expect("2nd dump").queue_delays, + [Duration::from_millis(200), Duration::from_millis(10)], + "open before the queue: 220 - its own 20; opened during it: no clean floor of its own", + ); + } + + /// Real kernel dump: a loopback connection on the listener's port, its bytes counted + #[tokio::test] + async fn a_dump_finds_the_listeners_connection_with_its_sent_bytes() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let port = listener.local_addr().expect("bound").port(); + let mut client = + tokio::net::TcpStream::connect(("127.0.0.1", port)).await.expect("connect"); + let (mut served, _) = listener.accept().await.expect("accept"); + served.write_all(&[7; 10_000]).await.expect("write"); + client.read_exact(&mut [0; 10_000]).await.expect("read"); + + let none_trusted = TrustedProxies::default(); + let samples = dump(port, &none_trusted).expect("sock_diag dump"); + // client's own socket (local port = ephemeral) excluded; the served one = sender + assert_eq!(samples.len(), 1, "{samples:?}"); + assert!(samples.iter().all(|sample| sample.totals.sent >= 10_000), "{samples:?}"); + + let loopback_trusted = TrustedProxies::new(vec!["127.0.0.0/8".parse().expect("net")]); + assert_eq!(dump(port, &loopback_trusted).expect("dump"), [], "proxy hop skipped"); + } +} diff --git a/packages/zingod-grpc/src/testing.rs b/packages/zingod-grpc/src/testing.rs index e52ef0b19..25c479269 100644 --- a/packages/zingod-grpc/src/testing.rs +++ b/packages/zingod-grpc/src/testing.rs @@ -170,7 +170,9 @@ impl Drop for LiveRoutes { pub(super) fn dispatch( routes: RouteDeps, ) -> Dispatch { - let dispatch = Dispatch::new(&crate::GrpcLimits::default()); + let limits = crate::GrpcLimits::default(); + let reads = crate::read_pool::ReadPool::new(limits.read_threads, limits.scan_threads); + let dispatch = Dispatch::new(reads.expect("test read pool")); dispatch.routing().route(routes); dispatch } diff --git a/packages/zingod-grpc/src/transport.rs b/packages/zingod-grpc/src/transport.rs index 4fc6ed927..a3a4da4f1 100644 --- a/packages/zingod-grpc/src/transport.rs +++ b/packages/zingod-grpc/src/transport.rs @@ -5,16 +5,19 @@ //! - hyper, not `tonic::transport::Server` (own accept loop: over-cap closed before a task //! exists, h2 settings per connection) -use std::net::SocketAddr; +use std::future::Future; +use std::net::{IpAddr, SocketAddr}; +use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; -use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; +use hyper_util::rt::{TokioIo, TokioTimer}; use hyper_util::server::conn::auto; use hyper_util::service::TowerToHyperService; use tokio::io::AsyncReadExt as _; use tokio::net::{TcpListener, TcpStream}; use tokio::time::Instant; +use tokio_metrics::TaskMonitor; use tokio_util::sync::CancellationToken; use tokio_util::task::TaskTracker; use tower::Layer as _; @@ -27,12 +30,14 @@ use crate::connections::{ConnectionCaps, Reserved}; use crate::guard::Guard; use crate::health::{Health, HealthRoute}; use crate::lifetime::{Activity, Retire, RetireReason, Retirement}; -use crate::overload::Signals; -use crate::pressure::{Pressure, Resource}; +use crate::overload; use crate::proxy_protocol; +use crate::read_pool::ReadPool; use crate::service::{Dispatch, Routing}; +use crate::stall::Parked; use crate::summary::{self, INTERVAL}; -use crate::{metrics, GrpcLimits}; +use crate::tcp_info; +use crate::{metrics, GrpcLimits, HostCapacity}; /// Per-stream send buffer (flow control paces from here: a slow wallet backs up itself, not the /// server) @@ -64,11 +69,15 @@ const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20); /// Locally-reset streams per peer before the connection closes (CVE-2023-44487) const RAPID_RESET_LIMIT: usize = 128; +/// lightwalletd's `grpc-max-concurrent-streams` (clients tuned against it) +const STREAMS_PER_CONNECTION: u32 = 100; + /// `CompactTxStreamer` endpoint: enabled [`RouteDeps`](crate::RouteDeps) on one listener, bounded by [`GrpcLimits`] pub struct GrpcService { dispatch: Dispatch, bind: SocketAddr, limits: GrpcLimits, + capacity: HostCapacity, tls: Option, admission: Arc, health: Option>, @@ -82,26 +91,42 @@ pub struct GrpcService { pub enum GrpcServeError { #[error("binding the gRPC listener: {0}")] Bind(#[source] std::io::Error), + #[error("starting {reads} read + {scans} scan threads: {source}")] + ReadThreads { reads: NonZeroUsize, scans: NonZeroUsize, source: rayon::ThreadPoolBuildError }, } impl GrpcService { /// Unrouted: health answered, every method `UNAVAILABLE` until [`Routing::route`] - pub fn new(bind: SocketAddr, limits: GrpcLimits) -> Self { - let dispatch = Dispatch::new(&limits); - let admission = Arc::new(AdmissionState::new(&limits)); + /// + /// - `capacity` = what the host holds (zingod: derived from its fd + memory limits) + pub fn new( + bind: SocketAddr, + limits: GrpcLimits, + capacity: HostCapacity, + ) -> Result { + let (reads, scans) = (limits.read_threads, limits.scan_threads); + let reads = ReadPool::new(reads, scans).map_err(|source| GrpcServeError::ReadThreads { + reads, + scans, + source, + })?; + let dispatch = Dispatch::new(reads); + let admission = + Arc::new(AdmissionState::new(crate::adaptive::WORK_CEILING, limits.work_share_per_ip)); let retire = Retire::default(); let origin_gate = crate::OriginGate::new(); - Self { + Ok(Self { dispatch, bind, limits, + capacity, tls: None, admission, health: None, retire, grpc_web: false, origin_gate, - } + }) } /// Serve gRPC-web (browser) clients too: permissive CORS (`*`) on this listener, native @@ -151,10 +176,24 @@ impl GrpcService { } } +/// hyper's per-stream tasks, spawned timed (woken → polled: the adaptive limit's input) +#[derive(Clone, Debug)] +struct Timed(TaskMonitor); + +impl hyper::rt::Executor for Timed +where + F: Future + Send + 'static, + F::Output: Send + 'static, +{ + fn execute(&self, task: F) { + tokio::spawn(TaskMonitor::instrument(&self.0, task)); + } +} + /// - h2 for gRPC /// - HTTP/1.1 only ever reaches the health paths (`health.rs`) -fn http(limits: &GrpcLimits) -> auto::Builder { - let mut builder = auto::Builder::new(TokioExecutor::new()); +fn http(tasks: &TaskMonitor) -> auto::Builder { + let mut builder = auto::Builder::new(Timed(tasks.clone())); builder .http1() // header read timeout needs a clock (slowloris) @@ -164,7 +203,7 @@ fn http(limits: &GrpcLimits) -> auto::Builder { .http2() // keepalive pings need a clock (hyper has none) .timer(TokioTimer::new()) - .max_concurrent_streams(limits.max_streams_per_connection.get()) + .max_concurrent_streams(STREAMS_PER_CONNECTION) .max_send_buf_size(SEND_BUFFER) .keep_alive_interval(KEEPALIVE_INTERVAL) .keep_alive_timeout(KEEPALIVE_TIMEOUT) @@ -213,8 +252,9 @@ fn cors(enabled: bool) -> tower_http::cors::CorsLayer { /// What every connection task shares struct Shared { caps: ConnectionCaps, + parked: Arc, tls: Option, - http: auto::Builder, + http: auto::Builder, health: Option>, retire: Retire, dispatch: Dispatch, @@ -258,11 +298,23 @@ impl BoundGrpcService { if let Some(tls) = &server.tls { tokio::spawn(tls.reload(cancel.clone()).instrument(Span::current())); } - let (mut cpu, mut io) = (Pressure::new(Resource::Cpu), Pressure::new(Resource::Io)); + match listener.local_addr() { + Ok(bound) => { + let proxies = server.limits.trusted_proxies.clone(); + let admission = Arc::clone(&server.admission); + let sampler = tcp_info::sample(bound.port(), proxies, admission, cancel.clone()); + tokio::spawn(sampler.instrument(Span::current())); + } + Err(error) => warn!(%error, "Listener address unreadable, link metrics off"), + } let shared = Arc::new(Shared { - caps: ConnectionCaps::new(&server.limits), + caps: ConnectionCaps::new( + server.capacity.connections, + server.limits.max_connections_per_ip, + ), + parked: Arc::new(Parked::new(server.capacity.parked_bytes)), tls: server.tls.as_ref().map(crate::Tls::acceptor), - http: http(&server.limits), + http: http(server.admission.tasks()), health: server.health, retire: server.retire, dispatch: server.dispatch, @@ -272,21 +324,33 @@ impl BoundGrpcService { origin_gate: server.origin_gate, cancel: cancel.clone(), }); + let (parked, admission) = (Arc::clone(&shared.parked), Arc::clone(&shared.admission)); + let sweep = crate::stall::reclaim_idle(parked, admission, cancel.clone()); + tokio::spawn(sweep.instrument(Span::current())); + let (admission, adapting) = (Arc::clone(&shared.admission), cancel.clone()); + tokio::spawn(async move { admission.adapt(&adapting).await }.instrument(Span::current())); let mut backoff = ACCEPT_BACKOFF_MIN; - let mut summaries = tokio::time::interval_at(Instant::now() + INTERVAL, INTERVAL); - summaries.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - let mut window_opened = Instant::now(); + let every = |period| { + let mut ticks = tokio::time::interval_at(Instant::now() + period, period); + ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + ticks + }; + let (mut summaries, mut overload_ticks) = (every(INTERVAL), every(overload::TICK)); + let (mut summary_opened, mut overload_opened) = (Instant::now(), Instant::now()); loop { let accepted = tokio::select! { _ = cancel.cancelled() => return, accepted = listener.accept() => accepted, now = summaries.tick() => { - let elapsed = now.saturating_duration_since(window_opened); - let signals = Signals { cpu: cpu.share(elapsed), io: io.share(elapsed) }; - let at_capacity = shared.admission.tick(elapsed, signals); - summary::summarise(elapsed, shared.caps.held(), at_capacity); - window_opened = now; + summary::summarise(now.saturating_duration_since(summary_opened), shared.caps.held()); + summary_opened = now; + continue; + } + now = overload_ticks.tick() => { + let elapsed = now.saturating_duration_since(overload_opened); + shared.admission.tick(elapsed, shared.caps.held()); + overload_opened = now; continue; } }; @@ -320,7 +384,8 @@ impl BoundGrpcService { let retirement = shared.retire.subscribe(); let connection = Arc::clone(&shared).connection(socket, peer, reserved, retirement); - connections.spawn(connection.instrument(Span::current())); + let timed = TaskMonitor::instrument(shared.admission.tasks(), connection); + connections.spawn(timed.instrument(Span::current())); } } } @@ -357,7 +422,7 @@ impl Shared { let Some(_connection) = self.caps.admit(reserved, peer_ip) else { return; }; - return self.secure(socket, peer, retirement).await; + return self.secure(socket, peer, peer_ip, retirement).await; } let header = tokio::time::timeout( @@ -381,34 +446,39 @@ impl Shared { // Bytes past the header = client's HTTP/2 stream: replayed first let (reader, writer) = socket.into_split(); let io = tokio::io::join(std::io::Cursor::new(read_ahead).chain(reader), writer); - self.secure(io, peer, retirement).await; + self.secure(io, peer, client, retirement).await; } /// TLS handshake when configured (bounded by [`TLS_HANDSHAKE_TIMEOUT`]), then [`Self::serve`] - async fn secure(&self, io: I, peer: SocketAddr, retirement: Retirement) + /// + /// - `client` = the peer, or the address a trusted proxy's PROXY header named + async fn secure(&self, io: I, peer: SocketAddr, client: IpAddr, retirement: Retirement) where I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, { + // admitted past every connection cap: one of the overload window's connections + self.admission.connected(); let Some(acceptor) = &self.tls else { - return self.serve(io, retirement).await; + return self.serve(io, client, retirement).await; }; match tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, acceptor.accept(io)).await { - Ok(Ok(stream)) => self.serve(stream, retirement).await, + Ok(Ok(stream)) => self.serve(stream, client, retirement).await, // scanners and plaintext clients: routine, not an operator signal Ok(Err(error)) => debug!(%error, %peer, "TLS handshake failed"), Err(_) => debug!(%peer, "TLS handshake timed out"), } } - /// Until the peer closes, `cancel` (graceful), or a stream holds unread data past - /// `unread_timeout` (dropped: graceful would wait on the very stream that stalled) + /// Until the peer closes, `cancel` (graceful), a stream holds unread data past + /// `unread_timeout`, or the node's parked budget picks it (both dropped: graceful would wait + /// on the very streams that stalled) /// /// - aged or idle (`lifetime.rs`): GOAWAY, in-flight streams get `max_connection_age_grace` - async fn serve(&self, io: I, retirement: Retirement) + async fn serve(&self, io: I, client: IpAddr, retirement: Retirement) where I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, { - let stalls = Arc::new(crate::stall::Watch::default()); + let stalls = self.parked.watch(client); let activity = Arc::new(Activity::default()); let admission = Arc::clone(&self.admission); let guard = Guard::new( @@ -440,6 +510,7 @@ impl Shared { let retired = tokio::select! { _ = serving.as_mut() => return, _ = stalls.stalled(limits.unread_timeout) => return metrics::connection_stalled(), + () = stalls.evicted() => return, _ = self.cancel.cancelled() => { serving.as_mut().graceful_shutdown(); let _ = serving.await; @@ -454,6 +525,7 @@ impl Shared { tokio::select! { _ = tokio::time::timeout(limits.max_connection_age_grace, serving.as_mut()) => {} _ = stalls.stalled(limits.unread_timeout) => metrics::connection_stalled(), + () = stalls.evicted() => {} } } } @@ -478,13 +550,19 @@ mod tests { use super::{GrpcServeError, GrpcService}; use crate::service::{Method, RouteDeps}; use crate::testing::{fixed_snapshots, indexed, routes_over, routes_serving, MAINNET}; - use crate::{GrpcLimits, TrustedProxies}; + use crate::{GrpcLimits, HostCapacity, TrustedProxies}; const ANY_PORT: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0); /// Real-clock headroom past a deadline (loaded runner: wake-ups + loopback handshakes) const SCHEDULING: Duration = Duration::from_secs(1); + /// Host capacity (zingod derives it from the host; tests never reach it) + const CAPACITY: HostCapacity = HostCapacity { + connections: NonZeroUsize::new(64).expect("64 is non-zero"), + parked_bytes: u64::MAX, + }; + /// Nothing served, chain view never polled: every `GetLightdInfo` = `UNAVAILABLE` fn unserved() -> RouteDeps { let chain = MockChain::regtest(); @@ -526,7 +604,9 @@ mod tests { async fn a_wallet_is_served_and_a_second_connection_from_its_address_is_closed_at_accept() { let one = NonZeroUsize::MIN; let limits = GrpcLimits { max_connections_per_ip: one, ..GrpcLimits::default() }; - let server = GrpcService::new(ANY_PORT, limits).with_routes(unserved()); + let server = GrpcService::new(ANY_PORT, limits, CAPACITY) + .expect("read threads start") + .with_routes(unserved()); let bound = server.bind().await.expect("binds"); let bind = bound.local_addr().expect("bound"); let cancel = CancellationToken::new(); @@ -560,7 +640,9 @@ mod tests { trusted_proxies: TrustedProxies::new(loopback), ..GrpcLimits::default() }; - let server = GrpcService::new(ANY_PORT, limits).with_routes(unserved()); + let server = GrpcService::new(ANY_PORT, limits, CAPACITY) + .expect("read threads start") + .with_routes(unserved()); let bound = server.bind().await.expect("binds"); let bind = bound.local_addr().expect("bound"); let cancel = CancellationToken::new(); @@ -610,7 +692,9 @@ mod tests { trusted_proxies: TrustedProxies::new(loopback), ..GrpcLimits::default() }; - let server = GrpcService::new(ANY_PORT, limits).with_routes(unserved()); + let server = GrpcService::new(ANY_PORT, limits, CAPACITY) + .expect("read threads start") + .with_routes(unserved()); let bound = server.bind().await.expect("binds"); let bind = bound.local_addr().expect("bound"); let cancel = CancellationToken::new(); @@ -658,11 +742,17 @@ mod tests { let held = tokio::net::TcpListener::bind(ANY_PORT).await.expect("a free port"); let bind = held.local_addr().expect("local addr"); - let outcome = - GrpcService::new(bind, GrpcLimits::default()).with_routes(unserved()).bind().await; + let outcome = GrpcService::new(bind, GrpcLimits::default(), CAPACITY) + .expect("read threads start") + .with_routes(unserved()) + .bind() + .await; let error = outcome.err(); - let kind = error.as_ref().map(|GrpcServeError::Bind(error)| error.kind()); + let kind = match &error { + Some(GrpcServeError::Bind(error)) => Some(error.kind()), + _ => None, + }; assert_eq!(kind, Some(std::io::ErrorKind::AddrInUse), "{error:?}"); } @@ -689,7 +779,9 @@ mod tests { let snapshots = fixed_snapshots(&chain, tip, views, TrustedValidatorSet::default(), &[]); let routes = routes_serving(MAINNET, &indexes, snapshots); - let server = GrpcService::new(ANY_PORT, GrpcLimits::default()).with_routes(routes); + let server = GrpcService::new(ANY_PORT, GrpcLimits::default(), CAPACITY) + .expect("read threads start") + .with_routes(routes); let bound = server.bind().await.expect("binds"); let bind = bound.local_addr().expect("bound"); let cancel = tokio_util::sync::CancellationToken::new(); @@ -738,8 +830,12 @@ mod tests { let snapshots = fixed_snapshots(&chain, genesis, views, TrustedValidatorSet::default(), &[]); let routes = routes_serving(MAINNET, &[IndexKind::TransparentAddress], snapshots); - let bound = - GrpcService::new(ANY_PORT, limits).with_routes(routes).bind().await.expect("binds"); + let bound = GrpcService::new(ANY_PORT, limits, CAPACITY) + .expect("read threads start") + .with_routes(routes) + .bind() + .await + .expect("binds"); let bind = bound.local_addr().expect("bound"); tokio::spawn(bound.run(CancellationToken::new())); bind @@ -890,7 +986,8 @@ mod tests { let cert = rcgen::generate_simple_self_signed(vec![host.to_owned()]).expect("cert"); std::fs::write(&files.cert_path, cert.cert.pem()).expect("cert pem"); std::fs::write(&files.key_path, cert.signing_key.serialize_pem()).expect("key pem"); - let server = GrpcService::new(ANY_PORT, crate::GrpcLimits::default()) + let server = GrpcService::new(ANY_PORT, crate::GrpcLimits::default(), CAPACITY) + .expect("read threads start") .with_tls(crate::Tls::load(files).expect("pair loads")) .with_health(Arc::new(Serving)); let (admission, routing) = (server.admission(), server.routing()); @@ -951,11 +1048,7 @@ mod tests { let healthy = ("200".to_owned(), r#"{"state":"serving","detail":null}"#.to_owned()); assert_eq!(readyz().await, healthy, "ALPN http/1.1 /readyz, unrouted"); - assert_eq!( - admission.held(crate::admission::Class::Work), - 0, - "a monitor's /readyz never holds a work slot" - ); + assert_eq!(admission.held(), 0, "a monitor's /readyz never holds a work slot"); let starting = (Code::Unavailable, crate::service::STARTING.to_owned()); assert_eq!(lightd_info().await, starting, "ALPN h2 → the gRPC stack, unrouted"); @@ -987,7 +1080,8 @@ mod tests { /// same listener is untouched by the layer #[tokio::test] async fn grpc_web_answers_a_preflight_and_still_serves_native_grpc() { - let server = GrpcService::new(ANY_PORT, GrpcLimits::default()) + let server = GrpcService::new(ANY_PORT, GrpcLimits::default(), CAPACITY) + .expect("read threads start") .with_grpc_web(true) .with_routes(unserved()); let bound = server.bind().await.expect("binds"); @@ -1018,7 +1112,9 @@ mod tests { /// gRPC-web off (the default): the same preflight gets no CORS grant, so a browser is refused #[tokio::test] async fn grpc_web_off_refuses_a_preflight() { - let server = GrpcService::new(ANY_PORT, GrpcLimits::default()).with_routes(unserved()); + let server = GrpcService::new(ANY_PORT, GrpcLimits::default(), CAPACITY) + .expect("read threads start") + .with_routes(unserved()); let bound = server.bind().await.expect("binds"); let bind = bound.local_addr().expect("bound"); let cancel = CancellationToken::new(); diff --git a/packages/zingod-grpc/src/wire.rs b/packages/zingod-grpc/src/wire.rs index 0910c36c4..a41547df0 100644 --- a/packages/zingod-grpc/src/wire.rs +++ b/packages/zingod-grpc/src/wire.rs @@ -104,8 +104,11 @@ where } /// `method`'s whole request body, refused past its cap (checked as it arrives, never buffered -/// beyond) or past [`request_limit::DEADLINE`] -pub(crate) async fn collect_request(body: B, method: Method) -> Result +/// beyond) or past [`request_limit::DEADLINE`] (`None` = an unknown path: the message cap) +pub(crate) async fn collect_request( + body: B, + method: Option, +) -> Result where B: http_body::Body, B::Error: fmt::Display, @@ -113,7 +116,7 @@ where use http_body_util::{BodyExt as _, LengthLimitError, Limited}; let limit = match method { - Method::SendTransaction => request_limit::TRANSACTION, + Some(Method::SendTransaction) => request_limit::TRANSACTION, _ => request_limit::MESSAGE, }; let body = body.map_err(|error| Status::internal(format!("reading request body: {error}"))); diff --git a/packages/zingod-grpc/usage.md b/packages/zingod-grpc/usage.md index 75537a837..c316482ad 100644 --- a/packages/zingod-grpc/usage.md +++ b/packages/zingod-grpc/usage.md @@ -92,9 +92,9 @@ Every method is one `Method` variant in `service.rs`; its name is its wire name metric label. A new RPC is: 1. a `Method` variant, -2. its arm in `Method::route`: its admission `Class` (`Work`, or `Subscription` for a stream - that idles between arrivals: own pool, never cut for silence, no latency recorded) and the - index whose view its handler reads (`None` = reads none, so never disabled), +2. its arm in `Method::route`: its `Reply` and the index whose view its handler reads (`None` = + reads none, so never disabled); every method but `GetMempoolStream` + (`Method::is_subscription`: idle between arrivals) takes a work slot, 3. its arm in `Wired::handle`, which hands the handler its decoded request (`wire::decode`, or `wire::decode_each` for a client stream); the handler returns `Result, Status>` built with `wire::unary_response`, `wire::streamed_response` or `wire::streaming`, never by @@ -121,13 +121,35 @@ accept loop is zingod's. Outermost first, per connection after the first three: ```text accept ─ total cap ─ PROXY header (trusted peers) ─ per-client cap ─ TLS ─ h2 / HTTP/1.1 ─ health (resolves the RPC) ─ CORS + gRPC-web (with_grpc_web) ─ guard (metrics, admission, - origin gate, stall watch) ─ dispatch (grpc-timeout, silence, request body) ─ handler + origin gate, stall watch) ─ dispatch (grpc-timeout, request body) ─ handler ``` The guard (`guard.rs`) wraps each response body once: the body owns its admission slot, its -stall-watch ticket and its close-out metrics, so all three end together when hyper drops it (a -stream ending or its client disconnecting). What each `[grpc]` cap bounds: -[the example config](../../book/src/operators/zingod.toml). +stall-watch ticket and its close-out metrics, so all three end when hyper drops it. + +- **Slot** held for the stream's life (bounds work in progress; freed per message, the 2-core + bench admitted past its CPU: 7× the failed sessions). +- **Client share**: one `stall::Client` (IPv4 address / IPv6 /64) has ≤ + `GrpcLimits::work_share_per_ip` of the limit (`WorkShare::of`, ≥ 1) as live work streams + (`AdmissionState::clients`, counted until the `Slot` drops, reclaimed or not: no + reclaim-then-reopen growth; entry gone at 0); refused past it = `Refusal::ClientShare`, never + the overload's (one client cannot take a node out of rotation). +- **Owing** = handed a frame, not polled since. hyper 1.10 (`PipeToSendStream`) polls a body only + once its last frame fits the client's window, so owing = waiting on the client (≈ 2 messages + buffered). +- **Reclaim** (`stall::reclaim_idle`, every 250 ms while `AdmissionState::pressed`): a stream + owing past `stall::GRACE` (1 s) loses its slot (`Claim::held` swapped, so the sweep and the + drop never both release). A stream leaves the owing list under the watch's lock before it + resumes; resuming takes a slot back even past the limit (never refused mid-stream). +- **Parked memory** (`stall::Parked`): each owing ticket charges 4 KiB + 2 × its frame against + `HostCapacity::parked_bytes`; over it, the client (IPv4 address / IPv6 /64) owing most loses + its connection owing most (only the connection can go: hyper never polls a stalled body). +- **Body before admission**: the guard collects the request body whole (`wire::collect_request`: + method cap, 30 s) before `admit`, its bytes charged meanwhile (`stall::Arriving`), so a + headers-only or trickled request holds no work slot and its buffer stays in the parked budget. +- **Hardware-sized caps** are no config: `HostCapacity` (zingod derives it from the open-file + limit and memory, `daemon/capacity.rs`), `adaptive::WORK_CEILING`, 100 streams per connection. + The rest: [the example config](../../book/src/operators/zingod.toml). - **Health** (`with_health(Arc)`): `GET /readyz` (`200` / `503`) and `GET /status` (always `200`), answered before admission over HTTP/1.1 or h2, so they never take a work slot. @@ -141,8 +163,9 @@ stream ending or its client disconnecting). What each `[grpc]` cap bounds: - **Origin gate** (`with_origin_gate(Arc)`, read in `guard.rs`): a request's `Origin` → `block` (`PermissionDenied` before admission), else the normal admission path; `allow` only carves a host out of a blocked parent, never lifts a cap (`Origin` is client-settable). A - missing `Origin` (native clients) is default and uncounted. Markers are set operator-side (`zingod origin`) and swapped - whole each second; `verdict` folds an incoming host to the most-specific marker covering it. + missing `Origin` (native clients) is default and uncounted. Markers are set operator-side + (`zingod origin`) and swapped whole each second; `verdict` folds an incoming host to the + most-specific marker covering it. - **TLS** (`with_tls(Tls::load(files)?)` or `with_tls(Tls::self_signed(dir, listen)?)`): rustls with the aws-lc-rs provider, ALPN `h2` then `http/1.1` (load-balancer monitors connect over HTTPS/1.1). A missing or mismatched pair fails `Tls::load`, never plaintext. The files are @@ -160,14 +183,19 @@ stream ending or its client disconnecting). What each `[grpc]` cap bounds: gets the same GOAWAY + grace, those open then and each one accepted while held. A repeated `hold` keeps the first deadline; `resume()` lifts it. `Retire::state()` = `Hold::Off`, `Draining` or `Drained`. -- **Adaptive limit.** Work streams admitted at once follow measured latency (Netflix - concurrency-limits' Gradient2). A sample is the server's time to produce one message (admission - to the first DATA frame, then poll to poll), so a client's backpressure never counts. Each - window (≥ 500 ms, ≥ 10 samples) sets `limit × clamp(1.5 × baseline / mean, 0.5, 1) + √limit`, - smoothed at 0.2, between 32 and `max_work_streams`; a window that peaked below half the limit - changes nothing. -- **Overload report.** `GrpcService::admission()` → `AdmissionState::overload()` gives the - first latched [overload](#overload) cause, moved once a minute. +- **Adaptive limit** (`adaptive.rs`, Netflix concurrency-limits' Gradient2). The input is CPU + queueing: every connection and stream task is spawned through one `tokio_metrics::TaskMonitor` + (`transport.rs`'s `Timed` executor), and each 500 ms window's mean woken → polled delay is a + sample (≥ 10 wakes, else skipped). A task waiting on a read, a client or the network is not + ready, so none of those count. Every 10 windows (5 s) a decision takes their upper median (a + block rush moves ≤ 4); over the 100 ms budget three decisions running (15 s) shrinks the limit + by `clamp(budget / median, 0.5, 1)`, smoothed at 0.2, never under 128; each decision not over + grows it 10 % toward `WORK_CEILING` (≈ 2.5 min from the floor). Gradient2 proper times whole + requests (queueing included); zingod's earlier input, its own production time, stayed ~0 ms + with the bench's CPU saturated. Each decision sets `adaptive_stream_limit`, + `adaptive_stream_ceiling` and `adaptive_scheduling_delay_seconds`. +- **Overload report.** `GrpcService::admission()` → `AdmissionState::overloaded()`, the + [overload](#overload) latch, stepped every 10 s (`overload::TICK`). - **Trusted proxies.** A peer inside `trusted_proxies` must open with a PROXY header (v1 or v2, read under 5 s, ≤ 4 KiB), and the per-client cap counts the address it names; `LOCAL` / `UNKNOWN` count the proxy itself. @@ -177,29 +205,34 @@ stream ending or its client disconnecting). What each `[grpc]` cap bounds: - Request bodies are capped before decode ([sizes](../../book/src/wallets/status-codes.md)). - **Deadline.** `grpc-timeout` is read at arrival (a malformed value is ignored, as tonic ignores it). Past it a pending handler answers `DEADLINE_EXCEEDED` and a stream ends with - `DEADLINE_EXCEEDED` trailers; its reads and slot go with it. + `DEADLINE_EXCEEDED` trailers; its slot goes with it, a queued read is skipped, and a read + already on a thread finishes there (bounded by `read_threads`). - **Unread.** A body that handed hyper a frame and is not polled again (flow control stalled on a client that stopped reading) owes that frame. Once any stream on a connection has owed for `unread_timeout`, the connection is closed. An idle stream (a quiet mempool subscription, a - read waiting for its lane) never owes. -- **Silence.** A handler or stream body with nothing to send for `silent_timeout` ends with - `UNAVAILABLE`; the clock restarts at every frame. `GetMempoolStream` is exempt. + pending read) never owes. - **Frames.** Records ready back to back are joined into DATA chunks of up to 16 KiB, and a record of 16 KiB or more passes through uncopied. One small frame per record makes an h2 0.4.16+ client that reads late answer `GOAWAY too_many_data_frames` (lightwalletd #593). - `method` and `code` metric labels come from fixed sets, so a misbehaving client cannot grow the series count. -### Read lanes +### Index reads -`ReadLanes` runs every read that touches index files on the blocking pool, under a permit of its -lane, never on a runtime worker: **point** (block, tree state, subtree roots), **range** (each -`GetBlockRange` window below the NFS layer), **scan** (address UTXOs, balances, transactions). A -heavy scan queues behind the other scans, never behind or ahead of a tip read. +Every read that touches index files runs on the read pool (`read_pool.rs`): `read_threads` +threads of its own, oldest read first, never a runtime worker and never tokio's blocking pool. +That pool belongs to sync's index writes and the `/metrics` scrape, so a wallet surge cannot delay +the tip or blind monitoring. Address-history scans (`ReadPool::scan`, the three +`transparent_address` index reads) have `scan_threads` threads apart, so they never queue a block +read. At most `read_threads` reads are in flight: a read whose request was +cancelled before a thread took it is skipped, so cancellations cannot stack reads. A read's wait +for a thread is `read_wait_seconds{pool}` (`read` / `scan`); the adaptive limit never sees it (a slow disk fills held +slots instead, and refusals reach the overload latch). Sizing per device: +[operators: settings](../../book/src/operators/dos-protection.md#settings). ### Answered without a read -The answers every synced wallet asks for right after each block never queue: +The answers every synced wallet asks for right after each block never wait for a read thread: | Answer | Why it needs no read | |---|---| @@ -212,15 +245,36 @@ The answers every synced wallet asks for right after each block never queue: The tree-state memos (`memo::PerView`) are keyed on the NFS publish (the `NfsPublication` `Arc`), not the `GrpcSnapshot`, which moves on every chain-view fold. A new publish starts empty, so -there is no invalidation rule. The first ask per publish computes on the point lane, -single-flight; every later ask is answered inline. +there is no invalidation rule. The first ask per publish computes on a read thread; concurrent +asks await that one computation without holding a thread (`tokio::sync::OnceCell`), and every +later ask is answered inline. ### Overload -`AdmissionState::overload()` names the first cause latched (`/readyz`: `Overloaded: `); -`AdmissionState::set_overload` changes the `[grpc.overload]` thresholds (`OverloadLimits`) live. -Causes, signals and enter / exit times: -[operators: overload](../../book/src/operators/maintenance.md#overload). +`overload.rs`: each 10 s tick's share of connections hurt, smoothed by an EWMA (60 s time +constant, elapsed-weighted, per cause). Hurt = refused at the adaptive limit (`Wallet` mark: once +a tick) or held back by a congested uplink (the sampler's latest mean waiting connections, a +level, as its dumps and the ticks never align). No minimum count: a refusal needs ≥ 128 in +flight, the network part ≥ 10 senders congested 30 s. Rules: +[operators: overload](../../book/src/operators/dos-protection.md#overload). + +### Uplink sampler + +`tcp_info.rs`, one task per listener (spawned beside the accept loop, ends with it): every 10 s a +`sock_diag` dump of ESTABLISHED sockets on the listener's port, both families, keyed by socket +cookie (never reused; a 4-tuple is, as NAT ports recycle). A socket first seen counts whole (opened +since the last dump); the first dump only primes; a closed one drops out. + +- waiting = `tcpi_busy_time` minus its receive-window and send-buffer parts +- floor = the socket's lifetime lowest `min_rtt` (`Seen`: the kernel's windows over + `tcp_min_rtt_wlen`, 300 s, and a standing queue lifts it); queue delay = srtt above it +- waiting reaches the overload latch only once `Window::congested` (≥ 10 sending sockets, median + queue delay or retransmitted share over its line) holds unbroken for 30 s (`Congestion`): a full + uplink stays congested, slow wallets' own queues flap (bench: ≤ 18 s unbroken) + +A trusted proxy's sockets are skipped (their state = the proxy's hop). A refused dump stops the task +with one warning; serving never depends on it. Rules: +[operators: overload](../../book/src/operators/dos-protection.md#overload). ### Serving log diff --git a/packages/zingod-index-compact-block/src/serve.rs b/packages/zingod-index-compact-block/src/serve.rs index 0c51eae4b..8e3a37a9c 100644 --- a/packages/zingod-index-compact-block/src/serve.rs +++ b/packages/zingod-index-compact-block/src/serve.rs @@ -54,7 +54,7 @@ impl CompactBlockReader> { /// `GetBlockRange` one chunk at a time, either direction: file window below the seam, layer record /// above it -/// - no `Iterator` impl (the caller routes a disk step to the blocking pool first) +/// - no `Iterator` impl (the caller routes a disk step to a read thread first) /// - `reader` held for the whole stream: durable records, layer and seam frozen /// - `next` `None` = spent /// - `last` = finalized height served, inclusive @@ -118,7 +118,7 @@ impl RangeCursor { Ok(Self { reader, budget, pools, descending, next: Some(next), last }) } - /// Next chunk reads the files (a cold window faults: the blocking pool's step) + /// Next chunk reads the files (a cold window faults: a read thread's step) pub fn next_touches_disk(&self) -> bool { self.next.is_some_and(|next| Some(next) <= self.reader.durable()) } diff --git a/packages/zingod-index-compact-block/usage.md b/packages/zingod-index-compact-block/usage.md index 16980cfb5..bfa5ef023 100644 --- a/packages/zingod-index-compact-block/usage.md +++ b/packages/zingod-index-compact-block/usage.md @@ -102,7 +102,7 @@ mid-stream cannot move the seam between the in-memory layer and the files. `next_chunk()` yields either one file window (at most 256 records, cut to 1 MiB, always at least one) or one layer record. `next_touches_disk()` tells the transport whether the next chunk reads files, since only that step belongs -on the blocking pool. There is no RAM cache for the files; the page cache is +on a read thread (`zingod-grpc`'s read pool). There is no RAM cache for the files; the page cache is the cache. ### What it does not answer diff --git a/packages/zingod-index-transparent-address/usage.md b/packages/zingod-index-transparent-address/usage.md index b29a25637..b76299f09 100644 --- a/packages/zingod-index-transparent-address/usage.md +++ b/packages/zingod-index-transparent-address/usage.md @@ -100,7 +100,7 @@ let touched = reader.transactions(&address, start, end)?; // Vec, (height, request fails with `ServeError::TooManyRows`. It never returns a short list or a partial balance. - Every method is synchronous and reads mmapped pages, so a transport runs it - off its async workers (`zingod-grpc`'s scan lane). + off its async workers (`zingod-grpc`'s read pool). - Blocks above the durable tip are `zingod-nfs` layers keyed exactly like the maps. An `NfsPublication`'s reader merges them over the durable store by key. diff --git a/packages/zingod-persistence/usage.md b/packages/zingod-persistence/usage.md index ecdc26d13..188f059d1 100644 --- a/packages/zingod-persistence/usage.md +++ b/packages/zingod-persistence/usage.md @@ -189,8 +189,8 @@ append-only file stays unfragmented where a copy-on-write B-tree under random in - **Mappings longer than the commit.** A mapping covers the whole file, which may include an interrupted commit or the zeroed reserve. Every read goes through `Pages`, sliced to the sealed length. -- **Page faults on async threads.** A cold read can block for milliseconds. Callers run reads on the - blocking pool (`zingod-grpc`'s read lanes), and multi-record reads issue `MADV_WILLNEED` first. +- **Page faults on async threads.** A cold read can block for milliseconds. Callers run reads on their own + threads (`zingod-grpc`'s read pool), and multi-record reads issue `MADV_WILLNEED` first. A batch of point lookups advises in two rounds, every candidate segment's fence page and then its record block, so the device sees the whole batch at once instead of two serial faults per segment per key. Point-lookup segments are mapped `MADV_RANDOM`, merge inputs diff --git a/packages/zingod/Cargo.toml b/packages/zingod/Cargo.toml index d458802d9..e824c3217 100644 --- a/packages/zingod/Cargo.toml +++ b/packages/zingod/Cargo.toml @@ -65,6 +65,7 @@ zstd = "0.14.0" tar = "0.4.46" sd-notify = "0.5" psl = "2.1.252" +procfs = { version = "0.18", default-features = false } [dev-dependencies] tempfile = { workspace = true } diff --git a/packages/zingod/src/cli.rs b/packages/zingod/src/cli.rs index c90f6bd6a..c02036d8a 100644 --- a/packages/zingod/src/cli.rs +++ b/packages/zingod/src/cli.rs @@ -42,15 +42,6 @@ pub(super) enum Command { Verify, #[command(flatten)] Hold(crate::command::hold::Action), - /// Override when this node reports `Overloaded`, across restarts: markers in `[serve] - /// state_dir`/overload over `[grpc.overload]`, read by the running zingod within a second. - /// - /// Prints the settings in force. Exits 0 once the marker matches, 1 on an invalid key or - /// value, or an unreadable config or state directory. - Overload { - #[command(subcommand)] - action: crate::command::overload::Action, - }, /// Origin policy for browser (gRPC-web) clients, across restarts: markers in `[serve] /// state_dir`/origins, read by the running zingod within a second. /// diff --git a/packages/zingod/src/command.rs b/packages/zingod/src/command.rs index ea753d535..74958e938 100644 --- a/packages/zingod/src/command.rs +++ b/packages/zingod/src/command.rs @@ -1,11 +1,10 @@ -//! One-shot subcommands: `verify`, `hold` / `resume`, `overload` +//! One-shot subcommands: `verify`, `hold` / `resume`, `origin` //! -//! - hold + overload = marker files in `[serve] state_dir` (CLI writes, running zingod polls each +//! - hold + origin = marker files in `[serve] state_dir` (CLI writes, running zingod polls each //! second: both halves of each contract live in its file) pub(super) mod hold; pub(super) mod origin; -pub(super) mod overload; pub(super) mod verify; use std::io; diff --git a/packages/zingod/src/command/overload.rs b/packages/zingod/src/command/overload.rs deleted file mode 100644 index b0958336c..000000000 --- a/packages/zingod/src/command/overload.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! `zingod overload on|off|set|unset`: operator markers in `/overload/` over -//! `[grpc.overload]` -//! -//! - `off` = never `Overloaded`; `` = that key's value; both survive restarts (as `held`) -//! - the running zingod reads them every second → the gRPC overload latch (a change = WARN; never -//! on public `/status`) - -use std::path::{Path, PathBuf}; -use std::process::ExitCode; -use std::sync::Arc; -use std::time::Duration; - -use tracing::warn; -use zingod_grpc::{AdmissionState, OverloadLimits}; - -use super::{remove_marker, write_marker, MarkerError}; - -const OFF: &str = "off"; - -#[derive(Debug, Clone, PartialEq, Eq, clap::Subcommand)] -pub(crate) enum Action { - /// Report `Overloaded` again when a cause latches. - On, - /// Never report `Overloaded` (a misfiring detector keeps the node in rotation). - Off, - /// Override one `[grpc.overload]` key, e.g. `cpu_pressure_percent 40`. - Set { key: String, value: String }, - /// Back to the config's value for one key. - Unset { key: String }, -} - -/// The config with every marker applied -#[derive(Debug, Clone, PartialEq, Eq)] -struct Settings { - limits: OverloadLimits, - detection: bool, - overrides: Vec, -} - -impl Settings { - fn unmarked(config: &OverloadLimits) -> Self { - Self { limits: config.clone(), detection: true, overrides: Vec::new() } - } - - /// Log notes (none while nothing is overridden) - fn notes(&self) -> Vec { - let off = - (!self.detection).then(|| "Overload detection off (zingod overload on)".to_owned()); - let set = (!self.overrides.is_empty()).then(|| { - format!("Overload overridden: {} (zingod overload unset)", self.overrides.join(", ")) - }); - off.into_iter().chain(set).collect() - } -} - -/// `config` with `markers` (`key`, `value`) applied, by `[grpc.overload]`'s own rules -/// -/// - each marker checked as it lands: a refusal names its `key = value` -fn merged(config: &OverloadLimits, markers: &[(String, String)]) -> Result { - let mut table = - toml::Table::try_from(config).expect("OverloadLimits serializes to a TOML table"); - let mut limits = config.clone(); - for (key, value) in markers { - let refused = |why: &str| format!("{key} = {value}: {why}"); - let parsed = toml::from_str::(&format!("value = {value}")) - .ok() - .and_then(|mut parsed| parsed.remove("value")) - .ok_or_else(|| refused("not a value"))?; - table.insert(key.clone(), parsed); - limits = table.clone().try_into().map_err(|e: toml::de::Error| refused(e.message()))?; - } - Ok(limits) -} - -/// `dir`'s markers over `config` (no `dir` = no markers) -fn read(dir: &Path, config: &OverloadLimits) -> Result { - let io = |path: &Path, source| MarkerError::Io { path: path.to_owned(), source }; - let entries = match std::fs::read_dir(dir) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Ok(Settings::unmarked(config)) - } - Err(error) => return Err(io(dir, error)), - }; - let mut markers = Vec::new(); - let mut detection = true; - for entry in entries { - let entry = entry.map_err(|error| io(dir, error))?; - let key = entry.file_name().to_string_lossy().into_owned(); - match key.as_str() { - OFF => detection = false, - _ => { - let path = entry.path(); - let value = std::fs::read_to_string(&path).map_err(|error| io(&path, error))?; - markers.push((key, value.trim().to_owned())); - } - } - } - markers.sort(); - let limits = merged(config, &markers).map_err(MarkerError::Invalid)?; - let overrides = markers.iter().map(|(key, value)| format!("{key} = {value}")).collect(); - Ok(Settings { limits, detection, overrides }) -} - -/// The marker `action` names written or removed (`Set` validated first) -fn apply(dir: &Path, config: &OverloadLimits, action: &Action) -> Result<(), MarkerError> { - match action { - Action::Off => write_marker(dir, OFF, ""), - Action::Set { key, value } => { - merged(config, &[(key.clone(), value.clone())]).map_err(MarkerError::Invalid)?; - write_marker(dir, key, value) - } - Action::On => remove_marker(dir, OFF).map(drop), - Action::Unset { key } => remove_marker(dir, key).map(drop), - } -} - -/// `zingod overload …`: prints the settings now in force -pub(crate) fn command(config_path: &Path, action: Action) -> Result { - let config = crate::config::load_config(config_path)?; - let dir = config.serve.state_dir.join("overload"); - let limits = &config.grpc.overload; - apply(&dir, limits, &action)?; - let settings = read(&dir, limits)?; - let printed = toml::to_string(&settings.limits).expect("OverloadLimits serializes to TOML"); - println!("detection = {}", settings.detection); - print!("{printed}"); - eprintln!( - "overridden: [{}] in {} (a running zingod applies within 1 s)", - settings.overrides.join(", "), - dir.display() - ); - Ok(ExitCode::SUCCESS) -} - -/// Every second for the process's life: the markers → `admission` (a change = WARN; unreadable or -/// invalid = WARN, settings kept) -pub(crate) fn spawn(admission: Arc, state_dir: &Path, config: OverloadLimits) { - let dir: PathBuf = state_dir.join("overload"); - tokio::spawn(async move { - let mut current = Settings::unmarked(&config); - let mut tick = tokio::time::interval(Duration::from_secs(1)); - loop { - tick.tick().await; - let settings = match read(&dir, &config) { - Ok(settings) if settings == current => continue, - Ok(settings) => settings, - Err(error) => { - warn!(%error, "Overload markers ignored, settings kept"); - continue; - } - }; - admission.set_overload(settings.limits.clone(), settings.detection); - warn!(notes = ?settings.notes(), "Overload settings changed by operator"); - current = settings; - } - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A session of commands, read back as the running zingod reads it: - /// - off / on toggle detection; set / unset one key over the config's (twice = once) - /// - notes name what is in force, none once all is undone - #[test] - fn markers_override_the_config_until_undone() { - let root = tempfile::tempdir().expect("tempdir"); - let dir = root.path().join("overload"); - let config = OverloadLimits::default(); - let run = |action: Action| apply(&dir, &config, &action); - let set = - |key: &str, value: &str| Action::Set { key: key.to_owned(), value: value.to_owned() }; - let defaults = Settings { limits: config.clone(), detection: true, overrides: vec![] }; - - assert_eq!(read(&dir, &config).expect("reads"), defaults, "no markers: the config"); - for action in [ - Action::Off, - Action::Off, - set("io_pressure_percent", "10"), - set("cpu_pressure_percent", "40"), - ] { - run(action).expect("applies"); - } - let expected = Settings { - limits: OverloadLimits { cpu_pressure_percent: 40, io_pressure_percent: 10 }, - detection: false, - overrides: vec!["cpu_pressure_percent = 40".into(), "io_pressure_percent = 10".into()], - }; - assert_eq!(read(&dir, &config).expect("reads"), expected, "off twice + two keys set"); - assert_eq!( - expected.notes(), - [ - "Overload detection off (zingod overload on)", - "Overload overridden: cpu_pressure_percent = 40, io_pressure_percent = 10 \ - (zingod overload unset)", - ], - "notes while overridden" - ); - - for action in [ - Action::On, - Action::On, - Action::Unset { key: "cpu_pressure_percent".into() }, - Action::Unset { key: "io_pressure_percent".into() }, - ] { - run(action).expect("applies"); - } - assert_eq!(read(&dir, &config).expect("reads"), defaults, "all undone"); - assert_eq!(defaults.notes(), Vec::::new(), "nothing overridden: no notes"); - } - - /// Invalid key or value refused naming it, before anything is written - #[test] - fn a_bad_override_is_refused_naming_it_and_never_lands() { - let root = tempfile::tempdir().expect("tempdir"); - let dir = root.path().join("overload"); - let config = OverloadLimits::default(); - - #[rustfmt::skip] - let refusals = [ - // key, value, refusal names - ("nope", "1", "nope = 1: unknown field `nope`"), - ("cpu_pressure_percent", "300", "cpu_pressure_percent = 300: invalid value"), - ("io_pressure_percent", "x", "io_pressure_percent = x: not a value"), - ]; - for (key, value, named) in refusals { - let set = Action::Set { key: key.to_owned(), value: value.to_owned() }; - let refused = apply(&dir, &config, &set).map_err(|error| error.to_string()); - assert!( - refused.as_ref().is_err_and(|refused| refused.contains(named)), - "{key} = {value}: refused naming {named:?}, got {refused:?}" - ); - } - let untouched = Settings { limits: config.clone(), detection: true, overrides: vec![] }; - assert_eq!(read(&dir, &config).expect("reads"), untouched, "nothing refused landed"); - } - - /// Marker dir present but unlistable (a file here) = error naming it, never "no markers" - #[test] - fn an_unreadable_marker_dir_is_an_error_not_the_config() { - let root = tempfile::tempdir().expect("tempdir"); - let dir = root.path().join("overload"); - std::fs::write(&dir, "").expect("file where the dir goes"); - - let read = read(&dir, &OverloadLimits::default()); - assert!( - matches!(&read, Err(MarkerError::Io { path, .. }) if *path == dir), - "Io error naming {}, got {read:?}", - dir.display() - ); - } -} diff --git a/packages/zingod/src/config.rs b/packages/zingod/src/config.rs index b4c0f606d..34ee923de 100644 --- a/packages/zingod/src/config.rs +++ b/packages/zingod/src/config.rs @@ -679,7 +679,7 @@ fn resolve_validators( tables.into_iter().map(resolve).collect() } -/// [`DaemonConfigFile`], resolved: what the daemon, `verify`, `hold` and `overload` run on +/// [`DaemonConfigFile`], resolved: what the daemon, `verify`, `hold` and `origin` run on #[derive(Debug)] pub(crate) struct DaemonConfig { pub(crate) network: NetworkType, @@ -1095,13 +1095,12 @@ cert_path = "/c.pem" key_path = "/k.pem" [grpc] -max_work_streams = 64 +max_connections_per_ip = 64 +work_share_per_ip = 1.0 unread_timeout_secs = 30 -silent_timeout_secs = 45 max_connection_age_secs = 0 max_connection_age_grace_secs = 60 max_connection_idle_secs = 120 -adaptive_work_streams = false shutdown_grace_secs = 600 trusted_proxies = ["10.0.0.0/8"] @@ -1126,13 +1125,12 @@ cache_dir = "/var/cache/zingod/peers" let secs = Duration::from_secs; let grpc = GrpcLimits { - max_work_streams: NonZeroUsize::new(64).expect("non-zero"), + max_connections_per_ip: NonZeroUsize::new(64).expect("non-zero"), + work_share_per_ip: zingod_grpc::WorkShare::try_from(1.0).expect("in (0, 1]"), unread_timeout: secs(30), - silent_timeout: secs(45), max_connection_age: None, max_connection_age_grace: secs(60), max_connection_idle: Some(secs(120)), - adaptive_work_streams: false, drain_timeout: secs(600), trusted_proxies: zingod_grpc::TrustedProxies::new(vec!["10.0.0.0/8" .parse() diff --git a/packages/zingod/src/daemon.rs b/packages/zingod/src/daemon.rs index 9bb86c5b4..dbec4131e 100644 --- a/packages/zingod/src/daemon.rs +++ b/packages/zingod/src/daemon.rs @@ -49,15 +49,15 @@ use zingod_source::{BlockchainInfo, ChainDataSource}; use zingod_sync::{FinalizedFollower, IndexKind}; use zingod_traffic::{Push, TrafficBalancer, TrustedValidatorId}; -use crate::command::{origin, overload}; +use crate::command::origin; use crate::config::{DaemonConfig, IndexConfig, ServeTls, TrustedValidatorConfig, ValidatorClient}; use crate::error::IndexerError; use crate::health::{admin, DaemonStatus, Sources}; use crate::telemetry::logging::component; use crate::telemetry::{disk, egress, progress, OpenedIndex}; +pub(crate) mod capacity; mod chainview; -pub(crate) mod fd_limit; pub(crate) mod index_snapshot; mod peers; @@ -79,7 +79,7 @@ pub(crate) async fn start( ) -> Result>, IndexerError> { warn!("In development, not for production mainnet use"); let signals = shutdown_signals(); - fd_limit::raise_for(config.grpc.max_connections)?; + capacity::raise_fd_limit()?; match config.validator_client { ValidatorClient::LegacyRpc => { start_over(config, chainview::legacy_client, status, signals).await @@ -138,11 +138,13 @@ async fn listen( tasks: &mut JoinSet, ) -> Result, IndexerError> { let origin_gate = zingod_grpc::OriginGate::new(); - let mut server = GrpcService::new(config.serve.grpc_listen_address, config.grpc.clone()) - .with_retire(status.retire().clone()) - .with_grpc_web(config.serve.grpc_web) - .with_origin_gate(Arc::clone(&origin_gate)) - .with_health(Arc::clone(status) as Arc); + let capacity = capacity::host_capacity()?; + let mut server = + GrpcService::new(config.serve.grpc_listen_address, config.grpc.clone(), capacity)? + .with_retire(status.retire().clone()) + .with_grpc_web(config.serve.grpc_web) + .with_origin_gate(Arc::clone(&origin_gate)) + .with_health(Arc::clone(status) as Arc); let span = component("Grpc"); let (endpoint, network) = (config.serve.grpc_listen_address, network_name(config.network)); // logged in the config's own spelling @@ -159,7 +161,6 @@ async fn listen( server = server.with_tls(tls); } let serving = Serving { routing: server.routing(), admission: server.admission() }; - overload::spawn(server.admission(), &config.serve.state_dir, config.grpc.overload.clone()); origin::spawn(origin_gate, &config.serve.state_dir); let server = server.bind().await?; span.in_scope(|| info!(%endpoint, network, tls = mode, "Listening")); @@ -639,8 +640,6 @@ mod tests { /// - the gRPC listener bound during boot is closed by then #[tokio::test] async fn a_shutdown_signal_during_boot_stops_the_daemon_cleanly() { - use std::num::NonZeroUsize; - let dir = tempfile::tempdir().expect("tempdir"); let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("a free port"); let (grpc, validator) = (probe.local_addr().expect("local addr"), "127.0.0.1:1"); @@ -652,7 +651,6 @@ mod tests { file.trusted_validators = vec![trusted]; file.serve.grpc_listen_address = grpc; file.serve.state_dir = Some(dir.path().join("state")); - file.grpc.max_connections = NonZeroUsize::new(16).expect("non-zero"); let config = file.resolve().expect("resolves"); let status = Arc::new(DaemonStatus::new(config.network, [])); let booting = tokio::spawn(start(config, Arc::clone(&status))); diff --git a/packages/zingod/src/daemon/capacity.rs b/packages/zingod/src/daemon/capacity.rs new file mode 100644 index 000000000..5e49a76bc --- /dev/null +++ b/packages/zingod/src/daemon/capacity.rs @@ -0,0 +1,111 @@ +//! What this host holds: gRPC's [`HostCapacity`], derived (no operator sets it) +//! +//! - open files: one per connection, past [`RESERVED`]; at the limit `accept()` and index opens fail +//! - memory (the cgroup's limit, else the host's): [`PER_CONNECTION`] each within +//! 1 / [`MEMORY_SHARE`]; streams waiting on their clients within 1 / [`PARKED_SHARE`] + +use std::num::NonZeroUsize; +use std::path::Path; + +use procfs::process::Process; +use procfs::{Current as _, Meminfo}; +use rlimit::Resource; +use tracing::info; +use zingod_grpc::HostCapacity; + +use crate::error::IndexerError; + +/// fds besides client sockets: index files (~290 measured on a syncing mainnet node, bounded by +/// tree levels + LSM segment caps), validator RPC pools, metrics, logs +const RESERVED: u64 = 1024; + +/// Heap one busy wallet connection costs, ~1.7× (bench: 60-75 KB each at 6-13k connections) +const PER_CONNECTION: u64 = 128 * 1024; + +/// 1 / this of memory for connections +const MEMORY_SHARE: u64 = 2; + +/// 1 / this of memory for messages held for clients not reading (over it: their connections close, +/// heaviest client first); the last quarter = index caches, read threads, page cache +const PARKED_SHARE: u64 = 4; + +/// Fewer = a host too small to serve (refused at boot, not discovered under load) +const MIN_CONNECTIONS: u64 = 256; + +/// Raises the soft open-file limit to the hard one (indexes and connections share it) +pub(crate) fn raise_fd_limit() -> Result<(), IndexerError> { + let limit = rlimit::increase_nofile_limit(u64::MAX).map_err(IndexerError::OpenFileLimit)?; + info!(limit, "Open-file limit"); + Ok(()) +} + +/// Connections = the lower of what the open files and the memory hold; parked = a memory share +pub(crate) fn host_capacity() -> Result { + let (open_files, _) = + rlimit::getrlimit(Resource::NOFILE).map_err(IndexerError::OpenFileLimit)?; + let host = Meminfo::current().map_err(|error| IndexerError::Memory(error.to_string()))?; + let memory = cgroup_memory_limit().map_or(host.mem_total, |limit| limit.min(host.mem_total)); + let capacity = derive(open_files, memory)?; + let (connections, parked_mib) = (capacity.connections, capacity.parked_bytes >> 20); + info!(connections, parked_mib, open_files, memory_mib = memory >> 20, "Connection cap"); + Ok(capacity) +} + +fn derive(open_files: u64, memory: u64) -> Result { + let by_files = open_files.saturating_sub(RESERVED); + let by_memory = memory / MEMORY_SHARE / PER_CONNECTION; + let connections = by_files.min(by_memory); + match connections >= MIN_CONNECTIONS { + true => Ok(HostCapacity { + connections: NonZeroUsize::new(usize::try_from(connections).unwrap_or(usize::MAX)) + .expect(">= MIN_CONNECTIONS"), + parked_bytes: memory / PARKED_SHARE, + }), + false => Err(IndexerError::TooSmall { open_files, memory_mib: memory >> 20, connections }), + } +} + +/// Lowest `memory.max` from this process's cgroup v2 up to the root (`None` = unlimited / v1) +fn cgroup_memory_limit() -> Option { + let cgroups = Process::myself().ok()?.cgroups().ok()?; + let own = cgroups.0.into_iter().find(|cgroup| cgroup.hierarchy == 0)?; + let own = Path::new("/sys/fs/cgroup").join(own.pathname.trim_start_matches('/')); + own.ancestors() + .take_while(|dir| dir.starts_with("/sys/fs/cgroup")) + .filter_map(|dir| std::fs::read_to_string(dir.join("memory.max")).ok()) + .filter_map(|max| max.trim().parse::().ok()) + .min() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Connections = the scarcer of open files (past the reserve) and memory (half, 128 KiB each); + /// parked = a quarter of memory; under 256 connections refused at boot, naming both + #[test] + fn the_cap_is_the_scarcer_of_open_files_and_memory_and_a_tiny_host_is_refused() { + const GIB: u64 = 1 << 30; + // case, open-file limit, memory, (connections, parked) (None = refused) + #[rustfmt::skip] + let cases = [ + ("systemd hard limit, 8 GiB VM", 524_288, 8 * GIB, Some((32_768, 2 * GIB))), + ("docker hard limit, 64 GiB box", 1_048_576, 64 * GIB, Some((262_144, 16 * GIB))), + ("8 GiB VM, files scarce", 5_120, 8 * GIB, Some((4_096, 2 * GIB))), + ("soft limit never raised", 1_024, 8 * GIB, None), + ("64 MiB container: 256, enough", 524_288, GIB / 16, Some((256, GIB / 64))), + ("32 MiB container", 524_288, GIB / 32, None), + ]; + for (case, open_files, memory, want) in cases { + let cap = derive(open_files, memory); + + let got = cap.as_ref().ok().map(|cap| (cap.connections.get(), cap.parked_bytes)); + assert_eq!(got, want, "{case}: {cap:?}"); + } + + let refused = derive(1_024, 8 * GIB).expect_err("no fds past the reserve").to_string(); + for named in ["1024 open files", "8192 MiB", "LimitNOFILE"] { + assert!(refused.contains(named), "{named}: {refused}"); + } + } +} diff --git a/packages/zingod/src/daemon/fd_limit.rs b/packages/zingod/src/daemon/fd_limit.rs deleted file mode 100644 index 1abbdc81d..000000000 --- a/packages/zingod/src/daemon/fd_limit.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! Open-file limit vs `grpc.max_connections` (one fd per connection) -//! -//! - Past the limit: `accept()` fails with `EMFILE`, index open too - -use std::num::NonZeroUsize; - -use tracing::info; - -use crate::error::IndexerError; - -/// fds besides client sockets: index files (~290 measured on a syncing mainnet node, bounded by -/// tree levels + LSM segment caps), validator RPC pools, metrics, logs -const RESERVED: u64 = 1024; - -/// Raises the soft limit to the hard one, then refuses a `max_connections` it cannot hold -pub(crate) fn raise_for(max_connections: NonZeroUsize) -> Result<(), IndexerError> { - let limit = rlimit::increase_nofile_limit(u64::MAX).map_err(IndexerError::RaiseFdLimit)?; - fits(max_connections, limit)?; - info!(limit, "Open-file limit"); - Ok(()) -} - -fn fits(max_connections: NonZeroUsize, limit: u64) -> Result<(), IndexerError> { - let needed = u64::try_from(max_connections.get()).unwrap_or(u64::MAX).saturating_add(RESERVED); - match needed <= limit { - true => Ok(()), - false => Err(IndexerError::FdLimit { max_connections, needed, reserved: RESERVED, limit }), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// - Connections + the reserve must fit (both sides of the boundary) - /// - Refusal names the knob and both remedies - #[test] - fn max_connections_plus_the_reserve_must_fit_the_limit() { - let connections = |n| NonZeroUsize::new(n).expect("non-zero"); - - let exactly = fits(connections(4096), 4096 + RESERVED); - assert!(exactly.is_ok(), "4096 + {RESERVED} reserved = the limit: fits, got {exactly:?}"); - let one_short = fits(connections(4096), 4096 + RESERVED - 1).map_err(|e| e.to_string()); - let needs = format!("needs {}", 4096 + RESERVED); - assert!( - one_short.as_ref().is_err_and(|refused| refused.contains(&needs)), - "one fd short: refused naming {needs:?}, got {one_short:?}" - ); - - let refused = fits(connections(4096), 1024).expect_err("systemd's default soft limit"); - let message = refused.to_string(); - for named in ["grpc.max_connections = 4096", "needs 5120", "limit is 1024", "LimitNOFILE"] { - assert!(message.contains(named), "{named}: {message}"); - } - } -} diff --git a/packages/zingod/src/error.rs b/packages/zingod/src/error.rs index 41110b4fb..81a8060cf 100644 --- a/packages/zingod/src/error.rs +++ b/packages/zingod/src/error.rs @@ -1,6 +1,5 @@ //! zingod daemon errors -use std::num::NonZeroUsize; use std::path::PathBuf; /// Configuring, booting or running the daemon (`TaskEnded` = a task ended cleanly before any @@ -11,14 +10,16 @@ pub(crate) enum IndexerError { Config(String), #[error("writing {}: {source}", path.display())] ConfigFile { path: PathBuf, source: std::io::Error }, - #[error("raising the open-file limit: {0}")] - RaiseFdLimit(std::io::Error), + #[error("reading or raising the open-file limit: {0}")] + OpenFileLimit(std::io::Error), + #[error("reading the memory size: {0}")] + Memory(String), #[error( - "grpc.max_connections = {max_connections} needs {needed} open files ({reserved} kept for \ - indexes and the validator) and the limit is {limit}: raise the hard limit (systemd \ - LimitNOFILE=, docker --ulimit nofile=) or lower grpc.max_connections" + "this host holds {connections} wallet connections ({open_files} open files, {memory_mib} \ + MiB memory), under 256: raise the hard open-file limit (systemd LimitNOFILE=, docker \ + --ulimit nofile=) or give zingod more memory" )] - FdLimit { max_connections: NonZeroUsize, needed: u64, reserved: u64, limit: u64 }, + TooSmall { open_files: u64, memory_mib: u64, connections: u64 }, #[error(transparent)] ValidatorEndpoint(#[from] zingod_source::EndpointError), #[error(transparent)] diff --git a/packages/zingod/src/health.rs b/packages/zingod/src/health.rs index 0cafc4f04..915d33708 100644 --- a/packages/zingod/src/health.rs +++ b/packages/zingod/src/health.rs @@ -13,7 +13,7 @@ use std::sync::{ use serde::Serialize; use tokio::sync::watch; use zcash_protocol::consensus::NetworkType; -use zingod_grpc::{Hold, OverloadCause, Retire}; +use zingod_grpc::{Hold, Retire}; use zingod_grpc_snapshot::{GrpcSnapshot, GrpcSnapshots, ServingStatus}; use zingod_persistence::DiskView; use zingod_primitives::metric::Metric; @@ -68,8 +68,7 @@ const METRICS: &[Metric] = &[ ), Metric::gauge( REASON, - "Why down, degraded or held, one-hot by reason (= /readyz's detail.reason; overloaded = \ - its cause in zingod_grpc_overload_latched)", + "Why down, degraded or held, one-hot by reason (= /readyz's detail.reason)", ), ]; @@ -149,7 +148,7 @@ struct Catchup { /// Why `down`, `degraded` or `held` /// -/// - `Overloaded` = `zingod_grpc::AdmissionState::overload` +/// - `Overloaded` = `zingod_grpc::AdmissionState::overloaded` /// - `GoawaySent` = held past `hold_goaway_delay_secs`, every connection GOAWAY'd (`zingod hold` /// waits for this) #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -157,7 +156,7 @@ pub(crate) enum DaemonReason { NoValidatorReachable, TipUnvouched, RuntimeStalled, - Overloaded(OverloadCause), + Overloaded, GoawayPending, GoawaySent, } @@ -178,7 +177,7 @@ impl DaemonReason { Self::NoValidatorReachable => "no_validator_reachable", Self::TipUnvouched => "tip_unvouched", Self::RuntimeStalled => "runtime_stalled", - Self::Overloaded(_) => "overloaded", + Self::Overloaded => "overloaded", Self::GoawayPending => "goaway_pending", Self::GoawaySent => "goaway_sent", } @@ -189,7 +188,7 @@ impl DaemonReason { Self::NoValidatorReachable => "No trusted validator reachable", Self::TipUnvouched => "No trusted validator vouches for the tip", Self::RuntimeStalled => "Runtime stalled", - Self::Overloaded(cause) => cause.detail(), + Self::Overloaded => "Overloaded: too many wallets refused or held back by the uplink", Self::GoawayPending => "GOAWAY pending", Self::GoawaySent => "GOAWAY sent", } @@ -217,7 +216,7 @@ enum Stage { /// One snapshot's facts: `height` = served (else handed), `target` = [`GrpcSnapshot::sync_target`] struct Booted { serving_status: ServingStatus, - overload: Option, + overloaded: bool, height: Option, target: Option, rate: Option, @@ -231,7 +230,7 @@ impl Booted { let now = now.map_or(0, |since| i64::try_from(since.as_secs()).unwrap_or(i64::MAX)); Self { serving_status: grpc_snapshot.serving_status(now), - overload: sources.grpc_admission.overload(), + overloaded: sources.grpc_admission.overloaded(), height: served.or(sources.progress.handed()).map(u32::from), target: grpc_snapshot.sync_target().map(u32::from), rate: *sources.block_rate.borrow(), @@ -253,8 +252,8 @@ fn readiness(hold: Hold, live: bool, stage: Stage) -> Readiness { Readiness::Down(DaemonReason::NoValidatorReachable) } (_, Stage::Starting { bootstrap, .. }) => Readiness::Provisioning(bootstrap), - (true, Stage::Booted(Booted { overload: Some(cause), .. })) => { - Readiness::Down(DaemonReason::Overloaded(cause)) + (true, Stage::Booted(Booted { overloaded: true, .. })) => { + Readiness::Down(DaemonReason::Overloaded) } (true, Stage::Booted(booted)) => match booted.serving_status { ServingStatus::Down => Readiness::Down(DaemonReason::TipUnvouched), @@ -490,20 +489,21 @@ mod tests { fn the_state_is_the_first_matching_rule_with_its_own_detail() { const LIVE: bool = true; const STALLED: bool = false; - let stage = |serving_status, overload, target: Option, rate: Option| { + let stage = |serving_status, overloaded, target: Option, rate: Option| { let (height, egress) = (Some(3_514_194), Some(Egress { start: 1_790_000_400, mbps: 12.5 })); - Stage::Booted(Booted { serving_status, overload, height, target, rate, egress }) + Stage::Booted(Booted { serving_status, overloaded, height, target, rate, egress }) }; - let booted = |serving_status, target, rate| stage(serving_status, None, target, rate); - let saturated = Some(OverloadCause::CpuPressure); - let overloaded = - |serving_status| stage(serving_status, saturated, Some(3_515_406), Some(6.2)); + let booted = |serving_status, target, rate| stage(serving_status, false, target, rate); + let overloaded = |serving_status| stage(serving_status, true, Some(3_515_406), Some(6.2)); let starting = |bootstrap, awaiting_validator| Stage::Starting { bootstrap, awaiting_validator }; let because = |reason: &str, message: &str| serde_json::json!({ "reason": reason, "message": message }); let stalled = because("runtime_stalled", "Runtime stalled"); - let saturated = because("overloaded", "Overloaded: CPU pressure"); + let saturated = because( + "overloaded", + "Overloaded: too many wallets refused or held back by the uplink", + ); let unvouched = because("tip_unvouched", "No trusted validator vouches for the tip"); let downloading = SnapshotProgress { phase: SnapshotPhase::Downloading, diff --git a/packages/zingod/src/health/state_log.rs b/packages/zingod/src/health/state_log.rs index bc0a1e9df..151d94d45 100644 --- a/packages/zingod/src/health/state_log.rs +++ b/packages/zingod/src/health/state_log.rs @@ -109,8 +109,6 @@ pub(crate) fn spawn(status: Arc) { #[cfg(test)] mod tests { - use zingod_grpc::OverloadCause; - use super::*; /// One node's day, second by second where it matters: @@ -125,8 +123,7 @@ mod tests { let (secs, mins) = (Duration::from_secs, |m: u64| Duration::from_secs(m * 60)); let changed = |from, after| Some(Line::Changed { from, after }); let not_ready = |elapsed| Some(Line::NotReady { elapsed }); - let io = DaemonReason::Overloaded(OverloadCause::IoPressure); - let cpu = DaemonReason::Overloaded(OverloadCause::CpuPressure); + let overloaded = DaemonReason::Overloaded; let (pending, sent) = (DaemonReason::GoawayPending, DaemonReason::GoawaySent); let unvouched = DaemonReason::TipUnvouched; @@ -140,13 +137,13 @@ mod tests { ("syncing: never repeats", at(1_200), Syncing(None), None), ("serving", at(1_200), Serving(None), changed(Some("syncing"), Some(mins(10)))), ("serving: never repeats", at(4_800), Serving(None), None), - ("overloaded", at(4_800), Down(io), changed(Some("serving"), Some(mins(60)))), - ("down: under REPEAT", at(4_830), Down(io), None), - ("down: REPEAT after the change", at(4_860), Down(io), not_ready(mins(1))), - ("down: under REPEAT since the last", at(4_890), Down(io), None), - ("down: second REPEAT", at(4_920), Down(io), not_ready(mins(2))), - ("down, new reason = a change", at(4_940), Down(cpu), changed(Some("down"), Some(secs(140)))), - ("down: REPEAT after the new reason", at(5_000), Down(cpu), not_ready(secs(60))), + ("overloaded", at(4_800), Down(overloaded), changed(Some("serving"), Some(mins(60)))), + ("down: under REPEAT", at(4_830), Down(overloaded), None), + ("down: REPEAT after the change", at(4_860), Down(overloaded), not_ready(mins(1))), + ("down: under REPEAT since the last", at(4_890), Down(overloaded), None), + ("down: second REPEAT", at(4_920), Down(overloaded), not_ready(mins(2))), + ("down, new reason = a change", at(4_940), Down(unvouched), changed(Some("down"), Some(secs(140)))), + ("down: REPEAT after the new reason", at(5_000), Down(unvouched), not_ready(secs(60))), ("held", at(5_000), Held(pending), changed(Some("down"), Some(mins(1)))), ("held, GOAWAYs sent = a change", at(5_010), Held(sent), changed(Some("held"), Some(secs(10)))), ("held: REPEAT", at(5_070), Held(sent), not_ready(mins(1))), diff --git a/packages/zingod/src/main.rs b/packages/zingod/src/main.rs index e50173a01..cce31b4d9 100644 --- a/packages/zingod/src/main.rs +++ b/packages/zingod/src/main.rs @@ -11,7 +11,7 @@ use clap::Parser; use tracing::{error, info, Instrument as _}; use crate::cli::{Cli, Command}; -use crate::command::{hold, origin, overload, verify}; +use crate::command::{hold, origin, verify}; use crate::config::load_config; use crate::error::IndexerError; use crate::health::{admin, notify, state_log, DaemonStatus}; @@ -41,11 +41,8 @@ fn main() -> ExitCode { let cli = Cli::parse(); // logging → stdout by default (reserved for `verify`'s JSON, `hold`/`resume`'s and - // `overload`'s state) - if !matches!( - cli.command, - Command::Verify | Command::Hold(_) | Command::Overload { .. } | Command::Origin { .. } - ) { + // `origin`'s state) + if !matches!(cli.command, Command::Verify | Command::Hold(_) | Command::Origin { .. }) { if let Err(error) = logging::init() { eprintln!("Error: RUST_LOG: {error}"); return ExitCode::from(2); @@ -74,7 +71,6 @@ fn main() -> ExitCode { } Command::Verify => verify::run(&config), Command::Hold(action) => exit(hold::command(&config, action), 1), - Command::Overload { action } => exit(overload::command(&config, action), 1), Command::Origin { action } => exit(origin::command(&config, action), 1), } }); diff --git a/packages/zingod/usage.md b/packages/zingod/usage.md index 2e8d18fe2..218a1ccce 100644 --- a/packages/zingod/usage.md +++ b/packages/zingod/usage.md @@ -15,7 +15,7 @@ hold, systemd, index snapshots, `verify`, network exposure): - `health/`: the state rules (`readiness`, pure), `/readyz`, `/status`, the admin listener, systemd notify and the state log. - `telemetry/`: logging, the metrics recorder, disk sampling, sync progress, gRPC egress. -- `command/`: `verify`, `hold` / `resume`, `overload`. +- `command/`: `verify`, `hold` / `resume`, `origin`. ## The admin listener @@ -55,4 +55,4 @@ What zingod logs and what to watch: [operators: logging](../../book/src/operator `daemon.rs` tests the task policy (a task ending first cancels the rest and fails the daemon, a signal stops it clean, during boot too) and the whole pipeline over a `MockValidator` and gRPC on localhost (`a_reorg_serves_the_heavier_chain_and_every_rpc_agrees_on_the_served_tip`). The state -rules, `/status`, systemd notify, hold, overload markers and `verify` test beside their code. +rules, `/status`, systemd notify, hold, origin markers and `verify` test beside their code.