faucet-core 1.14.1

Shared types, traits, and utilities for the faucet-stream ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Source lag (#733): how far a CDC / streaming pipeline is behind its source.
//!
//! A source that has a notion of "the head" (a WAL position, a binlog end, a
//! partition high watermark) reports the distance from where it has read to
//! that head through [`Source::lag`](crate::Source::lag). The pipeline polls it
//! at page boundaries and exports `faucet_source_lag_bytes`,
//! `faucet_source_lag_events` and `faucet_source_lag_seconds`.

use metrics::{Label, gauge};
use serde::{Deserialize, Serialize};

/// Distance from the source's head, in whichever units the source can measure.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct SourceLag {
    /// Bytes of unread change log (Postgres WAL, MySQL binlog).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bytes: Option<u64>,
    /// Unread events / messages (Kafka offsets, SQL Server change rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub events: Option<u64>,
    /// Age of the oldest unread change, in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seconds: Option<f64>,
}

impl SourceLag {
    /// Lag measured in bytes.
    pub fn bytes(n: u64) -> Self {
        Self {
            bytes: Some(n),
            ..Default::default()
        }
    }

    /// Lag measured in events.
    pub fn events(n: u64) -> Self {
        Self {
            events: Some(n),
            ..Default::default()
        }
    }

    /// Lag measured in seconds (negative clock skew clamps to zero).
    pub fn seconds(s: f64) -> Self {
        Self {
            seconds: Some(if s.is_finite() { s.max(0.0) } else { 0.0 }),
            ..Default::default()
        }
    }

    /// Whether no unit carries a value.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_none() && self.events.is_none() && self.seconds.is_none()
    }

    /// A compact human rendering: `412 MiB`, `1,204 events`, `3m 20s`, joined.
    pub fn human(&self) -> String {
        let mut parts = Vec::new();
        if let Some(b) = self.bytes {
            parts.push(human_bytes(b));
        }
        if let Some(e) = self.events {
            parts.push(format!("{e} event{}", if e == 1 { "" } else { "s" }));
        }
        if let Some(s) = self.seconds {
            parts.push(human_seconds(s));
        }
        parts.join(" · ")
    }
}

fn human_bytes(b: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut v = b as f64;
    let mut i = 0;
    while v >= 1024.0 && i + 1 < UNITS.len() {
        v /= 1024.0;
        i += 1;
    }
    if i == 0 {
        format!("{b} B")
    } else {
        format!("{v:.0} {}", UNITS[i])
    }
}

fn human_seconds(s: f64) -> String {
    let s = s.max(0.0);
    if s < 60.0 {
        return format!("{s:.0}s");
    }
    let total = s as u64;
    let (h, m, sec) = (total / 3600, (total % 3600) / 60, total % 60);
    if h > 0 {
        format!("{h}h {m}m")
    } else {
        format!("{m}m {sec}s")
    }
}

/// The latest lag sample of one run, shared with the caller (#733). Attach
/// with [`Pipeline::with_lag_observer`](crate::Pipeline::with_lag_observer).
#[derive(Debug, Default)]
pub struct LagObserver {
    last: std::sync::Mutex<Option<SourceLag>>,
}

impl LagObserver {
    /// An observer with no sample yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace the latest sample.
    pub fn record(&self, lag: SourceLag) {
        if let Ok(mut g) = self.last.lock() {
            *g = Some(lag);
        }
    }

    /// The latest sample, if the source reported one.
    pub fn last(&self) -> Option<SourceLag> {
        self.last.lock().ok().and_then(|g| *g)
    }
}

/// Export one lag sample as the `faucet_source_lag_*` gauges.
pub fn record_lag_gauges(labels: &[Label], lag: &SourceLag) {
    if let Some(b) = lag.bytes {
        gauge!("faucet_source_lag_bytes", labels.to_vec()).set(b as f64);
    }
    if let Some(e) = lag.events {
        gauge!("faucet_source_lag_events", labels.to_vec()).set(e as f64);
    }
    if let Some(s) = lag.seconds {
        gauge!("faucet_source_lag_seconds", labels.to_vec()).set(s);
    }
}

/// How often the pipeline asks a source for its lag while pages flow.
pub const LAG_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15);

/// How long one lag query may take before it is abandoned (logged once). After
/// the first such timeout the run stops asking, so a hung query stalls at most
/// one page.
pub const LAG_POLL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Polls [`Source::lag`](crate::Source::lag) for one run: on the first page,
/// then at most every [`LAG_POLL_INTERVAL`], and once more when the run ends.
/// A failing query is logged once and never fails the run; a slow one (over
/// [`LAG_POLL_TIMEOUT`]) is abandoned and lag polling stops for the rest of
/// the run, since every poll waits on the page path.
pub(crate) struct LagPoller<'a> {
    source: &'a dyn crate::Source,
    labels: Vec<Label>,
    observer: Option<std::sync::Arc<LagObserver>>,
    interval: std::time::Duration,
    timeout: std::time::Duration,
    last_poll: std::sync::Mutex<Option<std::time::Instant>>,
    warned: std::sync::atomic::AtomicBool,
    /// A query timed out: further polls would hold a page each, so stop.
    gave_up: std::sync::atomic::AtomicBool,
}

impl<'a> LagPoller<'a> {
    pub(crate) fn new(
        source: &'a dyn crate::Source,
        pipeline: &str,
        row: &str,
        observer: Option<std::sync::Arc<LagObserver>>,
    ) -> Self {
        use metrics::SharedString;
        Self {
            labels: vec![
                Label::new("pipeline", SharedString::from(pipeline.to_string())),
                Label::new("row", SharedString::from(row.to_string())),
                Label::new(
                    "connector",
                    SharedString::from(source.connector_name().to_string()),
                ),
            ],
            source,
            observer,
            interval: LAG_POLL_INTERVAL,
            timeout: LAG_POLL_TIMEOUT,
            last_poll: std::sync::Mutex::new(None),
            warned: std::sync::atomic::AtomicBool::new(false),
            gave_up: std::sync::atomic::AtomicBool::new(false),
        }
    }

    #[cfg(test)]
    fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }

    #[cfg(test)]
    fn with_interval(mut self, interval: std::time::Duration) -> Self {
        self.interval = interval;
        self
    }

    /// Poll unless the last poll was under the interval ago (`force` skips
    /// the throttle).
    pub(crate) async fn poll(&self, force: bool) {
        if self.gave_up.load(std::sync::atomic::Ordering::Relaxed) {
            return;
        }
        let now = std::time::Instant::now();
        {
            let Ok(mut last) = self.last_poll.lock() else {
                return;
            };
            if !force && last.is_some_and(|t| now.duration_since(t) < self.interval) {
                return;
            }
            *last = Some(now);
        }
        let result = match tokio::time::timeout(self.timeout, self.source.lag()).await {
            Ok(r) => r,
            Err(_) => {
                self.gave_up
                    .store(true, std::sync::atomic::Ordering::Relaxed);
                Err(crate::FaucetError::Source(format!(
                    "lag query did not answer within {:?}; not polled again this run",
                    self.timeout
                )))
            }
        };
        match result {
            Ok(Some(lag)) if !lag.is_empty() => {
                record_lag_gauges(&self.labels, &lag);
                if let Some(o) = &self.observer {
                    o.record(lag);
                }
            }
            Ok(_) => {}
            Err(e) => {
                if !self.warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
                    tracing::warn!(
                        connector = self.source.connector_name(),
                        error = %e,
                        "source lag query failed; lag is not reported for this run (logged once)"
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn constructors_and_rendering() {
        assert_eq!(SourceLag::bytes(10).bytes, Some(10));
        assert_eq!(SourceLag::events(3).events, Some(3));
        assert_eq!(SourceLag::seconds(-4.0).seconds, Some(0.0));
        assert_eq!(SourceLag::seconds(f64::NAN).seconds, Some(0.0));
        assert!(SourceLag::default().is_empty());
        assert!(!SourceLag::bytes(0).is_empty());
        assert_eq!(SourceLag::bytes(512).human(), "512 B");
        assert_eq!(SourceLag::bytes(412 * 1024 * 1024).human(), "412 MiB");
        assert_eq!(SourceLag::events(1).human(), "1 event");
        assert_eq!(SourceLag::events(5).human(), "5 events");
        assert_eq!(SourceLag::seconds(42.0).human(), "42s");
        assert_eq!(SourceLag::seconds(200.0).human(), "3m 20s");
        assert_eq!(SourceLag::seconds(7300.0).human(), "2h 1m");
        let both = SourceLag {
            bytes: Some(2048),
            seconds: Some(5.0),
            events: None,
        };
        assert_eq!(both.human(), "2 KiB · 5s");
    }

    struct LagSource {
        calls: std::sync::atomic::AtomicUsize,
        result: Result<Option<SourceLag>, ()>,
    }

    #[async_trait::async_trait]
    impl crate::Source for LagSource {
        async fn fetch_with_context(
            &self,
            _: &std::collections::HashMap<String, serde_json::Value>,
        ) -> Result<Vec<serde_json::Value>, crate::FaucetError> {
            Ok(Vec::new())
        }
        async fn lag(&self) -> Result<Option<SourceLag>, crate::FaucetError> {
            self.calls
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            self.result
                .map_err(|_| crate::FaucetError::Source("lag query failed".into()))
        }
    }

    fn lag_source(result: Result<Option<SourceLag>, ()>) -> LagSource {
        LagSource {
            calls: std::sync::atomic::AtomicUsize::new(0),
            result,
        }
    }

    #[tokio::test]
    async fn poller_throttles_records_and_forces() {
        let src = lag_source(Ok(Some(SourceLag::bytes(7))));
        let obs = std::sync::Arc::new(LagObserver::new());
        assert_eq!(obs.last(), None);
        let p = LagPoller::new(&src, "p", "r", Some(std::sync::Arc::clone(&obs)))
            .with_interval(std::time::Duration::from_secs(3600));
        p.poll(false).await;
        p.poll(false).await;
        assert_eq!(src.calls.load(std::sync::atomic::Ordering::Relaxed), 1);
        p.poll(true).await;
        assert_eq!(src.calls.load(std::sync::atomic::Ordering::Relaxed), 2);
        assert_eq!(obs.last(), Some(SourceLag::bytes(7)));
    }

    #[tokio::test]
    async fn poller_ignores_empty_and_failing_lag() {
        let obs = std::sync::Arc::new(LagObserver::new());
        let empty = lag_source(Ok(Some(SourceLag::default())));
        LagPoller::new(&empty, "p", "r", Some(std::sync::Arc::clone(&obs)))
            .poll(true)
            .await;
        let none = lag_source(Ok(None));
        LagPoller::new(&none, "p", "r", Some(std::sync::Arc::clone(&obs)))
            .poll(true)
            .await;
        let failing = lag_source(Err(()));
        let p = LagPoller::new(&failing, "p", "r", Some(std::sync::Arc::clone(&obs)));
        p.poll(true).await;
        p.poll(true).await;
        assert_eq!(failing.calls.load(std::sync::atomic::Ordering::Relaxed), 2);
        assert_eq!(obs.last(), None);
        LagPoller::new(&none, "p", "r", None).poll(true).await;
        use crate::Source;
        assert!(
            none.fetch_with_context(&Default::default())
                .await
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn gauges_record_without_a_recorder() {
        record_lag_gauges(
            &[],
            &SourceLag {
                bytes: Some(1),
                events: Some(2),
                seconds: Some(3.0),
            },
        );
        record_lag_gauges(&[], &SourceLag::default());
    }

    #[tokio::test]
    async fn a_hung_lag_query_is_abandoned() {
        struct Hangs;
        #[async_trait::async_trait]
        impl crate::Source for Hangs {
            async fn fetch_with_context(
                &self,
                _: &std::collections::HashMap<String, serde_json::Value>,
            ) -> Result<Vec<serde_json::Value>, crate::FaucetError> {
                Ok(Vec::new())
            }
            async fn lag(&self) -> Result<Option<SourceLag>, crate::FaucetError> {
                std::future::pending().await
            }
        }
        let obs = std::sync::Arc::new(LagObserver::new());
        let p = LagPoller::new(&Hangs, "p", "r", Some(std::sync::Arc::clone(&obs)))
            .with_timeout(std::time::Duration::from_millis(20));
        tokio::time::timeout(std::time::Duration::from_secs(5), p.poll(true))
            .await
            .expect("poll must return after its timeout");
        assert!(p.warned.load(std::sync::atomic::Ordering::Relaxed));
        // Once a query has hung, later polls (periodic or forced) return at
        // once instead of holding another page for the whole timeout.
        let p = p.with_timeout(std::time::Duration::from_secs(3600));
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            p.poll(true).await;
            p.poll(false).await;
        })
        .await
        .expect("a poller that gave up never waits again");
        assert_eq!(obs.last(), None);
        use crate::Source;
        assert!(
            Hangs
                .fetch_with_context(&Default::default())
                .await
                .unwrap()
                .is_empty()
        );
    }
}