glacier-web 0.5.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! 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, ()>;
    /// Adds `by` to the number at `key` in one step, starting from 0 (and
    /// expiring at `expires_at`) when there's none; the new number.
    fn increment<'a>(&'a self, key: &'a str, by: i64, expires_at: Timestamp) -> Pending<'a, i64>;
    /// Stores `entry` only if `key` has no live value, in one step; whether
    /// it did.
    fn add<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, bool>;
    /// Deletes `key` only if it holds `value`.
    fn delete_if<'a>(&'a self, key: &'a str, value: &'a str) -> Pending<'a, ()>;
    /// Deletes every key starting with `prefix` (all of them for `""`);
    /// how many.
    fn delete_prefix<'a>(&'a self, prefix: &'a str) -> Pending<'a, u64>;
}

/// 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 Memory {
    fn increment_now(&self, key: &str, by: i64, expires_at: Timestamp) -> i64 {
        let now = crate::time::now();
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        let current = map
            .get(key)
            .filter(|entry| entry.live(now))
            .and_then(|entry| {
                entry
                    .value
                    .parse::<i64>()
                    .ok()
                    .map(|n| (n, entry.expires_at))
            });
        let (number, expires_at) = match current {
            Some((n, expires)) => (n + by, expires),
            None => (by, Some(expires_at)),
        };
        map.insert(
            key.to_owned(),
            Entry {
                value: number.to_string(),
                written_at: now,
                expires_at,
            },
        );
        number
    }
}

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(()) })
    }

    fn increment<'a>(&'a self, key: &'a str, by: i64, expires_at: Timestamp) -> Pending<'a, i64> {
        let number = self.increment_now(key, by, expires_at);
        Box::pin(async move { Ok(number) })
    }

    fn add<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, bool> {
        let now = crate::time::now();
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        let added = if map.get(key).is_some_and(|old| old.live(now)) {
            false
        } else {
            map.insert(key.to_owned(), entry);
            true
        };
        Box::pin(async move { Ok(added) })
    }

    fn delete_if<'a>(&'a self, key: &'a str, value: &'a str) -> Pending<'a, ()> {
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        if map.get(key).is_some_and(|entry| entry.value == value) {
            map.remove(key);
        }
        Box::pin(async { Ok(()) })
    }

    fn delete_prefix<'a>(&'a self, prefix: &'a str) -> Pending<'a, u64> {
        let deleted = self.delete_prefix_now(prefix);
        Box::pin(async move { Ok(deleted) })
    }
}

impl Memory {
    fn delete_prefix_now(&self, prefix: &str) -> u64 {
        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
        let before = map.len();
        map.retain(|key, _| !key.starts_with(prefix));
        (before - map.len()) as u64
    }
}

/// 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(()) })
    }

    fn increment<'a>(&'a self, _key: &'a str, by: i64, _expires_at: Timestamp) -> Pending<'a, i64> {
        Box::pin(async move { Ok(by) })
    }

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

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

    fn delete_prefix<'a>(&'a self, _prefix: &'a str) -> Pending<'a, u64> {
        Box::pin(async { Ok(0) })
    }
}

/// 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(())
        })
    }

    fn increment<'a>(&'a self, key: &'a str, by: i64, expires_at: Timestamp) -> Pending<'a, i64> {
        Box::pin(async move {
            // Counts are shared: never answered from the memory in front.
            self.near
                .0
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(key);
            let now = crate::time::now();
            // One statement, so two servers counting at once both count.
            // An expired row starts again from `by`.
            let expired = |sql: &mut Sql| {
                sql.push(&format!(
                    "{TABLE}.expires_at IS NOT NULL AND {TABLE}.expires_at <= "
                ));
                sql.push_value(Value::Timestamp(now));
            };
            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(by.to_string()));
            sql.push(", ");
            sql.push_value(Value::Timestamp(expires_at));
            sql.push(", ");
            sql.push_value(Value::Timestamp(now));
            sql.push(", ");
            sql.push_value(Value::Timestamp(now));
            sql.push(") ON CONFLICT (key) DO UPDATE SET value = CASE WHEN ");
            expired(&mut sql);
            sql.push(&format!(
                " THEN excluded.value ELSE CAST(CAST({TABLE}.value AS BIGINT) + "
            ));
            sql.push_value(Value::Int(by));
            sql.push(" AS TEXT) END, expires_at = CASE WHEN ");
            expired(&mut sql);
            sql.push(&format!(
                " THEN excluded.expires_at ELSE {TABLE}.expires_at END, \
                 updated_at = excluded.updated_at RETURNING value"
            ));
            let rows = db::current()?.fetch_all(&sql).await?;
            let value: String = rows
                .first()
                .ok_or_else(|| Error::internal("cache increment returned no row"))?
                .get("value")?;
            value
                .parse()
                .map_err(|_| Error::internal(format!("cache `{key}` isn't a number")))
        })
    }

    fn add<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, bool> {
        Box::pin(async move {
            let now = crate::time::now();
            // Inserted, or written over an expired value: a row comes back.
            // A live value stays, and no row comes back.
            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(now));
            sql.push(", ");
            sql.push_value(Value::Timestamp(now));
            sql.push(&format!(
                ") ON CONFLICT (key) DO UPDATE SET value = excluded.value, \
                 expires_at = excluded.expires_at, updated_at = excluded.updated_at \
                 WHERE {TABLE}.expires_at IS NOT NULL AND {TABLE}.expires_at <= "
            ));
            sql.push_value(Value::Timestamp(now));
            sql.push(" RETURNING key");
            let added = !db::current()?.fetch_all(&sql).await?.is_empty();
            if added {
                self.near.set_now(key, near_copy(&entry));
            }
            Ok(added)
        })
    }

    fn delete_if<'a>(&'a self, key: &'a str, value: &'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()));
            sql.push(" AND value = ");
            sql.push_value(Value::Text(value.to_owned()));
            db::current()?.execute(&sql).await?;
            Ok(())
        })
    }

    fn delete_prefix<'a>(&'a self, prefix: &'a str) -> Pending<'a, u64> {
        Box::pin(async move {
            self.near.delete_prefix_now(prefix);
            let mut sql = Sql::new();
            sql.push(&format!("DELETE FROM {TABLE}"));
            if !prefix.is_empty() {
                // Exactly: SQLite's LIKE ignores case.
                sql.push(&format!(
                    " WHERE substr(key, 1, {}) = ",
                    prefix.chars().count()
                ));
                sql.push_value(Value::Text(prefix.to_owned()));
            }
            Ok(db::current()?.execute(&sql).await?)
        })
    }
}

/// 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
}

/// Adds `by` to the number cached at `key` and returns the new number,
/// in one step, so concurrent requests (and, with the database store,
/// other servers) each count: `cache::increment("views:7", 1,
/// 1.days())!`. A missing or expired key starts from 0 and expires after
/// `ttl`; a key already counting keeps its expiry. `read` gives the number.
///
/// # Errors
///
/// When the store can't be written, or the key holds something other than
/// a number.
pub async fn increment(key: &str, by: i64, ttl: impl Delay) -> Result<i64> {
    let expires_at = crate::time::now() + ttl.delay();
    store()
        .increment(key, by, expires_at)
        .instrument(span("increment", key))
        .await
}

/// Caches `value` under `key` for `ttl` only if nothing live is there,
/// in one step; whether it did. Two callers adding at once: one gets
/// `true`. Locks are built on it.
///
/// # Errors
///
/// When it can't be stored or serialized.
pub async fn add<T: Serialize + ?Sized>(key: &str, value: &T, ttl: impl Delay) -> Result<bool> {
    let value = serde_json::to_string(value)
        .map_err(|e| Error::internal(format!("caching `{key}`: {e}")))?;
    let now = crate::time::now();
    store()
        .add(
            key,
            Entry {
                value,
                written_at: now,
                expires_at: Some(now + ttl.delay()),
            },
        )
        .instrument(span("add", key))
        .await
}

/// Forgets `key` only if it holds `value` (as `write` stored it): a lock
/// lets go only of its own.
///
/// # Errors
///
/// When the store can't be written.
pub async fn delete_if<T: Serialize + ?Sized>(key: &str, value: &T) -> Result<()> {
    let value = serde_json::to_string(value)
        .map_err(|e| Error::internal(format!("caching `{key}`: {e}")))?;
    store()
        .delete_if(key, &value)
        .instrument(span("delete", key))
        .await
}

/// `increment` by `-by`.
///
/// # Errors
///
/// As `increment`'s.
pub async fn decrement(key: &str, by: i64, ttl: impl Delay) -> Result<i64> {
    increment(key, -by, ttl).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
}

/// The cached value for `key`, removed: read once, as Laravel's `pull`.
/// (Another process may read it in between.)
///
/// # Errors
///
/// When the store can't be read or written.
pub async fn pull<T: DeserializeOwned>(key: &str) -> Result<Option<T>> {
    let value = read(key).await?;
    if value.is_some() {
        delete(key).await?;
    }
    Ok(value)
}

/// Forgets every key starting with `prefix` (`"report:"`), returning how
/// many there were.
///
/// # Errors
///
/// When the store can't be written.
pub async fn delete_prefix(prefix: &str) -> Result<u64> {
    store()
        .delete_prefix(prefix)
        .instrument(span("delete_prefix", prefix))
        .await
}

/// Forgets everything in the cache, as `glacier cache clear` does,
/// returning how many values there were.
///
/// # Errors
///
/// When the store can't be written.
pub async fn clear() -> Result<u64> {
    delete_prefix("").await
}

/// `compute`'s value, once per request: later calls in the same request
/// with the same `key` get the first's, without the cache store (as
/// Laravel's `Cache::memo`). Outside a request, computed every time.
///
/// # Errors
///
/// `compute`'s error, which isn't kept.
pub async fn memo<T, F, Fut>(key: &str, compute: F) -> Result<T>
where
    T: Clone + Send + Sync + 'static,
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<T>>,
{
    if let Some(value) = crate::request::memo_get::<T>(key) {
        return Ok(value);
    }
    let value = compute().await?;
    crate::request::memo_set(key, value.clone());
    Ok(value)
}

/// 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?)
}