glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Caching computed values: in the process (fast, per server) and,
//! optionally, in the database, so every server shares them (as Rails'
//! Solid Cache).
//!
//! ```ignore
//! let summary: Summary = cache::fetch("reports/summary", 10.minutes(), || async {
//!     Summary::compute().await
//! })
//! .await?;
//!
//! // Keys from a record change when it's saved, so a cached view of it
//! // is never stale:
//! let card: String = cache::fetch(&cache::key(&post, "card"), 1.days(), || async {
//!     Ok(render_card(&post))
//! })
//! .await?;
//! ```
//!
//! `[cache] store` picks where values live: `"memory"` (the default),
//! `"database"` (a `glacier_cache` table from
//! `glacier::cache::create_table`, with the memory store in front of it
//! for a few seconds), or `"null"` (nothing is kept). Each
//! `#[glacier::test]` has an empty memory store of its own.
//!
//! Many callers missing the same key at once compute it once: the rest
//! wait for that value (in each process). `fetch_flexible` serves a
//! stale value while one caller refreshes it.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock};

use chrono::TimeDelta;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tracing::Instrument;

use crate::config::Config;
use crate::db::migration::Schema;
use crate::db::{self, Sql, Timestamp, Value};
use crate::error::{Error, Result};
use crate::jobs::Delay;
use crate::model::Model;

const TABLE: &str = "glacier_cache";
/// How long the memory store in front of the database keeps a value.
const NEAR: TimeDelta = TimeDelta::seconds(5);
/// Memory stores hold at most this many values.
const MEMORY_LIMIT: usize = 10_000;

/// The database store's table, for a migration's `up`.
pub fn create_table(s: &mut Schema) {
    s.create_table(TABLE, |t| {
        t.string("key").not_null().unique();
        t.text("value").not_null();
        t.timestamp("expires_at");
        t.timestamps();
    });
    s.add_index(TABLE, &["expires_at"]);
}

/// A stored value: JSON, when it was written, and when it expires.
#[derive(Clone, Debug)]
struct Entry {
    value: String,
    written_at: Timestamp,
    expires_at: Option<Timestamp>,
}

impl Entry {
    fn live(&self, now: Timestamp) -> bool {
        self.expires_at.is_none_or(|at| at > now)
    }
}

type Pending<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;

trait Store: Send + Sync {
    fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>>;
    fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()>;
    fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()>;
}

/// Values in this process, oldest dropped first past the limit.
#[derive(Default)]
struct Memory(Mutex<HashMap<String, Entry>>);

impl Memory {
    fn get_now(&self, key: &str) -> Option<Entry> {
        let now = crate::time::now();
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        match map.get(key) {
            Some(entry) if entry.live(now) => Some(entry.clone()),
            Some(_) => {
                map.remove(key);
                None
            }
            None => None,
        }
    }

    fn set_now(&self, key: &str, entry: Entry) {
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        if map.len() >= MEMORY_LIMIT && !map.contains_key(key) {
            let now = crate::time::now();
            map.retain(|_, entry| entry.live(now));
            if map.len() >= MEMORY_LIMIT {
                // Still full: drop the oldest tenth.
                let mut ages: Vec<(Timestamp, String)> =
                    map.iter().map(|(k, e)| (e.written_at, k.clone())).collect();
                ages.sort();
                for (_, old) in ages.into_iter().take(MEMORY_LIMIT / 10) {
                    map.remove(&old);
                }
            }
        }
        map.insert(key.to_owned(), entry);
    }
}

impl Store for Memory {
    fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>> {
        let entry = self.get_now(key);
        Box::pin(async move { Ok(entry) })
    }

    fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()> {
        self.set_now(key, entry);
        Box::pin(async { Ok(()) })
    }

    fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()> {
        self.0.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
        Box::pin(async { Ok(()) })
    }
}

/// Keeps nothing.
struct Null;

impl Store for Null {
    fn get<'a>(&'a self, _key: &'a str) -> Pending<'a, Option<Entry>> {
        Box::pin(async { Ok(None) })
    }

    fn set<'a>(&'a self, _key: &'a str, _entry: Entry) -> Pending<'a, ()> {
        Box::pin(async { Ok(()) })
    }

    fn delete<'a>(&'a self, _key: &'a str) -> Pending<'a, ()> {
        Box::pin(async { Ok(()) })
    }
}

/// The `glacier_cache` table, on the current connection, with a memory
/// store in front of it for a few seconds.
#[derive(Default)]
struct Database {
    near: Memory,
}

impl Store for Database {
    fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>> {
        Box::pin(async move {
            if let Some(entry) = self.near.get_now(key) {
                return Ok(Some(entry));
            }
            let mut sql = Sql::new();
            sql.push(&format!(
                "SELECT value, updated_at, expires_at FROM {TABLE} WHERE key = "
            ));
            sql.push_value(Value::Text(key.to_owned()));
            let rows = db::current()?.fetch_all(&sql).await?;
            let Some(row) = rows.first() else {
                return Ok(None);
            };
            let entry = Entry {
                value: row.get("value")?,
                written_at: row.get("updated_at")?,
                expires_at: row.get("expires_at")?,
            };
            if !entry.live(crate::time::now()) {
                return Ok(None);
            }
            self.near.set_now(key, near_copy(&entry));
            Ok(Some(entry))
        })
    }

    fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()> {
        Box::pin(async move {
            let mut sql = Sql::new();
            sql.push(&format!(
                "INSERT INTO {TABLE} (key, value, expires_at, inserted_at, updated_at) VALUES ("
            ));
            sql.push_value(Value::Text(key.to_owned()));
            sql.push(", ");
            sql.push_value(Value::Text(entry.value.clone()));
            sql.push(", ");
            sql.push_value(entry.expires_at.map_or(Value::Null, Value::Timestamp));
            sql.push(", ");
            sql.push_value(Value::Timestamp(entry.written_at));
            sql.push(", ");
            sql.push_value(Value::Timestamp(entry.written_at));
            sql.push(
                ") ON CONFLICT (key) DO UPDATE SET value = excluded.value, \
                 expires_at = excluded.expires_at, updated_at = excluded.updated_at",
            );
            db::current()?.execute(&sql).await?;
            self.near.set_now(key, near_copy(&entry));
            Ok(())
        })
    }

    fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()> {
        Box::pin(async move {
            self.near
                .0
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(key);
            let mut sql = Sql::new();
            sql.push(&format!("DELETE FROM {TABLE} WHERE key = "));
            sql.push_value(Value::Text(key.to_owned()));
            db::current()?.execute(&sql).await?;
            Ok(())
        })
    }
}

/// The memory store keeps a database value only briefly, so another
/// server's write is seen within a few seconds.
fn near_copy(entry: &Entry) -> Entry {
    let soon = crate::time::now() + NEAR;
    Entry {
        expires_at: Some(entry.expires_at.map_or(soon, |at| at.min(soon))),
        ..entry.clone()
    }
}

static STORE: RwLock<Option<Arc<dyn Store>>> = RwLock::new(None);

tokio::task_local! {
    /// A test's own store, from `#[glacier::test]`.
    static TEST_STORE: Arc<Memory>;
}

fn store() -> Arc<dyn Store> {
    if let Ok(store) = TEST_STORE.try_with(Arc::clone) {
        return store;
    }
    if let Some(store) = STORE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
        return store.clone();
    }
    let store: Arc<dyn Store> = Arc::new(Memory::default());
    *STORE.write().unwrap_or_else(|e| e.into_inner()) = Some(store.clone());
    store
}

/// Runs `fut` with an empty cache of its own. `#[glacier::test]` does this.
#[doc(hidden)]
pub async fn with_test_store<F: Future>(fut: F) -> F::Output {
    TEST_STORE.scope(Arc::default(), fut).await
}

/// Reads `[cache] store` from the config. `App::config` calls it.
pub(crate) fn configure(config: &Config) -> Result<()> {
    let store: Arc<dyn Store> = match config.get_opt::<String>("cache.store")?.as_deref() {
        None | Some("memory") => Arc::new(Memory::default()),
        Some("database") => Arc::new(Database::default()),
        Some("null") => Arc::new(Null),
        Some(other) => {
            return Err(Error::internal(format!(
                "cache.store `{other}`: expected memory, database or null"
            )));
        }
    };
    *STORE.write().unwrap_or_else(|e| e.into_inner()) = Some(store);
    Ok(())
}

/// The cached value for `key`, if there is one and it fits `T`.
///
/// # Errors
///
/// When the store can't be read.
pub async fn read<T: DeserializeOwned>(key: &str) -> Result<Option<T>> {
    let span = span("get", key);
    let found = store()
        .get(key)
        .instrument(span.clone())
        .await?
        .and_then(|entry| serde_json::from_str(&entry.value).ok());
    span.record("cache.hit", found.is_some());
    Ok(found)
}

/// A cache operation's span, `glacier.cache`, as the database's and the
/// HTTP client's have theirs: what was asked for, and (for a read)
/// whether it was there.
fn span(operation: &'static str, key: &str) -> tracing::Span {
    tracing::info_span!(
        target: "glacier",
        "glacier.cache",
        otel.name = %format!("cache {operation}"),
        otel.kind = "client",
        cache.operation = operation,
        cache.key = %key,
        cache.hit = tracing::field::Empty,
    )
}

/// Caches `value` under `key` for `ttl`.
///
/// # Errors
///
/// When it can't be stored or serialized.
pub async fn write<T: Serialize + ?Sized>(key: &str, value: &T, ttl: impl Delay) -> Result<()> {
    let value = serde_json::to_string(value)
        .map_err(|e| Error::internal(format!("caching `{key}`: {e}")))?;
    let now = crate::time::now();
    store()
        .set(
            key,
            Entry {
                value,
                written_at: now,
                expires_at: Some(now + ttl.delay()),
            },
        )
        .instrument(span("set", key))
        .await
}

/// Forgets `key`.
///
/// # Errors
///
/// When the store can't be written.
pub async fn delete(key: &str) -> Result<()> {
    store().delete(key).instrument(span("delete", key)).await
}

/// One computation per key at a time, in this process.
static COMPUTING: Mutex<Option<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = Mutex::new(None);

/// The lock's name: the key within this store, so tests (which each have
/// a store of their own) never share one.
fn lock_name(key: &str) -> String {
    format!("{:p}/{key}", Arc::as_ptr(&store()).cast::<()>())
}

fn computing(key: &str) -> Arc<tokio::sync::Mutex<()>> {
    let mut map = COMPUTING.lock().unwrap_or_else(|e| e.into_inner());
    map.get_or_insert_with(HashMap::new)
        .entry(lock_name(key))
        .or_default()
        .clone()
}

fn done_computing(key: &str) {
    let name = lock_name(key);
    let mut map = COMPUTING.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(map) = map.as_mut()
        && map
            .get(&name)
            .is_some_and(|lock| Arc::strong_count(lock) <= 1)
    {
        map.remove(&name);
    }
}

/// The cached value for `key`, or `compute`'s, cached for `ttl`. Callers
/// that miss the same key together compute it once.
///
/// # Errors
///
/// `compute`'s error (nothing is cached), or the store's.
pub async fn fetch<T, F, Fut>(key: &str, ttl: impl Delay, compute: F) -> Result<T>
where
    T: Serialize + DeserializeOwned,
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<T>>,
{
    if let Some(value) = read(key).await? {
        return Ok(value);
    }
    let ttl = ttl.delay();
    let lock = computing(key);
    let guard = lock.lock().await;
    // Another caller may have filled it while this one waited.
    let outcome = match read(key).await? {
        Some(value) => Ok(value),
        None => match compute().await {
            Ok(value) => write(key, &value, ttl).await.map(|()| value),
            Err(err) => Err(err),
        },
    };
    drop(guard);
    drop(lock);
    done_computing(key);
    outcome
}

/// A key for a value that's someone's, with the access in front:
/// `org:42/dashboard` for `key_for(access, "dashboard")`. Two orgs, or two
/// users, never share it; keys made without an access are shared by
/// everyone.
pub fn key_for(access: &dyn crate::access::Access, key: &str) -> String {
    format!("{}/{key}", access.describe())
}

/// [`fetch`] with the key [`key_for`] makes: a value that's the access's
/// own, `Cache.fetch_for(access, "dashboard", 5.minutes(), …)`.
///
/// # Errors
///
/// As `fetch`.
pub async fn fetch_for<T, F, Fut>(
    access: &dyn crate::access::Access,
    key: &str,
    ttl: impl Delay,
    compute: F,
) -> Result<T>
where
    T: Serialize + DeserializeOwned,
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<T>>,
{
    fetch(&key_for(access, key), ttl, compute).await
}

/// As [`fetch`], but a value older than `fresh` (and younger than
/// `fresh + stale`) is still served while one caller refreshes it; the
/// others don't wait. Past `fresh + stale` it's computed as `fetch` would.
///
/// # Errors
///
/// As `fetch`.
pub async fn fetch_flexible<T, F, Fut>(
    key: &str,
    fresh: impl Delay,
    stale: impl Delay,
    compute: F,
) -> Result<T>
where
    T: Serialize + DeserializeOwned,
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<T>>,
{
    let (fresh, stale) = (fresh.delay(), stale.delay());
    let now = crate::time::now();
    if let Some(entry) = store().get(key).await?
        && let Ok(value) = serde_json::from_str::<T>(&entry.value)
    {
        if now - entry.written_at < fresh {
            return Ok(value);
        }
        // Stale: whoever gets the lock refreshes; everyone else is served.
        let lock = computing(key);
        let Ok(guard) = lock.try_lock() else {
            return Ok(value);
        };
        let outcome = match compute().await {
            Ok(fresh_value) => write(key, &fresh_value, fresh + stale)
                .await
                .map(|()| fresh_value),
            // A failed refresh keeps serving what there is.
            Err(_) => Ok(value),
        };
        drop(guard);
        drop(lock);
        done_computing(key);
        return outcome;
    }
    fetch(key, fresh + stale, compute).await
}

/// A key for `record` that changes whenever it's saved: its table, id and
/// `updated_at`, then `suffix`: `posts/12-20261005T010203.123456/card`.
pub fn key<M: Model>(record: &M, suffix: &str) -> String {
    let id = record.id_value().to_text();
    let version = M::UPDATED_AT
        .and_then(|column| {
            record
                .values()
                .into_iter()
                .find(|(name, _)| *name == column)
        })
        .map(|(_, value)| value.to_text().replace([' ', ':', '-'], ""))
        .unwrap_or_default();
    let mut key = format!("{}/{id}", M::TABLE);
    if !version.is_empty() {
        key.push('-');
        key.push_str(&version);
    }
    if !suffix.is_empty() {
        key.push('/');
        key.push_str(suffix);
    }
    key
}

/// Deletes expired values from the database store; how many it deleted.
/// For the jobs scheduler: `.prune_with("glacier_cache", glacier::cache::prune)`.
///
/// # Errors
///
/// When the table can't be written.
pub async fn prune() -> Result<u64> {
    let mut sql = Sql::new();
    sql.push(&format!("DELETE FROM {TABLE} WHERE expires_at < "));
    sql.push_value(Value::Timestamp(crate::time::now()));
    Ok(db::current()?.execute(&sql).await?)
}