laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP 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
use crate::container::ContainerInternals as _;
use std::collections::HashMap;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;

use jiff::Timestamp;

use super::{Store, add_to_integer};
use crate::config::cache::DatabaseStore as DatabaseStoreConfig;
use crate::container::Container;
use crate::db::{AnyConnection, Builder, DatabaseManager, Driver, Values, col, values};
use crate::error::Result;

pub(super) struct DatabaseStore {
    database: Arc<DatabaseManager>,
    connection: Option<String>,
    table: String,
    lock_connection: Option<String>,
    lock_table: String,
    prune_every: Option<Duration>,
    /// When this process next checks whether a prune is due, in seconds on the application's clock.
    next_prune_check: AtomicI64,
    /// The store itself, for the background prune task to own.
    this: Weak<Self>,
}

const PRUNE_BATCH: u64 = 1000;

/// Create the database store for the cache manager, which sits below the database.
pub(super) fn create(services: &Container, config: &DatabaseStoreConfig) -> Result<Arc<dyn super::ErasedStore>> {
    let Some(database) = services.built::<DatabaseManager>() else {
        return Err(crate::error::fail(
            "the database cache store needs the database manager",
        ));
    };

    Ok(DatabaseStore::new(database, config)?)
}

impl DatabaseStore {
    pub(super) fn new(database: Arc<DatabaseManager>, config: &DatabaseStoreConfig) -> Result<Arc<Self>> {
        for table in [&config.table, &config.lock_table] {
            if !crate::db::identifier::is_identifier_path(table) {
                return Err(crate::error::fail(format!(
                    "the cache table `{table}` must be letters, digits and underscores, optionally schema-qualified"
                )));
            }
        }

        Ok(Arc::new_cyclic(|this| Self {
            database,
            connection: config.connection.clone(),
            table: config.table.clone(),
            lock_connection: config.lock_connection.clone(),
            lock_table: config.lock_table.clone(),
            prune_every: config.prune_every.map(Duration::from),
            next_prune_check: AtomicI64::new(0),
            this: this.clone(),
        }))
    }

    fn connection(&self) -> Result<AnyConnection> {
        self.connection.as_ref().map_or_else(
            || self.database.default_connection(),
            |name| self.database.connection(name),
        )
    }

    /// Locks stay outside any open transaction, so other connections see a lock while it's held. On
    /// SQLite, which allows one writer, a lock outside would wait for a transaction that has written, so
    /// it joins the transaction there. Other processes can't write until the transaction ends anyway.
    fn lock_connection(&self) -> Result<AnyConnection> {
        let connection = self
            .lock_connection
            .as_ref()
            .map_or_else(|| self.connection(), |name| self.database.connection(name))?;
        Ok(match connection.driver() {
            Driver::Sqlite => connection,
            _ => connection.outside_transaction(),
        })
    }

    fn values(&self) -> Result<Builder> {
        Ok(self.connection()?.table(self.table.as_str()))
    }

    fn locks(&self) -> Result<Builder> {
        Ok(self.lock_connection()?.table(self.lock_table.as_str()))
    }

    /// When a value written now with `ttl` expires.
    fn value_expiration(&self, ttl: Duration) -> Result<Timestamp> {
        Ok(expiration(ttl, self.connection()?.configuration().time_precision))
    }

    /// When a lock acquired now with `ttl` expires.
    fn lock_expiration(&self, ttl: Duration) -> Result<Timestamp> {
        Ok(expiration(ttl, self.lock_connection()?.configuration().time_precision))
    }

    fn prune_when_due(&self) {
        let Some(interval) = self.prune_every else {
            return;
        };

        let now = now().as_second();
        let next = self.next_prune_check.load(Ordering::Relaxed);
        let following = now.saturating_add(i64::try_from(interval.as_secs()).unwrap_or(i64::MAX));
        if now < next
            || self
                .next_prune_check
                .compare_exchange(next, following, Ordering::Relaxed, Ordering::Relaxed)
                .is_err()
        {
            return;
        }

        let Some(store) = self.this.upgrade() else {
            return;
        };

        let _ = crate::task::background(async move {
            if let Err(error) = store.prune_once_per_interval(interval).await {
                crate::foundation::telemetry::logging(
                    &error,
                    || tracing::warn!(%error, table = %store.table, "The cache couldn't prune expired entries"),
                );
            }

            Ok(())
        });
    }

    async fn prune_once_per_interval(&self, interval: Duration) -> Result<()> {
        let name = format!("laravel:cache:prune:{}", self.table);
        if !self.acquire_lock(&name, &super::owner_token(), interval).await? {
            return Ok(());
        }

        self.prune_expired().await
    }

    /// Delete expired rows in batches, until a batch comes back short, so no statement holds
    /// the table for long. Each batch deletes the keys it found only if they're still expired...
    async fn prune_expired(&self) -> Result<()> {
        for table in [self.values()?, self.locks()?] {
            loop {
                let expired = table.clone().filter(col("expiration").le(now()));
                let keys: Vec<String> = expired.clone().limit(PRUNE_BATCH).pluck("key").await?;
                expired.filter(col("key").is_in(&keys)).delete().await?;
                if keys.len() < PRUNE_BATCH as usize {
                    break;
                }
            }
        }

        Ok(())
    }
}

impl Store for DatabaseStore {
    async fn get(&self, key: &str) -> Result<Option<String>> {
        let values = self.values()?.filter(col("key").eq(key));
        let row = values
            .clone()
            .select(["value", "expiration"])
            .into_query()
            .retry_on_lost_connection()
            .select_one_as::<(String, Timestamp)>()
            .await?;
        let Some((value, expiration)) = row else {
            return Ok(None);
        };

        let now = now();
        if expiration <= now {
            values.filter(col("expiration").le(now)).delete().await?;
            return Ok(None);
        }

        Ok(Some(value))
    }

    async fn put(&self, key: &str, value: String, ttl: Duration) -> Result<()> {
        self.put_many(vec![(key.to_owned(), value)], ttl).await
    }

    async fn add(&self, key: &str, value: String, ttl: Duration) -> Result<bool> {
        self.prune_when_due();
        let values = self.values()?;

        values
            .clone()
            .filter(col("key").eq(key) & col("expiration").le(now()))
            .delete()
            .await?;
        let inserted = values
            .insert_or_ignore(values! { key: key, value: value, expiration: self.value_expiration(ttl)? })
            .await?;

        Ok(inserted > 0)
    }

    async fn increment(&self, key: &str, by: i64) -> Result<Option<i64>> {
        let values = self.values()?.filter(col("key").eq(key));
        loop {
            // A locking read sees the latest committed value inside a transaction, where a snapshot read
            // would keep returning the value the update below no longer matches...
            let row = values
                .clone()
                .select(["value", "expiration"])
                .lock_for_update()
                .first::<(String, Timestamp)>()
                .await?;
            let Some((current, expires)) = row else {
                return Ok(None);
            };
            if expires <= now() {
                return Ok(None);
            }

            let value = add_to_integer(key, &current, by)?;
            if by == 0 {
                return Ok(Some(value));
            }

            let updated = values
                .clone()
                .filter(col("value").eq(current))
                .update(values! { value: value.to_string() })
                .await?;
            if updated > 0 {
                return Ok(Some(value));
            }
        }
    }

    async fn forget(&self, key: &str) -> Result<bool> {
        let values = self.values()?.filter(col("key").eq(key));
        let now = now();
        let removed = values.clone().filter(col("expiration").gt(now)).delete().await?;
        if removed > 0 {
            return Ok(true);
        }

        values.filter(col("expiration").le(now)).delete().await?;

        Ok(false)
    }

    async fn flush(&self) -> Result<()> {
        self.values()?.delete().await?;

        Ok(())
    }

    async fn compare_and_swap(&self, key: &str, current: Option<&str>, new: String, ttl: Duration) -> Result<bool> {
        let Some(current) = current else {
            return self.add(key, new, ttl).await;
        };

        let swapped = self
            .values()?
            .filter(col("key").eq(key) & col("value").eq(current) & col("expiration").gt(now()))
            .update(values! { value: new, expiration: self.value_expiration(ttl)? })
            .await?;

        Ok(swapped > 0)
    }

    async fn touch(&self, key: &str, ttl: Duration) -> Result<bool> {
        let touched = self
            .values()?
            .filter(col("key").eq(key) & col("expiration").gt(now()))
            .update(values! { expiration: self.value_expiration(ttl)? })
            .await?;

        Ok(touched > 0)
    }

    async fn many(&self, keys: &[String]) -> Result<Vec<Option<String>>> {
        if keys.is_empty() {
            return Ok(Vec::new());
        }

        let rows = self
            .values()?
            .select(["key", "value", "expiration"])
            .filter(col("key").is_in(keys))
            .into_query()
            .retry_on_lost_connection()
            .select_as::<(String, String, Timestamp)>()
            .await?;
        let now = now();
        let found: HashMap<String, String> = rows
            .into_iter()
            .filter(|(_, _, expiration)| *expiration > now)
            .map(|(key, value, _)| (key, value))
            .collect();

        Ok(keys.iter().map(|key| found.get(key).cloned()).collect())
    }

    async fn put_many(&self, values: Vec<(String, String)>, ttl: Duration) -> Result<()> {
        self.prune_when_due();
        // One statement can't change a row twice, so a repeated key keeps its last value...
        let mut unique: Vec<(String, String)> = Vec::with_capacity(values.len());
        let mut positions = HashMap::new();
        for (key, value) in values {
            if let Some(&position) = positions.get(&key) {
                unique[position] = (key, value);
            } else {
                positions.insert(key.clone(), unique.len());
                unique.push((key, value));
            }
        }

        let expiration = self.value_expiration(ttl)?;
        let rows: Vec<Values> = unique
            .into_iter()
            .map(|(key, value)| values! { key: key, value: value, expiration: expiration })
            .collect();
        self.values()?.upsert(rows, ["key"], ["value", "expiration"]).await?;

        Ok(())
    }

    async fn prune(&self) -> Result<()> {
        self.prune_expired().await
    }

    async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> Result<bool> {
        self.prune_when_due();
        let locks = self.locks()?;
        let expiration = self.lock_expiration(ttl)?;
        let inserted = locks
            .insert_or_ignore(values! { key: name, owner: owner, expiration: expiration })
            .await?;

        let acquired = inserted > 0
            || locks
                .filter(col("key").eq(name) & col("expiration").le(now()))
                .update(values! { owner: owner, expiration: expiration })
                .await?
                > 0;

        Ok(acquired)
    }

    async fn release_lock(&self, name: &str, owner: &str) -> Result<bool> {
        let released = self
            .locks()?
            .filter(col("key").eq(name) & col("owner").eq(owner) & col("expiration").gt(now()))
            .delete()
            .await?;

        Ok(released > 0)
    }

    async fn force_release_lock(&self, name: &str) -> Result<()> {
        self.locks()?.filter(col("key").eq(name)).delete().await?;

        Ok(())
    }

    async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> Result<bool> {
        let refreshed = self
            .locks()?
            .filter(col("key").eq(name) & col("owner").eq(owner) & col("expiration").gt(now()))
            .update(values! { expiration: self.lock_expiration(ttl)? })
            .await?;

        Ok(refreshed > 0)
    }

    async fn lock_owner(&self, name: &str) -> Result<Option<String>> {
        self.locks()?
            .filter(col("key").eq(name) & col("expiration").gt(now()))
            .use_write_connection()
            .value("owner")
            .await
    }
}

fn now() -> Timestamp {
    crate::clock::system_timestamp()
}

/// When a value or lock with this lifetime expires, rounded up to the connection's `precision`,
/// the fractional digits of seconds it keeps. A write truncates a time to that precision, which
/// would otherwise expire the value early.
fn expiration(ttl: Duration, precision: u8) -> Timestamp {
    let Ok(expires) = now().checked_add(ttl) else {
        return Timestamp::MAX;
    };
    let step = 10_i128.pow(9 - u32::from(precision.min(9)));
    let nanoseconds = expires.as_nanosecond();
    let rounded = nanoseconds + (step - nanoseconds.rem_euclid(step)) % step;

    Timestamp::from_nanosecond(rounded).unwrap_or(Timestamp::MAX)
}

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

    #[test]
    fn expirations_round_up_to_the_connections_precision() {
        let now = now();

        let whole = expiration(Duration::from_millis(1500), 0);
        assert!(whole >= now + Duration::from_millis(1500) && whole.subsec_nanosecond() == 0);
        let micros = expiration(Duration::from_nanos(1), 6);
        assert!(micros > now && micros.subsec_nanosecond() % 1000 == 0);
        assert_eq!(expiration(Duration::MAX, 6), Timestamp::MAX);
    }
}