Skip to main content

allsource_core/infrastructure/web/
read_cost.rs

1//! Read cost of `GET /api/v1/events/query`: per-request facts, walks and
2//! aggregates. Design sections 6.3 and 10.4.
3//!
4//! The query handler attaches [`ReadCostFacts`] to its response. [`record`]
5//! sits inside [`super::response_limit::bounded`], so it measures a body over
6//! the 16 MiB bound before the bound replaces it. Nothing is persisted.
7
8use crate::{
9    application::dto::QueryEventsRequest,
10    domain::{
11        entities::egress::MAX_RESPONSE_BYTES,
12        stream_class::{is_class, stream_class_for_tenant},
13    },
14    infrastructure::{observability::metrics::MetricsRegistry, security::middleware::Admin},
15};
16use axum::{
17    Json,
18    body::HttpBody,
19    extract::{Extension, Query, Request, State},
20    http::{HeaderMap, StatusCode},
21    middleware::Next,
22    response::{IntoResponse, Response},
23};
24use chrono::{DateTime, Utc};
25use serde::{Deserialize, Serialize};
26use serde_json::{Value, json};
27use sha2::{Digest, Sha256};
28use std::{
29    collections::{BTreeSet, HashMap, HashSet},
30    sync::{
31        Arc, LazyLock, Mutex, MutexGuard, PoisonError,
32        atomic::{AtomicBool, Ordering},
33    },
34    time::{Duration, Instant},
35};
36
37const CALLER_HEADER: &str = "x-allsource-caller";
38const READ_ID_HEADER: &str = "x-allsource-read-id";
39const INVALID: &str = "invalid";
40const OTHER: &str = "other";
41
42const IN_FLIGHT_CAP: usize = 4_096;
43const WALKS_PER_TENANT: usize = 256;
44const WALK_IDLE: Duration = Duration::from_secs(30);
45const SWEEP_EVERY: Duration = Duration::from_secs(10);
46const CLASSES_PER_TENANT: usize = 128;
47const CALLERS_PER_TENANT: usize = 256;
48const TENANTS: usize = 128;
49const LABEL_CAP: usize = 256;
50const THRESHOLD_EVERY: Duration = Duration::from_mins(1);
51const THRESHOLD_KEYS: usize = 4_096;
52const THRESHOLD_PAGES: u64 = 20;
53const THRESHOLD_MATCHED: usize = 50_000;
54
55/// Which requests a read is: the shape decides what counts as a whole read.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Shape {
58    Whole,
59    Latest,
60    CountProbe,
61    Partial,
62}
63
64impl Shape {
65    pub fn of(served_limit: usize, descending: bool, since_set: bool, entity_set: bool) -> Self {
66        if served_limit == 0 {
67            Self::CountProbe
68        } else if descending && served_limit == 1 {
69            Self::Latest
70        } else if since_set || entity_set {
71            Self::Partial
72        } else {
73            Self::Whole
74        }
75    }
76}
77
78/// What one query page answered, as the handler saw it.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct QueryCounts {
81    pub matched: usize,
82    pub returned: usize,
83    pub served_limit: usize,
84    pub offset: usize,
85    pub has_more: bool,
86    pub since_set: bool,
87    pub entity_set: bool,
88    pub shape: Shape,
89}
90
91/// The read a page belongs to, before any header is considered.
92#[derive(Debug, Clone)]
93pub struct ReadFacts {
94    pub tenant: String,
95    pub stream_class: String,
96    pub counts: QueryCounts,
97}
98
99/// What a query request asked for, fixed before the store answers.
100#[derive(Debug, Clone)]
101pub struct ReadScope {
102    class: String,
103    since_set: bool,
104    entity_set: bool,
105    served_limit: usize,
106    offset: usize,
107    descending: bool,
108}
109
110impl ReadScope {
111    pub fn of(
112        req: &QueryEventsRequest,
113        tenant: Option<&str>,
114        offset: usize,
115        descending: bool,
116        max_page: usize,
117    ) -> Self {
118        Self {
119            class: stream_class_for_tenant(
120                tenant,
121                req.entity_id.as_deref(),
122                req.event_type_prefix.as_deref(),
123                req.event_type.as_deref(),
124            ),
125            since_set: req.since.is_some(),
126            entity_set: req.entity_id.is_some(),
127            served_limit: req.limit.unwrap_or(max_page).min(max_page),
128            offset,
129            descending,
130        }
131    }
132
133    /// Facts for a page that matched `matched` events and returned `returned`.
134    pub fn facts(
135        self,
136        tenant: String,
137        matched: usize,
138        returned: usize,
139        has_more: bool,
140    ) -> ReadFacts {
141        let shape = Shape::of(
142            self.served_limit,
143            self.descending,
144            self.since_set,
145            self.entity_set,
146        );
147        ReadFacts {
148            tenant,
149            stream_class: self.class,
150            counts: QueryCounts {
151                matched,
152                returned,
153                served_limit: self.served_limit,
154                offset: self.offset,
155                has_more,
156                since_set: self.since_set,
157                entity_set: self.entity_set,
158                shape,
159            },
160        }
161    }
162}
163
164/// A header that failed its pattern, kept by name and length only.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub struct RejectedHeader {
167    pub name: &'static str,
168    pub length: usize,
169}
170
171/// Attached to a query response as an extension. Removed by [`record`].
172#[derive(Debug, Clone)]
173pub struct ReadCostFacts {
174    pub read: ReadFacts,
175    /// `Some("invalid")` when the header is present and fails its pattern.
176    pub caller: Option<String>,
177    /// `None` when absent or invalid: an invalid read id counts as absent.
178    pub read_id: Option<String>,
179    pub rejected: Vec<RejectedHeader>,
180}
181
182impl ReadCostFacts {
183    pub fn from_headers(read: ReadFacts, headers: &HeaderMap) -> Self {
184        let mut rejected = Vec::new();
185        let caller = headers.get(CALLER_HEADER).map(|value| {
186            let text = value.to_str().unwrap_or_default();
187            if is_class(text) {
188                text.to_owned()
189            } else {
190                rejected.push(RejectedHeader {
191                    name: "caller",
192                    length: value.as_bytes().len(),
193                });
194                INVALID.to_owned()
195            }
196        });
197        // The gateway forwards a rejected value as `invalid` and has already
198        // logged and counted it.
199        let read_id = headers.get(READ_ID_HEADER).and_then(|value| {
200            if value.as_bytes() == INVALID.as_bytes() {
201                return None;
202            }
203            let text = value.to_str().ok().filter(|text| is_read_id(text));
204            if text.is_none() {
205                rejected.push(RejectedHeader {
206                    name: "read_id",
207                    length: value.as_bytes().len(),
208                });
209            }
210            text.map(str::to_owned)
211        });
212        Self {
213            read,
214            caller,
215            read_id,
216            rejected,
217        }
218    }
219}
220
221fn is_read_id(text: &str) -> bool {
222    text.len() == 16 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
223}
224
225/// How a page ended, from its status and final body length.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum Outcome {
228    Complete,
229    HasMore,
230    NotModified,
231    TooLarge,
232}
233
234impl Outcome {
235    pub fn of(status: StatusCode, body_bytes: u64, has_more: bool) -> Self {
236        if body_bytes > MAX_RESPONSE_BYTES {
237            Self::TooLarge
238        } else if status == StatusCode::NOT_MODIFIED {
239            Self::NotModified
240        } else if has_more {
241            Self::HasMore
242        } else {
243            Self::Complete
244        }
245    }
246
247    fn as_str(self) -> &'static str {
248        match self {
249            Self::Complete => "complete",
250            Self::HasMore => "has_more",
251            Self::NotModified => "not_modified",
252            Self::TooLarge => "too_large",
253        }
254    }
255}
256
257/// Exact counts for one stream class within one tenant.
258#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
259pub struct ClassRow {
260    pub logical_reads: u64,
261    pub pages: u64,
262    pub whole_reads: u64,
263    pub single_truncated: u64,
264    pub walk_abandoned: u64,
265    pub walk_evicted: u64,
266    pub matched_sum: u64,
267    pub matched_max: u64,
268    pub max_pages_per_walk: u64,
269}
270
271/// Counts for one caller and stream class within one tenant. A row created by
272/// replacing another inherits that row's counts and is `approximate`; so is a
273/// row that counted a body whose length was not known exactly.
274#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
275pub struct CallerRow {
276    pub logical_reads: u64,
277    pub pages: u64,
278    pub whole_reads: u64,
279    pub body_bytes: u64,
280    pub single_truncated: u64,
281    pub walk_abandoned: u64,
282    pub approximate: bool,
283    pub first_seen: Option<DateTime<Utc>>,
284    pub last_seen: Option<DateTime<Utc>>,
285}
286
287#[derive(Debug)]
288struct Walk {
289    class: String,
290    caller: Option<String>,
291    pages: u64,
292    last_seen: Instant,
293}
294
295#[derive(Debug, Default)]
296struct Tenant {
297    last_active: u64,
298    /// Rows cover only pages since then: `Tables::since` while no tenant has
299    /// been evicted, since a tenant first seen then had no earlier pages;
300    /// otherwise the time it entered, as it may have been evicted before.
301    tracked_since: Option<DateTime<Utc>>,
302    classes: HashMap<String, ClassRow>,
303    callers: HashMap<(Option<String>, String), CallerRow>,
304}
305
306#[derive(Debug, Default)]
307struct Tables {
308    /// When recording last started: the process start, or the switch turning
309    /// recording back on, which clears every table.
310    since: DateTime<Utc>,
311    tick: u64,
312    /// A tenant has been pushed out of `tenants` since `since`.
313    tenant_evicted: bool,
314    tenants: HashMap<String, Tenant>,
315    walks: HashMap<(String, String), Walk>,
316    /// Every walk in `walks` by last seen, so the oldest is found without a scan.
317    walks_by_age: BTreeSet<(Instant, String, String)>,
318    /// Each tenant's walks by last seen, keyed by read id.
319    walks_per_tenant: HashMap<String, BTreeSet<(Instant, String)>>,
320    labels: HashSet<String>,
321    label_overflow_logged: bool,
322    last_sweep: Option<Instant>,
323    threshold_logged: HashMap<(String, String, String), Instant>,
324    header_logged: HashMap<&'static str, Instant>,
325    /// Series bumps and log lines queued under the lock and emitted by
326    /// [`ReadCost::unlock`] after it is released. Empty whenever unlocked.
327    effects: Vec<Effect>,
328}
329
330#[derive(Debug)]
331enum Effect {
332    Page {
333        label: String,
334        outcome: &'static str,
335    },
336    Matched {
337        label: String,
338        matched: u64,
339    },
340    Whole {
341        label: String,
342    },
343    Truncated {
344        label: String,
345        kind: &'static str,
346    },
347    LabelOverflow {
348        log: bool,
349    },
350    HeaderInvalid {
351        header: &'static str,
352        length: usize,
353        log: bool,
354    },
355    Threshold {
356        fingerprint: String,
357        caller: String,
358        class: String,
359        reason: &'static str,
360        pages: u64,
361        matched: usize,
362    },
363}
364
365impl Tables {
366    fn insert_walk(&mut self, key: (String, String), walk: Walk) {
367        self.remove_walk(&key);
368        let last_seen = walk.last_seen;
369        self.walks_by_age
370            .insert((last_seen, key.0.clone(), key.1.clone()));
371        self.walks_per_tenant
372            .entry(key.0.clone())
373            .or_default()
374            .insert((last_seen, key.1.clone()));
375        self.walks.insert(key, walk);
376    }
377
378    fn remove_walk(&mut self, key: &(String, String)) -> Option<Walk> {
379        let walk = self.walks.remove(key)?;
380        self.walks_by_age
381            .remove(&(walk.last_seen, key.0.clone(), key.1.clone()));
382        if let Some(own) = self.walks_per_tenant.get_mut(&key.0) {
383            own.remove(&(walk.last_seen, key.1.clone()));
384            if own.is_empty() {
385                self.walks_per_tenant.remove(&key.0);
386            }
387        }
388        Some(walk)
389    }
390
391    fn clear_walks(&mut self) {
392        self.walks.clear();
393        self.walks_by_age.clear();
394        self.walks_per_tenant.clear();
395    }
396}
397
398/// Process-wide read-cost state, shared by the query handler's layer and the
399/// admin switch.
400pub struct ReadCost {
401    enabled: AtomicBool,
402    metrics: Arc<MetricsRegistry>,
403    tables: Mutex<Tables>,
404}
405
406impl ReadCost {
407    pub fn new(metrics: Arc<MetricsRegistry>, enabled: bool) -> Arc<Self> {
408        Arc::new(Self {
409            enabled: AtomicBool::new(enabled),
410            metrics,
411            tables: Mutex::new(Tables {
412                since: Utc::now(),
413                ..Tables::default()
414            }),
415        })
416    }
417
418    /// Enabled unless `ALLSOURCE_READ_COST=off` at boot.
419    pub fn from_env(metrics: Arc<MetricsRegistry>) -> Arc<Self> {
420        let disabled = std::env::var("ALLSOURCE_READ_COST")
421            .is_ok_and(|value| value.eq_ignore_ascii_case("off"));
422        Self::new(metrics, !disabled)
423    }
424
425    pub fn enabled(&self) -> bool {
426        self.enabled.load(Ordering::Relaxed)
427    }
428
429    /// Turning recording off drops every live walk, since pages it skips can
430    /// neither continue nor abandon one. Turning it back on clears every table
431    /// and restarts `since`, so no row spans the gap.
432    pub fn set_enabled(&self, enabled: bool) {
433        let mut tables = self.lock();
434        let was = self.enabled.swap(enabled, Ordering::Relaxed);
435        if !enabled {
436            tables.clear_walks();
437        } else if !was {
438            *tables = Tables {
439                since: Utc::now(),
440                // Prometheus series outlive the tables, and the label cap counts them.
441                labels: std::mem::take(&mut tables.labels),
442                label_overflow_logged: tables.label_overflow_logged,
443                ..Tables::default()
444            };
445        }
446    }
447
448    /// Caller and class rows for one tenant, ordered by `order` and cut to
449    /// `limit`, with whether recording is on and the tenant is in the table.
450    pub fn read_costs(&self, tenant: &str, order: RowOrder, limit: usize) -> ReadCostsResponse {
451        let tables = self.lock();
452        let enabled = self.enabled();
453        let since = tables.since;
454        let Some(state) = tables.tenants.get(tenant) else {
455            return ReadCostsResponse {
456                callers: Vec::new(),
457                classes: Vec::new(),
458                enabled,
459                since,
460                instance_id: instance_id(),
461                tenant_tracked: false,
462                tenant_since: None,
463            };
464        };
465        let tenant_since = state.tracked_since;
466        let mut callers: Vec<CallerCost> = state
467            .callers
468            .iter()
469            .map(|((caller, class), counts)| CallerCost {
470                caller: caller.clone().unwrap_or_else(|| UNATTRIBUTED.to_owned()),
471                stream_class: class.clone(),
472                counts: *counts,
473            })
474            .collect();
475        let mut classes: Vec<ClassCost> = state
476            .classes
477            .iter()
478            .map(|(class, counts)| ClassCost {
479                stream_class: class.clone(),
480                counts: *counts,
481            })
482            .collect();
483        drop(tables);
484        callers.sort_by(|a, b| {
485            caller_key(order, &b.counts)
486                .cmp(&caller_key(order, &a.counts))
487                .then_with(|| (&a.caller, &a.stream_class).cmp(&(&b.caller, &b.stream_class)))
488        });
489        callers.truncate(limit);
490        classes.sort_by(|a, b| {
491            class_key(order, &b.counts)
492                .cmp(&class_key(order, &a.counts))
493                .then_with(|| a.stream_class.cmp(&b.stream_class))
494        });
495        classes.truncate(limit);
496        ReadCostsResponse {
497            callers,
498            classes,
499            enabled,
500            since,
501            instance_id: instance_id(),
502            tenant_tracked: true,
503            tenant_since,
504        }
505    }
506
507    fn lock(&self) -> MutexGuard<'_, Tables> {
508        self.tables.lock().unwrap_or_else(PoisonError::into_inner)
509    }
510
511    /// Releases the lock, then emits what the update queued.
512    fn unlock(&self, mut tables: MutexGuard<'_, Tables>) {
513        let effects = std::mem::take(&mut tables.effects);
514        drop(tables);
515        let metrics = self.metrics.read_cost();
516        for effect in effects {
517            match effect {
518                Effect::Page { label, outcome } => metrics
519                    .read_pages_total
520                    .with_label_values(&[label.as_str(), outcome])
521                    .inc(),
522                Effect::Matched { label, matched } => metrics
523                    .read_events_matched_total
524                    .with_label_values(&[label.as_str()])
525                    .inc_by(matched),
526                Effect::Whole { label } => metrics
527                    .read_whole_reads_total
528                    .with_label_values(&[label.as_str()])
529                    .inc(),
530                Effect::Truncated { label, kind } => metrics
531                    .read_truncated_total
532                    .with_label_values(&[label.as_str(), kind])
533                    .inc(),
534                Effect::LabelOverflow { log } => {
535                    metrics
536                        .read_label_overflow_total
537                        .with_label_values(&["stream_class"])
538                        .inc();
539                    if log {
540                        tracing::warn!(event = "read_label_overflow", label = "stream_class");
541                    }
542                }
543                Effect::HeaderInvalid {
544                    header,
545                    length,
546                    log,
547                } => {
548                    metrics
549                        .read_header_invalid_total
550                        .with_label_values(&[header])
551                        .inc();
552                    if log {
553                        tracing::warn!(event = "read_header_invalid", header, length);
554                    }
555                }
556                Effect::Threshold {
557                    fingerprint,
558                    caller,
559                    class,
560                    reason,
561                    pages,
562                    matched,
563                } => tracing::warn!(
564                    event = "read_cost_threshold",
565                    tenant_fingerprint = %fingerprint,
566                    caller = %caller,
567                    stream_class = %class,
568                    reason,
569                    pages,
570                    matched,
571                ),
572            }
573        }
574    }
575
576    /// Folds one page into the walks, aggregates, series and logs.
577    pub fn observe(&self, now: Instant, facts: &ReadCostFacts, outcome: Outcome, body_bytes: u64) {
578        self.observe_sized(now, facts, outcome, body_bytes, true);
579    }
580
581    /// [`Self::observe`] for a body whose length may be only a lower bound.
582    fn observe_sized(
583        &self,
584        now: Instant,
585        facts: &ReadCostFacts,
586        outcome: Outcome,
587        body_bytes: u64,
588        bytes_exact: bool,
589    ) {
590        let wall = Utc::now();
591        let mut tables = self.lock();
592        if !self.enabled() {
593            return;
594        }
595        self.sweep_if_due(&mut tables, now);
596        log_rejected(&mut tables, now, &facts.rejected);
597
598        let read = &facts.read;
599        let counts = read.counts;
600        let tenant = read.tenant.as_str();
601        let class = read.stream_class.as_str();
602        let caller = facts.caller.as_deref();
603        let who = Who {
604            tenant,
605            caller,
606            class,
607        };
608        let whole = counts.shape == Shape::Whole;
609        let single = is_single_truncated(facts);
610
611        let mut logical = true;
612        let mut pages = 1;
613        if let Some(read_id) = facts.read_id.as_deref() {
614            let key = (tenant.to_owned(), read_id.to_owned());
615            let idle = tables
616                .walks
617                .get(&key)
618                .is_some_and(|walk| now.saturating_duration_since(walk.last_seen) > WALK_IDLE);
619            if idle && let Some(walk) = tables.remove_walk(&key) {
620                self.abandon(&mut tables, now, tenant, &walk);
621            }
622            if let Some(mut walk) = tables.remove_walk(&key) {
623                logical = false;
624                pages = walk.pages + 1;
625                if counts.has_more {
626                    walk.pages = pages;
627                    walk.last_seen = now;
628                    tables.insert_walk(key, walk);
629                }
630            } else if counts.has_more {
631                self.make_room(&mut tables, tenant);
632                tables.insert_walk(
633                    key,
634                    Walk {
635                        class: class.to_owned(),
636                        caller: caller.map(str::to_owned),
637                        pages: 1,
638                        last_seen: now,
639                    },
640                );
641            }
642        }
643
644        let whole = whole && logical;
645        let label = self.admit_label(&mut tables, class);
646        let state = tenant_mut(&mut tables, tenant);
647        let row = class_row(state, class);
648        row.pages += 1;
649        row.logical_reads += u64::from(logical);
650        row.whole_reads += u64::from(whole);
651        row.single_truncated += u64::from(single);
652        row.matched_sum += wide(counts.matched);
653        row.matched_max = row.matched_max.max(wide(counts.matched));
654        row.max_pages_per_walk = row.max_pages_per_walk.max(pages);
655        let row = caller_row(state, caller.map(str::to_owned), class);
656        row.pages += 1;
657        row.logical_reads += u64::from(logical);
658        row.whole_reads += u64::from(whole);
659        row.single_truncated += u64::from(single);
660        row.body_bytes += body_bytes;
661        row.approximate |= !bytes_exact;
662        row.first_seen.get_or_insert(wall);
663        row.last_seen = Some(wall);
664
665        if whole {
666            tables.effects.push(Effect::Whole {
667                label: label.clone(),
668            });
669        }
670        if single {
671            truncated(&mut tables, &label, "single");
672        }
673        tables.effects.push(Effect::Matched {
674            label: label.clone(),
675            matched: wide(counts.matched),
676        });
677        tables.effects.push(Effect::Page {
678            label,
679            outcome: outcome.as_str(),
680        });
681
682        if pages > THRESHOLD_PAGES {
683            threshold(&mut tables, now, who, "walk_pages", pages, counts.matched);
684        }
685        if counts.matched > THRESHOLD_MATCHED {
686            threshold(
687                &mut tables,
688                now,
689                who,
690                "matched_pages",
691                pages,
692                counts.matched,
693            );
694        }
695        if single && caller.is_some() {
696            threshold(
697                &mut tables,
698                now,
699                who,
700                "single_truncated",
701                pages,
702                counts.matched,
703            );
704        }
705        self.unlock(tables);
706    }
707
708    /// Ends every walk idle for more than `WALK_IDLE` as abandoned. Does
709    /// nothing while recording is off.
710    pub fn sweep(&self, now: Instant) {
711        let mut tables = self.lock();
712        if !self.enabled() {
713            return;
714        }
715        self.sweep_locked(&mut tables, now);
716        self.unlock(tables);
717    }
718
719    fn sweep_if_due(&self, tables: &mut Tables, now: Instant) {
720        if tables
721            .last_sweep
722            .is_some_and(|last| now.saturating_duration_since(last) < SWEEP_EVERY)
723        {
724            return;
725        }
726        self.sweep_locked(tables, now);
727    }
728
729    fn sweep_locked(&self, tables: &mut Tables, now: Instant) {
730        tables.last_sweep = Some(now);
731        let idle: Vec<(String, String)> = tables
732            .walks_by_age
733            .iter()
734            .take_while(|(last_seen, _, _)| now.saturating_duration_since(*last_seen) > WALK_IDLE)
735            .map(|(_, tenant, read_id)| (tenant.clone(), read_id.clone()))
736            .collect();
737        for key in idle {
738            if let Some(walk) = tables.remove_walk(&key) {
739                self.abandon(tables, now, &key.0, &walk);
740            }
741        }
742    }
743
744    fn abandon(&self, tables: &mut Tables, now: Instant, tenant: &str, walk: &Walk) {
745        let label = self.admit_label(tables, &walk.class);
746        if let Some(state) = tables.tenants.get_mut(tenant) {
747            class_row(state, &walk.class).walk_abandoned += 1;
748            caller_row(state, walk.caller.clone(), &walk.class).walk_abandoned += 1;
749        }
750        truncated(tables, &label, "walk_abandoned");
751        let who = Who {
752            tenant,
753            caller: walk.caller.as_deref(),
754            class: &walk.class,
755        };
756        threshold(tables, now, who, "walk_abandoned", walk.pages, 0);
757    }
758
759    /// Evicts `tenant`'s least recently seen walk when it holds
760    /// [`WALKS_PER_TENANT`], else the table's least recently seen walk when
761    /// the table is full, so one tenant cannot push out another's walks. An
762    /// evicted walk is `walk_evicted`, never `walk_abandoned`. Neither an
763    /// eviction nor an abandon marks a tenant active.
764    fn make_room(&self, tables: &mut Tables, tenant: &str) {
765        let own = tables.walks_per_tenant.get(tenant);
766        let oldest = if let Some(own) = own.filter(|own| own.len() >= WALKS_PER_TENANT) {
767            own.first()
768                .map(|(_, read_id)| (tenant.to_owned(), read_id.clone()))
769        } else if tables.walks.len() >= IN_FLIGHT_CAP {
770            tables
771                .walks_by_age
772                .first()
773                .map(|(_, t, read_id)| (t.clone(), read_id.clone()))
774        } else {
775            None
776        };
777        let Some(key) = oldest else { return };
778        if let Some(walk) = tables.remove_walk(&key) {
779            let label = self.admit_label(tables, &walk.class);
780            if let Some(state) = tables.tenants.get_mut(&key.0) {
781                class_row(state, &walk.class).walk_evicted += 1;
782            }
783            truncated(tables, &label, "walk_evicted");
784        }
785    }
786
787    /// The Prometheus label for `class`: the class itself while the process
788    /// has room for it, else `other`.
789    fn admit_label(&self, tables: &mut Tables, class: &str) -> String {
790        if tables.labels.contains(class) {
791            return class.to_owned();
792        }
793        if tables.labels.len() < LABEL_CAP {
794            tables.labels.insert(class.to_owned());
795            return class.to_owned();
796        }
797        let log = !tables.label_overflow_logged;
798        tables.label_overflow_logged = true;
799        tables.effects.push(Effect::LabelOverflow { log });
800        OTHER.to_owned()
801    }
802}
803
804fn truncated(tables: &mut Tables, label: &str, kind: &'static str) {
805    tables.effects.push(Effect::Truncated {
806        label: label.to_owned(),
807        kind,
808    });
809}
810
811/// A walk page's tenant, caller and stream class, for log keys.
812#[derive(Clone, Copy)]
813struct Who<'a> {
814    tenant: &'a str,
815    caller: Option<&'a str>,
816    class: &'a str,
817}
818
819/// Single truncated per design 4: no read id, no since, no entity, offset 0,
820/// a served limit of two or more, and a full page with more behind it.
821fn is_single_truncated(facts: &ReadCostFacts) -> bool {
822    let counts = facts.read.counts;
823    facts.read_id.is_none()
824        && !counts.since_set
825        && !counts.entity_set
826        && counts.offset == 0
827        && counts.served_limit >= 2
828        && counts.returned == counts.served_limit
829        && counts.has_more
830}
831
832fn tenant_mut<'a>(tables: &'a mut Tables, tenant: &str) -> &'a mut Tenant {
833    tables.tick += 1;
834    let tick = tables.tick;
835    if !tables.tenants.contains_key(tenant)
836        && tables.tenants.len() >= TENANTS
837        && let Some(coldest) = tables
838            .tenants
839            .iter()
840            .min_by_key(|(_, state)| state.last_active)
841            .map(|(name, _)| name.clone())
842    {
843        tables.tenants.remove(&coldest);
844        tables.tenant_evicted = true;
845    }
846    let first_seen = if tables.tenant_evicted {
847        Utc::now()
848    } else {
849        tables.since
850    };
851    let state = tables.tenants.entry(tenant.to_owned()).or_default();
852    state.last_active = tick;
853    state.tracked_since.get_or_insert(first_seen);
854    state
855}
856
857fn class_row<'a>(state: &'a mut Tenant, class: &str) -> &'a mut ClassRow {
858    let key = if state.classes.contains_key(class) || state.classes.len() < CLASSES_PER_TENANT {
859        class
860    } else {
861        OTHER
862    };
863    state.classes.entry(key.to_owned()).or_default()
864}
865
866fn caller_row<'a>(state: &'a mut Tenant, caller: Option<String>, class: &str) -> &'a mut CallerRow {
867    let key = (caller, class.to_owned());
868    if !state.callers.contains_key(&key) && state.callers.len() >= CALLERS_PER_TENANT {
869        let coldest = state
870            .callers
871            .iter()
872            .min_by_key(|(_, row)| row.body_bytes)
873            .map(|(k, row)| (k.clone(), *row));
874        if let Some((victim, row)) = coldest {
875            state.callers.remove(&victim);
876            state.callers.insert(
877                key.clone(),
878                CallerRow {
879                    approximate: true,
880                    ..row
881                },
882            );
883        }
884    }
885    state.callers.entry(key).or_default()
886}
887
888fn threshold(
889    tables: &mut Tables,
890    now: Instant,
891    who: Who<'_>,
892    reason: &'static str,
893    pages: u64,
894    matched: usize,
895) {
896    let key = (
897        fingerprint(who.tenant),
898        who.caller.unwrap_or("none").to_owned(),
899        who.class.to_owned(),
900    );
901    if tables
902        .threshold_logged
903        .get(&key)
904        .is_some_and(|last| now.saturating_duration_since(*last) < THRESHOLD_EVERY)
905    {
906        return;
907    }
908    if !tables.threshold_logged.contains_key(&key)
909        && tables.threshold_logged.len() >= THRESHOLD_KEYS
910    {
911        tables
912            .threshold_logged
913            .retain(|_, last| now.saturating_duration_since(*last) < THRESHOLD_EVERY);
914        if tables.threshold_logged.len() >= THRESHOLD_KEYS {
915            return;
916        }
917    }
918    tables.threshold_logged.insert(key.clone(), now);
919    let (fingerprint, caller, class) = key;
920    tables.effects.push(Effect::Threshold {
921        fingerprint,
922        caller,
923        class,
924        reason,
925        pages,
926        matched,
927    });
928}
929
930fn log_rejected(tables: &mut Tables, now: Instant, rejected: &[RejectedHeader]) {
931    for header in rejected {
932        let log = tables
933            .header_logged
934            .get(header.name)
935            .is_none_or(|last| now.saturating_duration_since(*last) >= THRESHOLD_EVERY);
936        if log {
937            tables.header_logged.insert(header.name, now);
938        }
939        tables.effects.push(Effect::HeaderInvalid {
940            header: header.name,
941            length: header.length,
942            log,
943        });
944    }
945}
946
947/// Six bytes of SHA-256 over the tenant: the only form a log line carries.
948fn fingerprint(tenant: &str) -> String {
949    hex::encode(&Sha256::digest(tenant.as_bytes())[..6])
950}
951
952fn wide(value: usize) -> u64 {
953    u64::try_from(value).unwrap_or(u64::MAX)
954}
955
956/// Pages and the sweeper both read the tokio clock, so a paused test clock
957/// drives both.
958fn clock() -> Instant {
959    tokio::time::Instant::now().into_std()
960}
961
962/// Sweeps every `SWEEP_EVERY` until the last `Arc<ReadCost>` drops.
963pub fn spawn_sweeper(read_cost: &Arc<ReadCost>) -> tokio::task::JoinHandle<()> {
964    let read_cost = Arc::downgrade(read_cost);
965    tokio::spawn(async move {
966        let mut ticks = tokio::time::interval(SWEEP_EVERY);
967        ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
968        loop {
969            ticks.tick().await;
970            let Some(read_cost) = read_cost.upgrade() else {
971                return;
972            };
973            read_cost.sweep(clock());
974        }
975    })
976}
977
978/// Layer inside [`super::response_limit::bounded`]: reads the facts a query
979/// handler attached and records them. Responses without facts pass untouched.
980pub async fn record(
981    State(read_cost): State<Arc<ReadCost>>,
982    request: Request,
983    next: Next,
984) -> Response {
985    let mut response = next.run(request).await;
986    let Some(facts) = response.extensions_mut().remove::<ReadCostFacts>() else {
987        return response;
988    };
989    if read_cost.enabled() {
990        let hint = response.body().size_hint();
991        let body_bytes = hint.exact().unwrap_or_else(|| hint.lower());
992        let outcome = Outcome::of(response.status(), body_bytes, facts.read.counts.has_more);
993        read_cost.observe_sized(clock(), &facts, outcome, body_bytes, hint.exact().is_some());
994    }
995    response
996}
997
998#[derive(Debug, Deserialize)]
999pub struct ReadCostSwitch {
1000    pub enabled: bool,
1001}
1002
1003/// Sort order for `GET /api/v1/read-costs`.
1004#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
1005#[serde(rename_all = "lowercase")]
1006pub enum RowOrder {
1007    #[default]
1008    Bytes,
1009    Pages,
1010    Matched,
1011    Whole,
1012    Truncated,
1013}
1014
1015#[derive(Debug, Deserialize)]
1016pub struct ReadCostsParams {
1017    pub tenant_id: Option<String>,
1018    pub limit: Option<usize>,
1019    pub order: Option<RowOrder>,
1020}
1021
1022#[derive(Debug, Serialize)]
1023pub struct CallerCost {
1024    pub caller: String,
1025    pub stream_class: String,
1026    #[serde(flatten)]
1027    pub counts: CallerRow,
1028}
1029
1030#[derive(Debug, Serialize)]
1031pub struct ClassCost {
1032    pub stream_class: String,
1033    #[serde(flatten)]
1034    pub counts: ClassRow,
1035}
1036
1037/// Rows plus what they cover: empty rows mean "no reads" only when recording
1038/// is on and the tenant is tracked.
1039#[derive(Debug, Serialize)]
1040pub struct ReadCostsResponse {
1041    pub callers: Vec<CallerCost>,
1042    pub classes: Vec<ClassCost>,
1043    /// Recording is on now.
1044    pub enabled: bool,
1045    /// When the tables last started empty: process start or recording
1046    /// switched back on.
1047    pub since: DateTime<Utc>,
1048    /// Random per Core process. Rows cover only the pages this process
1049    /// served, so two machines, or one restarted, answer with different ids.
1050    pub instance_id: &'static str,
1051    /// The tenant has rows. `false` for a tenant with no reads since `since`
1052    /// and for one pushed out of the 128-tenant table; the two look alike.
1053    pub tenant_tracked: bool,
1054    /// When the tenant's rows started: `since`, unless a tenant had been
1055    /// pushed out of the table when this one entered, in which case this one
1056    /// may have been pushed out too and its rows start when it came back.
1057    pub tenant_since: Option<DateTime<Utc>>,
1058}
1059
1060static INSTANCE_ID: LazyLock<String> = LazyLock::new(|| uuid::Uuid::new_v4().simple().to_string());
1061
1062fn instance_id() -> &'static str {
1063    INSTANCE_ID.as_str()
1064}
1065
1066const UNATTRIBUTED: &str = "unattributed";
1067const READ_COSTS_DEFAULT_LIMIT: usize = 50;
1068const READ_COSTS_MAX_LIMIT: usize = 256;
1069
1070/// Caller rows carry no matched count, so `matched` orders them by pages.
1071fn caller_key(order: RowOrder, counts: &CallerRow) -> u64 {
1072    match order {
1073        RowOrder::Bytes => counts.body_bytes,
1074        RowOrder::Pages | RowOrder::Matched => counts.pages,
1075        RowOrder::Whole => counts.whole_reads,
1076        RowOrder::Truncated => counts.single_truncated,
1077    }
1078}
1079
1080/// Class rows carry no byte count, so `bytes` orders them by pages.
1081fn class_key(order: RowOrder, counts: &ClassRow) -> u64 {
1082    match order {
1083        RowOrder::Bytes | RowOrder::Pages => counts.pages,
1084        RowOrder::Matched => counts.matched_sum,
1085        RowOrder::Whole => counts.whole_reads,
1086        RowOrder::Truncated => counts.single_truncated,
1087    }
1088}
1089
1090/// `GET /api/v1/read-costs`: the tenant named by the gateway, never another.
1091pub async fn serve_read_costs(
1092    Extension(read_cost): Extension<Arc<ReadCost>>,
1093    Query(params): Query<ReadCostsParams>,
1094) -> Response {
1095    let Some(tenant) = params.tenant_id.filter(|tenant| !tenant.is_empty()) else {
1096        return (
1097            StatusCode::BAD_REQUEST,
1098            Json(json!({ "error": "tenant_id is required" })),
1099        )
1100            .into_response();
1101    };
1102    let limit = params
1103        .limit
1104        .unwrap_or(READ_COSTS_DEFAULT_LIMIT)
1105        .min(READ_COSTS_MAX_LIMIT);
1106    let rows = read_cost.read_costs(&tenant, params.order.unwrap_or_default(), limit);
1107    Json(rows).into_response()
1108}
1109
1110/// `PUT /api/v1/admin/read-cost {"enabled": bool}`. Admin only.
1111pub async fn set_read_cost(
1112    _admin: Admin,
1113    Extension(read_cost): Extension<Arc<ReadCost>>,
1114    Json(switch): Json<ReadCostSwitch>,
1115) -> Json<Value> {
1116    read_cost.set_enabled(switch.enabled);
1117    Json(json!({ "enabled": switch.enabled }))
1118}
1119
1120#[cfg(test)]
1121#[path = "read_cost_tests.rs"]
1122mod read_cost_tests;