Skip to main content

gunnar_core/
flow.rs

1//! **The flow ledger: what MOVED through a namespace, per UTC day.**
2//!
3//! # The hole this fills
4//!
5//! Every meter gunnar had before this file was a **stock** meter: `pack_bytes`,
6//! `cache_bytes`, `cold_bytes`, `lfs_bytes`, `tombstoned_bytes`, `objects` and
7//! `repos` all answer *how much is sitting on the disk right now*. They are the
8//! right numbers to bill from and the wrong ones to run a service on, because
9//! every one of them reads the same for a tenant who pushed this morning and a
10//! tenant who last touched the server in March. A silent customer and a busy
11//! one are indistinguishable in a stock meter, and so are a customer who is
12//! working and a customer who is being refused at the door.
13//!
14//! This module counts the other kind: **flow** — bytes in, bytes out, pushes,
15//! fetches, refusals, and when the tenant was last seen. Nothing here is ever a
16//! wall. Every counter is `Enforcement::Measured` in monetize's vocabulary
17//! (`monetize_product::Enforcement`, which gunnar took onto the wire in
18//! `usage.proto` on purpose): they are counted and reported, and nothing on this
19//! box refuses because of one. Promoting any of them to `Enforced` would need a
20//! refusal to exist first, and there is none.
21//!
22//! # Two halves, and why
23//!
24//! * [`FlowLedger`] is the LIVE half: pre-sized atomics, one slot per namespace
25//!   that has been touched since boot. A transfer bumps a handful of
26//!   `fetch_add`s under a read lock and allocates nothing. This is what the
27//!   transfer paths call.
28//! * [`FlowStore`] is the KEPT half: one document per namespace in the control
29//!   store (redb, the same store family the catalog, the auth table and the
30//!   entitlement facts live in), holding up to [`RETENTION_DAYS`] days of
31//!   [`FlowDay`] rows.
32//!
33//! A periodic flush copies the live slot into the store. **It copies, it does
34//! not add**: the live slot holds the whole of today, and the stored row for
35//! today is a snapshot of it, so a flush that runs twice writes the same number
36//! twice rather than doubling it. That is the property that makes a restart
37//! safe in both directions — nothing is counted twice, and nothing older than
38//! one flush interval is lost, because a slot opened after a restart is SEEDED
39//! from the stored row for today rather than from zero.
40//!
41//! # The day boundary
42//!
43//! Days are UTC, numbered as whole days since the Unix epoch ([`day_of`]). A
44//! transfer is charged to the day its *record* is taken, which is the day it
45//! finished. A transfer that starts at 23:59 and ends at 00:01 lands wholly in
46//! the second day; splitting one transfer across two days would need the byte
47//! counters to be sampled on a clock, and a meter that is sampled is a meter
48//! that can be read while it is being written.
49//!
50//! # What is NOT here
51//!
52//! **A key that resolves to nobody has no namespace**, and this ledger is per
53//! namespace. `ssh.auth.refused` with `reason = "unknown-key"` happens before
54//! any repository is named — there is no exec line yet — so it cannot be
55//! charged to a tenant and is not counted here. It is counted server-wide by
56//! `ServerMetrics::add_connections_refused`, where it belongs.
57//! [`FlowDay::auth_failures`] is the OTHER half of the same sentence: a
58//! principal that authenticated and then held no grant on the repository it
59//! asked for. That one names a namespace, so that one is a tenant's number.
60
61use std::collections::{BTreeMap, BTreeSet, HashMap};
62use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
63use std::sync::{Arc, Mutex, RwLock};
64
65use crate::control::ControlStore;
66use crate::doc::{impl_doc, DocRef, ShardedMap};
67use crate::error::Result;
68
69/// **The name the flow document is stored under** in the control store.
70pub const FLOW_REF: &str = "refs/gunnar/flow";
71
72/// Milliseconds in a day. UTC, no leap seconds: the wire carries Unix
73/// milliseconds and a Unix millisecond has never counted one.
74pub const DAY_MS: i64 = 86_400_000;
75
76/// **How many days of flow are kept per namespace: 400.**
77///
78/// The same window `monetize_server::state::UsageStore::RETENTION_MS` keeps its
79/// readings for, and for the same reason: a shade over a year, so a question
80/// about "this month last year" can still be answered, and bounded, so a table
81/// written on every transfer is not a disk-fill bug with a schedule.
82pub const RETENTION_DAYS: i64 = 400;
83
84/// **The most principals one namespace-day counts by name.**
85///
86/// [`FlowDay::principals`] is an EXACT set rather than a sketch. A HyperLogLog
87/// would answer "roughly how many" in a fixed 1–2 KiB; a `BTreeSet` of
88/// fingerprints answers "exactly how many, and which" in about 50 B each. At
89/// the scale a git server has — a namespace is a team, and a team with ten
90/// thousand distinct keys pushing in one day is not a team — exact costs less
91/// than the sketch and answers a strictly harder question, which is the whole
92/// argument. The ceiling exists so that the pathological case is bounded rather
93/// than unbounded, and when it is hit [`FlowDay::principals_capped`] says so,
94/// because a count that stopped growing must never be read as a total.
95pub const PRINCIPAL_CEILING: usize = 10_000;
96
97/// The UTC day a millisecond timestamp falls in, as whole days since the epoch.
98/// Euclidean, so a timestamp before 1970 floors rather than truncating toward
99/// zero and cannot share a day number with one after it.
100pub fn day_of(unix_ms: i64) -> i64 {
101    unix_ms.div_euclid(DAY_MS)
102}
103
104/// Midnight UTC of a day number, in Unix milliseconds — the value the wire
105/// carries as `DayActivity.day_unix_ms`.
106pub fn midnight_of(day: i64) -> i64 {
107    day.saturating_mul(DAY_MS)
108}
109
110/// **Unix milliseconds → `YYYY-MM-DDTHH:MM:SSZ`, in std alone.**
111///
112/// Eleven lines of arithmetic rather than a date crate in every consumer's
113/// graph, and the ONE runtime copy of it: `gunnar control usage` and `gunnar
114/// control activity` both print timestamps off this, so the two cannot render
115/// the same instant two ways. (`gunnar-common/build.rs` has the same
116/// arithmetic and must: a build script cannot link the crate it is building.)
117///
118/// The civil date is Howard Hinnant's `civil_from_days`, exact for every
119/// representable day and needing no table. Pre-1970 falls out correctly because
120/// the era arithmetic floors.
121pub fn iso8601_utc(unix_ms: i64) -> String {
122    let secs = unix_ms.div_euclid(1000);
123    let days = secs.div_euclid(86_400);
124    let rem = secs.rem_euclid(86_400);
125    let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
126    // Shift the epoch to 0000-03-01 so leap days land at the end of the cycle.
127    let z = days + 719_468;
128    let era = z.div_euclid(146_097);
129    let doe = z.rem_euclid(146_097);
130    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
131    let y = yoe + era * 400;
132    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
133    let mp = (5 * doy + 2) / 153;
134    let d = doy - (153 * mp + 2) / 5 + 1;
135    let m = if mp < 10 { mp + 3 } else { mp - 9 };
136    let y = if m <= 2 { y + 1 } else { y };
137    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
138}
139
140/// **Why a transfer was turned away**, in the three words an operator can act
141/// on differently.
142///
143/// Deliberately three and not the gate's six. `gunnar_ssh::Refusal` has six
144/// variants because the admission gate has six ceilings, and which of them was
145/// hit is an operator's question about the BOX. A tenant's question is a
146/// different one — *is the server busy, am I over my plan, or am I not allowed*
147/// — and those are three answers. The six-way detail stays where it is, on the
148/// gate's own `AdmissionStats` and in the `admission-*` reason on the log line.
149#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
150pub enum Refusal {
151    /// **The box was full.** Every `gunnar_ssh::Refusal` variant: the gate is at
152    /// capacity, the principal's share is spent, a lane is full, the anonymous
153    /// ceiling is reached, the keyed reserve is held, the memory budget is
154    /// spent. Nothing about the tenant is wrong; the server said "not now".
155    Admission,
156    /// **The plan said no before a byte.** `PlanGate::pack_quota` refusing a
157    /// namespace already at its `pack_bytes` cap, and the LFS allowance
158    /// refusing an upload past `lfs_bytes`. This is the one an invoice can fix.
159    Cap,
160    /// **The push gate said no.** A protected ref, a required review, a
161    /// signature that did not verify — `gunnar_policy`'s verdict. Nothing an
162    /// invoice can fix and nothing the operator should page about.
163    Policy,
164}
165
166impl Refusal {
167    /// `admission` | `cap` | `policy` — the wire spelling, one writer. The same
168    /// idiom as `Scope::name` and `Growth::name` on monetize's side: a word,
169    /// never an enum's ordinal, because an ordinal is an encoding of the
170    /// meaning rather than the meaning.
171    pub fn name(self) -> &'static str {
172        match self {
173            Refusal::Admission => "admission",
174            Refusal::Cap => "cap",
175            Refusal::Policy => "policy",
176        }
177    }
178
179    /// Every reason, in the order a breakdown is rendered in.
180    pub const ALL: [Refusal; 3] = [Refusal::Admission, Refusal::Cap, Refusal::Policy];
181}
182
183/// **One namespace's flow for one UTC day.**
184///
185/// Every field is a count of something that HAPPENED. There is no field here
186/// whose absence could be mistaken for a reading that was never taken: a day
187/// with no row is a day with no traffic, and a row of zeroes is the same thing
188/// said twice. That is the opposite of the stock meters, where a missing
189/// reading and a zero mean different things — and the difference is that a
190/// transfer either occurred or did not.
191#[derive(Clone, Default, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct FlowDay {
194    /// Bytes the server ACCEPTED off the wire: receive-pack, and the client
195    /// half of every other conversation. Measured by the transport's own
196    /// `Metered` reader, which is the one place a byte arriving is counted.
197    #[serde(default)]
198    pub bytes_in: u64,
199    /// Bytes the server SERVED: upload-pack, the advertisement, and the archive
200    /// stream. Measured by the transport's own `Metered` writer.
201    #[serde(default)]
202    pub bytes_out: u64,
203    /// receive-pack sessions that finished without an error.
204    #[serde(default)]
205    pub pushes: u64,
206    /// upload-pack sessions, clones included. The bare advertisement
207    /// (`GET /info/refs`, `git ls-remote`) is NOT one: it reads the ref list and
208    /// asks for no objects, and counting it would make a monitoring probe look
209    /// like a customer.
210    #[serde(default)]
211    pub fetches: u64,
212    /// LFS object bytes received. A subset of nothing: LFS rides its own
213    /// conversation, so these bytes are also in [`FlowDay::bytes_in`] as wire
214    /// bytes, and this is the applied figure the session itself counted.
215    #[serde(default)]
216    pub lfs_bytes_in: u64,
217    /// LFS object bytes sent. See [`FlowDay::lfs_bytes_in`].
218    #[serde(default)]
219    pub lfs_bytes_out: u64,
220    /// [`Refusal::Admission`] — the box was full.
221    #[serde(default)]
222    pub refused_admission: u64,
223    /// [`Refusal::Cap`] — the plan refused.
224    #[serde(default)]
225    pub refused_cap: u64,
226    /// [`Refusal::Policy`] — the push gate refused.
227    #[serde(default)]
228    pub refused_policy: u64,
229    /// **A principal that authenticated and then held no grant here.** See the
230    /// module doc for the half that is deliberately absent: a key that resolves
231    /// to nobody names no namespace and is not a tenant's number.
232    #[serde(default)]
233    pub auth_failures: u64,
234    /// The last transfer that put bytes IN, in Unix milliseconds; `0` for a day
235    /// with no push. Kept per day rather than only in the latest row so a
236    /// series answers *when in that week did they stop* and not only *have they
237    /// stopped*.
238    #[serde(default)]
239    pub last_push_unix_ms: i64,
240    /// The last transfer that took bytes OUT. `0` for a day with no fetch.
241    #[serde(default)]
242    pub last_fetch_unix_ms: i64,
243    /// **Which principals were seen**, by the fingerprint the auth table knows
244    /// them as. Exact, bounded by [`PRINCIPAL_CEILING`]; see there for why a
245    /// set and not a sketch.
246    #[serde(default)]
247    pub principals: BTreeSet<String>,
248    /// **The principal set stopped growing at [`PRINCIPAL_CEILING`]**, so
249    /// `principals.len()` is a FLOOR and not a total. It has never been true on
250    /// any real namespace; it exists so that if it ever is, the number says so
251    /// instead of quietly flattening.
252    #[serde(default)]
253    pub principals_capped: bool,
254}
255
256impl FlowDay {
257    /// Every refusal, whatever the reason.
258    pub fn refused(&self) -> u64 {
259        self.refused_admission
260            .saturating_add(self.refused_cap)
261            .saturating_add(self.refused_policy)
262    }
263
264    /// The count for one reason.
265    pub fn refused_for(&self, reason: Refusal) -> u64 {
266        match reason {
267            Refusal::Admission => self.refused_admission,
268            Refusal::Cap => self.refused_cap,
269            Refusal::Policy => self.refused_policy,
270        }
271    }
272
273    /// **Distinct principals seen that day** — a floor when
274    /// [`FlowDay::principals_capped`].
275    pub fn distinct_principals(&self) -> u64 {
276        self.principals.len() as u64
277    }
278
279    /// **Nothing happened**: no bytes, no sessions, no refusals, nobody seen. A
280    /// row like this is never written — a day with no traffic has no row — and
281    /// this is what the flush asks before writing one.
282    pub fn is_empty(&self) -> bool {
283        *self == FlowDay::default()
284    }
285
286    /// The last time anything moved in either direction, or `0`.
287    pub fn last_seen_unix_ms(&self) -> i64 {
288        self.last_push_unix_ms.max(self.last_fetch_unix_ms)
289    }
290
291    /// **Add `other` into this day.** Used to fold a series into a window
292    /// total, never by the flush — see the module doc for why the flush copies
293    /// rather than adds.
294    pub fn add(&mut self, other: &FlowDay) {
295        self.bytes_in = self.bytes_in.saturating_add(other.bytes_in);
296        self.bytes_out = self.bytes_out.saturating_add(other.bytes_out);
297        self.pushes = self.pushes.saturating_add(other.pushes);
298        self.fetches = self.fetches.saturating_add(other.fetches);
299        self.lfs_bytes_in = self.lfs_bytes_in.saturating_add(other.lfs_bytes_in);
300        self.lfs_bytes_out = self.lfs_bytes_out.saturating_add(other.lfs_bytes_out);
301        self.refused_admission = self.refused_admission.saturating_add(other.refused_admission);
302        self.refused_cap = self.refused_cap.saturating_add(other.refused_cap);
303        self.refused_policy = self.refused_policy.saturating_add(other.refused_policy);
304        self.auth_failures = self.auth_failures.saturating_add(other.auth_failures);
305        self.last_push_unix_ms = self.last_push_unix_ms.max(other.last_push_unix_ms);
306        self.last_fetch_unix_ms = self.last_fetch_unix_ms.max(other.last_fetch_unix_ms);
307        for who in &other.principals {
308            if self.principals.len() >= PRINCIPAL_CEILING {
309                self.principals_capped = true;
310                break;
311            }
312            self.principals.insert(who.clone());
313        }
314        self.principals_capped |= other.principals_capped;
315    }
316}
317
318/// One namespace's kept days, newest last. Absent days are days with no
319/// traffic.
320#[derive(Clone, Default, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
321#[serde(deny_unknown_fields)]
322pub struct NamespaceFlow {
323    /// Keyed by the day number [`day_of`] returns.
324    #[serde(default)]
325    pub days: BTreeMap<i64, FlowDay>,
326}
327
328/// The document as it is stored.
329#[derive(Default, Clone, serde::Serialize, serde::Deserialize)]
330#[serde(deny_unknown_fields)]
331struct FlowDoc {
332    /// Keyed by namespace name. One entry per namespace, holding at most
333    /// [`RETENTION_DAYS`] rows — a few tens of kilobytes at the top end, which
334    /// is one blob and one read rather than a scan over a day-keyed table.
335    #[serde(default)]
336    flows: ShardedMap<NamespaceFlow>,
337}
338
339impl_doc!(FlowDoc { flows });
340
341/// **The kept half**: read and write a namespace's days. Cheap to clone; every
342/// clone reads and writes the same document.
343#[derive(Clone, Debug)]
344pub struct FlowStore {
345    doc: DocRef<FlowDoc>,
346}
347
348impl FlowStore {
349    /// Open the flow document held in `store` (the server's control store). A
350    /// store that has never held one reads as empty, which is the truth for
351    /// every server that predates this file: no flow was counted, so no flow is
352    /// reported — never a zero that would read as *nothing happened*.
353    pub fn new(store: Arc<dyn ControlStore>) -> Result<Self> {
354        Ok(FlowStore {
355            doc: DocRef::new(store, FLOW_REF)?,
356        })
357    }
358
359    /// The name the document is stored under.
360    pub fn ref_name(&self) -> &str {
361        self.doc.ref_name()
362    }
363
364    /// One namespace's row for one day, or `None` when that day has no traffic.
365    pub fn day(&self, namespace: &str, day: i64) -> Result<Option<FlowDay>> {
366        Ok(self
367            .doc
368            .load()?
369            .flows
370            .get(namespace)?
371            .and_then(|flow| flow.days.get(&day).cloned()))
372    }
373
374    /// **The series for one namespace, oldest first**, over the inclusive day
375    /// range. Days with no traffic are absent rather than zero-filled: the
376    /// caller knows the range it asked for, and a row that was never written is
377    /// not a row of zeroes that was.
378    pub fn series(&self, namespace: &str, from_day: i64, to_day: i64) -> Result<Vec<(i64, FlowDay)>> {
379        let Some(flow) = self.doc.load()?.flows.get(namespace)? else {
380            return Ok(Vec::new());
381        };
382        Ok(flow
383            .days
384            .range(from_day..=to_day)
385            .map(|(day, row)| (*day, row.clone()))
386            .collect())
387    }
388
389    /// Every namespace that has ever had a row. Whole-map, O(entries) — the
390    /// fleet view and the flush, never a transfer.
391    pub fn namespaces(&self) -> Result<Vec<String>> {
392        let mut names: Vec<String> = self.doc.load()?.flows.keys()?;
393        names.sort();
394        Ok(names)
395    }
396
397    /// **Write these rows, replacing whatever each day held, and drop anything
398    /// older than [`RETENTION_DAYS`] before `today`.**
399    ///
400    /// Replace and not add, because the live slot holds the whole of the day it
401    /// is writing: see the module doc. An empty row REMOVES the day rather than
402    /// storing zeroes — a namespace that had a row and then had a day of
403    /// silence must not grow a row saying so.
404    ///
405    /// One document update for the whole batch, so a flush touching forty
406    /// namespaces is one compare-and-swap and not forty.
407    pub fn put(&self, rows: &[(String, i64, FlowDay)], today: i64) -> Result<()> {
408        if rows.is_empty() {
409            return Ok(());
410        }
411        let oldest = today.saturating_sub(RETENTION_DAYS);
412        let rows = rows.to_vec();
413        self.doc.update(|doc| {
414            for (namespace, day, row) in &rows {
415                let mut flow = doc.flows.get(namespace)?.unwrap_or_default();
416                if row.is_empty() {
417                    flow.days.remove(day);
418                } else {
419                    flow.days.insert(*day, row.clone());
420                }
421                flow.days.retain(|day, _| *day > oldest);
422                if flow.days.is_empty() {
423                    doc.flows.remove(namespace)?;
424                } else {
425                    doc.flows.insert(namespace.clone(), flow)?;
426                }
427            }
428            Ok(())
429        })
430    }
431
432    /// Forget one namespace's whole series, reporting whether there was one.
433    /// The flow half of deleting a namespace — a tenant that is gone must not
434    /// leave a record of who pushed to it.
435    pub fn forget(&self, namespace: &str) -> Result<bool> {
436        let key = namespace.to_owned();
437        self.doc.update(|doc| Ok(doc.flows.remove(&key)?.is_some()))
438    }
439}
440
441/// **One namespace's flow at a glance**: today, and when it was last seen.
442///
443/// The shape `Usage.Read` carries. `last_*` deliberately look back over the
444/// whole kept window rather than over `today` — see [`FlowLedger::glance`].
445#[derive(Clone, Default, PartialEq, Eq, Debug)]
446pub struct Glance {
447    /// Today's counts. All zero for a day with no traffic, which for a FLOW
448    /// meter is a fact and not a gap: a transfer either occurred or it did not.
449    pub today: FlowDay,
450    /// The last push anywhere in the kept window, or `0` for a namespace that
451    /// has never been pushed to inside it.
452    pub last_push_unix_ms: i64,
453    /// The last fetch anywhere in the kept window, or `0`.
454    pub last_fetch_unix_ms: i64,
455}
456
457impl Glance {
458    /// The last time anything moved in either direction, or `0`.
459    pub fn last_seen_unix_ms(&self) -> i64 {
460        self.last_push_unix_ms.max(self.last_fetch_unix_ms)
461    }
462}
463
464/// **The whole box's flow at a glance**, folded over every namespace. See
465/// [`FlowLedger::fleet`].
466#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
467pub struct Fleet {
468    /// Wire bytes accepted today, across every namespace.
469    pub bytes_in_today: u64,
470    /// Wire bytes served today, across every namespace.
471    pub bytes_out_today: u64,
472    /// Transfers turned away today, across every namespace.
473    pub refused_today: u64,
474    /// How many namespaces this fold looked at.
475    pub namespaces: u64,
476    /// **How many have neither pushed nor fetched inside the caller's window.**
477    /// A tenant that has never been seen at all counts here: it is the quietest
478    /// one there is, and rounding it to "not silent" would hide exactly the
479    /// account an operator is looking for.
480    pub silent: u64,
481}
482
483/// The live counters for one namespace's current day. Every field is an atomic
484/// so the hot path takes no lock; `roll` is taken only when the day turns and
485/// when the flush snapshots.
486#[derive(Debug)]
487struct Slot {
488    day: AtomicI64,
489    bytes_in: AtomicU64,
490    bytes_out: AtomicU64,
491    pushes: AtomicU64,
492    fetches: AtomicU64,
493    lfs_bytes_in: AtomicU64,
494    lfs_bytes_out: AtomicU64,
495    refused_admission: AtomicU64,
496    refused_cap: AtomicU64,
497    refused_policy: AtomicU64,
498    auth_failures: AtomicU64,
499    last_push_unix_ms: AtomicI64,
500    last_fetch_unix_ms: AtomicI64,
501    /// The one thing that is not an atomic. A `BTreeSet` insert per transfer —
502    /// once per SESSION, never per byte — is not on the byte path.
503    principals: Mutex<(BTreeSet<String>, bool)>,
504    /// Held while the day turns and while the flush reads, so the two cannot
505    /// interleave and a completed day cannot be written twice.
506    roll: Mutex<()>,
507}
508
509impl Slot {
510    fn seeded(day: i64, from: FlowDay) -> Slot {
511        Slot {
512            day: AtomicI64::new(day),
513            bytes_in: AtomicU64::new(from.bytes_in),
514            bytes_out: AtomicU64::new(from.bytes_out),
515            pushes: AtomicU64::new(from.pushes),
516            fetches: AtomicU64::new(from.fetches),
517            lfs_bytes_in: AtomicU64::new(from.lfs_bytes_in),
518            lfs_bytes_out: AtomicU64::new(from.lfs_bytes_out),
519            refused_admission: AtomicU64::new(from.refused_admission),
520            refused_cap: AtomicU64::new(from.refused_cap),
521            refused_policy: AtomicU64::new(from.refused_policy),
522            auth_failures: AtomicU64::new(from.auth_failures),
523            last_push_unix_ms: AtomicI64::new(from.last_push_unix_ms),
524            last_fetch_unix_ms: AtomicI64::new(from.last_fetch_unix_ms),
525            principals: Mutex::new((from.principals, from.principals_capped)),
526            roll: Mutex::new(()),
527        }
528    }
529
530    /// A snapshot, without disturbing the counters.
531    fn read(&self) -> FlowDay {
532        let (principals, principals_capped) = {
533            let held = self.principals.lock().expect("flow principals");
534            (held.0.clone(), held.1)
535        };
536        FlowDay {
537            bytes_in: self.bytes_in.load(Ordering::Relaxed),
538            bytes_out: self.bytes_out.load(Ordering::Relaxed),
539            pushes: self.pushes.load(Ordering::Relaxed),
540            fetches: self.fetches.load(Ordering::Relaxed),
541            lfs_bytes_in: self.lfs_bytes_in.load(Ordering::Relaxed),
542            lfs_bytes_out: self.lfs_bytes_out.load(Ordering::Relaxed),
543            refused_admission: self.refused_admission.load(Ordering::Relaxed),
544            refused_cap: self.refused_cap.load(Ordering::Relaxed),
545            refused_policy: self.refused_policy.load(Ordering::Relaxed),
546            auth_failures: self.auth_failures.load(Ordering::Relaxed),
547            last_push_unix_ms: self.last_push_unix_ms.load(Ordering::Relaxed),
548            last_fetch_unix_ms: self.last_fetch_unix_ms.load(Ordering::Relaxed),
549            principals,
550            principals_capped,
551        }
552    }
553
554    /// Zero everything and open a new day.
555    fn reset_to(&self, day: i64) {
556        for counter in [
557            &self.bytes_in,
558            &self.bytes_out,
559            &self.pushes,
560            &self.fetches,
561            &self.lfs_bytes_in,
562            &self.lfs_bytes_out,
563            &self.refused_admission,
564            &self.refused_cap,
565            &self.refused_policy,
566            &self.auth_failures,
567        ] {
568            counter.store(0, Ordering::Relaxed);
569        }
570        self.last_push_unix_ms.store(0, Ordering::Relaxed);
571        self.last_fetch_unix_ms.store(0, Ordering::Relaxed);
572        {
573            let mut held = self.principals.lock().expect("flow principals");
574            held.0.clear();
575            held.1 = false;
576        }
577        self.day.store(day, Ordering::Release);
578    }
579
580    fn saw(&self, principal: &str) {
581        if principal.is_empty() {
582            return;
583        }
584        let mut held = self.principals.lock().expect("flow principals");
585        if held.0.contains(principal) {
586            return;
587        }
588        if held.0.len() >= PRINCIPAL_CEILING {
589            held.1 = true;
590            return;
591        }
592        held.0.insert(principal.to_owned());
593    }
594}
595
596/// **What one finished transfer moved.** Built by the counting point, applied
597/// once.
598///
599/// One struct rather than eight `record_*` methods, because a transfer is ONE
600/// event and its numbers must land on one day together: eight calls could
601/// straddle midnight and split a single push across two rows.
602#[derive(Clone, Default, PartialEq, Eq, Debug)]
603pub struct Transfer {
604    /// Wire bytes accepted.
605    pub bytes_in: u64,
606    /// Wire bytes served.
607    pub bytes_out: u64,
608    /// A receive-pack session that finished.
609    pub pushed: bool,
610    /// An upload-pack session that was asked for objects — never the bare
611    /// advertisement.
612    pub fetched: bool,
613    /// LFS object bytes received, as the LFS session counted them.
614    pub lfs_bytes_in: u64,
615    /// LFS object bytes sent.
616    pub lfs_bytes_out: u64,
617    /// The principal, by the fingerprint the auth table knows. Empty for a
618    /// transfer with no identity, which is counted in the bytes and in nobody's
619    /// name.
620    pub principal: String,
621}
622
623impl Transfer {
624    /// Did anything move at all? A transfer that moved no byte in either
625    /// direction and neither pushed nor fetched is not written.
626    pub fn is_empty(&self) -> bool {
627        self.bytes_in == 0
628            && self.bytes_out == 0
629            && !self.pushed
630            && !self.fetched
631            && self.lfs_bytes_in == 0
632            && self.lfs_bytes_out == 0
633    }
634}
635
636/// **The live half: the counters every transfer path bumps.**
637///
638/// Cheap to clone through an `Arc`. A record is: one read lock, one hash
639/// lookup, a handful of relaxed `fetch_add`s, and one `BTreeSet` insert per
640/// session. Nothing on that path allocates once the namespace has a slot, and a
641/// slot is made once per namespace per process.
642#[derive(Debug)]
643pub struct FlowLedger {
644    store: FlowStore,
645    /// One slot per namespace touched since boot. The write lock is taken only
646    /// to make a slot.
647    live: RwLock<HashMap<String, Arc<Slot>>>,
648    /// Days that turned over and have not been written yet. The flush drains
649    /// this before it snapshots today.
650    completed: Mutex<Vec<(String, i64, FlowDay)>>,
651    /// **Who is told a namespace's flow moved** (2026-10-06): the server's
652    /// usage ledger, so a batched usage read (`UsageBatch.ReadMany` with a
653    /// cursor) answers the namespaces whose `*_today` meters changed — and
654    /// re-measures their bytes, since a transfer is also what grows a
655    /// repository, its LFS store and its exploded read cache. One call per
656    /// recorded transfer, refusal or auth failure; never per object.
657    observer: RwLock<Option<FlowObserver>>,
658}
659
660/// The callback [`FlowLedger::observe`] installs, with a `Debug` that says
661/// only that it is there.
662#[derive(Clone)]
663pub struct FlowObserver(pub Arc<dyn Fn(&str) + Send + Sync>);
664
665impl std::fmt::Debug for FlowObserver {
666    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
667        f.write_str("FlowObserver(..)")
668    }
669}
670
671impl FlowLedger {
672    /// Open the ledger over a control store.
673    pub fn new(store: FlowStore) -> FlowLedger {
674        FlowLedger {
675            store,
676            live: RwLock::new(HashMap::new()),
677            completed: Mutex::new(Vec::new()),
678            observer: RwLock::new(None),
679        }
680    }
681
682    /// **Tell `observer` the name of every namespace whose flow moves** — a
683    /// recorded transfer, a refusal, an auth failure. Replaces any earlier
684    /// observer. Called on the transfer path, so it must be cheap: the
685    /// server's usage ledger inserts the name into a set and returns.
686    pub fn observe(&self, observer: FlowObserver) {
687        *self.observer.write().expect("flow observer") = Some(observer);
688    }
689
690    fn tell_observer(&self, namespace: &str) {
691        if let Some(observer) = self.observer.read().expect("flow observer").as_ref() {
692            (observer.0)(namespace);
693        }
694    }
695
696    /// The kept half, for the readers that want a series rather than today.
697    pub fn store(&self) -> &FlowStore {
698        &self.store
699    }
700
701    /// The slot for a namespace, made and seeded from the store on first touch.
702    ///
703    /// **Seeded, not zeroed.** A server that restarts at noon must go on
704    /// counting today from where the last flush left it; starting from zero
705    /// would make every restart look like a quiet morning.
706    fn slot(&self, namespace: &str, day: i64) -> Arc<Slot> {
707        if let Some(slot) = self
708            .live
709            .read()
710            .expect("flow slots")
711            .get(namespace)
712            .map(Arc::clone)
713        {
714            self.roll_to(namespace, &slot, day);
715            return slot;
716        }
717        // The store read happens outside the write lock: it is I/O, and a
718        // second namespace's first transfer must not wait behind it.
719        let seed = self.store.day(namespace, day).unwrap_or_default().unwrap_or_default();
720        let mut live = self.live.write().expect("flow slots");
721        let slot = Arc::clone(
722            live.entry(namespace.to_owned())
723                .or_insert_with(|| Arc::new(Slot::seeded(day, seed))),
724        );
725        drop(live);
726        self.roll_to(namespace, &slot, day);
727        slot
728    }
729
730    /// Turn the day if it has turned, parking the completed row for the flush.
731    fn roll_to(&self, namespace: &str, slot: &Slot, day: i64) {
732        if slot.day.load(Ordering::Acquire) == day {
733            return;
734        }
735        let _held = slot.roll.lock().expect("flow roll");
736        let was = slot.day.load(Ordering::Acquire);
737        if was == day {
738            return;
739        }
740        let finished = slot.read();
741        if !finished.is_empty() {
742            self.completed
743                .lock()
744                .expect("flow completed")
745                .push((namespace.to_owned(), was, finished));
746        }
747        slot.reset_to(day);
748    }
749
750    /// **The counting point for a finished transfer.** One call, one day.
751    pub fn record(&self, namespace: &str, at_unix_ms: i64, transfer: &Transfer) {
752        if namespace.is_empty() || transfer.is_empty() {
753            return;
754        }
755        let slot = self.slot(namespace, day_of(at_unix_ms));
756        add(&slot.bytes_in, transfer.bytes_in);
757        add(&slot.bytes_out, transfer.bytes_out);
758        add(&slot.lfs_bytes_in, transfer.lfs_bytes_in);
759        add(&slot.lfs_bytes_out, transfer.lfs_bytes_out);
760        if transfer.pushed {
761            slot.pushes.fetch_add(1, Ordering::Relaxed);
762            slot.last_push_unix_ms.store(at_unix_ms, Ordering::Relaxed);
763        }
764        if transfer.fetched {
765            slot.fetches.fetch_add(1, Ordering::Relaxed);
766            slot.last_fetch_unix_ms.store(at_unix_ms, Ordering::Relaxed);
767        }
768        slot.saw(&transfer.principal);
769        self.tell_observer(namespace);
770    }
771
772    /// **The counting point for a refusal.** No bytes moved; the tenant met a
773    /// door.
774    pub fn refuse(&self, namespace: &str, at_unix_ms: i64, reason: Refusal) {
775        if namespace.is_empty() {
776            return;
777        }
778        let slot = self.slot(namespace, day_of(at_unix_ms));
779        let counter = match reason {
780            Refusal::Admission => &slot.refused_admission,
781            Refusal::Cap => &slot.refused_cap,
782            Refusal::Policy => &slot.refused_policy,
783        };
784        counter.fetch_add(1, Ordering::Relaxed);
785        self.tell_observer(namespace);
786    }
787
788    /// **The counting point for a principal with no grant here.** See the
789    /// module doc for the half that is not counted.
790    pub fn auth_failure(&self, namespace: &str, at_unix_ms: i64) {
791        if namespace.is_empty() {
792            return;
793        }
794        let slot = self.slot(namespace, day_of(at_unix_ms));
795        slot.auth_failures.fetch_add(1, Ordering::Relaxed);
796        self.tell_observer(namespace);
797    }
798
799    /// **Today's live figure for one namespace**, whether or not it has been
800    /// flushed. Read straight off the atomics — the store is not consulted,
801    /// because the slot holds the whole day and the stored row is a copy of it.
802    ///
803    /// `None` when this process has not seen the namespace today AND the store
804    /// holds no row for it: nothing happened, which is a fact and not a gap.
805    pub fn today(&self, namespace: &str, now_unix_ms: i64) -> Option<FlowDay> {
806        let day = day_of(now_unix_ms);
807        if let Some(slot) = self
808            .live
809            .read()
810            .expect("flow slots")
811            .get(namespace)
812            .map(Arc::clone)
813        {
814            if slot.day.load(Ordering::Acquire) == day {
815                let row = slot.read();
816                return (!row.is_empty()).then_some(row);
817            }
818        }
819        self.store.day(namespace, day).ok().flatten()
820    }
821
822    /// **What `Usage.Read` puts beside the stock meters**: today's flow, and
823    /// when the namespace was last seen over the WHOLE kept window.
824    ///
825    /// The two halves answer different questions and must not be folded into
826    /// one. *How much moved today* is a rate; *when did anything last move* is
827    /// what an operator reads to decide a tenant has gone quiet, and a tenant
828    /// who has done nothing for six weeks has a today of zeroes and a last-seen
829    /// six weeks ago. Reading the second out of the first is exactly the
830    /// mistake this pair exists to prevent.
831    pub fn glance(&self, namespace: &str, now_unix_ms: i64) -> Glance {
832        let today_number = day_of(now_unix_ms);
833        let today = self.today(namespace, now_unix_ms).unwrap_or_default();
834        let mut glance = Glance {
835            last_push_unix_ms: today.last_push_unix_ms,
836            last_fetch_unix_ms: today.last_fetch_unix_ms,
837            today,
838        };
839        // Backwards from yesterday, and stop as soon as both are known: a
840        // namespace that pushed yesterday costs one row, not four hundred.
841        let kept = self
842            .store
843            .series(namespace, today_number - RETENTION_DAYS, today_number - 1)
844            .unwrap_or_default();
845        for (_, row) in kept.iter().rev() {
846            if glance.last_push_unix_ms == 0 {
847                glance.last_push_unix_ms = row.last_push_unix_ms;
848            }
849            if glance.last_fetch_unix_ms == 0 {
850                glance.last_fetch_unix_ms = row.last_fetch_unix_ms;
851            }
852            if glance.last_push_unix_ms != 0 && glance.last_fetch_unix_ms != 0 {
853                break;
854            }
855        }
856        glance
857    }
858
859    /// **The whole box's flow, folded** — what moved today across every
860    /// namespace, and how many tenants have gone quiet.
861    ///
862    /// O(namespaces), and it reads the control document. It is for the
863    /// dashboard band and for an operator's fleet view, NEVER for a transfer:
864    /// the flush tick computes it once a minute and the screen reads the
865    /// result, because the dashboard's own two-second tick is documented as
866    /// reading a few atomics and nothing else.
867    ///
868    /// `silent_after_days` is the caller's policy, not this module's. Fourteen
869    /// days is what the console uses; a different deployment may reasonably
870    /// call a tenant quiet sooner, and a constant here would make that a fork.
871    pub fn fleet(&self, now_unix_ms: i64, silent_after_days: i64) -> Fleet {
872        let mut names: BTreeSet<String> = self.store.namespaces().unwrap_or_default().into_iter().collect();
873        names.extend(self.live.read().expect("flow slots").keys().cloned());
874        let quiet_before = now_unix_ms.saturating_sub(silent_after_days.saturating_mul(DAY_MS));
875        let mut fleet = Fleet {
876            namespaces: names.len() as u64,
877            ..Fleet::default()
878        };
879        for name in &names {
880            let glance = self.glance(name, now_unix_ms);
881            fleet.bytes_in_today = fleet.bytes_in_today.saturating_add(glance.today.bytes_in);
882            fleet.bytes_out_today = fleet.bytes_out_today.saturating_add(glance.today.bytes_out);
883            fleet.refused_today = fleet.refused_today.saturating_add(glance.today.refused());
884            // A namespace that has NEVER been seen inside the kept window is
885            // silent too — `last_seen_unix_ms()` is 0 there, which is before
886            // any cutoff. That is the right answer: a tenant nobody has ever
887            // pushed to is the quietest one there is.
888            if glance.last_seen_unix_ms() < quiet_before {
889                fleet.silent = fleet.silent.saturating_add(1);
890            }
891        }
892        fleet
893    }
894
895    /// **Copy every live slot into the store, and drop what has aged out.**
896    ///
897    /// The flush. Runs on a tick; touches redb once for the whole batch. It
898    /// COPIES rather than adds, so running it twice in a row writes the same
899    /// rows twice rather than doubling them — which is what makes it safe to
900    /// run it again on shutdown, and safe for a restart to seed from it.
901    ///
902    /// Returns how many rows it wrote, for the caller's log line.
903    pub fn flush(&self, now_unix_ms: i64) -> Result<usize> {
904        let today = day_of(now_unix_ms);
905        let mut rows: Vec<(String, i64, FlowDay)> =
906            std::mem::take(&mut *self.completed.lock().expect("flow completed"));
907        let slots: Vec<(String, Arc<Slot>)> = self
908            .live
909            .read()
910            .expect("flow slots")
911            .iter()
912            .map(|(name, slot)| (name.clone(), Arc::clone(slot)))
913            .collect();
914        for (namespace, slot) in slots {
915            // Roll first: a slot nobody has touched since yesterday still holds
916            // yesterday, and the tick is what notices on an idle server.
917            self.roll_to(&namespace, &slot, today);
918            let _held = slot.roll.lock().expect("flow roll");
919            let row = slot.read();
920            if !row.is_empty() {
921                rows.push((namespace, slot.day.load(Ordering::Acquire), row));
922            }
923        }
924        // A roll during the loop above parks rows in `completed`; take them too
925        // rather than leaving them for the next tick.
926        rows.extend(std::mem::take(&mut *self.completed.lock().expect("flow completed")));
927        let written = rows.len();
928        if written > 0 {
929            if let Err(err) = self.store.put(&rows, today) {
930                // A refused write (the transaction log released while the data set is
931                // grown, a full disk) must not LOSE the completed days taken out of
932                // `completed` above: a live slot is still in memory, a rolled day is
933                // only here. Parked again, the next flush writes them. A live-slot row
934                // parked beside them is harmless: `put` copies, it does not add.
935                self.completed.lock().expect("flow completed").extend(rows);
936                return Err(err);
937            }
938        }
939        Ok(written)
940    }
941
942    /// **Bytes moved — in plus out — per UTC day, over the last `days` days,
943    /// today included**: `(day, bytes)` for each day that moved anything,
944    /// oldest first. The durable half of admission's usage: `edda_admit`'s
945    /// table SEEDS a namespace from this once, on first sight, and is the
946    /// cache from then on — so this is read once per namespace per process,
947    /// never per transfer (it takes the ledger's locks and reads the store).
948    ///
949    /// Wire bytes only. LFS bytes are already inside them (see
950    /// [`FlowDay::lfs_bytes_in`]), so adding the LFS pair would count one
951    /// transfer twice.
952    ///
953    /// * **today** is the live slot, read off its atomics;
954    /// * **the closed days** are the store's rows, plus any closed day still
955    ///   parked for the flush — a parked row is the FINAL figure for its day
956    ///   and replaces the store's last-tick copy of it, never adds to it.
957    ///
958    /// A slot still holding yesterday is rolled first, so a read just after
959    /// midnight does not take yesterday's live bytes for today's.
960    pub fn moved(&self, namespace: &str, now_unix_ms: i64, days: u32) -> Vec<(i64, u64)> {
961        let today = day_of(now_unix_ms);
962        let live_slot = self
963            .live
964            .read()
965            .expect("flow slots")
966            .get(namespace)
967            .map(Arc::clone);
968        if let Some(slot) = live_slot {
969            self.roll_to(namespace, &slot, today);
970        }
971        let from = today - i64::from(days.max(1)) + 1;
972        let mut rows: BTreeMap<i64, u64> = if from < today {
973            self.store
974                .series(namespace, from, today - 1)
975                .unwrap_or_default()
976                .into_iter()
977                .map(|(day, row)| (day, row.bytes_in.saturating_add(row.bytes_out)))
978                .collect()
979        } else {
980            BTreeMap::new()
981        };
982        rows.extend(
983            self.completed
984                .lock()
985                .expect("flow completed")
986                .iter()
987                .filter(|(name, day, _)| name == namespace && *day >= from && *day < today)
988                .map(|(_, day, row)| (*day, row.bytes_in.saturating_add(row.bytes_out))),
989        );
990        if let Some(t) = self.today(namespace, now_unix_ms) {
991            rows.insert(today, t.bytes_in.saturating_add(t.bytes_out));
992        }
993        rows.into_iter().filter(|(_, b)| *b > 0).collect()
994    }
995
996    /// [`FlowLedger::moved`], summed: bytes in + out over the window.
997    pub fn window_bytes(&self, namespace: &str, now_unix_ms: i64, days: u32) -> u64 {
998        self.moved(namespace, now_unix_ms, days)
999            .iter()
1000            .fold(0u64, |acc, (_, b)| acc.saturating_add(*b))
1001    }
1002
1003    /// Drop a namespace's live slot and its whole kept series. The flow half of
1004    /// deleting a namespace.
1005    pub fn forget(&self, namespace: &str) -> Result<bool> {
1006        self.live.write().expect("flow slots").remove(namespace);
1007        self.completed
1008            .lock()
1009            .expect("flow completed")
1010            .retain(|(name, _, _)| name != namespace);
1011        self.store.forget(namespace)
1012    }
1013}
1014
1015/// `fetch_add` that skips the bus traffic for the common zero.
1016fn add(counter: &AtomicU64, by: u64) {
1017    if by > 0 {
1018        counter.fetch_add(by, Ordering::Relaxed);
1019    }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use super::*;
1025    use crate::control::RedbControlStore;
1026
1027    fn ledger() -> FlowLedger {
1028        let store = Arc::new(RedbControlStore::in_memory().unwrap()) as Arc<dyn ControlStore>;
1029        FlowLedger::new(FlowStore::new(store).unwrap())
1030    }
1031
1032    fn push(bytes: u64, who: &str) -> Transfer {
1033        Transfer {
1034            bytes_in: bytes,
1035            pushed: true,
1036            principal: who.into(),
1037            ..Transfer::default()
1038        }
1039    }
1040
1041    fn fetch(bytes: u64, who: &str) -> Transfer {
1042        Transfer {
1043            bytes_out: bytes,
1044            fetched: true,
1045            principal: who.into(),
1046            ..Transfer::default()
1047        }
1048    }
1049
1050    /// ★ **The admission window is today plus the closed days before it**,
1051    /// in + out, from the live slot, the parked rows and the store — each day
1052    /// counted once, whichever of those three it sits in.
1053    #[test]
1054    fn the_window_sums_thirty_days_counting_each_day_once() {
1055        let flow = ledger();
1056        let day0 = 20_000 * DAY_MS + 3_600_000;
1057        // 31 days ago: outside a 30-day window.
1058        flow.record("team", day0, &push(1_000_000, "a"));
1059        // 29 days ago: the oldest day inside it.
1060        flow.record("team", day0 + DAY_MS, &push(1000, "a"));
1061        flow.flush(day0 + DAY_MS).unwrap();
1062        // Yesterday: rolled but NOT flushed — parked, and the store holds nothing of it.
1063        flow.record("team", day0 + 29 * DAY_MS, &fetch(200, "a"));
1064        flow.record("team", day0 + 30 * DAY_MS, &push(30, "a"));
1065        flow.record("team", day0 + 30 * DAY_MS, &fetch(7, "b"));
1066        let now = day0 + 30 * DAY_MS;
1067        assert_eq!(flow.window_bytes("team", now, 30), 1000 + 200 + 30 + 7);
1068        let days = flow.moved("team", now, 30);
1069        let today = day_of(now);
1070        assert_eq!(days, vec![(today - 29, 1000), (today - 1, 200), (today, 37)], "oldest first, per day");
1071        assert_eq!(flow.window_bytes("team", now, 1), 37, "a one-day window is today");
1072        assert_eq!(flow.window_bytes("other", now, 30), 0);
1073        // After the flush the parked row is in the store: the same total, not double.
1074        flow.flush(now).unwrap();
1075        assert_eq!(flow.window_bytes("team", now, 30), 1237);
1076        // Today is live: a new transfer today shows at once.
1077        flow.record("team", now + 1, &push(3, "a"));
1078        assert_eq!(flow.window_bytes("team", now + 1, 30), 1240);
1079        // The next day the oldest day falls out.
1080        assert_eq!(flow.window_bytes("team", now + DAY_MS, 30), 200 + 40);
1081    }
1082
1083    /// A slot still holding yesterday is rolled before it is read: the first
1084    /// read after midnight does not take yesterday's live bytes for today's,
1085    /// nor lose them.
1086    #[test]
1087    fn the_window_rolls_a_stale_slot_before_reading_it() {
1088        let flow = ledger();
1089        let day0 = 20_000 * DAY_MS;
1090        flow.flush(day0).unwrap();
1091        flow.record("team", day0 + 10, &push(500, "a"));
1092        flow.flush(day0 + 20).unwrap(); // the store holds a copy of day0 = 500
1093        flow.record("team", day0 + 30, &push(5, "a")); // live day0 = 505, store 500
1094        let next = day0 + DAY_MS + 1;
1095        assert_eq!(flow.window_bytes("team", next, 30), 505);
1096        assert_eq!(flow.window_bytes("team", next, 1), 0, "nothing moved today yet");
1097    }
1098
1099    /// ★ **A push charges the namespace it was pushed to, and nobody else.**
1100    ///
1101    /// The first thing that has to be true of a per-tenant meter, and the one
1102    /// that a global counter — which is all gunnar had — cannot be.
1103    #[test]
1104    fn a_push_lands_on_its_own_namespace_and_no_other() {
1105        let flow = ledger();
1106        let now = 1_757_000_000_000;
1107        flow.record("team", now, &push(4096, "SHA256:aaa"));
1108
1109        let mine = flow.today("team", now).expect("the push was counted");
1110        assert_eq!(mine.bytes_in, 4096);
1111        assert_eq!(mine.pushes, 1);
1112        assert_eq!(mine.bytes_out, 0, "a push serves no pack");
1113        assert_eq!(mine.last_push_unix_ms, now);
1114        assert_eq!(mine.distinct_principals(), 1);
1115
1116        assert_eq!(flow.today("other", now), None, "a namespace with no traffic has no row, not a row of zeroes");
1117    }
1118
1119    /// A fetch is bytes OUT and a fetch count; a bare advertisement is neither.
1120    #[test]
1121    fn a_fetch_is_bytes_out_and_an_advertisement_is_not_a_fetch() {
1122        let flow = ledger();
1123        let now = 1_757_000_000_000;
1124        flow.record("team", now, &fetch(9000, "SHA256:bbb"));
1125        // The advertisement: bytes out, no session.
1126        flow.record(
1127            "team",
1128            now,
1129            &Transfer { bytes_out: 120, ..Transfer::default() },
1130        );
1131
1132        let row = flow.today("team", now).unwrap();
1133        assert_eq!(row.bytes_out, 9120, "both wrote bytes");
1134        assert_eq!(row.fetches, 1, "only one of them asked for objects");
1135        assert_eq!(row.last_fetch_unix_ms, now);
1136    }
1137
1138    /// ★ **A refusal is counted, by reason, and moves no bytes.**
1139    #[test]
1140    fn a_refusal_is_counted_by_reason_and_leaves_the_bytes_alone() {
1141        let flow = ledger();
1142        let now = 1_757_000_000_000;
1143        flow.record("team", now, &push(4096, "SHA256:aaa"));
1144        flow.refuse("team", now, Refusal::Cap);
1145        flow.refuse("team", now, Refusal::Cap);
1146        flow.refuse("team", now, Refusal::Admission);
1147
1148        let row = flow.today("team", now).unwrap();
1149        assert_eq!(row.bytes_in, 4096, "a refused push moved nothing");
1150        assert_eq!(row.pushes, 1);
1151        assert_eq!(row.refused(), 3);
1152        assert_eq!(row.refused_for(Refusal::Cap), 2);
1153        assert_eq!(row.refused_for(Refusal::Admission), 1);
1154        assert_eq!(row.refused_for(Refusal::Policy), 0);
1155    }
1156
1157    /// ★ **A day rollover splits the counts**, and yesterday keeps its own.
1158    #[test]
1159    fn the_day_boundary_splits_the_counts() {
1160        let flow = ledger();
1161        let day_one = day_of(1_757_000_000_000);
1162        let late = midnight_of(day_one) + DAY_MS - 1;
1163        let early = midnight_of(day_one + 1) + 1;
1164
1165        flow.record("team", late, &push(1000, "SHA256:aaa"));
1166        flow.record("team", early, &push(7, "SHA256:aaa"));
1167
1168        let today = flow.today("team", early).unwrap();
1169        assert_eq!(today.bytes_in, 7, "the new day starts from nothing");
1170        assert_eq!(today.pushes, 1);
1171
1172        flow.flush(early).unwrap();
1173        let yesterday = flow.store().day("team", day_one).unwrap().expect("yesterday was written");
1174        assert_eq!(yesterday.bytes_in, 1000);
1175        assert_eq!(yesterday.pushes, 1);
1176    }
1177
1178    /// ★ **A restart keeps yesterday and drops nothing of today.**
1179    ///
1180    /// The whole reason the flush copies rather than adds, and the reason a new
1181    /// slot is seeded from the store: a second ledger over the same control
1182    /// store must go on counting today from where the first left it.
1183    #[test]
1184    fn a_restart_keeps_yesterday_and_resumes_today() {
1185        let store = Arc::new(RedbControlStore::in_memory().unwrap()) as Arc<dyn ControlStore>;
1186        let day_one = day_of(1_757_000_000_000);
1187        let yesterday_at = midnight_of(day_one) + 3_600_000;
1188        let today_at = midnight_of(day_one + 1) + 3_600_000;
1189        let later_today = today_at + 60_000;
1190
1191        {
1192            let flow = FlowLedger::new(FlowStore::new(Arc::clone(&store)).unwrap());
1193            flow.record("team", yesterday_at, &push(1000, "SHA256:aaa"));
1194            flow.flush(yesterday_at).unwrap();
1195            flow.record("team", today_at, &push(500, "SHA256:aaa"));
1196            flow.flush(today_at).unwrap();
1197        }
1198        // The server restarts.
1199        let flow = FlowLedger::new(FlowStore::new(Arc::clone(&store)).unwrap());
1200        assert_eq!(
1201            flow.today("team", today_at).unwrap().bytes_in,
1202            500,
1203            "today survived the restart"
1204        );
1205        flow.record("team", later_today, &push(1, "SHA256:aaa"));
1206        assert_eq!(
1207            flow.today("team", later_today).unwrap().bytes_in,
1208            501,
1209            "counting resumed from the stored figure, not from zero"
1210        );
1211        assert_eq!(flow.today("team", later_today).unwrap().pushes, 2);
1212        assert_eq!(
1213            flow.store().day("team", day_one).unwrap().unwrap().bytes_in,
1214            1000,
1215            "yesterday is untouched"
1216        );
1217    }
1218
1219    /// **Flushing twice writes the same numbers twice, not double them.** The
1220    /// property that makes the flush safe to run on a tick AND on shutdown.
1221    #[test]
1222    fn a_second_flush_is_not_a_second_count() {
1223        let flow = ledger();
1224        let now = 1_757_000_000_000;
1225        flow.record("team", now, &push(4096, "SHA256:aaa"));
1226        flow.flush(now).unwrap();
1227        flow.flush(now).unwrap();
1228        flow.flush(now).unwrap();
1229        assert_eq!(flow.store().day("team", day_of(now)).unwrap().unwrap().bytes_in, 4096);
1230    }
1231
1232    /// ★ **The series comes back oldest first**, and days with no traffic are
1233    /// absent rather than zero-filled.
1234    #[test]
1235    fn the_series_is_oldest_first_and_silent_days_are_absent() {
1236        let flow = ledger();
1237        let first = day_of(1_757_000_000_000);
1238        for (offset, bytes) in [(0i64, 100u64), (1, 200), (3, 400)] {
1239            let at = midnight_of(first + offset) + 1000;
1240            flow.record("team", at, &push(bytes, "SHA256:aaa"));
1241            flow.flush(at).unwrap();
1242        }
1243        let series = flow.store().series("team", first, first + 3).unwrap();
1244        assert_eq!(
1245            series.iter().map(|(day, _)| *day).collect::<Vec<_>>(),
1246            vec![first, first + 1, first + 3],
1247            "oldest first, and the silent day is not a row"
1248        );
1249        assert_eq!(series.iter().map(|(_, r)| r.bytes_in).collect::<Vec<_>>(), vec![100, 200, 400]);
1250        // A window that starts after the first day starts there.
1251        let narrow = flow.store().series("team", first + 1, first + 3).unwrap();
1252        assert_eq!(narrow.len(), 2);
1253    }
1254
1255    /// **Retention is 400 days, and the writer prunes.** A row older than the
1256    /// window is gone the next time its namespace is written.
1257    #[test]
1258    fn nothing_older_than_the_window_survives_a_write() {
1259        let flow = ledger();
1260        let ancient = day_of(1_757_000_000_000);
1261        let at = midnight_of(ancient) + 1000;
1262        flow.record("team", at, &push(100, "SHA256:aaa"));
1263        flow.flush(at).unwrap();
1264        assert!(flow.store().day("team", ancient).unwrap().is_some());
1265
1266        let much_later = midnight_of(ancient + RETENTION_DAYS + 1) + 1000;
1267        flow.record("team", much_later, &push(1, "SHA256:aaa"));
1268        flow.flush(much_later).unwrap();
1269        assert_eq!(flow.store().day("team", ancient).unwrap(), None, "aged out");
1270        assert!(flow.store().day("team", day_of(much_later)).unwrap().is_some());
1271    }
1272
1273    /// Distinct principals are exact and de-duplicated; the ceiling says so
1274    /// when it is hit rather than flattening quietly.
1275    #[test]
1276    fn principals_are_exact_and_the_ceiling_announces_itself() {
1277        let flow = ledger();
1278        let now = 1_757_000_000_000;
1279        for _ in 0..5 {
1280            flow.record("team", now, &push(1, "SHA256:aaa"));
1281            flow.record("team", now, &fetch(1, "SHA256:bbb"));
1282        }
1283        let row = flow.today("team", now).unwrap();
1284        assert_eq!(row.distinct_principals(), 2, "ten transfers, two people");
1285        assert!(!row.principals_capped);
1286
1287        let mut wide = FlowDay::default();
1288        for n in 0..PRINCIPAL_CEILING + 10 {
1289            wide.principals.insert(format!("SHA256:{n}"));
1290        }
1291        let mut folded = FlowDay::default();
1292        folded.add(&wide);
1293        assert!(folded.principals_capped, "a count that stopped growing must say so");
1294        assert_eq!(folded.distinct_principals(), PRINCIPAL_CEILING as u64);
1295    }
1296
1297    /// Forgetting a namespace forgets its whole series and its live slot.
1298    #[test]
1299    fn forgetting_a_namespace_forgets_its_flow() {
1300        let flow = ledger();
1301        let now = 1_757_000_000_000;
1302        flow.record("team", now, &push(4096, "SHA256:aaa"));
1303        flow.record("other", now, &push(1, "SHA256:aaa"));
1304        flow.flush(now).unwrap();
1305        assert!(flow.forget("team").unwrap());
1306        assert_eq!(flow.today("team", now), None);
1307        assert!(flow.today("other", now).is_some(), "the other tenant is untouched");
1308    }
1309
1310    /// A transfer that moved nothing is not a row, and an empty namespace name
1311    /// is refused rather than charged to `""`.
1312    #[test]
1313    fn nothing_is_never_written_as_something() {
1314        let flow = ledger();
1315        let now = 1_757_000_000_000;
1316        flow.record("team", now, &Transfer::default());
1317        flow.record("", now, &push(4096, "SHA256:aaa"));
1318        assert_eq!(flow.today("team", now), None);
1319        assert_eq!(flow.today("", now), None);
1320        assert_eq!(flow.flush(now).unwrap(), 0, "nothing to write");
1321    }
1322
1323    /// The date renderer, against the two dates in this file's fixtures and the
1324    /// epoch itself.
1325    #[test]
1326    fn the_date_renderer_is_utc_and_floors_before_the_epoch() {
1327        assert_eq!(iso8601_utc(0), "1970-01-01T00:00:00Z");
1328        assert_eq!(iso8601_utc(1_757_000_000_000), "2025-09-04T15:33:20Z");
1329        assert_eq!(iso8601_utc(1_789_041_600_000), "2026-09-10T12:00:00Z");
1330        assert_eq!(iso8601_utc(-1), "1969-12-31T23:59:59Z", "one millisecond before the epoch");
1331        // A leap day, which is where a table-free formula goes wrong if it can.
1332        assert_eq!(iso8601_utc(1_709_164_800_000), "2024-02-29T00:00:00Z");
1333    }
1334
1335    /// The day arithmetic, including before the epoch, where truncation toward
1336    /// zero would put two different days in one bucket.
1337    #[test]
1338    fn the_day_arithmetic_floors() {
1339        assert_eq!(day_of(0), 0);
1340        assert_eq!(day_of(DAY_MS - 1), 0);
1341        assert_eq!(day_of(DAY_MS), 1);
1342        assert_eq!(day_of(-1), -1, "the last millisecond of 1969 is not day 0");
1343        assert_eq!(midnight_of(day_of(1_757_000_000_000)), 1_756_944_000_000);
1344    }
1345}