Skip to main content

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.
148pub mod mirror_http;
149pub mod grpc_gate;
150/// The tree diff `Refs.Diff` serves. Its own module because it is an algorithm
151/// with an opinion about what it will not compute, and that opinion needs
152/// somewhere to be written down.
153/// An encrypted repository's push, checked before a byte of it is kept (crypt-level2 item 4).
154/// It lives in [`storage`] (it walks the pushed pack with the znippy engine's own reader, and
155/// the engine is named there and nowhere else — xtask `Rule::EngineByName`); its path stays.
156#[cfg(feature = "engine-znippy")]
157pub use storage::encrypted_quarantine;
158pub mod diff;
159/// Whole-file blame: `verify`'s line→commit link 1, done once for every line of
160/// a file. Reuses `verify`'s tree/blob and parent readers and the `diff`
161/// engine (one implementation).
162pub mod blame;
163/// Latest-revision literal code search: walk the tree at a ref, scan text
164/// blobs. Bounded by a file-size and a match ceiling; not a persistent index.
165pub mod search;
166/// A hand-built in-memory git for the `blame` and `search` tests, so their
167/// assertions name oids the test chose rather than trusting the answer.
168#[cfg(test)]
169#[cfg(test)]
170mod testgit;
171/// A repository's first commit, written by the server (`Repos.Create{readme}`).
172pub mod first_commit;
173/// The start-up disk test the appliance runs on /data (seq write/read, 4 KiB
174/// fsync ops) — one `disktest` row on the screen.
175pub mod durable;
176pub mod disktest;
177/// The machine at a glance (`StorageReality.glance`, 2026-10-04): the Machine card's lines, decided here.
178pub mod glance;
179/// `Admin.Topology`'s facts from this server: the pairing feed, the front's principals, the plugin registration (2026-10-04).
180pub mod topology;
181/// **The metered appliance** (the metered plan): the paid state per
182/// namespace — verified, logged, stored, and read by the front doors. Compiled
183/// only with the `metered` feature; see `Cargo.toml` for the doctrine.
184#[cfg(feature = "metered")]
185pub mod entitlement;
186/// **The key that signs an actor ticket**: the appliance's word that one human
187/// may act for one tenant. Its own key, minted at runtime into the secret
188/// store, signing raw Ed25519 because the verifier on the far side of the
189/// monetize seam is `monetize_embed`'s and not SSH's. Metered only — the
190/// community appliance carries no service that would spend one.
191#[cfg(feature = "metered")]
192pub mod actor_ticket;
193/// The descriptor limit: raised once (PID 1 to a million, anyone else to its
194/// hard limit), and the open-repository handle cache sized to fit under it.
195/// The fix for the rig's "202nd repository" `EMFILE` (2026-08-29).
196pub mod limits;
197/// The artifact registry and the OCI images it holds.
198pub mod oci;
199/// Gunnar's end of PID 1. The jobs an operating system used to do for the
200/// server (signals, reaping, the network, DHCP, the stop and the power-off)
201/// are edda's `appliance-pid1`, shared with Holger; this is what Gunnar says
202/// about itself to it (`GUNNAR_NET`, the host name, the narration tap, GN-99).
203pub mod boot;
204/// **The fifth** of those jobs, added 2026-09-23: saying where the boot is.
205/// `boot::ship_boot_narration` ends at `end of hand-off` and the estate's twin
206/// died in the silence after it; this is the narrator that speaks from there
207/// on — a stage line at every boundary, a tick a minute, and a fatal fault that
208/// sends a stable code, waits to be heard and then powers the box off cleanly.
209pub mod narrate;
210pub mod stop_record;
211/// **The fourth** of those jobs, added 2026-09-14: the wall clock. The appliance
212/// booted two hours fast and refused every genuine credential and every Stripe
213/// webhook for it; UDP/123 is closed on that network, so "now" arrives in the
214/// `Date` header of an HTTPS response, from three sources that must agree.
215pub mod clock;
216/// **The boot window**: whether the stores have finished their post-crash work,
217/// and the retryable `starting` answer a client gets until they have. The
218/// 0.6-0.7 s of `the repository is unavailable; try again` after a power cut.
219pub mod readiness;
220/// The registry's one rule: no artifact without valid, logged provenance.
221pub mod registry;
222/// The build runner: checkout, sandbox, artifacts, signed provenance.
223pub mod runner;
224/// The build sandbox: a network namespace of the build's own, unprivileged.
225pub mod sandbox;
226/// The counters over HTTP. Opt-in; binds nothing by default.
227pub mod scrape;
228pub mod serve;
229/// **The layout config** (`/boot/korp/layout.conf`): what the installer
230/// decided, written down and sealed by the thing that did the deciding. gunnar
231/// is TOLD where its storage is and obeys; it never surveys disks, an absent
232/// config is answered as absent rather than inferred, and an unsigned one is
233/// never presented as verified.
234pub mod layout_config;
235/// **The slow disk** (`/serialdat`): the other spindle, and the other failure
236/// domain. One code path whatever is underneath it, and a three-valued claim —
237/// off-stripe, same-device, unverified — over the three copies that are
238/// supposed to outlive losing a data disk.
239pub mod slow;
240/// How gunnar reaches a company's identity provider (company SSO).
241pub mod sso_egress;
242/// The znippy cold tier, wired where objects enter the server.
243pub mod storage;
244pub mod push_space;
245pub mod stores;
246/// **The usage ledger** (2026-10-06): every namespace's stock meters, re-measured
247/// only where something changed — what `UsageBatch.ReadMany` answers from.
248pub mod usage_ledger;
249/// **Can this control plane be moved onto mutual TLS, and who does it cost?**
250/// The one preflight `gunnar serve --grpc-tls-self` refuses on and
251/// `gunnar issuer readiness` asks in advance.
252pub mod tls_preflight;
253pub mod transport;
254/// `gunnar verify` — the unbroken chain, walked backwards from a line of source.
255pub mod verify;
256/// **WireGuard**, so the appliance has an address that outlives its DHCP lease.
257/// USERSPACE and compiled in (`wg-appliance-core`/boringtun), so it needs no
258/// `wireguard` kernel module and works whatever the packed kernel thinks about
259/// `CONFIG_WIREGUARD` — only `/dev/net/tun`, which is builtin. The tunnel
260/// address goes on through `appliance_pid1::net::apply`, the same netlink writer every other
261/// address does. Off unless the data root carries a `wg0.conf`.
262///
263/// Behind `wg-client`. With the feature off `wg-appliance-core` leaves the
264/// dependency graph and boringtun's crypto tail (x25519-dalek,
265/// chacha20poly1305, blake2, ring) goes with it — which is what an appliance
266/// customer who unticks "WireGuard" is buying.
267#[cfg(feature = "wg-client")]
268pub mod wg;
269/// The pairing loop PID 1 runs itself (nordisk-pairing) — see the module.
270#[cfg(feature = "wg-client")]
271pub mod pairing;
272/// The installer's feed at rest: sealed, owner-only (h-feed-at-rest).
273#[cfg(feature = "wg-client")]
274pub mod fed_at_rest;
275/// The principals the installer feeds (`principal.<id>`), installed by the
276/// primary itself right after its fed admin — see the module.
277#[cfg(feature = "wg-client")]
278pub mod fed_principals;
279/// The installer's mTLS endpoint on this VM (edda nordisk-pairing 0.3): the
280/// bootstrap listener, the boot log the installer collects, the fresh-install reset.
281#[cfg(feature = "wg-client")]
282pub mod installer_listener;
283/// **Live update** (owner 2026-10-12): what this box runs, a new app staged, the graceful
284/// re-exec, the confirm — generic primitives over korp-installer's `live`.
285pub mod live_update;
286/// DEV-NARRATE (Skidbladnir nordisk-narrate): this box's boot log, sealed to
287/// the installer's key, over UDP before the installer's link exists. A DEV
288/// build only — no release row names the feature.
289#[cfg(feature = "dev-narrate")]
290pub mod dev_narrate;
291/// The metered primary registers its OWN monetize plugin into vm1's plugin door
292/// (owner 2026-09-25) — see the module.
293#[cfg(all(feature = "wg-client", feature = "metered"))]
294pub mod self_register;
295/// The estate values the installer's door feeds (monetize key, clock key and peer),
296/// taken instead of the medium's — see the module.
297pub mod feed;
298
299/// Whether a smart-HTTP credential may arrive over cleartext. Re-exported
300/// from `gunnar-http` so `gunnar-cli`'s `serve` dispatch can name it without a
301/// direct `gunnar-http` dependency of its own.
302#[cfg(feature = "http")]
303pub use gunnar_http::Cleartext;
304
305/// **Dispatch a server verb.** The one entry point both this crate's binary and
306/// `gunnar-cli`'s `run()` route server commands through, so the wiring lives
307/// exactly once (one implementation).
308///
309/// The trailing catch-all is there only so this compiles inside a `gunnar-solo`
310/// build, where feature unification gives [`gunnar_common::cli::Command`] the
311/// client/control variants too. It is never reached: a server-only binary has no
312/// other variants, and `gunnar-cli` routes only the server ones here.
313///
314/// # It also closes the stores, and that is why the dispatch is wrapped
315///
316/// [`storage::shutdown`] runs on the way out, on the error path as well as the
317/// success path. Being *the* server dispatch is what makes one call site enough:
318/// `gunnar-server`'s `main` and every `gunnar-cli` binary's server verbs both
319/// arrive here, so neither `main` has to remember. Both of those `main`s end in
320/// `std::process::exit(1)` on error, which unwinds nothing and drops nothing —
321/// hence a call, before the value is returned to them, rather than a guard.
322///
323/// See [`storage::shutdown`] and `storage::znippy_engine::shutdown` for what is
324/// being released and what it costs not to.
325pub fn run(
326    data_root: std::path::PathBuf,
327    command: gunnar_common::cli::Command,
328) -> anyhow::Result<()> {
329    let outcome = dispatch(data_root, command);
330    storage::shutdown();
331    outcome
332}
333
334fn dispatch(
335    data_root: std::path::PathBuf,
336    command: gunnar_common::cli::Command,
337) -> anyhow::Result<()> {
338    use gunnar_common::cli::Command;
339
340    match command {
341        Command::Serve(args) => {
342            use std::sync::Arc;
343
344            let stores = Arc::new(stores::ServerStores::open(&data_root)?);
345            let wire = transport::WireConfig::from_serve_args(&args)?;
346            // **The installer's feed** (`crate::feed`): the values the join door
347            // fed, persisted by the pairing loop to `<data>/pairing/joined.toml`
348            // on an earlier boot. Published for the clock (which reads it on
349            // every sync) and resolved against the medium's monetize key below.
350            let fed_at_start = crate::feed::load_at_start(&data_root);
351            let fed_monetize = fed_at_start.as_ref().and_then(|f| f.monetize_pubkey.clone());
352            #[cfg(not(feature = "metered"))]
353            if let Some(key) = &fed_monetize {
354                anyhow::bail!(
355                    "REFUSED [pairing-feed-monetize-open-build] the installer's door fed monetize key {key}, \
356                     but this gunnar-server was built without the `metered` feature and contains no \
357                     entitlement code at all; it would serve every namespace Free. Build the \
358                     `gunnar-server-metered` variant, or stop the front feeding `monetize_pubkey`."
359                );
360            }
361            #[cfg(not(feature = "metered"))]
362            crate::feed::record_monetize_in_force(None);
363            // `--monetize-pubkey` on a build that cannot honour it is refused BY
364            // NAME, the `GUNNAR_NET=:dhcp` rule (`appliance_pid1::net::NetConfig::parse`): a
365            // box told to bill by a binary that cannot must stop, not boot Free.
366            #[cfg(not(feature = "metered"))]
367            if let Some(key) = &args.monetize_pubkey {
368                anyhow::bail!(
369                    "--monetize-pubkey {key} was given, but this gunnar-server was built without \
370                     the `metered` feature and contains no entitlement code at all; it would \
371                     serve every namespace Free. Build the `gunnar-server-metered` variant."
372                );
373            }
374            // And the mirror of that refusal on the metered side: NO DEFAULT
375            // URL. This used to read `.unwrap_or("https://gunnar.rs/billing")`,
376            // which put the builder's own page into every other builder's
377            // binary — a metered gunnar with a forgotten flag pointed its
378            // tenants at Vetra. `load` refuses instead, by flag name; see
379            // `MeteredConfig::load` for why a missing link is not tolerable.
380            // The medium's key (`--monetize-pubkey`) against the door's fed one:
381            // either alone is taken, both must agree (`feed::resolve_monetize`
382            // refuses a disagreement by name). `--billing-url` with no key from
383            // EITHER source is refused here — the rule clap's `requires` used
384            // to make before the key could arrive from the door.
385            #[cfg(feature = "metered")]
386            let metered = {
387                // `fed` (the constant medium, 2026-09-24 evening): the medium
388                // carries no key and SAYS so — the door feeds it. Until it has
389                // (the first boot, before the join) the server starts KEYLESS
390                // and the key applies LIVE when it arrives (`feed::monetize_arrived`,
391                // owner 2026-09-25: avoid restarts); a later start reads it from
392                // joined.toml.
393                let awaits_feed = args.monetize_pubkey.as_ref().is_some_and(|k| k.is_fed());
394                let medium = match &args.monetize_pubkey {
395                    Some(key) if key.is_fed() => None,
396                    Some(key) => Some(entitlement::read_pubkey(key)?),
397                    None => None,
398                };
399                let resolved = crate::feed::resolve_monetize(medium, fed_monetize.as_deref())
400                    .map_err(|why| anyhow::anyhow!(why))?;
401                if medium.is_none() && resolved.is_some() {
402                    tracing::info!("monetize key: from the installer's feed (<data>/pairing/joined.toml); the medium carries none");
403                }
404                crate::feed::record_monetize_in_force(resolved);
405                match resolved {
406                    None if awaits_feed => {
407                        tracing::warn!(
408                            "monetize key: the medium says `{}` — the installer's door feeds it, and it has not yet \
409                             (first boot, before the join). Enforcing NOTHING until it arrives; it then applies in \
410                             place, with no restart",
411                            gunnar_common::monetize_key::FED
412                        );
413                        let mut cfg = entitlement::MeteredConfig::awaiting_feed(args.billing_url.as_deref())?;
414                        cfg.vital = args.monetize_vital;
415                        Some(cfg)
416                    }
417                    Some(key) => {
418                        let mut cfg = entitlement::MeteredConfig::load(
419                            &gunnar_common::monetize_key::MonetizePubkey::Literal(key),
420                            args.billing_url.as_deref(),
421                        )?;
422                        cfg.vital = args.monetize_vital;
423                        Some(cfg)
424                    }
425                    None if args.billing_url.is_some() => anyhow::bail!(
426                        "--billing-url (GUNNAR_BILLING_URL) was given, but no monetize key: neither \
427                         --monetize-pubkey (GUNNAR_MONETIZE_PUBKEY) on the medium nor `monetize_pubkey` \
428                         fed by the installer's door. A pay page with no key to verify facts with \
429                         bills nobody."
430                    ),
431                    None => None,
432                }
433            };
434            // The community plan gate's floor. Parsed here, once, so a typo is a
435            // startup error with the flag's name in it and not a gate that
436            // silently runs on the default.
437            let disk_floor = gunnar_ssh::DiskFloor::parse(&args.disk_floor)
438                .map_err(|err| anyhow::anyhow!(err))?;
439            // The usage share's settings, parsed here for the same reason: a
440            // typo in `--admit-limit` is a startup error naming the flag.
441            #[cfg(feature = "admit-share")]
442            let admit = admit_settings(args.admit_limit.as_deref(), args.admit_window_days)?;
443            let config = serve::ServeConfig {
444                ssh_bind: args.ssh_bind,
445                disk_floor,
446                grpc_bind: args.grpc_bind,
447                grpc_bind_device: None,
448                admin_key: args.admin_key.clone(),
449                restore_pubkeys: args.restore_pubkeys.clone(),
450                no_grpc: args.no_grpc,
451                wg_only: args.wg_only,
452                twin_role: args.role == gunnar_common::cli::ServeRole::Twin,
453                allow_anonymous: !args.no_anonymous,
454                anonymous: match args.anonymous {
455                    gunnar_common::cli::AnonymousArg::Allow => gunnar_ssh::AnonymousPolicy::Allow,
456                    gunnar_common::cli::AnonymousArg::Refuse => gunnar_ssh::AnonymousPolicy::Refuse {
457                        browse_host: args.browse_host.clone(),
458                    },
459                },
460                max_concurrent_transfers: args.max_concurrent_transfers,
461                memory_budget_bytes: args.git_memory_bytes,
462                admission_wait: args.admission_wait_ms.map(std::time::Duration::from_millis),
463                max_transfers_per_principal: args.max_transfers_per_principal,
464                max_anonymous_transfers: args.max_anonymous_transfers,
465                #[cfg(feature = "admit-share")]
466                admit,
467                per_principal_limit_is_hard: args.hard_per_principal_limit,
468                max_object_bytes: args.max_object_bytes,
469                metrics_bind: args.metrics_bind,
470                // I11's passive heartbeat. `map` and not a bare struct: the
471                // three tuning flags carry `default_value_t`, so they are always
472                // present, and it is `--watch-primary` alone that decides
473                // whether a watchdog exists at all.
474                #[cfg(feature = "replication")]
475                standby_watch: args.watch_primary.map(|primary| {
476                    crate::standby_watch::StandbyWatch {
477                        primary,
478                        probe_interval: std::time::Duration::from_millis(args.watch_probe_ms),
479                        connect_timeout: std::time::Duration::from_millis(args.watch_connect_ms),
480                        promote_after: args.watch_promote_after,
481                    }
482                }),
483                // 5.4: the boot check runs on every box with replication (it only
484                // SAYS unless `--repair-auto`); the pull channel only with `--fleet`.
485                #[cfg(feature = "replication")]
486                repair: Some(crate::repair::RepairConfig {
487                    auto: args.repair_auto,
488                    key: args.repair_key.clone(),
489                    twin: args.repair_twin.clone(),
490                    // The medium's flags, or the installer's feed (the front hands every box
491                    // the ONE's door, M-D35); both and different refuses to start.
492                    fleet: crate::repair::resolve_fleet(match (&args.fleet, &args.fleet_instance) {
493                        (Some(url), Some(instance)) => Some(crate::repair::FleetConfig {
494                            url: url.clone(),
495                            ca: args.fleet_ca.clone(),
496                            ca_pem: None,
497                            at: None,
498                            instance: instance.clone(),
499                            role: args.fleet_role.clone().unwrap_or_default(),
500                            monetize_pubkey: args.monetize_pubkey.as_ref().and_then(|k| k.literal()),
501                            every: std::time::Duration::from_secs(args.fleet_every_s.max(1)),
502                        }),
503                        (Some(_), None) => anyhow::bail!("--fleet needs --fleet-instance (GUNNAR_FLEET_INSTANCE): the estate this box reports for"),
504                        _ => None,
505                    }, fed_at_start.as_ref(), std::time::Duration::from_secs(args.fleet_every_s.max(1)))
506                    .map_err(|why| anyhow::anyhow!(why))?,
507                }),
508                #[cfg(feature = "http")]
509                http_bind: args.http_bind,
510                #[cfg(feature = "http")]
511                http_cleartext: if args.http_allow_cleartext_credentials {
512                    Cleartext::Allowed
513                } else {
514                    Cleartext::RequireProxyTls
515                },
516                #[cfg(feature = "http")]
517                http_tls: if args.http_tls_self {
518                    Some(serve::HttpTls::SelfMinted)
519                } else if let (Some(cert), Some(key)) = (&args.http_tls_cert, &args.http_tls_key) {
520                    Some(serve::HttpTls::Identity(gunnar_http::TlsIdentity {
521                        cert_chain_pem: std::fs::read_to_string(cert)
522                            .map_err(|e| anyhow::anyhow!("reading {}: {e}", cert.display()))?,
523                        key_pem: std::fs::read_to_string(key)
524                            .map_err(|e| anyhow::anyhow!("reading {}: {e}", key.display()))?,
525                    }))
526                } else {
527                    None
528                },
529                grpc_tls: if args.grpc_tls_self {
530                    Some(serve::GrpcTls::SelfMinted)
531                } else {
532                    None
533                },
534                web_relying_parties: args.web_relying_party.clone(),
535                grpc_replication_bind: args.grpc_replication_bind,
536                runner: args.runner.then(|| runner::WatchConfig {
537                    // `requires_all` on the flag makes both present; the
538                    // `expect` names which invariant is being leaned on rather
539                    // than defaulting to a path nobody chose.
540                    workspace: args
541                        .runner_workspace
542                        .clone()
543                        .expect("--runner requires --runner-workspace"),
544                    builder: args
545                        .runner_builder
546                        .clone()
547                        .expect("--runner requires --runner-builder"),
548                    allow_network: args.runner_allow_network,
549                    refs: Vec::new(),
550                    max_builds: None,
551                }),
552                wire,
553                #[cfg(feature = "metered")]
554                metered,
555                ..serve::ServeConfig::default()
556            };
557            // The runtime is built by `serve` rather than with `#[tokio::main]`
558            // so the blocking-pool size, which used to be the server's accidental
559            // concurrency ceiling, is a named constant next to the limit
560            // it has to stay above rather than a tokio default nobody chose.
561            serve::runtime()?.block_on(serve::run(stores, config, args.check))
562        }
563
564        Command::Namespace(command) => {
565            let stores = stores::ServerStores::open(&data_root)?;
566            admin::namespace(&stores, command)
567        }
568        Command::Repo(command) => {
569            // **`archive-out` must work while the server is running**, and
570            // `ServerStores::open` takes redb's exclusive lock on
571            // `control.redb` — a live server holds it, so opening the stores
572            // here would make the one verb a backup needs the one verb a
573            // serving box cannot run. It does not need them: an archive is
574            // three files under `repos/<ns>/<name>.git` and the path resolver
575            // is the same sandbox the SSH listener uses.
576            #[cfg(feature = "engine-znippy")]
577            if matches!(command, gunnar_common::cli::RepoCommand::ArchiveOut { .. }) {
578                return admin::repo_archive_out_without_stores(&data_root, command);
579            }
580            let stores = stores::ServerStores::open(&data_root)?;
581            admin::repo(&stores, command)
582        }
583        Command::Principal(command) => {
584            let stores = stores::ServerStores::open(&data_root)?;
585            admin::principal(&stores, command)
586        }
587        Command::Issuer(command) => {
588            let stores = stores::ServerStores::open(&data_root)?;
589            admin::issuer(&stores, command)
590        }
591        Command::Key(command) => {
592            let stores = stores::ServerStores::open(&data_root)?;
593            admin::key(&stores, command)
594        }
595        Command::Token(command) => {
596            let stores = stores::ServerStores::open(&data_root)?;
597            admin::token(&stores, command)
598        }
599        Command::Attest(command) => {
600            let stores = stores::ServerStores::open(&data_root)?;
601            admin::attest(&stores, command)
602        }
603        Command::Verify(args) => admin::verify(&data_root, args),
604        Command::Blame(args) => admin::blame(&data_root, args),
605        Command::Search(args) => admin::search(&data_root, args),
606        Command::Build(command) => {
607            let stores = stores::ServerStores::open(&data_root)?;
608            admin::build(&stores, command)
609        }
610        Command::Forge(command) => {
611            let stores = stores::ServerStores::open(&data_root)?;
612            admin::forge(&stores, command)
613        }
614        Command::Registry(command) => {
615            let stores = std::sync::Arc::new(stores::ServerStores::open(&data_root)?);
616            admin::registry(&stores, command)
617        }
618        Command::Grant(args) => {
619            let stores = stores::ServerStores::open(&data_root)?;
620            admin::grant(&stores, args)
621        }
622        Command::Revoke(args) => {
623            let stores = stores::ServerStores::open(&data_root)?;
624            admin::revoke(&stores, args)
625        }
626        Command::Gc(args) => {
627            let stores = stores::ServerStores::open(&data_root)?;
628            admin::gc(&stores, args)
629        }
630        // No `ServerStores::open`: that opens `control.redb`, and redb takes an
631        // exclusive file lock a running server already holds. Reading history
632        // must touch nothing but the repository. (Until 2026-08-10 the lock this
633        // named was the control *repository*'s; the sentence survives the
634        // migration because the control database takes one of its own —
635        // one process per store root — and this verb has to run against a live server.)
636        Command::Reflog(args) => admin::reflog(&data_root, args),
637        // No stores at all: minting a key touches nothing this server owns.
638        #[cfg(feature = "wg-client")]
639        Command::Wg(command) => wg::keygen_verb(command),
640        // Built without the tunnel, so there is no keypair to mint and no
641        // implementation to mint it with. An HONEST REFUSAL naming the missing
642        // feature, never the generic "only server commands" below: an operator
643        // typing `gunnar wg` at a binary that was deliberately built without
644        // WireGuard must be told THAT, not left to wonder about a typo.
645        #[cfg(not(feature = "wg-client"))]
646        Command::Wg(_) => anyhow::bail!(
647            "this binary was built WITHOUT the `wg-client` feature: it contains no \
648             WireGuard implementation, so `gunnar wg` has no keypair to mint. Rebuild \
649             with --features wg-client, or use a build that has it."
650        ),
651
652        #[allow(unreachable_patterns)]
653        _ => anyhow::bail!("gunnar-server handles only server commands"),
654    }
655}
656
657/// Replication to a second gunnar. **On the appliance since
658/// 2026-08-30.**
659///
660/// The push half is `gunnar-client`'s send-pack, proved against the real
661/// `git receive-pack` binary, and writing a second one here to keep a dependency
662/// edge clean would trade one implementation for a graph assertion. The gate used to be the
663/// `client` feature, which is why this doc comment used to end *"the appliance
664/// build does not replicate yet … closing the gap is a manifest change"*.
665///
666/// It was that manifest change, and it has landed. `gunnar-client` and
667/// `nornir-git` each put their gix porcelain behind a default-on `porcelain`
668/// feature, so the WIRE half — send-pack, the russh dialler, the ref plan —
669/// resolves alone, and the gate is now `replication`. MEASURED 2026-08-30,
670/// `cargo tree -p gunnar-server -e normal`: **365** packages without it,
671/// **369** with it, against **493** under the old all-or-nothing `client`.
672/// `.nornir/build-variants.toml`'s `gunnar-server` row names the feature, so the
673/// packed appliance carries it; the two-appliance drill exercises it.
674#[cfg(feature = "replication")]
675pub mod mirror;
676/// **I11's passive heartbeat**: the standby half of failover, which notices a
677/// primary that died without abdicating and takes over by itself. Off unless a
678/// `--watch-primary` says otherwise — `control_plane.rs` states the rule it
679/// obeys, that naming a new primary is a decision and never a default.
680#[cfg(feature = "replication")]
681pub mod standby_watch;
682/// **The estate repairs itself** (5.4): the boot check (auto-fix OFF by default)
683/// and the pull channel to monetize, both through `gunnar-repair` — see the module.
684#[cfg(feature = "replication")]
685pub mod repair;
686
687/// S10: the main mails a sold estate's resend sign-in link itself — see the module.
688#[cfg(feature = "replication")]
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}