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