Skip to main content

gunnar_core/
observe.rs

1//! **What an operator can see**: the `tracing` targets, the request id, and
2//! the server's counters.
3//!
4//! # The measurement this module answers
5//!
6//! 58 `tracing::` call sites in 27182 lines of code, no `span!`, no
7//! `#[instrument]`, no request id, no timing and no counters. Closing the gRPC
8//! audit hole moved the worst of that distribution and none of the total.
9//! At forge scale an operator has minutes to answer *which connection, which
10//! principal, which repository, how long did it take, how many failed, is the
11//! queue growing*. None of it was answerable from gunnar's output at all.
12//!
13//! # One vocabulary, not one per crate
14//!
15//! [`TARGET_AUDIT`] already existed, in `gunnar_grpc::auth`. Everything added
16//! since is a **sibling of it**, defined here once, so `RUST_LOG` selects a
17//! *subsystem* rather than a crate name that happens to hold the call site:
18//!
19//! | target | what is on it |
20//! |---|---|
21//! | [`TARGET_AUDIT`] | control-plane mutations: who called what, and the decision |
22//! | [`TARGET_SSH`] | the connection: accept, publickey, exec dispatch, every refusal |
23//! | [`TARGET_GIT`] | transfers: upload-pack, receive-pack, objects, packs, bytes |
24//! | [`TARGET_POLICY`] | the push gate: which gate refused which reference |
25//! | [`TARGET_STORE`] | ref transactions, compare-and-swap contention, repack |
26//! | [`TARGET_METRICS`] | the counters: the heartbeat, and the scrape endpoint |
27//! | [`TARGET_LFS`] | large-file transfers: the session, its verbs, its refusals |
28//! | [`TARGET_RUNNER`] | the build runner: what it picked up, what it built, its refusals |
29//! | [`TARGET_ARCHIVE`] | archiving a repository off the box and back in |
30//! | [`TARGET_REPLICATION`] | replication to a standby: shipped, lagging, refused |
31//! | [`TARGET_SPACE`] | disk headroom: what a write may take, and the refusals when it is short |
32//! | [`TARGET_REPAIR`] | the repair plane: the boot check, the pull channel, the recharges they run |
33//! | [`TARGET_LIVE`] | the live update: a version staged, the re-exec, the trial and its roll back |
34//! | [`TARGET_ACTIVITY`] | a principal's last sign-in and last operation: a stamp that could not be kept |
35//!
36//! ```text
37//!   RUST_LOG=warn,gunnar::audit=info,gunnar::git=info   # the two an operator watches
38//!   RUST_LOG=gunnar::ssh=debug                          # one connection, in detail
39//! ```
40//!
41//! `gunnar-grpc` cannot link this crate (it is expressed in `gunnar-proto`
42//! terms and deliberately has no `gunnar-core` edge), so it keeps its own
43//! `AUDIT_TARGET` **string**. That is the one place a constant is stated twice,
44//! and it is not left to a comment: `gunnar-cli` links both crates and
45//! `the_audit_target_is_the_same_string_in_both_crates` asserts they are equal.
46//!
47//! # Levels
48//!
49//! `info` is the production default and must stay legible: one line per
50//! connection authenticated, one per transfer served with its applied outputs,
51//! one per reference moved, and every refusal at `warn`. `debug` is the
52//! diagnostic tier: per-frame detail, environment requests, CAS retries. A
53//! server that has to run at `trace` to be legible has failed.
54//!
55//! # Cost
56//!
57//! [`RequestId`] is a `u64` that formats itself; it never allocates and never
58//! touches a lock. [`ServerMetrics`] is a flat block of [`AtomicU64`] read and
59//! written with [`Ordering::Relaxed`]. **No mutex is taken to record a
60//! counter**, because a signal that costs a lock is paid for by the thing it is
61//! measuring. `tracing`'s macros evaluate their field expressions only inside
62//! the `enabled!` branch, so a line that will not be emitted allocates nothing
63//! even where the field is a `String`.
64
65use std::sync::atomic::{AtomicU64, Ordering};
66use std::sync::OnceLock;
67
68// ───────────────────────────────────────────────────────────────────────────
69// Targets
70// ───────────────────────────────────────────────────────────────────────────
71
72/// Control-plane mutations: who called what, over which credential, and what
73/// was decided. Written by `gunnar-grpc`, which states the same literal
74/// because it cannot link this crate. See the module docs.
75pub const TARGET_AUDIT: &str = "gunnar::audit";
76
77/// The SSH connection: accepted, authenticated, dispatched, refused.
78pub const TARGET_SSH: &str = "gunnar::ssh";
79
80/// Git transfers: `upload-pack`, `receive-pack`, and their applied outputs.
81pub const TARGET_GIT: &str = "gunnar::git";
82
83/// The push gate: which gate refused which reference, and why.
84pub const TARGET_POLICY: &str = "gunnar::policy";
85
86/// Storage: ref transactions, compare-and-swap contention, repack.
87pub const TARGET_STORE: &str = "gunnar::store";
88
89/// The counter heartbeat, and the scrape endpoint.
90pub const TARGET_METRICS: &str = "gunnar::metrics";
91
92/// Large-file transfers: the LFS session, its verbs, and every refusal.
93///
94/// Added 2026-08-05, and it did not replace nothing. `gunnar-lfs` was emitting
95/// on **`"gunnar.lfs"`** — a dot, not a `::` — at five call sites, and
96/// the old znippy engine crate, `gunnar-cli`'s znippy-engine arm and `gunnar-znippy` were
97/// emitting on `"gunnar.store"` at twelve more. `RUST_LOG=gunnar::lfs=debug`
98/// selected none of them; neither did `gunnar::store=info`, which this
99/// module's own table tells an operator to use. Seventeen lines that could be
100/// written and never read.
101///
102/// That is exactly the failure [`TARGETS`] was written to prevent, and
103/// [`TARGETS`] could not see it: it checked the constants in its own list and
104/// no call site ever passes through it. The guard that can is
105/// `every_tracing_target_in_the_shipped_source_is_one_of_ours` in `gunnar-cli`'s
106/// `tests/observability.rs`, which reads the source of every shipped crate.
107pub const TARGET_LFS: &str = "gunnar::lfs";
108
109/// The build runner: what it picked up, what it built, and every refusal.
110///
111/// Added with the runner (roadmap phase 3). A separate target from
112/// [`TARGET_GIT`] because the two answer different questions — "did the push
113/// land" and "did the build run" — and an operator watching one rarely wants a
114/// wall of the other.
115pub const TARGET_RUNNER: &str = "gunnar::runner";
116
117/// Archiving a repository out of the box and back in (`Repos.ArchiveOut`).
118///
119/// `repo.archive_out` when a repository is written to its archive,
120/// `repo.archive_out_failed` when that write does not land.
121///
122/// Emitted by `gunnar-grpc`'s `service::repos` and undeclared until the two
123/// halves of this repository were merged (2026-08-31) — so
124/// `gunnar_core::observe::log_filter`, the filter a deployment installs,
125/// selected neither of its two call sites. The same defect [`TARGET_LFS`]
126/// documents, found by the guard that exists for it.
127///
128/// Undeclared is not harmless here: an archive-out that FAILS is the one event
129/// an operator has to see, so the failure of the very thing that protects the
130/// objects was the least visible line gunnar emitted.
131pub const TARGET_ARCHIVE: &str = "gunnar::archive";
132
133/// Replication to a standby: what was shipped, what lagged, what
134/// refused.
135///
136/// `replication.never_synced`, `replication.stale`, `replication.recovered`.
137///
138/// Emitted by `gunnar-server`'s `replication_view` and undeclared until
139/// 2026-08-31, alongside [`TARGET_ARCHIVE`] and for the same reason. It is the
140/// worst of the three to have had dark: a standby that receives nothing looks
141/// exactly like a standby with nothing to receive, and the lines that tell them
142/// apart were written into a filter that did not select them — so a mirror
143/// could quietly stop being a mirror.
144pub const TARGET_REPLICATION: &str = "gunnar::replication";
145/// The process's own limits: the descriptor budget PID 1 raised, and the WARN
146/// row when it could not raise it far enough.
147///
148/// Added 2026-08-30 for a defect of exactly the shape [`TARGET_LFS`]
149/// documents: `crate::limits` shipped emitting on `"gunnar::limits"`
150/// at two call sites, and no documented filter selected either of them. One of
151/// the two is the `!WARN limits.nofile.low` row the dashboard guide tells an
152/// operator to watch for.
153pub const TARGET_LIMITS: &str = "gunnar::limits";
154
155/// The object index: a reader's own scan of a pending pack, and the memory
156/// watchdog's pause and spill.
157///
158/// Emitted by the znippy git plugin, which cannot link this crate and states
159/// the literal, and rendered by the dashboard as `index paused: …` /
160/// `index.spilled`. Undeclared until 2026-08-30, so
161/// `gunnar_core::observe::log_filter` — the filter a deployment installs —
162/// selected none of it, which is exactly the memory-pressure story an operator
163/// needs when a box collapses under sustained create load.
164pub const TARGET_INDEX: &str = "gunnar::index";
165
166/// Plan enforcement (the `metered` build): a fact accepted or refused at
167/// `Entitlement.Set`, a push refused for a suspended namespace, a cap applied.
168/// Emitted by `gunnar-server::entitlement`; absent from a community binary,
169/// declared here regardless so the filter and the probes name it.
170pub const TARGET_ENTITLEMENT: &str = "gunnar::entitlement";
171/// The twin following a primary's transaction log (`gunnar-server::twin`).
172pub const TARGET_TWIN: &str = "gunnar::twin";
173/// Disk space: the headroom a write is admitted against, the space a push may
174/// take, and the refusals when the volume is short (`gunnar-ssh::space`,
175/// `gunnar-ssh::headroom`). Emitted since 5.x but undeclared until 2026-10-10
176/// (stinky row 22), so the installed filter selected none of it.
177pub const TARGET_SPACE: &str = "gunnar::space";
178
179/// The repair plane: the boot check's findings, the pull channel's word, and
180/// the recharges they run (`gunnar-server::serve`, 5.4 resilience).
181pub const TARGET_REPAIR: &str = "gunnar::repair";
182
183
184/// The live update: a version staged, the graceful stop and re-exec, the trial
185/// and a roll back.
186///
187/// Emitted by `gunnar-server::live_update` since the live update landed
188/// (2026-10-12) and undeclared until 2026-10-14 — so the filter a deployment
189/// installs selected none of its call sites. The defect [`TARGET_LFS`]
190/// documents, found by the guard that exists for it.
191pub const TARGET_LIVE: &str = "gunnar::live";
192
193/// A principal's activity stamps: last sign-in and last operation, kept in the
194/// control redb and on the twin (`gunnar-core::activity`). A stamp that could
195/// not be read or written is a warning here.
196///
197/// Emitted since the admin's Principals list (89818d10, merged in cd07bc2f,
198/// 2026-10-21) and undeclared until 2026-10-25 (ODEN-CI round 2), so the filter
199/// a deployment installs selected none of it.
200pub const TARGET_ACTIVITY: &str = "gunnar::activity";
201
202/// Every target gunnar emits on, so a filter, a document or a test can
203/// enumerate them rather than guess.
204///
205/// A test asserts this list is exactly the constants above and that each is a
206/// `gunnar::` sibling. A target invented at one call site and spelled slightly
207/// differently is invisible to every filter written for the others, which is
208/// the failure this constant exists to prevent.
209pub const TARGETS: &[&str] = &[
210    TARGET_AUDIT,
211    TARGET_SSH,
212    TARGET_GIT,
213    TARGET_POLICY,
214    TARGET_STORE,
215    TARGET_METRICS,
216    TARGET_LFS,
217    TARGET_RUNNER,
218    TARGET_ARCHIVE,
219    TARGET_REPLICATION,
220    TARGET_LIMITS,
221    TARGET_INDEX,
222    TARGET_ENTITLEMENT,
223    TARGET_TWIN,
224    TARGET_SPACE,
225    TARGET_REPAIR,
226    TARGET_LIVE,
227    TARGET_ACTIVITY,
228];
229
230/// A `RUST_LOG` directive list: `base` for everything gunnar did not write, and
231/// `gunnar` for every one of [`TARGETS`].
232///
233/// **Built FROM [`TARGETS`], never written out beside it.** The table in this
234/// module's docs is prose and a reader can copy it wrong; a filter that a
235/// deployment installs must not be able to fall behind the list (one implementation). The
236/// 2026-08-05 `"gunnar.lfs"` finding is what a hand-written filter costs:
237/// seventeen call sites no documented filter selected, and nothing failed.
238///
239/// The two levels are separate arguments because they answer different
240/// questions. `base` is how much `russh`, `h2` and `gix` an operator wants to
241/// wade through; `gunnar` is how much of gunnar's own story they want. A single
242/// level cannot say "everything gunnar does, and nothing else at that volume".
243pub fn log_filter(base: &str, gunnar: &str) -> String {
244    let mut spec = String::with_capacity(base.len() + TARGETS.len() * 24);
245    spec.push_str(base);
246    for target in TARGETS {
247        spec.push(',');
248        spec.push_str(target);
249        spec.push('=');
250        spec.push_str(gunnar);
251    }
252    spec
253}
254
255/// Everything outside gunnar, in the filter a service is installed with.
256///
257/// `info` and not `warn`: the lines that say a listener bound, a host key was
258/// loaded and a runtime started come from gunnar at `info` too, and an operator
259/// reading a journal from the top wants the boot to be legible.
260pub const SERVICE_LOG_BASE: &str = "info";
261
262/// gunnar's own targets, in the filter a service is installed with.
263///
264/// `debug` rather than `info`, deliberately. A service is watched when
265/// something is being commissioned or has gone wrong, and the rungs above
266/// `info` in gunnar are per-frame protocol detail on gunnar's OWN targets only
267/// — `base` stays at `info`, so this does not drag `russh`, `h2` and `gix`
268/// debug into the journal with it. Turn it down with `--log-filter`, or move it
269/// live with `SIGUSR1` (`gunnar_cli::logging`).
270pub const SERVICE_LOG_GUNNAR: &str = "debug";
271
272/// **The `RUST_LOG` a `gunnar service install` bakes into the unit.**
273///
274/// One function, so the unit, the documentation and the test that proves the
275/// filter selects gunnar's lines all read the same string.
276pub fn service_log_filter() -> String {
277    log_filter(SERVICE_LOG_BASE, SERVICE_LOG_GUNNAR)
278}
279
280// ───────────────────────────────────────────────────────────────────────────
281// The request id
282// ───────────────────────────────────────────────────────────────────────────
283
284/// A per-connection (or per-request) identifier, carried as a span field so
285/// every line emitted underneath is attributable without repeating it.
286///
287/// # Why not a UUID
288///
289/// A UUID costs a dependency, 16 bytes and a formatting allocation to say
290/// something a 64-bit integer already says. This is a **process seed** in the
291/// high 32 bits and a monotonic counter in the low 32, rendered as 16 hex
292/// digits. Two ids from the same process never collide; two ids from different
293/// runs of the same server collide only if both start within the same
294/// microsecond *and* reach the same counter value, which is not a property a
295/// log correlation needs.
296///
297/// It is `Copy`, it is one `fetch_add(Relaxed)` to mint, and its `Display`
298/// writes into the formatter without allocating.
299#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
300pub struct RequestId(u64);
301
302static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
303
304/// The high half: distinct per process, so two servers' logs merged into one
305/// stream do not appear to share connections.
306fn process_seed() -> u64 {
307    static SEED: OnceLock<u64> = OnceLock::new();
308    *SEED.get_or_init(|| {
309        let nanos = std::time::SystemTime::now()
310            .duration_since(std::time::UNIX_EPOCH)
311            .map(|d| d.as_nanos() as u64)
312            .unwrap_or(0);
313        // Mix the pid in so two processes started in the same nanosecond bucket
314        // still differ. `id()` is a `u32` and free.
315        (nanos ^ ((std::process::id() as u64) << 40)) & 0xffff_ffff
316    })
317}
318
319impl RequestId {
320    /// Mint the next id. One relaxed atomic increment; never blocks.
321    pub fn next() -> RequestId {
322        let n = NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
323        RequestId((process_seed() << 32) | (n & 0xffff_ffff))
324    }
325
326    /// The raw value, for a caller that wants to store it as a number.
327    pub fn get(&self) -> u64 {
328        self.0
329    }
330}
331
332impl std::fmt::Display for RequestId {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        write!(f, "{:016x}", self.0)
335    }
336}
337
338// ───────────────────────────────────────────────────────────────────────────
339// The counters
340// ───────────────────────────────────────────────────────────────────────────
341
342/// Everything an operator watches, as one flat block of atomics.
343///
344/// Held behind an `Arc` and shared by the SSH listener and the git transport,
345/// which is what makes "connections refused" and "pushes rejected" numbers
346/// about the **same server** rather than two crates' private tallies.
347///
348/// Every method is one `fetch_add(Relaxed)`. There is no lock anywhere in this
349/// type, and [`ServerMetrics::snapshot`] reads the fields independently rather
350/// than under a barrier: these are a signal, and a signal read atomically
351/// across eighteen fields would cost more than it tells anyone.
352#[derive(Debug, Default)]
353pub struct ServerMetrics {
354    connections_opened: AtomicU64,
355    connections_accepted: AtomicU64,
356    connections_anonymous: AtomicU64,
357    connections_refused: AtomicU64,
358    auth_faults: AtomicU64,
359    exec_refused: AtomicU64,
360    transfers_started: AtomicU64,
361    transfers_in_flight: AtomicU64,
362    transfers_failed: AtomicU64,
363    packs_served: AtomicU64,
364    objects_sent: AtomicU64,
365    bytes_out: AtomicU64,
366    bytes_in: AtomicU64,
367    pushes_accepted: AtomicU64,
368    pushes_rejected: AtomicU64,
369    refs_updated: AtomicU64,
370    refs_deleted: AtomicU64,
371    refs_rejected: AtomicU64,
372    gate_refusals: AtomicU64,
373    usage_reconcile_missed: AtomicU64,
374}
375
376/// A reading of [`ServerMetrics`], taken at one moment.
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
378pub struct MetricsSnapshot {
379    /// TCP connections russh handed to gunnar.
380    pub connections_opened: u64,
381    /// Connections whose offered key named a principal.
382    pub connections_accepted: u64,
383    /// Connections admitted with **no key at all**, served as the
384    /// anonymous principal, which can only ever read a public repository.
385    ///
386    /// Counted separately from [`MetricsSnapshot::connections_accepted`] rather
387    /// than folded into it: "how much of my traffic is strangers" is the first
388    /// question an operator asks after making anything public, and a total that
389    /// mixed the two could not answer it.
390    pub connections_anonymous: u64,
391    /// Connections whose offered key named nobody. **Not** the same as
392    /// [`MetricsSnapshot::auth_faults`].
393    pub connections_refused: u64,
394    /// Connections refused because the identity table could not be *read*. A
395    /// storage fault looks exactly like an empty table from the client's side,
396    /// and an operator must be able to tell them apart.
397    pub auth_faults: u64,
398    /// Exec requests refused or denied after authentication: a non-git
399    /// command, an unknown repository, a missing grant.
400    pub exec_refused: u64,
401    /// Transfers admitted and begun.
402    pub transfers_started: u64,
403    /// Transfers running right now. A **gauge**, not a total.
404    pub transfers_in_flight: u64,
405    /// Transfers that ended with a protocol or storage error.
406    pub transfers_failed: u64,
407    /// `upload-pack` sessions that sent a packfile.
408    pub packs_served: u64,
409    /// Objects written into those packs.
410    pub objects_sent: u64,
411    /// Bytes gunnar wrote to git clients, counted at the wire.
412    pub bytes_out: u64,
413    /// Bytes gunnar read from git clients, counted at the wire.
414    pub bytes_in: u64,
415    /// Pushes in which every reference landed.
416    pub pushes_accepted: u64,
417    /// Pushes in which at least one reference was refused.
418    pub pushes_rejected: u64,
419    /// References moved.
420    pub refs_updated: u64,
421    /// References deleted.
422    pub refs_deleted: u64,
423    /// Reference updates refused, for any reason.
424    pub refs_rejected: u64,
425    /// Reference updates refused **by a named policy gate**. A subset of
426    /// [`MetricsSnapshot::refs_rejected`], which also counts connectivity
427    /// failures and the collateral refusals of an `--atomic` push.
428    pub gate_refusals: u64,
429    /// Ticks of the usage ledger's reconcile pass that could not run (the
430    /// catalog could not be read, so nothing was re-measured). Counted, warned
431    /// and published rather than dropped (A28 M17): a pass that silently skips
432    /// is a ledger that silently goes stale.
433    pub usage_reconcile_missed: u64,
434}
435
436// **Every field above is written by real code.** A counter nothing increments
437// reads as "this never happens" and is worse than no counter at all. `repacks`
438// was in this struct for exactly one revision before it came out again, because
439// `gunnar gc` runs in a separate process that has no `ServerMetrics` to write
440// to. `a_real_clone_and_push_move_the_counters` in `gunnar-cli` pins the ones a
441// transfer touches; the rest have a red-first proof in their own crate.
442
443/// What a number **means to a reader**: a total that only climbs, or a level
444/// that moves both ways.
445///
446/// One field in this type is a gauge — [`MetricsSnapshot::transfers_in_flight`]
447/// — and it is the whole reason the distinction is carried rather than assumed.
448/// A scraper told everything is a counter charts a busy server's concurrency as
449/// a *rate of transfers per second*, which is a different number with a
450/// plausible shape, and the operator reading it has no way to know.
451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
452pub enum MetricKind {
453    /// Monotonic since start-up. A reader takes its rate.
454    Counter,
455    /// A level, read as it stands.
456    Gauge,
457}
458
459impl MetricKind {
460    /// The word the exposition format's `# TYPE` line uses.
461    pub fn as_str(self) -> &'static str {
462        match self {
463            MetricKind::Counter => "counter",
464            MetricKind::Gauge => "gauge",
465        }
466    }
467}
468
469/// The kind word in the [`counters!`] table, as a value.
470///
471/// Two arms and no fallback, deliberately: a counter declared `guage` — or
472/// declared with no kind at all — **fails to compile**. The alternative is a
473/// default, and a default here would silently publish the next gauge as a
474/// counter, which is the one error in this file that produces a plausible
475/// wrong number instead of an obvious one.
476macro_rules! metric_kind {
477    (counter) => {
478        MetricKind::Counter
479    };
480    (gauge) => {
481        MetricKind::Gauge
482    };
483}
484
485macro_rules! counters {
486    ($($kind:ident $field:ident => $add:ident),* $(,)?) => {
487        impl ServerMetrics {
488            $(
489                #[doc = concat!("Add `n` to `", stringify!($field), "`.")]
490                pub fn $add(&self, n: u64) {
491                    self.$field.fetch_add(n, Ordering::Relaxed);
492                }
493            )*
494
495            /// Read every counter.
496            pub fn snapshot(&self) -> MetricsSnapshot {
497                MetricsSnapshot {
498                    $($field: self.$field.load(Ordering::Relaxed),)*
499                }
500            }
501        }
502
503        impl MetricsSnapshot {
504            /// Every counter as `(name, kind, value)`, in declaration order.
505            ///
506            /// Generated by the same macro arm that declares the fields, so a
507            /// counter added to [`ServerMetrics`] appears here — and therefore
508            /// on the scrape endpoint — **without anyone remembering to add
509            /// it**. The alternative was a second hand-written list of nineteen
510            /// names, and the counter left out of it would be the one nobody
511            /// could see.
512            ///
513            /// That is not a hypothetical. The heartbeat *was* such a list, and
514            /// it carried eighteen of the nineteen: `connections_anonymous` —
515            /// written by both transports, and the answer to *how much of my
516            /// traffic is strangers* — never appeared in a single line gunnar
517            /// ever printed. See [`MetricsSnapshot::emit_heartbeat`].
518            pub fn fields(&self) -> Vec<(&'static str, MetricKind, u64)> {
519                vec![$((stringify!($field), metric_kind!($kind), self.$field),)*]
520            }
521
522            /// The heartbeat line: one `info` on [`TARGET_METRICS`] naming every
523            /// counter.
524            ///
525            /// Here, and generated, for the reason above: this used to be a
526            /// hand-written `tracing::info!` in `gunnar-cli` listing eighteen of
527            /// the nineteen fields. Expanding from the declaration is the only
528            /// version of it that cannot fall behind (one implementation), and it puts the
529            /// log line and [`MetricsSnapshot::fields`] — the log and the wire —
530            /// on one source of truth rather than two that agree today.
531            ///
532            /// Structured fields and not a rendered string, unchanged from what
533            /// it replaced: `bytes_out=` has to stay greppable in the server's
534            /// stderr, and a JSON subscriber has to still see nineteen typed
535            /// numbers rather than one blob.
536            pub fn emit_heartbeat(&self) {
537                tracing::info!(
538                    target: TARGET_METRICS,
539                    event = "metrics",
540                    $($field = self.$field,)*
541                    "gunnar"
542                );
543            }
544        }
545    };
546}
547
548counters! {
549    counter connections_opened => add_connections_opened,
550    counter connections_accepted => add_connections_accepted,
551    counter connections_anonymous => add_connections_anonymous,
552    counter connections_refused => add_connections_refused,
553    counter auth_faults => add_auth_faults,
554    counter exec_refused => add_exec_refused,
555    counter transfers_started => add_transfers_started,
556    gauge   transfers_in_flight => add_transfers_in_flight,
557    counter transfers_failed => add_transfers_failed,
558    counter packs_served => add_packs_served,
559    counter objects_sent => add_objects_sent,
560    counter bytes_out => add_bytes_out,
561    counter bytes_in => add_bytes_in,
562    counter pushes_accepted => add_pushes_accepted,
563    counter pushes_rejected => add_pushes_rejected,
564    counter refs_updated => add_refs_updated,
565    counter refs_deleted => add_refs_deleted,
566    counter refs_rejected => add_refs_rejected,
567    counter gate_refusals => add_gate_refusals,
568    counter usage_reconcile_missed => add_usage_reconcile_missed,
569}
570
571impl ServerMetrics {
572    /// A fresh set of counters, all zero.
573    pub fn new() -> ServerMetrics {
574        ServerMetrics::default()
575    }
576
577    /// A transfer began. Returns a guard whose [`Drop`] decrements
578    /// `transfers_in_flight`, so the gauge cannot be leaked by an error path
579    /// that forgot to close it, the failure mode that turns a working gauge
580    /// into a server that appears permanently busy.
581    pub fn transfer_started(self: &std::sync::Arc<Self>) -> InFlightGuard {
582        self.transfers_started.fetch_add(1, Ordering::Relaxed);
583        self.transfers_in_flight.fetch_add(1, Ordering::Relaxed);
584        InFlightGuard {
585            metrics: std::sync::Arc::clone(self),
586        }
587    }
588}
589
590/// A held `transfers_in_flight` slot. Released by [`Drop`], never by a call.
591#[derive(Debug)]
592pub struct InFlightGuard {
593    metrics: std::sync::Arc<ServerMetrics>,
594}
595
596impl Drop for InFlightGuard {
597    fn drop(&mut self) {
598        self.metrics
599            .transfers_in_flight
600            .fetch_sub(1, Ordering::Relaxed);
601    }
602}
603
604impl MetricsSnapshot {
605    /// Has anything at all been served? Used by the heartbeat to stay quiet on
606    /// an idle server without going quiet on a busy one.
607    pub fn is_zero(&self) -> bool {
608        *self == MetricsSnapshot::default()
609    }
610}
611
612// ───────────────────────────────────────────────────────────────────────────
613// The scrape body
614// ───────────────────────────────────────────────────────────────────────────
615
616/// What every exposed name starts with, so one `gunnar_` selector reaches all
617/// of them and nothing gunnar publishes can collide with a neighbour's series.
618pub const SCRAPE_PREFIX: &str = "gunnar_";
619
620/// The `Content-Type` a Prometheus-compatible scraper expects. Stated once
621/// here, beside the renderer that decides the format, rather than in the
622/// listener that merely writes the header.
623pub const SCRAPE_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
624
625impl MetricsSnapshot {
626    /// This reading in the Prometheus text exposition format.
627    ///
628    /// ```text
629    /// # TYPE gunnar_bytes_out counter
630    /// gunnar_bytes_out 4096
631    /// # TYPE gunnar_transfers_in_flight gauge
632    /// gunnar_transfers_in_flight 1
633    /// ```
634    ///
635    /// # Why the names are not suffixed `_total`
636    ///
637    /// Prometheus convention would call the first one `gunnar_bytes_out_total`.
638    /// It is a convention and not a requirement — `# TYPE` is what actually
639    /// carries the semantics, and this renderer emits it for every series — and
640    /// paying it would mean **one counter with two names**: `bytes_out=` in the
641    /// log and `gunnar_bytes_out_total` on the wire. The module's opening
642    /// section argues for one vocabulary across the whole server, and an
643    /// operator who greps the heartbeat and then greps the endpoint for the
644    /// same string is exactly who that section is for. The prefix is worth its
645    /// cost because it prevents collision; the suffix buys a lint.
646    ///
647    /// # Why there is no `# HELP`
648    ///
649    /// Every one of these fields is documented on [`MetricsSnapshot`], and a
650    /// `HELP` line would be a second copy of that prose, in a macro table,
651    /// diverging from the first (one implementation). `# TYPE` is the part a scraper reads.
652    ///
653    /// # Why this is here and not in the listener
654    ///
655    /// It is pure — a `&self` to a `String`, no clock, no I/O, no socket — so
656    /// the format can be asserted without binding a port, and the listener that
657    /// serves it stays a listener. It also means `gunnar-core` gained no
658    /// dependency for the endpoint: the HTTP is somebody else's problem.
659    pub fn render_prometheus(&self) -> String {
660        let mut out = String::with_capacity(self.fields().len() * 64);
661        for (name, kind, value) in self.fields() {
662            out.push_str("# TYPE ");
663            out.push_str(SCRAPE_PREFIX);
664            out.push_str(name);
665            out.push(' ');
666            out.push_str(kind.as_str());
667            out.push('\n');
668            out.push_str(SCRAPE_PREFIX);
669            out.push_str(name);
670            out.push(' ');
671            {
672                use std::fmt::Write as _;
673                // Writing into the buffer rather than `format!`-ing nineteen
674                // little `String`s and dropping each one. `write!` to a
675                // `String` is infallible; the `Result` is discarded for that
676                // reason and not because a failure would be tolerable.
677                let _ = write!(out, "{value}");
678            }
679            out.push('\n');
680        }
681        out
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688    use std::sync::Arc;
689
690    #[test]
691    fn every_target_is_a_gunnar_sibling_and_the_list_is_complete() {
692        // The scheme, asserted rather than described: one prefix, one `::`
693        // separator, no crate names. A target invented at a call site and
694        // spelled `gunnar_ssh` would be invisible to every filter written for
695        // the others.
696        for target in TARGETS {
697            assert!(
698                target.starts_with("gunnar::"),
699                "{target} is not a sibling of {TARGET_AUDIT}"
700            );
701            assert_eq!(
702                target.matches("::").count(),
703                1,
704                "{target} is not one level deep"
705            );
706        }
707        let mut sorted = TARGETS.to_vec();
708        sorted.sort_unstable();
709        sorted.dedup();
710        assert_eq!(sorted.len(), TARGETS.len(), "TARGETS holds a duplicate");
711        assert!(TARGETS.contains(&TARGET_AUDIT));
712    }
713
714    /// The filter must name **every** target, and it must be derived rather
715    /// than restated — that is the whole reason it is a function.
716    ///
717    /// The identity-value guard is the second half: a filter of `"trace"` would
718    /// select every line in this process and satisfy any test that only asked
719    /// "does gunnar's output appear". So this asserts the filter is a LIST that
720    /// names each target with the gunnar level, and that the base level is
721    /// still in it and is NOT that level. `tests/observability.rs` in
722    /// `gunnar-cli` then asserts the string actually decides events that way.
723    #[test]
724    fn the_service_filter_is_derived_from_the_target_list() {
725        let filter = service_log_filter();
726        for target in TARGETS {
727            let directive = format!("{target}={SERVICE_LOG_GUNNAR}");
728            assert!(
729                filter.contains(&directive),
730                "{directive} is missing from {filter}: a target added to TARGETS did not \
731                 reach the filter a service is installed with"
732            );
733        }
734        assert!(
735            filter.starts_with(SERVICE_LOG_BASE),
736            "the filter must open with the base level: {filter}"
737        );
738        assert_ne!(
739            SERVICE_LOG_BASE, SERVICE_LOG_GUNNAR,
740            "with one level for both, this filter says nothing a bare level does not, and \
741             the test above cannot tell a derived filter from a blanket one"
742        );
743        assert_eq!(
744            filter.matches(',').count(),
745            TARGETS.len(),
746            "the filter holds a directive that is not one of ours: {filter}"
747        );
748    }
749
750    #[test]
751    fn request_ids_do_not_repeat() {
752        let a = RequestId::next();
753        let b = RequestId::next();
754        assert_ne!(a, b, "two ids from the same process collided");
755        assert_ne!(
756            a.to_string(),
757            b.to_string(),
758            "two ids RENDERED the same, which is what a log correlation sees"
759        );
760        assert_eq!(a.to_string().len(), 16, "the id must be fixed-width");
761        assert!(
762            a.to_string().chars().all(|c| c.is_ascii_hexdigit()),
763            "the id must be greppable"
764        );
765        // …and the seed half is stable within a process, so a human can spot
766        // two connections belonging to the same server at a glance.
767        assert_eq!(a.get() >> 32, b.get() >> 32);
768    }
769
770    #[test]
771    fn a_counter_moves_and_the_gauge_comes_back_down() {
772        let metrics = Arc::new(ServerMetrics::new());
773        let before = metrics.snapshot();
774        assert!(before.is_zero(), "a fresh set of counters must read zero");
775
776        metrics.add_bytes_out(4096);
777        metrics.add_objects_sent(7);
778        let guard = metrics.transfer_started();
779        let during = metrics.snapshot();
780        assert_eq!(during.bytes_out - before.bytes_out, 4096);
781        assert_eq!(during.objects_sent - before.objects_sent, 7);
782        assert_eq!(during.transfers_started, 1);
783        assert_eq!(during.transfers_in_flight, 1, "the gauge must be up");
784
785        drop(guard);
786        let after = metrics.snapshot();
787        assert_eq!(
788            after.transfers_in_flight, 0,
789            "the in-flight gauge leaked; a server that never comes back to zero \
790             reads as permanently saturated"
791        );
792        assert_eq!(
793            after.transfers_started, 1,
794            "the total is a total, not a gauge"
795        );
796    }
797
798    /// The guard that would have caught `connections_anonymous`.
799    ///
800    /// It names its own subject: **every field of [`MetricsSnapshot`] must be
801    /// reachable through [`MetricsSnapshot::fields`]**, counted against the
802    /// struct itself and not against a list this test also keeps. A second list
803    /// here would be the same defect one layer up — the one the endpoint would
804    /// then be missing a counter from, silently.
805    ///
806    /// It is counted from `Debug`, which the compiler derives from the struct
807    /// definition, so adding a field to `MetricsSnapshot` and forgetting the
808    /// `counters!` table makes this fail without anyone touching this file.
809    #[test]
810    fn every_field_of_the_snapshot_is_published() {
811        let snapshot = MetricsSnapshot::default();
812        let published: Vec<&str> = snapshot.fields().iter().map(|(name, _, _)| *name).collect();
813
814        // `MetricsSnapshot { connections_opened: 0, connections_accepted: 0, … }`
815        let debug = format!("{snapshot:?}");
816        let declared: Vec<String> = debug
817            .trim_start_matches("MetricsSnapshot {")
818            .trim_end_matches('}')
819            .split(',')
820            .filter_map(|pair| pair.split_once(':'))
821            .map(|(name, _)| name.trim().to_owned())
822            .collect();
823        assert_eq!(
824            declared.len(),
825            20,
826            "the Debug parse found {} fields, not the 20 this struct has, so this guard is \
827             reading nothing and would pass against an empty `fields()`: {debug}",
828            declared.len()
829        );
830
831        for field in &declared {
832            assert!(
833                published.contains(&field.as_str()),
834                "`{field}` is a counter of this server that NOTHING publishes: not the \
835                 heartbeat, not the scrape endpoint. That is exactly how \
836                 `connections_anonymous` stayed invisible."
837            );
838        }
839        assert_eq!(
840            published.len(),
841            declared.len(),
842            "fields() publishes {} names for {} struct fields",
843            published.len(),
844            declared.len()
845        );
846    }
847
848    /// The scrape body, asserted as **text a scraper parses**, not as a call
849    /// that returned.
850    #[test]
851    fn the_scrape_body_names_every_counter_with_its_kind_and_value() {
852        let metrics = Arc::new(ServerMetrics::new());
853        metrics.add_bytes_out(4096);
854        metrics.add_connections_anonymous(3);
855        let _guard = metrics.transfer_started();
856        let body = metrics.snapshot().render_prometheus();
857
858        // The value, not merely the name: a renderer that printed every series
859        // as 0 would satisfy a name-only assertion, and 0 is what a broken
860        // counter also looks like.
861        assert!(
862            body.contains("\ngunnar_bytes_out 4096\n"),
863            "the applied value is not in the body:\n{body}"
864        );
865        assert!(
866            body.contains("\ngunnar_connections_anonymous 3\n"),
867            "the counter no line ever carried is still not carried:\n{body}"
868        );
869        // Kind, and the one that matters: a scraper told the gauge is a counter
870        // charts concurrency as a rate.
871        assert!(
872            body.contains("# TYPE gunnar_transfers_in_flight gauge\n"),
873            "the in-flight gauge is not typed as a gauge:\n{body}"
874        );
875        assert!(
876            body.contains("# TYPE gunnar_bytes_out counter\n"),
877            "a total is not typed as a counter:\n{body}"
878        );
879        // Every series is prefixed and every series is typed, checked over the
880        // whole body rather than over the four names above.
881        let mut samples = 0;
882        for line in body.lines() {
883            if let Some(spec) = line.strip_prefix("# TYPE ") {
884                let (name, kind) = spec.split_once(' ').expect("a TYPE line is `name kind`");
885                assert!(name.starts_with(SCRAPE_PREFIX), "{name} is unprefixed");
886                assert!(kind == "counter" || kind == "gauge", "{kind} is not a kind");
887                continue;
888            }
889            assert!(line.starts_with(SCRAPE_PREFIX), "stray line: {line:?}");
890            let (name, value) = line.split_once(' ').expect("a sample is `name value`");
891            value
892                .parse::<u64>()
893                .unwrap_or_else(|_| panic!("{name} rendered {value:?}, which is not a number"));
894            assert!(
895                body.contains(&format!("# TYPE {name} ")),
896                "{name} is a sample with no TYPE line"
897            );
898            samples += 1;
899        }
900        assert_eq!(
901            samples,
902            metrics.snapshot().fields().len(),
903            "the body carries {samples} samples for {} counters",
904            metrics.snapshot().fields().len()
905        );
906    }
907
908    #[test]
909    fn counters_survive_concurrent_writers() {
910        // Relaxed ordering is still atomic. If any of this were a `+= 1` on a
911        // plain integer the total would come out short.
912        let metrics = Arc::new(ServerMetrics::new());
913        let mut threads = Vec::new();
914        for _ in 0..8 {
915            let metrics = Arc::clone(&metrics);
916            threads.push(std::thread::spawn(move || {
917                for _ in 0..1000 {
918                    metrics.add_bytes_out(1);
919                    let _guard = metrics.transfer_started();
920                }
921            }));
922        }
923        for t in threads {
924            t.join().expect("a counting thread");
925        }
926        let snapshot = metrics.snapshot();
927        assert_eq!(snapshot.bytes_out, 8000);
928        assert_eq!(snapshot.transfers_started, 8000);
929        assert_eq!(snapshot.transfers_in_flight, 0);
930    }
931}