Skip to main content

faucet_core/
usage.rs

1//! Per-run usage metering (#704): what a run moved and what it asked its
2//! backends to do, so the CLI can account for cost per pipeline / row /
3//! dataset and enforce run budgets (#703).
4//!
5//! A [`UsageMeter`] is attached to a [`Pipeline`](crate::Pipeline) with
6//! [`Pipeline::with_usage_meter`](crate::Pipeline::with_usage_meter). The
7//! observability decorators count every record and an estimate of its
8//! serialized size; the pre-labelled [`RoundtripRecorder`] each connector
9//! already receives tallies backend round trips by `op` and carries
10//! **cost signals** — backend-reported usage such as BigQuery's bytes
11//! billed or a streaming insert's payload size — into the same meter. A
12//! library caller that attaches no meter pays nothing: counting is skipped
13//! entirely.
14//!
15//! Byte counts are **estimates** of the JSON serialization (no allocation,
16//! one walk over each value) — good enough to attribute cost and enforce a
17//! `max_bytes` budget, never a wire-accurate figure.
18//!
19//! [`RoundtripRecorder`]: crate::observability::RoundtripRecorder
20
21use schemars::JsonSchema;
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24use std::collections::BTreeMap;
25use std::sync::Mutex;
26use std::sync::atomic::{AtomicU64, Ordering};
27
28/// Approximate serialized JSON size of `v`, in bytes, without allocating.
29///
30/// Strings count their UTF-8 length plus quotes (escapes are ignored),
31/// numbers their decimal rendering, containers their brackets, commas and
32/// key quotes/colons. Close enough for accounting and budgets.
33pub fn estimate_json_bytes(v: &Value) -> u64 {
34    match v {
35        Value::Null => 4,
36        Value::Bool(true) => 4,
37        Value::Bool(false) => 5,
38        Value::Number(n) => {
39            if let Some(i) = n.as_i64() {
40                digits_i64(i)
41            } else if let Some(u) = n.as_u64() {
42                digits_u64(u)
43            } else {
44                // Floats: `serde_json` renders the shortest round-trip form;
45                // ~17 significant digits is the upper bound that matters.
46                17
47            }
48        }
49        Value::String(s) => s.len() as u64 + 2,
50        Value::Array(items) => {
51            let inner: u64 = items.iter().map(estimate_json_bytes).sum();
52            inner + 2 + items.len().saturating_sub(1) as u64
53        }
54        Value::Object(map) => {
55            let inner: u64 = map
56                .iter()
57                .map(|(k, val)| k.len() as u64 + 3 + estimate_json_bytes(val))
58                .sum();
59            inner + 2 + map.len().saturating_sub(1) as u64
60        }
61    }
62}
63
64/// Estimated serialized size of a page of records.
65pub fn estimate_page_bytes(records: &[Value]) -> u64 {
66    records.iter().map(estimate_json_bytes).sum()
67}
68
69fn digits_u64(mut u: u64) -> u64 {
70    let mut n = 1;
71    while u >= 10 {
72        u /= 10;
73        n += 1;
74    }
75    n
76}
77
78fn digits_i64(i: i64) -> u64 {
79    if i < 0 {
80        1 + digits_u64(i.unsigned_abs())
81    } else {
82        digits_u64(i as u64)
83    }
84}
85
86/// Which side of the pipeline a round trip or signal came from.
87#[derive(
88    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
89)]
90#[serde(rename_all = "snake_case")]
91pub enum UsageSide {
92    Source,
93    Sink,
94}
95
96impl UsageSide {
97    pub fn as_str(self) -> &'static str {
98        match self {
99            Self::Source => "source",
100            Self::Sink => "sink",
101        }
102    }
103}
104
105/// A backend-reported usage figure a connector learned during the run —
106/// BigQuery's `totalBytesBilled`, the payload size of a streaming insert, a
107/// warehouse's credits — attributed to the connector that reported it.
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
109pub struct CostSignal {
110    /// What was measured: `bytes_billed`, `bytes_processed`, `bytes_streamed`,
111    /// `credits`, … A closed set per connector, documented in its README.
112    pub kind: String,
113    /// The unit of `quantity`: `bytes`, `credits`, `requests`, …
114    pub unit: String,
115    pub quantity: f64,
116    pub side: UsageSide,
117    /// Connector kind (`bigquery`, `s3`, …).
118    pub connector: String,
119}
120
121fn fold_signal(signals: &mut Vec<CostSignal>, signal: CostSignal) {
122    match signals.iter_mut().find(|s| {
123        s.kind == signal.kind
124            && s.unit == signal.unit
125            && s.side == signal.side
126            && s.connector == signal.connector
127    }) {
128        Some(s) => s.quantity += signal.quantity,
129        None => signals.push(signal),
130    }
131}
132
133/// The counters a run accumulated, frozen for reporting and storage.
134#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
135pub struct UsageSnapshot {
136    /// Records the source yielded.
137    pub records_read: u64,
138    /// Records the sink accepted.
139    pub records_written: u64,
140    /// Estimated serialized bytes read.
141    pub bytes_read: u64,
142    /// Estimated serialized bytes written.
143    pub bytes_written: u64,
144    /// Source backend round trips by `op` (`page`, `get`, `list`, …).
145    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
146    pub source_roundtrips: BTreeMap<String, u64>,
147    /// Sink backend round trips by `op` (`insert`, `put`, `merge`, …).
148    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
149    pub sink_roundtrips: BTreeMap<String, u64>,
150    /// Backend-reported usage figures.
151    #[serde(default, skip_serializing_if = "Vec::is_empty")]
152    pub signals: Vec<CostSignal>,
153    /// Rate-limit responses (HTTP 429 and equivalents) the source received.
154    #[serde(default, skip_serializing_if = "is_zero_u64")]
155    pub throttled: u64,
156    /// Seconds the source actually slept because of those responses.
157    #[serde(default, skip_serializing_if = "is_zero_f64")]
158    pub throttle_wait_secs: f64,
159    /// Source-side retries by retry class (`rate_limited`, `http_5xx`,
160    /// `connection`, `timeout`).
161    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
162    pub source_retries: BTreeMap<String, u64>,
163}
164
165fn is_zero_u64(v: &u64) -> bool {
166    *v == 0
167}
168
169fn is_zero_f64(v: &f64) -> bool {
170    *v == 0.0
171}
172
173impl UsageSnapshot {
174    /// Total round trips on `side`.
175    pub fn roundtrips(&self, side: UsageSide) -> u64 {
176        match side {
177            UsageSide::Source => self.source_roundtrips.values().sum(),
178            UsageSide::Sink => self.sink_roundtrips.values().sum(),
179        }
180    }
181
182    /// Fold another snapshot into this one (sums; signals summed per kind,
183    /// unit, side and connector).
184    pub fn merge(&mut self, other: &UsageSnapshot) {
185        self.records_read += other.records_read;
186        self.records_written += other.records_written;
187        self.bytes_read += other.bytes_read;
188        self.bytes_written += other.bytes_written;
189        for (k, v) in &other.source_roundtrips {
190            *self.source_roundtrips.entry(k.clone()).or_default() += v;
191        }
192        for (k, v) in &other.sink_roundtrips {
193            *self.sink_roundtrips.entry(k.clone()).or_default() += v;
194        }
195        for sig in &other.signals {
196            fold_signal(&mut self.signals, sig.clone());
197        }
198        self.throttled += other.throttled;
199        self.throttle_wait_secs += other.throttle_wait_secs;
200        for (k, v) in &other.source_retries {
201            *self.source_retries.entry(k.clone()).or_default() += v;
202        }
203    }
204}
205
206/// The live, thread-safe counters of one run. Cheap to share (`Arc`).
207#[derive(Debug, Default)]
208pub struct UsageMeter {
209    records_read: AtomicU64,
210    records_written: AtomicU64,
211    bytes_read: AtomicU64,
212    bytes_written: AtomicU64,
213    roundtrips: Mutex<BTreeMap<(UsageSide, &'static str), u64>>,
214    signals: Mutex<Vec<CostSignal>>,
215    throttled: AtomicU64,
216    throttle_wait_nanos: AtomicU64,
217    source_retries: Mutex<BTreeMap<&'static str, u64>>,
218}
219
220impl UsageMeter {
221    pub fn new() -> Self {
222        Self::default()
223    }
224
225    /// Count a page the source yielded.
226    pub fn add_read(&self, records: u64, bytes: u64) {
227        self.records_read.fetch_add(records, Ordering::Relaxed);
228        self.bytes_read.fetch_add(bytes, Ordering::Relaxed);
229    }
230
231    /// Count a page the sink accepted.
232    pub fn add_written(&self, records: u64, bytes: u64) {
233        self.records_written.fetch_add(records, Ordering::Relaxed);
234        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
235    }
236
237    /// Count one backend round trip.
238    pub fn add_roundtrip(&self, side: UsageSide, op: &'static str) {
239        let mut map = self.roundtrips.lock().unwrap_or_else(|e| e.into_inner());
240        *map.entry((side, op)).or_default() += 1;
241    }
242
243    /// Record a backend-reported usage figure, summed into the entry with the
244    /// same kind, unit, side and connector.
245    pub fn add_signal(&self, signal: CostSignal) {
246        fold_signal(
247            &mut self.signals.lock().unwrap_or_else(|e| e.into_inner()),
248            signal,
249        );
250    }
251
252    /// Count one rate-limit response the source received.
253    pub fn add_throttled(&self) {
254        self.throttled.fetch_add(1, Ordering::Relaxed);
255    }
256
257    /// Add time the source actually slept on a rate limit.
258    pub fn add_throttle_wait(&self, slept: std::time::Duration) {
259        self.throttle_wait_nanos.fetch_add(
260            u64::try_from(slept.as_nanos()).unwrap_or(u64::MAX),
261            Ordering::Relaxed,
262        );
263    }
264
265    /// Count one source-side retry of `class`.
266    pub fn add_source_retry(&self, class: &'static str) {
267        let mut map = self
268            .source_retries
269            .lock()
270            .unwrap_or_else(|e| e.into_inner());
271        *map.entry(class).or_default() += 1;
272    }
273
274    /// Records the sink accepted so far (what a `max_records` budget checks).
275    pub fn records_written(&self) -> u64 {
276        self.records_written.load(Ordering::Relaxed)
277    }
278
279    /// Estimated bytes the sink accepted so far (what a `max_bytes` budget
280    /// checks).
281    pub fn bytes_written(&self) -> u64 {
282        self.bytes_written.load(Ordering::Relaxed)
283    }
284
285    /// Freeze the counters.
286    pub fn snapshot(&self) -> UsageSnapshot {
287        let mut source_roundtrips = BTreeMap::new();
288        let mut sink_roundtrips = BTreeMap::new();
289        for ((side, op), n) in self
290            .roundtrips
291            .lock()
292            .unwrap_or_else(|e| e.into_inner())
293            .iter()
294        {
295            match side {
296                UsageSide::Source => *source_roundtrips.entry((*op).to_string()).or_default() += n,
297                UsageSide::Sink => *sink_roundtrips.entry((*op).to_string()).or_default() += n,
298            }
299        }
300        UsageSnapshot {
301            records_read: self.records_read.load(Ordering::Relaxed),
302            records_written: self.records_written.load(Ordering::Relaxed),
303            bytes_read: self.bytes_read.load(Ordering::Relaxed),
304            bytes_written: self.bytes_written.load(Ordering::Relaxed),
305            source_roundtrips,
306            sink_roundtrips,
307            signals: self
308                .signals
309                .lock()
310                .unwrap_or_else(|e| e.into_inner())
311                .clone(),
312            throttled: self.throttled.load(Ordering::Relaxed),
313            throttle_wait_secs: std::time::Duration::from_nanos(
314                self.throttle_wait_nanos.load(Ordering::Relaxed),
315            )
316            .as_secs_f64(),
317            source_retries: self
318                .source_retries
319                .lock()
320                .unwrap_or_else(|e| e.into_inner())
321                .iter()
322                .map(|(k, v)| ((*k).to_string(), *v))
323                .collect(),
324        }
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use serde_json::json;
332
333    #[test]
334    fn byte_estimate_tracks_serialized_size() {
335        for v in [
336            json!(null),
337            json!(true),
338            json!(false),
339            json!(0),
340            json!(-42),
341            json!(1234567890123u64),
342            json!("héllo"),
343            json!([]),
344            json!({}),
345            json!([1, 2, 3]),
346            json!({"a": 1, "bb": [true, null], "c": {"d": "x"}}),
347        ] {
348            let exact = serde_json::to_vec(&v).unwrap().len() as u64;
349            assert_eq!(estimate_json_bytes(&v), exact, "{v}");
350        }
351        // Floats are bounded, not exact.
352        assert!(estimate_json_bytes(&json!(1.5)) >= 3);
353        assert_eq!(
354            estimate_page_bytes(&[json!({"a": 1}), json!({"a": 22})]),
355            7 + 8
356        );
357    }
358
359    #[test]
360    fn meter_counts_and_snapshots() {
361        let m = UsageMeter::new();
362        m.add_read(3, 30);
363        m.add_written(2, 20);
364        m.add_roundtrip(UsageSide::Source, "page");
365        m.add_roundtrip(UsageSide::Source, "page");
366        m.add_roundtrip(UsageSide::Sink, "insert");
367        m.add_signal(CostSignal {
368            kind: "bytes_billed".into(),
369            unit: "bytes".into(),
370            quantity: 1024.0,
371            side: UsageSide::Sink,
372            connector: "bigquery".into(),
373        });
374        assert_eq!(m.records_written(), 2);
375        assert_eq!(m.bytes_written(), 20);
376        let s = m.snapshot();
377        assert_eq!(s.records_read, 3);
378        assert_eq!(s.bytes_read, 30);
379        assert_eq!(s.source_roundtrips["page"], 2);
380        assert_eq!(s.sink_roundtrips["insert"], 1);
381        assert_eq!(s.roundtrips(UsageSide::Source), 2);
382        assert_eq!(s.roundtrips(UsageSide::Sink), 1);
383        assert_eq!(s.signals.len(), 1);
384        assert_eq!(UsageSide::Sink.as_str(), "sink");
385
386        let mut total = UsageSnapshot::default();
387        total.merge(&s);
388        total.merge(&s);
389        assert_eq!(total.records_written, 4);
390        assert_eq!(total.source_roundtrips["page"], 4);
391        assert_eq!(total.signals.len(), 1);
392        assert_eq!(total.signals[0].quantity, 2048.0);
393        let round: UsageSnapshot =
394            serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();
395        assert_eq!(round, s);
396    }
397
398    #[test]
399    fn meter_tallies_throttling_and_retries() {
400        let m = UsageMeter::new();
401        let quiet = m.snapshot();
402        let v = serde_json::to_value(&quiet).unwrap();
403        assert!(v.get("throttled").is_none());
404        assert!(v.get("throttle_wait_secs").is_none());
405        assert!(v.get("source_retries").is_none());
406
407        m.add_throttled();
408        m.add_throttled();
409        m.add_throttle_wait(std::time::Duration::from_millis(1500));
410        m.add_throttle_wait(std::time::Duration::from_millis(500));
411        m.add_source_retry("rate_limited");
412        m.add_source_retry("rate_limited");
413        m.add_source_retry("http_5xx");
414        let s = m.snapshot();
415        assert_eq!(s.throttled, 2);
416        assert!((s.throttle_wait_secs - 2.0).abs() < 1e-9);
417        assert_eq!(s.source_retries["rate_limited"], 2);
418        assert_eq!(s.source_retries["http_5xx"], 1);
419
420        let mut total = UsageSnapshot::default();
421        total.merge(&s);
422        total.merge(&s);
423        assert_eq!(total.throttled, 4);
424        assert!((total.throttle_wait_secs - 4.0).abs() < 1e-9);
425        assert_eq!(total.source_retries["rate_limited"], 4);
426        let round: UsageSnapshot =
427            serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();
428        assert_eq!(round, s);
429    }
430
431    #[test]
432    fn signals_are_summed_per_kind_unit_side_and_connector() {
433        let sig = |kind: &str, q: f64| CostSignal {
434            kind: kind.into(),
435            unit: "bytes".into(),
436            quantity: q,
437            side: UsageSide::Sink,
438            connector: "bigquery".into(),
439        };
440        let m = UsageMeter::new();
441        for _ in 0..1000 {
442            m.add_signal(sig("bytes_streamed", 2.0));
443        }
444        m.add_signal(sig("bytes_billed", 5.0));
445        let mut snap = m.snapshot();
446        assert_eq!(snap.signals.len(), 2);
447        assert_eq!(snap.signals[0].quantity, 2000.0);
448        let other = snap.clone();
449        snap.merge(&other);
450        assert_eq!(snap.signals.len(), 2);
451        assert_eq!(snap.signals[0].quantity, 4000.0);
452        assert_eq!(snap.signals[1].quantity, 10.0);
453    }
454}