Repository navigation
refactor(node): decompose the ~1,876-line run() bring-up into ordered phase functions (#1253) - #1312
Conversation
…nHandles (#1253) First phase of decomposing the ~1,876-line `run()` bring-up (#1253). The contiguous teardown block at the end of `run()` becomes a free `async fn shutdown(handles, router, signal, drain_trigger, cache)`; every stop sender, cancellation token, watcher handle, and the JoinSet now travels through a named `ShutdownHandles` struct instead of ad-hoc locals. The move is verbatim — the load-bearing teardown order is unchanged (metrics-stop first; origin-watcher shutdown before the origin checkpoint flush; capacity-bond-watcher cancel after router.shutdown). The only edit is a deref adjustment on the `admin_stop_order` call now that `drain_trigger` is a reference param. `shutdown` opens with an exhaustive `ShutdownHandles` destructure (no `..` rest), so a dropped stop signal becomes a compile error under `-D warnings`. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Second phase of #1253. The front infra-construction block of `run()` (RPC preflight through the endpoint/gossip/limiter build) moves into a free `async fn build_infra(cfg, reload_state) -> anyhow::Result<Infra>`. `run()` immediately destructures the returned `Infra` into the same-named locals, so every downstream reference is unchanged. `started_at` stays as `run()`'s first statement (its doc-comment requires it precede the RPC preflight). The two `reload_state.attach_cache` / `attach_limiter` side effects stay verbatim inside `build_infra`. Awaiting the extracted phase is wrapped in `Box::pin` to keep `run()`'s future under the `large_futures` threshold; the two `&cfg` call sites drop to `cfg` now that the param is a borrow. No behavior change; 865 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntil_shutdown() (#1253) Third phase of #1253. The blacklist-gated router spawn, signal-stream install, and the shutdown-signal `select!` loop move into a free `async fn serve_until_shutdown(reload_state, config_path, drain_trigger, ServeInputs) -> anyhow::Result<(Router, ShutdownSignal)>`. The router-build consumers (`ep`, the three handlers, `gossip`, `limiter`, `blacklist_ready_rx`) travel in a named `ServeInputs`; `drain_trigger` is borrowed (run() still owns the Arc for the later `shutdown` call). Verbatim move — the fail-closed blacklist-gate `?` is preserved. The only textual change is `config_path.as_deref()` -> `config_path`, a no-op forced by the new `Option<&Path>` param type. No behavior change; 865 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…andlers() (#1253) Fourth phase of #1253. The chain-providers, watchers, and handler-construction region of `run()` moves into a free `async fn build_chain_and_handlers(cfg, reload_state, infra) -> anyhow::Result<ChainHandlers<impl Provider + Clone>>`. `infra` is now a held binding (`let infra = ...`), and downstream references are qualified to `infra.<field>` / `ch.<field>`; the phase is generic over the single opaque seller-wallet provider carried by `payment_service`. The one deliberate reordering (authorized by the plan): the buyer-side construction block (`buyer_wallet_provider` / `buyer_channel_store` / `buyer_pending_settle_store`) is relocated to the top of the background region so its opaque provider type never crosses the chain->background seam — keeping `ChainHandlers` single-generic. This is behavior-preserving: the block is pure synchronous construction (no await, no side effect), and `rpc_url` (its only by-value consumer) is now a `ChainHandlers` field. Nothing between the block's old and new position reads or mutates its values. Verified verbatim by a normalized token-stream comparison of the moved region; the buyer-task tracing field name `payment_channel_addr` is preserved. No behavior change; 865 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tasks() (#1253) Fifth phase of #1253. The background-tasks region of `run()` (relocated buyer bootstrap, metrics/GC/republish/bucket runners, rpc watchdog, gossip service, settlement indexer, reputation sweep, admin server, startup banner) moves into a free `async fn spawn_background_tasks(cfg, config_path, reload_state, infra, ch, started_at) -> anyhow::Result<Background>`. `run()` is now a thin ~70-line orchestrator: build_infra -> build_chain_and_handlers -> spawn_background_tasks -> serve_until_shutdown -> shutdown, with the seams carried by the named phase structs. Because the phase takes `&Infra`/`&ChainHandlers` by reference, the five non-Copy `ch` fields the region consumed by value (`rpc_url`, `voucher_domain`, `slash_domain`, `bind_domain`, `reputation_rpc_url`) become `.clone()` — behavior-identical, since each is consumed once and `ch` never reads them again. The `Copy` `ch.payment_channel_addr` is pre-bound into a `_for_buyer` local so the buyer task's `async move` disjoint-captures the address, not the borrowed `ch`. `Background` is non-generic; `drain_trigger` is borrowed (not moved) at both the serve and shutdown calls. No behavior change; 865 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ines)] (#1253) With the bring-up decomposed into build_infra / build_chain_and_handlers / spawn_background_tasks / serve_until_shutdown / shutdown, `run()` is a thin ~70-line orchestrator that trips neither lint, so its blanket `#[allow]` is removed — the acceptance criterion for #1253. The suppression now lives only on the specific dense leaf phases that earn it (each individually reviewable); `serve_until_shutdown` keeps just `cognitive_complexity` (38/25 from the SIGHUP-reload select loop), not `too_many_lines`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…time::run (#1253) Closes the coverage gap the decomposition exposed: no in-crate test drove `runtime::run` end-to-end, so a dropped stop sender or a reordered teardown would only surface at runtime. This `anvil-e2e`-gated test boots the real runtime in-process against a freshly-deployed protocol (anvil + the production DeployProtocol script), polls `admin_v1_health` to readiness, triggers `admin_v1_drain`, and asserts `run()` returns `Ok(())` within the shutdown deadline — the only test that exercises the assembled `ShutdownHandles` and the load-bearing teardown order together. Operator stake/registration is not needed for bring-up (the registry bootstrap only reads the staker set; buyer bootstrap is non-fatal), so the test stays a focused smoke test. No production source changed; no visibility widened. Gated off by default, so the normal test run stays fast. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Warning Review limit reached
Next review available in: 48 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (1)
WalkthroughThe node runtime is reorganized into explicit infrastructure, chain-handler, background-task, and serving phases. A gated Anvil end-to-end test now deploys contracts, starts the runtime, checks health, invokes admin drain, and verifies graceful shutdown. ChangesRuntime lifecycle and shutdown
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Runtime
participant Infra
participant ChainHandlers
participant BackgroundTasks
participant AdminAPI
Runtime->>Infra: build shared runtime handles
Runtime->>ChainHandlers: build chain services and handlers
Runtime->>BackgroundTasks: spawn maintenance and provisioning tasks
Runtime->>AdminAPI: serve health and drain endpoints
AdminAPI-->>Runtime: report readiness and receive drain request
Runtime-->>BackgroundTasks: initiate shutdown
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
There was a problem hiding this comment.
Code Review
This pull request refactors the node runtime by decomposing the monolithic run function into modular phase functions (build_infra, build_chain_and_handlers, spawn_background_tasks, serve_until_shutdown, and shutdown) and introducing helper structs to manage state. It also adds an Anvil-backed end-to-end integration test to verify the bring-up and graceful shutdown sequence. Feedback is provided regarding redundant Box::pin allocations on immediately-awaited futures in the refactored run function.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
Refactors the decdn_node daemon runtime bring-up by decomposing the previously monolithic runtime::run into ordered phase functions with explicit input/output structs, and adds an anvil-backed end-to-end smoke test to exercise full bring-up + graceful drain shutdown.
Changes:
- Split
crates/node/src/runtime/mod.rs::runinto phase functions (build_infra,build_chain_and_handlers,spawn_background_tasks,serve_until_shutdown,shutdown) with structured seams (Infra,ChainHandlers,Background,ServeInputs,ShutdownHandles). - Introduce an
anvil-e2e-gated test that boots the real runtime against an anvil-deployed protocol, waits for admin health readiness, triggersadmin_v1_drain, and assertsrun()returnsOk(()).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/node/src/runtime/mod.rs | Decomposes runtime bring-up/serve/shutdown into explicit phases and handle bundles while preserving the existing teardown sequence. |
| crates/node/tests/anvil_bringup_shutdown_e2e.rs | Adds an anvil-backed bring-up/shutdown smoke test covering the assembled runtime end-to-end under the anvil-e2e feature. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 81.49% (was 81.77%, ▼ 0.28%) — 49713/61008 lines
History
|
…ox::pin (#1253) The `Box::pin` wrappers on `build_infra` / `build_chain_and_handlers` / `spawn_background_tasks` were added mid-refactor, when the rest of `run()` was still inline and the awaited phase futures were large enough to trip `clippy::large_futures`. Now that every phase is extracted, `run()`'s frame is small and the phase futures await cleanly on the stack — clippy `-D warnings` passes without the boxes, so they are redundant heap allocations at bring-up. Removed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Closes #1253.
What
decdn_node::runtime::runwas a single ~1,876-line straight-lineasync fncarrying a blanket#[allow(clippy::cognitive_complexity, clippy::too_many_lines)], with all bring-up + teardown state expressed as ~147 flat locals (9 oneshot stop senders, 4CancellationTokens, ~6WatcherHandles, aJoinSet, and ~14_c/_for_buyerArc clones threaded implicitly between sections).This PR decomposes it into a 72-line orchestrator over five free phase functions, each with explicit named inputs/outputs:
The implicit Arc-clone web is now named struct seams:
Infra,ChainHandlers<P>,Background,ServeInputs,ShutdownHandles<P>.run()'s blanket#[allow]is gone; the suppression now lives only on the specific dense leaf phases that earn it, each individually reviewable.This is a legibility refactor with no behavior change.
How it stays behavior-preserving
?added or removed inside logic.router.shutdown()).shutdownopens with an exhaustiveShutdownHandlesdestructure (no..rest), so a dropped stop signal becomes a compile error under-D warnings.build_chain_and_handlers): the buyer-side provider/store construction is relocated to the top of the background region so its opaque provider type never crosses the chain→background seam, keepingChainHandlerssingle-generic. It's pure synchronous construction (no await, no side effect), andrpc_url(its only by-value consumer) becomes aChainHandlersfield; nothing between the block's old and new position interacts with it. Concretely this flips the relative order of the buyer construction vs the blacklist-watcher spawn + DHT bootstrap (which stay inbuild_chain_and_handlersand now run first) — behavior-irrelevant, since neither reads any buyer value and the buyer handles are first consumed later in the background task spawn.Two premises from the issue were corrected in flight:
run()is a free fn (notRuntime::run), and the five phases aren't contiguous by concern (handlers are built early but the router spawns last, gated on the blacklist watcher's first sync) — so the split is source-order-faithful.New test
Adds an
anvil-e2e-gated bring-up/shutdown smoke test — the only in-crate test that drivesruntime::runend-to-end. It boots the real runtime against a freshly-deployed protocol (anvil + the productionDeployProtocolscript), pollsadmin_v1_healthto readiness, triggersadmin_v1_drain, and assertsrun()returnsOk(())within the shutdown deadline. This is the net that catches a dropped stop sender or a teardown reorder that type-checking cannot. Gated off by default, so the normal test run stays fast.Review guidance
Reviewable commit-by-commit (7 commits, each independently green): extract
shutdown→build_infra→serve_until_shutdown→build_chain_and_handlers(+ buyer relocation) →spawn_background_tasks→ droprun()'s#[allow]→ smoke test.Verification
cargo clippy -p decdn-node --all-targets -- -D warnings— cleancargo nextest run -p decdn-node— 865 passed, 0 skippedcargo fmt -- --check— cleancargo nextest run -p decdn-node --features anvil-e2e anvil_bringup_shutdown— passes🤖 Generated with Claude Code
Summary by CodeRabbit
Refactor
Tests