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