gunnar_server/lib.rs
1//! The gunnar git server: everything that used to live behind gunnar-cli's
2//! `--features server`, now its own crate.
3//!
4//! Nothing in here may reach `gunnar-client` except the `client`-gated
5//! [`mirror`] module (replication's send-pack). That edge is what would drag
6//! gix's worktree, status and index machinery into an appliance image, and it
7//! is asserted absent from a resolved dependency graph in
8//! `gunnar-cli/tests/feature_split.rs`.
9#![doc(html_logo_url = "https://gunnar.rs/download/gunnar.webp", html_favicon_url = "https://gunnar.rs/download/favicon.svg")]
10
11/// **The allocator every gunnar that serves is built on.**
12///
13/// A `#[global_allocator]` is the *executable's* to choose — `bench`'s
14/// `stages.rs` says so in its own header, and cargo enforces it: two of them in
15/// one binary is a hard error. So this crate does not install one. It publishes
16/// the *choice* as a type, and each serving binary spends one line on the
17/// declaration:
18///
19/// ```ignore
20/// #[global_allocator]
21/// static ALLOC: gunnar_server::ServerAllocator = gunnar_server::SERVER_ALLOCATOR;
22/// ```
23///
24/// That is one implementation applied to the heap with the grain of the language rather than
25/// against it. The choice lives in exactly one place, so the appliance, the
26/// `gunnar-solo`/`gunnar-service` builds and the bench's `git-store-serve`
27/// cannot drift onto different allocators — and `bench`'s counting probes,
28/// which must install a wrapper of their own, wrap *this* rather than `System`,
29/// so `alloc_mib_*` describes the allocator that actually ships. Installing it
30/// in the library instead looks tidier for exactly as long as it takes someone
31/// to build a probe: it collided with `stage-probe`'s `CountingAlloc` on the
32/// first compile.
33///
34/// The type is defined either way — `System` when the feature is off — so no
35/// declaration site needs a `#[cfg]`.
36///
37/// # Why, with the numbers
38///
39/// znippy's resolver used to retain its whole read arena. Freeing it
40/// (`znippy 0f14d9b`) took anon-after-seed from 4481 MB to 438 MB and
41/// **cost 78% on clone CPU** — 1.47 s to 2.62 s on a 352 396-object clone.
42/// The obvious reading is that the eviction forces re-resolution. It does
43/// not; the clone path never calls the resolver. The retained arena was an
44/// accidental *pre-warmed malloc pool* for the clone's own ~2 GB of
45/// allocations, and giving it back put glibc's `malloc` on the critical path
46/// for every clone thereafter. Bisected: a build that frees but does not
47/// refcount reproduces the whole regression, so the cost is the not-leaking,
48/// not the counting.
49///
50/// Four-way grid, one box, interleaved, quiet, steady state:
51///
52/// | resolver | allocator | clone CPU | anon after seed |
53/// |---|---|---:|---:|
54/// | leaking | glibc | 1.47 s | 4481 MB |
55/// | freeing | glibc | 2.62 s | 438 MB |
56/// | leaking | mimalloc | 1.18 s | 1767 MB |
57/// | **freeing** | **mimalloc** | **1.17 s** | **701 MB** |
58///
59/// The last row beats the leaking build's best cell on *both* axes at once,
60/// and with a competent allocator the two resolvers are within 0.01 s — the
61/// regression was never in znippy. It is user-space allocator cost and not
62/// page faults: system time is identical (0.14 s) and suppressing trim with
63/// `M_TOP_PAD` removed 20 762 faults while moving CPU by 0.04 s.
64///
65/// Opt out with `--no-default-features`; see this crate's manifest for what
66/// that buys and what the dependency budget does and does not actually forbid.
67#[cfg(feature = "mimalloc")]
68pub type ServerAllocator = mimalloc::MiMalloc;
69
70/// The value to declare. See [`ServerAllocator`].
71#[cfg(feature = "mimalloc")]
72pub const SERVER_ALLOCATOR: ServerAllocator = mimalloc::MiMalloc;
73
74/// `System`, because the `mimalloc` feature is off. See [`ServerAllocator`] for
75/// what that costs — on the measured clone it is 2.2x the CPU.
76#[cfg(not(feature = "mimalloc"))]
77pub type ServerAllocator = std::alloc::System;
78
79/// The value to declare. See [`ServerAllocator`].
80#[cfg(not(feature = "mimalloc"))]
81pub const SERVER_ALLOCATOR: ServerAllocator = std::alloc::System;
82
83pub mod admin;
84/// **The appliance identity ceremony** — load-or-mint the WireGuard keypair on
85/// the durable data root, emit the ONE canonical identity line every product
86/// in the fleet emits, and refuse (never re-mint) a corrupt one. A thin caller
87/// of `wg_appliance_core::appliance`, shared with holger and korp. Gated on
88/// `GUNNAR_APPLIANCE=1`, which the `[[build.installer]]` declaration carries.
89///
90/// Behind `wg-client` with [`wg`]: the ceremony mints a WIREGUARD keypair and
91/// exists to serve the tunnel, so a binary built without the tunnel has
92/// nothing to mint and no reason to link `wg_appliance_core`.
93#[cfg(feature = "wg-client")]
94pub mod appliance;
95pub mod attest;
96/// The LFS tee: an object is a transaction-log frame before it is published.
97pub mod txlog_lfs;
98/// The twin: follows the primary's transaction log, applies it, restores from it.
99pub mod twin;
100/// The twin's mutual-TLS credential: minted at pairing, never on the medium.
101pub mod twin_tls;
102pub mod tunnel_addr;
103/// **The declared budgets** — concurrent transfers, open repository handles and
104/// the git memory budget — derived from cores + `RLIMIT_NOFILE` + `MemAvailable`
105/// and named in one INFO row at start. The replacement for the three emergent
106/// ceilings of 2026-08-29 (`19`, `25`, `256`).
107pub mod budget;
108/// **`Admin.Capacity`: "if a tenant's cap rose to N bytes, could you serve
109/// it?"** — the question monetize must ask before it buys a disk. Answers with
110/// a verdict measured off the SAME `statvfs` the push door refuses under, and,
111/// independently, whether this data set can ever grow at all: the appliance is
112/// SEALED (an md set laid once at install, no runtime growth path, PID 1 with
113/// no shell), so a disk bought for it is billed and invisible.
114pub mod capacity;
115pub mod control_plane;
116/// **The runtime data-set growth** (`DATA-SET-GROWTH-FLOW.md` §3): the phase
117/// machine over a `World` seam, the go-ahead, and — with `grow-runtime` — the
118/// appliance world that links edda's engine.
119pub mod grow;
120/// The VGA-console status screen the appliance draws as PID 1 (header band +
121/// rolling events off the log tap).
122pub mod dashboard;
123
124/// **What emptying an account means**, in one place: the four classes of
125/// bytes a user owns and the walk that reclaims them.
126pub mod account_purge;
127/// The account audit logs' retention sweep (2026-10-05).
128pub mod account_audit_sweep;
129/// **One worker, one job at a time, FIFO, deduplicated by subject** — the
130/// runner `gc_queue` and `purge_queue` are two kinds on, and the hook a third
131/// kind plugs into without editing it.
132pub mod job_queue;
133/// **One gc at a time, for the whole box** — the queue behind `Repos.Gc`.
134pub mod gc_queue;
135/// **One account purge at a time, and the lockout always comes off.** The
136/// `Accounts.Purge` queue; see its module docs for why it is its own line and
137/// not the gc one.
138pub mod purge_queue;
139/// **One mirror sync at a time, for the whole box** — the third kind on the one
140/// runner, and the queue behind `Mirror.Sync`.
141pub mod mirror_queue;
142/// **What a mirror sync does**: one `gunnar-wire` `fetch_pack` over one of two
143/// transports, and one compare-and-swap that moves the references.
144pub mod mirror_fetch;
145/// **Smart HTTP for the fetch side**, as the `BufRead`/`Write` pair
146/// `fetch_pack` takes. The adapter that turns a request/response protocol back
147/// into a stream.
148#[cfg(feature = "mirror-http")]
149pub mod mirror_http;
150pub mod grpc_gate;
151/// The tree diff `Refs.Diff` serves. Its own module because it is an algorithm
152/// with an opinion about what it will not compute, and that opinion needs
153/// somewhere to be written down.
154/// An encrypted repository's push, checked before a byte of it is kept (crypt-level2 item 4).
155/// It lives in [`storage`] (it walks the pushed pack with the znippy engine's own reader, and
156/// the engine is named there and nowhere else — xtask `Rule::EngineByName`); its path stays.
157#[cfg(feature = "engine-znippy")]
158pub use storage::encrypted_quarantine;
159pub mod diff;
160/// Whole-file blame: `verify`'s line→commit link 1, done once for every line of
161/// a file. Reuses `verify`'s tree/blob and parent readers and the `diff`
162/// engine (one implementation).
163pub mod blame;
164/// Latest-revision literal code search: walk the tree at a ref, scan text
165/// blobs. Bounded by a file-size and a match ceiling; not a persistent index.
166pub mod search;
167/// A hand-built in-memory git for the `blame` and `search` tests, so their
168/// assertions name oids the test chose rather than trusting the answer.
169#[cfg(test)]
170#[cfg(test)]
171mod testgit;
172/// A repository's first commit, written by the server (`Repos.Create{readme}`).
173pub mod first_commit;
174/// The start-up disk test the appliance runs on /data (seq write/read, 4 KiB
175/// fsync ops) — one `disktest` row on the screen.
176pub mod durable;
177pub mod disktest;
178/// The machine at a glance (`StorageReality.glance`, 2026-10-04): the Machine card's lines, decided here.
179pub mod glance;
180/// `Admin.Topology`'s facts from this server: the pairing feed, the front's principals, the plugin registration (2026-10-04).
181pub mod topology;
182/// **The metered appliance** (the metered plan): the paid state per
183/// namespace — verified, logged, stored, and read by the front doors. Compiled
184/// only with the `metered` feature; see `Cargo.toml` for the doctrine.
185#[cfg(feature = "metered")]
186pub mod entitlement;
187/// **The key that signs an actor ticket**: the appliance's word that one human
188/// may act for one tenant. Its own key, minted at runtime into the secret
189/// store, signing raw Ed25519 because the verifier on the far side of the
190/// monetize seam is `monetize_embed`'s and not SSH's. Metered only — the
191/// community appliance carries no service that would spend one.
192#[cfg(feature = "metered")]
193pub mod actor_ticket;
194/// The descriptor limit: raised once (PID 1 to a million, anyone else to its
195/// hard limit), and the open-repository handle cache sized to fit under it.
196/// The fix for the rig's "202nd repository" `EMFILE` (2026-08-29).
197pub mod limits;
198/// The artifact registry and the OCI images it holds.
199pub mod oci;
200/// Gunnar's end of PID 1. The jobs an operating system used to do for the
201/// server (signals, reaping, the network, DHCP, the stop and the power-off)
202/// are edda's `appliance-pid1`, shared with Holger; this is what Gunnar says
203/// about itself to it (`GUNNAR_NET`, the host name, the narration tap, GN-99).
204pub mod boot;
205/// **The fifth** of those jobs, added 2026-09-23: saying where the boot is.
206/// `boot::ship_boot_narration` ends at `end of hand-off` and the estate's twin
207/// died in the silence after it; this is the narrator that speaks from there
208/// on — a stage line at every boundary, a tick a minute, and a fatal fault that
209/// sends a stable code, waits to be heard and then powers the box off cleanly.
210pub mod narrate;
211pub mod stop_record;
212/// **The fourth** of those jobs, added 2026-09-14: the wall clock. The appliance
213/// booted two hours fast and refused every genuine credential and every Stripe
214/// webhook for it; UDP/123 is closed on that network, so "now" arrives in the
215/// `Date` header of an HTTPS response, from three sources that must agree.
216pub mod clock;
217/// **The boot window**: whether the stores have finished their post-crash work,
218/// and the retryable `starting` answer a client gets until they have. The
219/// 0.6-0.7 s of `the repository is unavailable; try again` after a power cut.
220pub mod readiness;
221/// The registry's one rule: no artifact without valid, logged provenance.
222pub mod registry;
223/// The build runner: checkout, sandbox, artifacts, signed provenance.
224pub mod runner;
225/// The build sandbox: a network namespace of the build's own, unprivileged.
226pub mod sandbox;
227/// The counters over HTTP. Opt-in; binds nothing by default.
228pub mod scrape;
229pub mod serve;
230/// **The layout config** (`/boot/korp/layout.conf`): what the installer
231/// decided, written down and sealed by the thing that did the deciding. gunnar
232/// is TOLD where its storage is and obeys; it never surveys disks, an absent
233/// config is answered as absent rather than inferred, and an unsigned one is
234/// never presented as verified.
235pub mod layout_config;
236/// **The slow disk** (`/serialdat`): the other spindle, and the other failure
237/// domain. One code path whatever is underneath it, and a three-valued claim —
238/// off-stripe, same-device, unverified — over the three copies that are
239/// supposed to outlive losing a data disk.
240pub mod slow;
241/// How gunnar reaches a company's identity provider (company SSO).
242#[cfg(feature = "sso-egress")]
243pub mod sso_egress;
244/// The znippy cold tier, wired where objects enter the server.
245pub mod storage;
246pub mod push_space;
247pub mod stores;
248/// **The usage ledger** (2026-10-06): every namespace's stock meters, re-measured
249/// only where something changed — what `UsageBatch.ReadMany` answers from.
250pub mod usage_ledger;
251/// **Can this control plane be moved onto mutual TLS, and who does it cost?**
252/// The one preflight `gunnar serve --grpc-tls-self` refuses on and
253/// `gunnar issuer readiness` asks in advance.
254pub mod tls_preflight;
255pub mod transport;
256/// `gunnar verify` — the unbroken chain, walked backwards from a line of source.
257pub mod verify;
258/// **WireGuard**, so the appliance has an address that outlives its DHCP lease.
259/// USERSPACE and compiled in (`wg-appliance-core`/boringtun), so it needs no
260/// `wireguard` kernel module and works whatever the packed kernel thinks about
261/// `CONFIG_WIREGUARD` — only `/dev/net/tun`, which is builtin. The tunnel
262/// address goes on through `appliance_pid1::net::apply`, the same netlink writer every other
263/// address does. Off unless the data root carries a `wg0.conf`.
264///
265/// Behind `wg-client`. With the feature off `wg-appliance-core` leaves the
266/// dependency graph and boringtun's crypto tail (x25519-dalek,
267/// chacha20poly1305, blake2, ring) goes with it — which is what an appliance
268/// customer who unticks "WireGuard" is buying.
269#[cfg(feature = "wg-client")]
270pub mod wg;
271/// The pairing loop PID 1 runs itself (nordisk-pairing) — see the module.
272#[cfg(feature = "wg-client")]
273pub mod pairing;
274/// The installer's feed at rest: sealed, owner-only (h-feed-at-rest).
275#[cfg(feature = "wg-client")]
276pub mod fed_at_rest;
277/// The principals the installer feeds (`principal.<id>`), installed by the
278/// primary itself right after its fed admin — see the module.
279#[cfg(feature = "wg-client")]
280pub mod fed_principals;
281/// The installer's mTLS endpoint on this VM (edda nordisk-pairing 0.3): the
282/// bootstrap listener, the boot log the installer collects, the fresh-install reset.
283#[cfg(feature = "wg-client")]
284pub mod installer_listener;
285/// **Live update** (owner 2026-10-12): what this box runs, a new app staged, the graceful
286/// re-exec, the confirm — generic primitives over korp-installer's `live`.
287pub mod live_update;
288/// DEV-NARRATE (Skidbladnir nordisk-narrate): this box's boot log, sealed to
289/// the installer's key, over UDP before the installer's link exists. A DEV
290/// build only — no release row names the feature.
291#[cfg(feature = "dev-narrate")]
292pub mod dev_narrate;
293/// The estate values the installer's door feeds (monetize key, clock key and peer),
294/// taken instead of the medium's — see the module.
295pub mod feed;
296
297/// Whether a smart-HTTP credential may arrive over cleartext. Re-exported
298/// from `gunnar-http` so `gunnar-cli`'s `serve` dispatch can name it without a
299/// direct `gunnar-http` dependency of its own.
300#[cfg(feature = "http")]
301pub use gunnar_http::Cleartext;
302
303/// **Dispatch a server verb.** The one entry point both this crate's binary and
304/// `gunnar-cli`'s `run()` route server commands through, so the wiring lives
305/// exactly once (one implementation).
306///
307/// The trailing catch-all is there only so this compiles inside a `gunnar-solo`
308/// build, where feature unification gives [`gunnar_common::cli::Command`] the
309/// client/control variants too. It is never reached: a server-only binary has no
310/// other variants, and `gunnar-cli` routes only the server ones here.
311///
312/// # It also closes the stores, and that is why the dispatch is wrapped
313///
314/// [`storage::shutdown`] runs on the way out, on the error path as well as the
315/// success path. Being *the* server dispatch is what makes one call site enough:
316/// `gunnar-server`'s `main` and every `gunnar-cli` binary's server verbs both
317/// arrive here, so neither `main` has to remember. Both of those `main`s end in
318/// `std::process::exit(1)` on error, which unwinds nothing and drops nothing —
319/// hence a call, before the value is returned to them, rather than a guard.
320///
321/// See [`storage::shutdown`] and `storage::znippy_engine::shutdown` for what is
322/// being released and what it costs not to.
323pub fn run(
324 data_root: std::path::PathBuf,
325 command: gunnar_common::cli::Command,
326) -> anyhow::Result<()> {
327 let outcome = dispatch(data_root, command);
328 storage::shutdown();
329 outcome
330}
331
332fn dispatch(
333 data_root: std::path::PathBuf,
334 command: gunnar_common::cli::Command,
335) -> anyhow::Result<()> {
336 use gunnar_common::cli::Command;
337
338 match command {
339 Command::Serve(args) => {
340 use std::sync::Arc;
341
342 let stores = Arc::new(stores::ServerStores::open(&data_root)?);
343 let wire = transport::WireConfig::from_serve_args(&args)?;
344 // **The installer's feed** (`crate::feed`): the values the join door
345 // fed, persisted by the pairing loop to `<data>/pairing/joined.toml`
346 // on an earlier boot. Published for the clock (which reads it on
347 // every sync) and resolved against the medium's monetize key below.
348 let fed_at_start = crate::feed::load_at_start(&data_root);
349 let fed_monetize = fed_at_start.as_ref().and_then(|f| f.monetize_pubkey.clone());
350 #[cfg(not(feature = "metered"))]
351 if let Some(key) = &fed_monetize {
352 anyhow::bail!(
353 "REFUSED [pairing-feed-monetize-open-build] the installer's door fed monetize key {key}, \
354 but this gunnar-server was built without the `metered` feature and contains no \
355 entitlement code at all; it would serve every namespace Free. Build the \
356 `gunnar-server-metered` variant, or stop the front feeding `monetize_pubkey`."
357 );
358 }
359 #[cfg(not(feature = "metered"))]
360 crate::feed::record_monetize_in_force(None);
361 // `--monetize-pubkey` on a build that cannot honour it is refused BY
362 // NAME, the `GUNNAR_NET=:dhcp` rule (`appliance_pid1::net::NetConfig::parse`): a
363 // box told to bill by a binary that cannot must stop, not boot Free.
364 #[cfg(not(feature = "metered"))]
365 if let Some(key) = &args.monetize_pubkey {
366 anyhow::bail!(
367 "--monetize-pubkey {key} was given, but this gunnar-server was built without \
368 the `metered` feature and contains no entitlement code at all; it would \
369 serve every namespace Free. Build the `gunnar-server-metered` variant."
370 );
371 }
372 // And the mirror of that refusal on the metered side: NO DEFAULT
373 // URL. This used to read `.unwrap_or("https://gunnar.rs/billing")`,
374 // which put the builder's own page into every other builder's
375 // binary — a metered gunnar with a forgotten flag pointed its
376 // tenants at Vetra. `load` refuses instead, by flag name; see
377 // `MeteredConfig::load` for why a missing link is not tolerable.
378 // The medium's key (`--monetize-pubkey`) against the door's fed one:
379 // either alone is taken, both must agree (`feed::resolve_monetize`
380 // refuses a disagreement by name). `--billing-url` with no key from
381 // EITHER source is refused here — the rule clap's `requires` used
382 // to make before the key could arrive from the door.
383 #[cfg(feature = "metered")]
384 let metered = {
385 // `fed` (the constant medium, 2026-09-24 evening): the medium
386 // carries no key and SAYS so — the door feeds it. Until it has
387 // (the first boot, before the join) the server starts KEYLESS
388 // and the key applies LIVE when it arrives (`feed::monetize_arrived`,
389 // owner 2026-09-25: avoid restarts); a later start reads it from
390 // joined.toml.
391 let awaits_feed = args.monetize_pubkey.as_ref().is_some_and(|k| k.is_fed());
392 let medium = match &args.monetize_pubkey {
393 Some(key) if key.is_fed() => None,
394 Some(key) => Some(entitlement::read_pubkey(key)?),
395 None => None,
396 };
397 let resolved = crate::feed::resolve_monetize(medium, fed_monetize.as_deref())
398 .map_err(|why| anyhow::anyhow!(why))?;
399 if medium.is_none() && resolved.is_some() {
400 tracing::info!("monetize key: from the installer's feed (<data>/pairing/joined.toml); the medium carries none");
401 }
402 crate::feed::record_monetize_in_force(resolved);
403 match resolved {
404 None if awaits_feed => {
405 tracing::warn!(
406 "monetize key: the medium says `{}` — the installer's door feeds it, and it has not yet \
407 (first boot, before the join). Enforcing NOTHING until it arrives; it then applies in \
408 place, with no restart",
409 gunnar_common::monetize_key::FED
410 );
411 let mut cfg = entitlement::MeteredConfig::awaiting_feed(args.billing_url.as_deref())?;
412 cfg.vital = args.monetize_vital;
413 Some(cfg)
414 }
415 Some(key) => {
416 let mut cfg = entitlement::MeteredConfig::load(
417 &gunnar_common::monetize_key::MonetizePubkey::Literal(key),
418 args.billing_url.as_deref(),
419 )?;
420 cfg.vital = args.monetize_vital;
421 Some(cfg)
422 }
423 None if args.billing_url.is_some() => anyhow::bail!(
424 "--billing-url (GUNNAR_BILLING_URL) was given, but no monetize key: neither \
425 --monetize-pubkey (GUNNAR_MONETIZE_PUBKEY) on the medium nor `monetize_pubkey` \
426 fed by the installer's door. A pay page with no key to verify facts with \
427 bills nobody."
428 ),
429 None => None,
430 }
431 };
432 // The community plan gate's floor. Parsed here, once, so a typo is a
433 // startup error with the flag's name in it and not a gate that
434 // silently runs on the default.
435 let disk_floor = gunnar_ssh::DiskFloor::parse(&args.disk_floor)
436 .map_err(|err| anyhow::anyhow!(err))?;
437 // The usage share's settings, parsed here for the same reason: a
438 // typo in `--admit-limit` is a startup error naming the flag.
439 #[cfg(feature = "admit-share")]
440 let admit = admit_settings(args.admit_limit.as_deref(), args.admit_window_days)?;
441 let config = serve::ServeConfig {
442 ssh_bind: args.ssh_bind,
443 disk_floor,
444 grpc_bind: args.grpc_bind,
445 grpc_bind_device: None,
446 admin_key: args.admin_key.clone(),
447 restore_pubkeys: args.restore_pubkeys.clone(),
448 no_grpc: args.no_grpc,
449 wg_only: args.wg_only,
450 twin_role: args.role == gunnar_common::cli::ServeRole::Twin,
451 allow_anonymous: !args.no_anonymous,
452 anonymous: match args.anonymous {
453 gunnar_common::cli::AnonymousArg::Allow => gunnar_ssh::AnonymousPolicy::Allow,
454 gunnar_common::cli::AnonymousArg::Refuse => gunnar_ssh::AnonymousPolicy::Refuse {
455 browse_host: args.browse_host.clone(),
456 },
457 },
458 max_concurrent_transfers: args.max_concurrent_transfers,
459 memory_budget_bytes: args.git_memory_bytes,
460 admission_wait: args.admission_wait_ms.map(std::time::Duration::from_millis),
461 max_transfers_per_principal: args.max_transfers_per_principal,
462 max_anonymous_transfers: args.max_anonymous_transfers,
463 #[cfg(feature = "admit-share")]
464 admit,
465 per_principal_limit_is_hard: args.hard_per_principal_limit,
466 max_object_bytes: args.max_object_bytes,
467 metrics_bind: args.metrics_bind,
468 // I11's passive heartbeat. `map` and not a bare struct: the
469 // three tuning flags carry `default_value_t`, so they are always
470 // present, and it is `--watch-primary` alone that decides
471 // whether a watchdog exists at all.
472 #[cfg(feature = "replication")]
473 standby_watch: args.watch_primary.map(|primary| {
474 crate::standby_watch::StandbyWatch {
475 primary,
476 probe_interval: std::time::Duration::from_millis(args.watch_probe_ms),
477 connect_timeout: std::time::Duration::from_millis(args.watch_connect_ms),
478 promote_after: args.watch_promote_after,
479 }
480 }),
481 // 5.4: the boot check runs on every box with replication (it only
482 // SAYS unless `--repair-auto`); the pull channel only with `--fleet`.
483 #[cfg(feature = "replication")]
484 repair: Some(crate::repair::RepairConfig {
485 auto: args.repair_auto,
486 key: args.repair_key.clone(),
487 twin: args.repair_twin.clone(),
488 // The medium's flags, or the installer's feed (the front hands every box
489 // the ONE's door, M-D35); both and different refuses to start.
490 fleet: crate::repair::resolve_fleet(match (&args.fleet, &args.fleet_instance) {
491 (Some(url), Some(instance)) => Some(crate::repair::FleetConfig {
492 url: url.clone(),
493 ca: args.fleet_ca.clone(),
494 ca_pem: None,
495 at: None,
496 instance: instance.clone(),
497 role: args.fleet_role.clone().unwrap_or_default(),
498 monetize_pubkey: args.monetize_pubkey.as_ref().and_then(|k| k.literal()),
499 every: std::time::Duration::from_secs(args.fleet_every_s.max(1)),
500 }),
501 (Some(_), None) => anyhow::bail!("--fleet needs --fleet-instance (GUNNAR_FLEET_INSTANCE): the estate this box reports for"),
502 _ => None,
503 }, fed_at_start.as_ref(), std::time::Duration::from_secs(args.fleet_every_s.max(1)))
504 .map_err(|why| anyhow::anyhow!(why))?,
505 }),
506 #[cfg(feature = "http")]
507 http_bind: args.http_bind,
508 #[cfg(feature = "http")]
509 http_cleartext: if args.http_allow_cleartext_credentials {
510 Cleartext::Allowed
511 } else {
512 Cleartext::RequireProxyTls
513 },
514 #[cfg(feature = "http")]
515 http_tls: if args.http_tls_self {
516 Some(serve::HttpTls::SelfMinted)
517 } else if let (Some(cert), Some(key)) = (&args.http_tls_cert, &args.http_tls_key) {
518 Some(serve::HttpTls::Identity(gunnar_http::TlsIdentity {
519 cert_chain_pem: std::fs::read_to_string(cert)
520 .map_err(|e| anyhow::anyhow!("reading {}: {e}", cert.display()))?,
521 key_pem: std::fs::read_to_string(key)
522 .map_err(|e| anyhow::anyhow!("reading {}: {e}", key.display()))?,
523 }))
524 } else {
525 None
526 },
527 grpc_tls: if args.grpc_tls_self {
528 Some(serve::GrpcTls::SelfMinted)
529 } else {
530 None
531 },
532 web_relying_parties: args.web_relying_party.clone(),
533 web_require_user_verification: args.web_require_user_verification,
534 grpc_replication_bind: args.grpc_replication_bind,
535 runner: args.runner.then(|| runner::WatchConfig {
536 // `requires_all` on the flag makes both present; the
537 // `expect` names which invariant is being leaned on rather
538 // than defaulting to a path nobody chose.
539 workspace: args
540 .runner_workspace
541 .clone()
542 .expect("--runner requires --runner-workspace"),
543 builder: args
544 .runner_builder
545 .clone()
546 .expect("--runner requires --runner-builder"),
547 allow_network: args.runner_allow_network,
548 refs: Vec::new(),
549 max_builds: None,
550 }),
551 wire,
552 #[cfg(feature = "metered")]
553 metered,
554 ..serve::ServeConfig::default()
555 };
556 // The runtime is built by `serve` rather than with `#[tokio::main]`
557 // so the blocking-pool size, which used to be the server's accidental
558 // concurrency ceiling, is a named constant next to the limit
559 // it has to stay above rather than a tokio default nobody chose.
560 serve::runtime()?.block_on(serve::run(stores, config, args.check))
561 }
562
563 Command::Namespace(command) => {
564 let stores = stores::ServerStores::open(&data_root)?;
565 admin::namespace(&stores, command)
566 }
567 Command::Repo(command) => {
568 // **`archive-out` must work while the server is running**, and
569 // `ServerStores::open` takes redb's exclusive lock on
570 // `control.redb` — a live server holds it, so opening the stores
571 // here would make the one verb a backup needs the one verb a
572 // serving box cannot run. It does not need them: an archive is
573 // three files under `repos/<ns>/<name>.git` and the path resolver
574 // is the same sandbox the SSH listener uses.
575 #[cfg(feature = "engine-znippy")]
576 if matches!(command, gunnar_common::cli::RepoCommand::ArchiveOut { .. }) {
577 return admin::repo_archive_out_without_stores(&data_root, command);
578 }
579 let stores = stores::ServerStores::open(&data_root)?;
580 admin::repo(&stores, command)
581 }
582 Command::Principal(command) => {
583 let stores = stores::ServerStores::open(&data_root)?;
584 admin::principal(&stores, command)
585 }
586 Command::Issuer(command) => {
587 let stores = stores::ServerStores::open(&data_root)?;
588 admin::issuer(&stores, command)
589 }
590 Command::Key(command) => {
591 let stores = stores::ServerStores::open(&data_root)?;
592 admin::key(&stores, command)
593 }
594 Command::Token(command) => {
595 let stores = stores::ServerStores::open(&data_root)?;
596 admin::token(&stores, command)
597 }
598 Command::Attest(command) => {
599 let stores = stores::ServerStores::open(&data_root)?;
600 admin::attest(&stores, command)
601 }
602 Command::Verify(args) => admin::verify(&data_root, args),
603 Command::Blame(args) => admin::blame(&data_root, args),
604 Command::Search(args) => admin::search(&data_root, args),
605 Command::Build(command) => {
606 let stores = stores::ServerStores::open(&data_root)?;
607 admin::build(&stores, command)
608 }
609 Command::Forge(command) => {
610 let stores = stores::ServerStores::open(&data_root)?;
611 admin::forge(&stores, command)
612 }
613 Command::Registry(command) => {
614 let stores = std::sync::Arc::new(stores::ServerStores::open(&data_root)?);
615 admin::registry(&stores, command)
616 }
617 Command::Grant(args) => {
618 let stores = stores::ServerStores::open(&data_root)?;
619 admin::grant(&stores, args)
620 }
621 Command::Revoke(args) => {
622 let stores = stores::ServerStores::open(&data_root)?;
623 admin::revoke(&stores, args)
624 }
625 Command::Gc(args) => {
626 let stores = stores::ServerStores::open(&data_root)?;
627 admin::gc(&stores, args)
628 }
629 // No `ServerStores::open`: that opens `control.redb`, and redb takes an
630 // exclusive file lock a running server already holds. Reading history
631 // must touch nothing but the repository. (Until 2026-08-10 the lock this
632 // named was the control *repository*'s; the sentence survives the
633 // migration because the control database takes one of its own —
634 // one process per store root — and this verb has to run against a live server.)
635 Command::Reflog(args) => admin::reflog(&data_root, args),
636 // No stores at all: minting a key touches nothing this server owns.
637 #[cfg(feature = "wg-client")]
638 Command::Wg(command) => wg::keygen_verb(command),
639 // Built without the tunnel, so there is no keypair to mint and no
640 // implementation to mint it with. An HONEST REFUSAL naming the missing
641 // feature, never the generic "only server commands" below: an operator
642 // typing `gunnar wg` at a binary that was deliberately built without
643 // WireGuard must be told THAT, not left to wonder about a typo.
644 #[cfg(not(feature = "wg-client"))]
645 Command::Wg(_) => anyhow::bail!(
646 "this binary was built WITHOUT the `wg-client` feature: it contains no \
647 WireGuard implementation, so `gunnar wg` has no keypair to mint. Rebuild \
648 with --features wg-client, or use a build that has it."
649 ),
650
651 #[allow(unreachable_patterns)]
652 _ => anyhow::bail!("gunnar-server handles only server commands"),
653 }
654}
655
656/// Replication to a second gunnar. **On the appliance since
657/// 2026-08-30.**
658///
659/// The push half is `gunnar-client`'s send-pack, proved against the real
660/// `git receive-pack` binary, and writing a second one here to keep a dependency
661/// edge clean would trade one implementation for a graph assertion. The gate used to be the
662/// `client` feature, which is why this doc comment used to end *"the appliance
663/// build does not replicate yet … closing the gap is a manifest change"*.
664///
665/// It was that manifest change, and it has landed. `gunnar-client` and
666/// `nornir-git` each put their gix porcelain behind a default-on `porcelain`
667/// feature, so the WIRE half — send-pack, the russh dialler, the ref plan —
668/// resolves alone, and the gate is now `replication`. MEASURED 2026-08-30,
669/// `cargo tree -p gunnar-server -e normal`: **365** packages without it,
670/// **369** with it, against **493** under the old all-or-nothing `client`.
671/// `.nornir/build-variants.toml`'s `gunnar-server` row names the feature, so the
672/// packed appliance carries it; the two-appliance drill exercises it.
673#[cfg(feature = "replication")]
674pub mod mirror;
675/// **I11's passive heartbeat**: the standby half of failover, which notices a
676/// primary that died without abdicating and takes over by itself. Off unless a
677/// `--watch-primary` says otherwise — `control_plane.rs` states the rule it
678/// obeys, that naming a new primary is a decision and never a default.
679#[cfg(feature = "replication")]
680pub mod standby_watch;
681/// **The estate repairs itself** (5.4): the boot check (auto-fix OFF by default)
682/// and the pull channel to monetize, both through `gunnar-repair` — see the module.
683#[cfg(feature = "replication")]
684pub mod repair;
685
686/// S10: the main mails a sold estate's resend sign-in link itself — see the module. Only a
687/// build that pulls the order (`fleet-pull`) mails it.
688#[cfg(feature = "fleet-pull")]
689pub mod postman;
690
691/// G16-d: a sold estate's paid data step, pulled (`grow_go_ahead`) — the box's half.
692#[cfg(feature = "replication")]
693pub mod paid_growth;
694/// `Report.product` (ONE monetize, G1 pull): the main's own word about its product.
695#[cfg(feature = "replication")]
696pub mod product_report;
697pub mod replication_view;
698
699/// **Outbound webhooks: delivery to an external URL.** A subscriber to the
700/// same bus the replicator consumes, gated behind the `webhooks` feature — off,
701/// `ControlPlane`'s default bodies refuse the verbs by name.
702#[cfg(feature = "webhooks")]
703pub mod webhook;
704
705/// **Replication's configuration, over the control plane.** The seam between
706/// [`mirror`] (which knows nothing about gRPC) and [`control_plane`] (which
707/// knows nothing about replication's types).
708///
709/// Behind `replication` for the same reason [`mirror`] is: with the feature off
710/// there is nothing to configure, and `ControlPlane`'s default bodies refuse the
711/// three verbs by name.
712#[cfg(feature = "replication")]
713pub mod replication_wire;
714
715/// **Record one functional-status row for the nornir test matrix.**
716///
717/// Wraps `nornir_testmatrix::functional_status` behind the `testmatrix`
718/// feature — a compiled-out `#[inline]` no-op otherwise, with no nornir edge in
719/// a release appliance. The appliance rollup
720/// (`edda/crates/nornir-testmatrix/src/appliance.rs`) folds rows whose
721/// `component` is `"<product>-appliance"` (host form) or
722/// `"<product>-appliance/<form>"`, so the ONE string gunnar's host form spells
723/// is `"gunnar-appliance"`. Same shim as holger `server/cli/src/main.rs:1095`.
724#[inline]
725pub fn functional_status(component: &str, check: &str, ok: bool, detail: &str) {
726 #[cfg(feature = "testmatrix")]
727 nornir_testmatrix::functional_status(component, check, ok, detail);
728 #[cfg(not(feature = "testmatrix"))]
729 {
730 let _ = (component, check, ok, detail);
731 }
732}
733
734pub use attest::{AttestationLog, ATTESTATION_LOG};
735pub use control_plane::CoreControlPlane;
736pub use grpc_gate::{activity_ledger, control_audit_ledger, control_transfer_gate};
737#[cfg(feature = "replication")]
738pub use mirror::{
739 ReplicationConfig, ReplicationCounters, ReplicationScope, ReplicationTarget, Replicator,
740 TargetStatus, VisibilityScope,
741};
742pub use serve::{GrpcTls, ServeConfig, Server};
743pub use stores::{ServerStores, CONTROL_DB, CONTROL_DIR};
744pub use transport::{WireConfig, WireTransport};
745
746/// **`--admit-limit` / `--admit-window-days` → the usage share's settings.**
747/// Absent flags take `edda_admit::Settings::default()`; `none` is PassThrough.
748/// A typo is a startup error naming the flag.
749#[cfg(feature = "admit-share")]
750pub fn admit_settings(
751 limit: Option<&str>,
752 window_days: Option<u32>,
753) -> anyhow::Result<gunnar_ssh::edda_admit::Settings> {
754 let mut settings = gunnar_ssh::edda_admit::Settings::default();
755 if let Some(limit) = limit {
756 settings.limit = gunnar_ssh::edda_admit::parse_bytes(limit)
757 .map_err(|err| anyhow::anyhow!("--admit-limit (GUNNAR_ADMIT_LIMIT): {err}"))?;
758 }
759 if let Some(days) = window_days {
760 anyhow::ensure!(days > 0, "--admit-window-days (GUNNAR_ADMIT_WINDOW_DAYS) must be at least 1");
761 settings.window_days = days;
762 }
763 Ok(settings)
764}