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
121/// The counters a run accumulated, frozen for reporting and storage.
122#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
123pub struct UsageSnapshot {
124    /// Records the source yielded.
125    pub records_read: u64,
126    /// Records the sink accepted.
127    pub records_written: u64,
128    /// Estimated serialized bytes read.
129    pub bytes_read: u64,
130    /// Estimated serialized bytes written.
131    pub bytes_written: u64,
132    /// Source backend round trips by `op` (`page`, `get`, `list`, …).
133    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
134    pub source_roundtrips: BTreeMap<String, u64>,
135    /// Sink backend round trips by `op` (`insert`, `put`, `merge`, …).
136    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
137    pub sink_roundtrips: BTreeMap<String, u64>,
138    /// Backend-reported usage figures.
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub signals: Vec<CostSignal>,
141    /// Rate-limit responses (HTTP 429 and equivalents) the source received.
142    #[serde(default, skip_serializing_if = "is_zero_u64")]
143    pub throttled: u64,
144    /// Seconds the source actually slept because of those responses.
145    #[serde(default, skip_serializing_if = "is_zero_f64")]
146    pub throttle_wait_secs: f64,
147    /// Source-side retries by retry class (`rate_limited`, `http_5xx`,
148    /// `connection`, `timeout`).
149    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
150    pub source_retries: BTreeMap<String, u64>,
151}
152
153fn is_zero_u64(v: &u64) -> bool {
154    *v == 0
155}
156
157fn is_zero_f64(v: &f64) -> bool {
158    *v == 0.0
159}
160
161impl UsageSnapshot {
162    /// Total round trips on `side`.
163    pub fn roundtrips(&self, side: UsageSide) -> u64 {
164        match side {
165            UsageSide::Source => self.source_roundtrips.values().sum(),
166            UsageSide::Sink => self.sink_roundtrips.values().sum(),
167        }
168    }
169
170    /// Fold another snapshot into this one (sums; signals concatenated).
171    pub fn merge(&mut self, other: &UsageSnapshot) {
172        self.records_read += other.records_read;
173        self.records_written += other.records_written;
174        self.bytes_read += other.bytes_read;
175        self.bytes_written += other.bytes_written;
176        for (k, v) in &other.source_roundtrips {
177            *self.source_roundtrips.entry(k.clone()).or_default() += v;
178        }
179        for (k, v) in &other.sink_roundtrips {
180            *self.sink_roundtrips.entry(k.clone()).or_default() += v;
181        }
182        self.signals.extend(other.signals.iter().cloned());
183        self.throttled += other.throttled;
184        self.throttle_wait_secs += other.throttle_wait_secs;
185        for (k, v) in &other.source_retries {
186            *self.source_retries.entry(k.clone()).or_default() += v;
187        }
188    }
189}
190
191/// The live, thread-safe counters of one run. Cheap to share (`Arc`).
192#[derive(Debug, Default)]
193pub struct UsageMeter {
194    records_read: AtomicU64,
195    records_written: AtomicU64,
196    bytes_read: AtomicU64,
197    bytes_written: AtomicU64,
198    roundtrips: Mutex<BTreeMap<(UsageSide, &'static str), u64>>,
199    signals: Mutex<Vec<CostSignal>>,
200    throttled: AtomicU64,
201    throttle_wait_nanos: AtomicU64,
202    source_retries: Mutex<BTreeMap<&'static str, u64>>,
203}
204
205impl UsageMeter {
206    pub fn new() -> Self {
207        Self::default()
208    }
209
210    /// Count a page the source yielded.
211    pub fn add_read(&self, records: u64, bytes: u64) {
212        self.records_read.fetch_add(records, Ordering::Relaxed);
213        self.bytes_read.fetch_add(bytes, Ordering::Relaxed);
214    }
215
216    /// Count a page the sink accepted.
217    pub fn add_written(&self, records: u64, bytes: u64) {
218        self.records_written.fetch_add(records, Ordering::Relaxed);
219        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
220    }
221
222    /// Count one backend round trip.
223    pub fn add_roundtrip(&self, side: UsageSide, op: &'static str) {
224        let mut map = self.roundtrips.lock().unwrap_or_else(|e| e.into_inner());
225        *map.entry((side, op)).or_default() += 1;
226    }
227
228    /// Record a backend-reported usage figure.
229    pub fn add_signal(&self, signal: CostSignal) {
230        self.signals
231            .lock()
232            .unwrap_or_else(|e| e.into_inner())
233            .push(signal);
234    }
235
236    /// Count one rate-limit response the source received.
237    pub fn add_throttled(&self) {
238        self.throttled.fetch_add(1, Ordering::Relaxed);
239    }
240
241    /// Add time the source actually slept on a rate limit.
242    pub fn add_throttle_wait(&self, slept: std::time::Duration) {
243        self.throttle_wait_nanos.fetch_add(
244            u64::try_from(slept.as_nanos()).unwrap_or(u64::MAX),
245            Ordering::Relaxed,
246        );
247    }
248
249    /// Count one source-side retry of `class`.
250    pub fn add_source_retry(&self, class: &'static str) {
251        let mut map = self
252            .source_retries
253            .lock()
254            .unwrap_or_else(|e| e.into_inner());
255        *map.entry(class).or_default() += 1;
256    }
257
258    /// Records the sink accepted so far (what a `max_records` budget checks).
259    pub fn records_written(&self) -> u64 {
260        self.records_written.load(Ordering::Relaxed)
261    }
262
263    /// Estimated bytes the sink accepted so far (what a `max_bytes` budget
264    /// checks).
265    pub fn bytes_written(&self) -> u64 {
266        self.bytes_written.load(Ordering::Relaxed)
267    }
268
269    /// Freeze the counters.
270    pub fn snapshot(&self) -> UsageSnapshot {
271        let mut source_roundtrips = BTreeMap::new();
272        let mut sink_roundtrips = BTreeMap::new();
273        for ((side, op), n) in self
274            .roundtrips
275            .lock()
276            .unwrap_or_else(|e| e.into_inner())
277            .iter()
278        {
279            match side {
280                UsageSide::Source => *source_roundtrips.entry((*op).to_string()).or_default() += n,
281                UsageSide::Sink => *sink_roundtrips.entry((*op).to_string()).or_default() += n,
282            }
283        }
284        UsageSnapshot {
285            records_read: self.records_read.load(Ordering::Relaxed),
286            records_written: self.records_written.load(Ordering::Relaxed),
287            bytes_read: self.bytes_read.load(Ordering::Relaxed),
288            bytes_written: self.bytes_written.load(Ordering::Relaxed),
289            source_roundtrips,
290            sink_roundtrips,
291            signals: self
292                .signals
293                .lock()
294                .unwrap_or_else(|e| e.into_inner())
295                .clone(),
296            throttled: self.throttled.load(Ordering::Relaxed),
297            throttle_wait_secs: std::time::Duration::from_nanos(
298                self.throttle_wait_nanos.load(Ordering::Relaxed),
299            )
300            .as_secs_f64(),
301            source_retries: self
302                .source_retries
303                .lock()
304                .unwrap_or_else(|e| e.into_inner())
305                .iter()
306                .map(|(k, v)| ((*k).to_string(), *v))
307                .collect(),
308        }
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use serde_json::json;
316
317    #[test]
318    fn byte_estimate_tracks_serialized_size() {
319        for v in [
320            json!(null),
321            json!(true),
322            json!(false),
323            json!(0),
324            json!(-42),
325            json!(1234567890123u64),
326            json!("héllo"),
327            json!([]),
328            json!({}),
329            json!([1, 2, 3]),
330            json!({"a": 1, "bb": [true, null], "c": {"d": "x"}}),
331        ] {
332            let exact = serde_json::to_vec(&v).unwrap().len() as u64;
333            assert_eq!(estimate_json_bytes(&v), exact, "{v}");
334        }
335        // Floats are bounded, not exact.
336        assert!(estimate_json_bytes(&json!(1.5)) >= 3);
337        assert_eq!(
338            estimate_page_bytes(&[json!({"a": 1}), json!({"a": 22})]),
339            7 + 8
340        );
341    }
342
343    #[test]
344    fn meter_counts_and_snapshots() {
345        let m = UsageMeter::new();
346        m.add_read(3, 30);
347        m.add_written(2, 20);
348        m.add_roundtrip(UsageSide::Source, "page");
349        m.add_roundtrip(UsageSide::Source, "page");
350        m.add_roundtrip(UsageSide::Sink, "insert");
351        m.add_signal(CostSignal {
352            kind: "bytes_billed".into(),
353            unit: "bytes".into(),
354            quantity: 1024.0,
355            side: UsageSide::Sink,
356            connector: "bigquery".into(),
357        });
358        assert_eq!(m.records_written(), 2);
359        assert_eq!(m.bytes_written(), 20);
360        let s = m.snapshot();
361        assert_eq!(s.records_read, 3);
362        assert_eq!(s.bytes_read, 30);
363        assert_eq!(s.source_roundtrips["page"], 2);
364        assert_eq!(s.sink_roundtrips["insert"], 1);
365        assert_eq!(s.roundtrips(UsageSide::Source), 2);
366        assert_eq!(s.roundtrips(UsageSide::Sink), 1);
367        assert_eq!(s.signals.len(), 1);
368        assert_eq!(UsageSide::Sink.as_str(), "sink");
369
370        let mut total = UsageSnapshot::default();
371        total.merge(&s);
372        total.merge(&s);
373        assert_eq!(total.records_written, 4);
374        assert_eq!(total.source_roundtrips["page"], 4);
375        assert_eq!(total.signals.len(), 2);
376        let round: UsageSnapshot =
377            serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();
378        assert_eq!(round, s);
379    }
380
381    #[test]
382    fn meter_tallies_throttling_and_retries() {
383        let m = UsageMeter::new();
384        let quiet = m.snapshot();
385        let v = serde_json::to_value(&quiet).unwrap();
386        assert!(v.get("throttled").is_none());
387        assert!(v.get("throttle_wait_secs").is_none());
388        assert!(v.get("source_retries").is_none());
389
390        m.add_throttled();
391        m.add_throttled();
392        m.add_throttle_wait(std::time::Duration::from_millis(1500));
393        m.add_throttle_wait(std::time::Duration::from_millis(500));
394        m.add_source_retry("rate_limited");
395        m.add_source_retry("rate_limited");
396        m.add_source_retry("http_5xx");
397        let s = m.snapshot();
398        assert_eq!(s.throttled, 2);
399        assert!((s.throttle_wait_secs - 2.0).abs() < 1e-9);
400        assert_eq!(s.source_retries["rate_limited"], 2);
401        assert_eq!(s.source_retries["http_5xx"], 1);
402
403        let mut total = UsageSnapshot::default();
404        total.merge(&s);
405        total.merge(&s);
406        assert_eq!(total.throttled, 4);
407        assert!((total.throttle_wait_secs - 4.0).abs() < 1e-9);
408        assert_eq!(total.source_retries["rate_limited"], 4);
409        let round: UsageSnapshot =
410            serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();
411        assert_eq!(round, s);
412    }
413}