Skip to main content

micromegas_auth/
db_snapshot.rs

1//! Generic whole-table snapshot cache, extracted from what used to be
2//! `db_audience_grants.rs`'s entire cache-mechanics implementation. [`crate::db_snapshot::SnapshotLoader`] is the one
3//! thing each store (audience grants, groups) supplies: how to fetch a fresh snapshot and which
4//! metric/name to report on a refresh failure. [`crate::db_snapshot::SnapshotSource`] is everything else -- cold-start
5//! throttling, last-good serving after the first success, `ProviderUnavailable` wrapping -- copied
6//! unchanged from the original `DbAudienceGrantsSource`.
7//!
8//! Modeled on `db_api_key.rs`'s config/pool conventions, but a single cached value rather than a
9//! per-key `moka` cache: the whole table is small enough to hold as one snapshot, so `moka`'s
10//! eviction/LRU machinery has nothing to do here.
11
12use crate::types::ProviderUnavailable;
13use anyhow::{Result, anyhow};
14use async_trait::async_trait;
15use sqlx::PgPool;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicI64, Ordering};
18use std::time::{Duration, Instant};
19
20/// The result of parsing a batch of rows where a malformed row is dropped rather than failing the
21/// whole batch. Rows only ever *grant*, so dropping one can only narrow what someone can do.
22#[derive(Debug, Clone)]
23pub struct Parsed<T> {
24    pub value: T,
25    /// One human-readable reason per skipped row, e.g. "audience_grants row ('team alpha',
26    /// read, user:a@x): invalid audience name".
27    pub skipped: Vec<String>,
28}
29
30/// Logs one `warn!` per skipped row, naming the store. Callers emit their own literal-named
31/// metric (`imetric!` needs a static name) and call this only when `skipped` is non-empty.
32pub fn report_skipped(name: &str, skipped: &[String]) {
33    for reason in skipped {
34        micromegas_tracing::warn!("{name}: skipping malformed row: {reason}");
35    }
36}
37
38/// What a [`SnapshotSource`] needs from a specific store: how to fetch a fresh snapshot from the
39/// pool, and the name/metric to report on a refresh failure.
40#[async_trait]
41pub trait SnapshotLoader: Send + Sync + 'static {
42    /// The loaded, ready-to-serve snapshot type (e.g. `AudienceGrants`, `GroupGraph`).
43    type Snapshot: Send + Sync;
44
45    /// Human-readable store name used in error/log text (e.g. "audience grant store", "group
46    /// store").
47    const NAME: &'static str;
48
49    /// Queries the whole table(s) and builds a fresh snapshot.
50    async fn fetch(pool: &PgPool) -> Result<Self::Snapshot>;
51
52    /// Emits this store's own refresh-error metric (`imetric!()` with its own literal name) --
53    /// called by [`SnapshotSource::current`] at both failure sites.
54    fn count_refresh_error();
55}
56
57#[derive(Debug)]
58struct Snapshot<T> {
59    value: Arc<T>,
60    /// Time of the last *successful* load -- never advanced on a failed refresh. Feeds the age
61    /// reported in the refresh-failure log/error context ("how stale is the view right now"),
62    /// independent of `fetched_at`; it is not itself emitted as a metric.
63    loaded_at: Instant,
64    /// Time of the last refresh *attempt*, successful or not -- gates how often a failing DB is
65    /// re-queried once at least one load has succeeded, so a post-first-success outage costs one
66    /// query per TTL, not one per request.
67    fetched_at: Instant,
68}
69
70/// The whole-table snapshot cache described in the module doc comment, generic over a
71/// [`SnapshotLoader`].
72pub struct SnapshotSource<L: SnapshotLoader> {
73    pool: PgPool,
74    ttl: Duration,
75    snapshot: tokio::sync::RwLock<Option<Snapshot<L::Snapshot>>>,
76    /// Process-start baseline every `last_attempt_at` reading is measured from -- captured once
77    /// here, not `Instant::now()` at each read, so `last_attempt_at` values are comparable across
78    /// calls the same way a wall-clock timestamp would be, but monotonic: unlike
79    /// `Utc::now().timestamp()`, a backwards clock step (NTP correction, VM migration, manual
80    /// clock set) can never make a later reading smaller than an earlier one.
81    start: Instant,
82    /// Milliseconds since `start` of the last refresh *attempt*, recorded outside `Snapshot` so
83    /// it exists even before any load has ever succeeded -- mirrors `db_api_key.rs`'s
84    /// `last_logged_at`, but monotonic rather than a Unix-epoch-seconds value (see [`Self::start`]).
85    /// This is what gates cold-start retries: with no `Snapshot` yet, there is nowhere else to
86    /// remember "we just tried and failed a moment ago", so without this field every `current()`
87    /// call during process startup against a still-coming-up DB would re-query with no throttling
88    /// at all, unlike the post-success path which `fetched_at` already gates. Initialized to
89    /// `i64::MIN` -- not `0`, which (being only milliseconds after `start`) would be indistinguishable
90    /// from a real attempt made moments after construction and would incorrectly throttle the very
91    /// first cold-start call -- so the first real attempt's `saturating_sub` against it is always
92    /// far past `ttl` regardless of how soon after construction it lands.
93    last_attempt_at: AtomicI64,
94}
95
96impl<L: SnapshotLoader> std::fmt::Debug for SnapshotSource<L> {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("SnapshotSource")
99            .field("name", &L::NAME)
100            .field("ttl", &self.ttl)
101            .finish()
102    }
103}
104
105impl<L: SnapshotLoader> SnapshotSource<L> {
106    /// Builds a source over `pool` (expected to be a [`crate::db_api_key::dedicated_key_store_pool`],
107    /// not the caller's lake pool directly), with no snapshot loaded yet -- the first `current()`
108    /// call performs the first query.
109    pub fn new(pool: PgPool, ttl: Duration) -> Self {
110        Self {
111            pool,
112            ttl,
113            snapshot: tokio::sync::RwLock::new(None),
114            start: Instant::now(),
115            last_attempt_at: AtomicI64::new(i64::MIN),
116        }
117    }
118
119    /// Milliseconds elapsed since `self.start` -- the monotonic clock `last_attempt_at` is
120    /// measured against.
121    fn elapsed_millis(&self) -> i64 {
122        i64::try_from(self.start.elapsed().as_millis()).unwrap_or(i64::MAX)
123    }
124
125    /// The synthesized error for a throttled cold-start window (see [`Self::current`]'s doc
126    /// comment) -- never a stored, re-handed-out `anyhow::Error` from a prior attempt, since that
127    /// type isn't `Clone` and this store deliberately carries none of `db_api_key.rs`'s
128    /// moka/`Arc<E>` sharing machinery to make it so.
129    ///
130    /// `last_attempt_millis` is measured against `self.start` (see that field's doc comment), not
131    /// a wall-clock instant, so there is no absolute timestamp left to report here -- the message
132    /// reports the throttle window's remaining duration instead, which stays meaningful (and never
133    /// goes backwards) regardless of the system clock.
134    fn throttled_error(&self, last_attempt_millis: i64) -> anyhow::Error {
135        let since_last_attempt = Duration::from_millis(
136            self.elapsed_millis()
137                .saturating_sub(last_attempt_millis)
138                .max(0) as u64,
139        );
140        let retry_in = self.ttl.saturating_sub(since_last_attempt);
141        // Wrapped in `ProviderUnavailable` (not a bare `anyhow!`) so `caller_context`
142        // (`flight_sql_service_impl.rs`) downcasts this to `Status::unavailable` rather than
143        // `Status::permission_denied` -- a throttled cold start is a store-outage symptom, not an
144        // authorization decision.
145        ProviderUnavailable(anyhow!(
146            "{} unavailable; cold-start retry throttled, retry available in {} seconds",
147            L::NAME,
148            retry_in.as_secs()
149        ))
150        .into()
151    }
152
153    /// Returns the current snapshot, refreshing it first if stale.
154    ///
155    /// Both the cold-start path (no `Snapshot` yet) and the post-success path are throttled to at
156    /// most one DB query per TTL window: cold-start via `last_attempt_at` (checked-and-set the
157    /// same compare-exchange way `db_api_key.rs::maybe_log_error` rate-limits its own log line),
158    /// the post-success path via `Snapshot::fetched_at` as before. A `current()` call that lands
159    /// inside an already-throttled window returns the last snapshot if one exists; if not, it
160    /// returns a freshly synthesized error describing the throttled cold-start state rather than
161    /// storing and re-handing-out the prior attempt's `anyhow::Error`. A concurrent caller that
162    /// loses the `last_attempt_at` compare-exchange while the very first cold-start attempt is
163    /// still in flight re-checks `self.snapshot` once more before giving up: if the winning
164    /// caller has since populated it, the loser serves that snapshot instead of failing; only if
165    /// it is still empty does it get the synthesized throttled-state error. It never blocks on
166    /// another caller's still-in-flight query, and it never skips the query silently with nothing
167    /// to show for it.
168    ///
169    /// `Err` only when there has never been one successful load -- a fresh process whose first
170    /// query hits a down DB has no "last good" to serve, so it fails closed like everything else
171    /// on this seam, at a rate capped by `last_attempt_at` rather than once per request. Once any
172    /// load has succeeded, a later refresh failure is logged + counted (via
173    /// [`SnapshotLoader::count_refresh_error`]) and the last good snapshot keeps serving,
174    /// unbounded -- this store has no per-item TTL eviction to fall back on the way
175    /// `db_api_key.rs`'s cache does, so an outage degrades to staleness for as long as it lasts,
176    /// not just one TTL window.
177    pub async fn current(&self) -> Result<Arc<L::Snapshot>> {
178        // Fast path: an unexpired snapshot needs no refresh attempt at all.
179        {
180            let guard = self.snapshot.read().await;
181            if let Some(snap) = guard.as_ref()
182                && snap.fetched_at.elapsed() < self.ttl
183            {
184                return Ok(Arc::clone(&snap.value));
185            }
186        }
187
188        let had_snapshot = self.snapshot.read().await.is_some();
189
190        if had_snapshot {
191            // Post-success path: no single-flight/dedup lock -- a plain `SELECT` with no side
192            // effect to de-duplicate, gated only by `fetched_at` above. A few concurrent callers
193            // landing right at the TTL boundary can each re-run this; strictly simpler and still
194            // cheap (the whole point of "the table is small").
195            match L::fetch(&self.pool).await {
196                Ok(value) => {
197                    let value = Arc::new(value);
198                    let mut guard = self.snapshot.write().await;
199                    *guard = Some(Snapshot {
200                        value: Arc::clone(&value),
201                        loaded_at: Instant::now(),
202                        fetched_at: Instant::now(),
203                    });
204                    Ok(value)
205                }
206                Err(err) => {
207                    L::count_refresh_error();
208                    let mut guard = self.snapshot.write().await;
209                    match guard.as_mut() {
210                        Some(snap) => {
211                            let age_secs = snap.loaded_at.elapsed().as_secs();
212                            micromegas_tracing::error!(
213                                "{} refresh failed, serving stale snapshot (age={age_secs}s): \
214                                 {err:#}",
215                                L::NAME
216                            );
217                            snap.fetched_at = Instant::now();
218                            Ok(Arc::clone(&snap.value))
219                        }
220                        // Snapshot vanished between the check above and now -- this store never
221                        // clears a snapshot once set, so this is unreachable in practice; treat
222                        // it as a cold-start failure rather than panicking. Wrapped in
223                        // `ProviderUnavailable` for the same reason `throttled_error` is: a real
224                        // DB failure here must surface to `caller_context` as
225                        // `Status::unavailable`, not `Status::permission_denied`.
226                        None => Err(ProviderUnavailable(err).into()),
227                    }
228                }
229            }
230        } else {
231            // Cold-start path: `last_attempt_at`'s compare-exchange *is* the dedup mechanism, so
232            // only one caller per TTL window fires the query and the rest get the synthesized
233            // throttled-state error instead of racing in. Measured against `self.start`
234            // (monotonic), not `Utc::now()` -- a backwards wall-clock step can never widen this
235            // window the way it could with an epoch-seconds comparison.
236            let now = self.elapsed_millis();
237            let prev = self.last_attempt_at.load(Ordering::Relaxed);
238            let ttl_millis = self.ttl.as_millis().max(1) as i64;
239            // `throttled_millis`, when set, is the timestamp that actually explains the
240            // remaining wait: on the throttle-hit branch that's `prev` (still accurate, no
241            // exchange attempted); on the CAS-loss branch it's the value the failed
242            // `compare_exchange` reports as *currently* stored, not the stale `prev` this
243            // caller read before attempting the exchange -- using `prev` there would report
244            // the wrong (often ancient/sentinel) retry window instead of the window the
245            // winning caller just started.
246            let throttled_millis = if now.saturating_sub(prev) < ttl_millis {
247                Some(prev)
248            } else {
249                self.last_attempt_at
250                    .compare_exchange(prev, now, Ordering::Relaxed, Ordering::Relaxed)
251                    .err()
252            };
253            if let Some(last_attempt_millis) = throttled_millis {
254                // The winner of the compare-exchange may have already finished its first query
255                // and populated the snapshot by the time we lost the race -- re-check before
256                // treating this as a throttled cold start, so concurrent callers during the very
257                // first load don't get denied purely from contention on a healthy DB. A cheap
258                // re-check, not a full single-flight/wait: if the winner hasn't finished yet,
259                // this still falls through to the throttled error below.
260                if let Some(snap) = self.snapshot.read().await.as_ref() {
261                    return Ok(Arc::clone(&snap.value));
262                }
263                return Err(self.throttled_error(last_attempt_millis));
264            }
265
266            match L::fetch(&self.pool).await {
267                Ok(value) => {
268                    let value = Arc::new(value);
269                    let mut guard = self.snapshot.write().await;
270                    *guard = Some(Snapshot {
271                        value: Arc::clone(&value),
272                        loaded_at: Instant::now(),
273                        fetched_at: Instant::now(),
274                    });
275                    Ok(value)
276                }
277                Err(err) => {
278                    L::count_refresh_error();
279                    micromegas_tracing::error!("{} cold-start load failed: {err:#}", L::NAME);
280                    // Wrapped in `ProviderUnavailable` for the same reason `throttled_error` is:
281                    // a real DB failure here must surface to `caller_context` as
282                    // `Status::unavailable`, not `Status::permission_denied`.
283                    Err(ProviderUnavailable(err).into())
284                }
285            }
286        }
287    }
288}