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
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
use std::time::Duration;

use laravel::Application;
use laravel::cache::{self, CacheManager, Repository};
use laravel::config::Env;
use laravel::config::cache::DatabaseStore;
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, AnyConnection, DatabaseManager, Driver};
use laravel::testing::MakesConsoleRequests;

use crate::cache::eventually;
use crate::support::TempDir;

const MINUTE: Duration = Duration::from_secs(60);
const HOUR: Duration = Duration::from_secs(60 * 60);

fn time(connection: &AnyConnection) -> &'static str {
    match connection.driver() {
        Driver::MySql | Driver::MariaDb => "DATETIME(6)",
        _ => "TIMESTAMP(6)",
    }
}

fn create_table(connection: &AnyConnection, table: &str) -> String {
    let (key, value) = match connection.driver() {
        Driver::MySql | Driver::MariaDb => ("`key` VARCHAR(255) NOT NULL PRIMARY KEY", "`value` MEDIUMTEXT NOT NULL"),
        _ => ("\"key\" VARCHAR(255) NOT NULL PRIMARY KEY", "\"value\" TEXT NOT NULL"),
    };

    format!(
        "CREATE TABLE {table} ({key}, {value}, expiration {} NOT NULL)",
        time(connection)
    )
}

fn create_lock_table(connection: &AnyConnection, table: &str) -> String {
    let key = match connection.driver() {
        Driver::MySql | Driver::MariaDb => "`key` VARCHAR(255) NOT NULL PRIMARY KEY",
        _ => "\"key\" VARCHAR(255) NOT NULL PRIMARY KEY",
    };

    format!(
        "CREATE TABLE {table} ({key}, owner VARCHAR(255) NOT NULL, expiration {} NOT NULL)",
        time(connection)
    )
}

async fn recreate_tables(connection: &AnyConnection, tables: &[&str]) -> laravel::Result<()> {
    for table in tables {
        let create = if table.ends_with("_locks") {
            create_lock_table(connection, table)
        } else {
            create_table(connection, table)
        };

        connection
            .query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
            .statement()
            .await?;
        connection.query(db::sqlx::AssertSqlSafe(create)).statement().await?;
    }

    Ok(())
}

/// An application whose default `database` store is `store` on `laravel_cache`, beside a `reports` store on
/// `laravel_report_cache`. Both share `laravel_cache_locks`, and every table starts empty.
async fn application(connection: ConnectionConfig, store: DatabaseStore) -> laravel::Result<Application> {
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "database")]))
        .with_config(move |config, _| {
            config.database.default = "cache".into();
            config.database.add_connection("cache", connection);
            config
                .cache
                .add_store(
                    "database",
                    store.table("laravel_cache").lock_table("laravel_cache_locks"),
                )
                .add_store(
                    "reports",
                    DatabaseStore::new()
                        .table("laravel_report_cache")
                        .lock_table("laravel_cache_locks")
                        .without_pruning(),
                );
        })
        .create();

    recreate_tables(
        &db_connection(&app).await?,
        &["laravel_cache", "laravel_report_cache", "laravel_cache_locks"],
    )
    .await?;

    Ok(app)
}

fn sqlite(directory: &TempDir) -> ConnectionConfig {
    ConnectionConfig::new(format!(
        "sqlite://{}?mode=rwc",
        directory.join("cache.sqlite").display()
    ))
}

async fn db_connection(app: &Application) -> laravel::Result<AnyConnection> {
    app.resolve::<DatabaseManager>().await.default_connection()
}

async fn store(app: &Application, name: &str) -> laravel::Result<Repository> {
    app.resolve::<CacheManager>().await.store(name)
}

async fn count_rows(app: &Application, table: &str) -> laravel::Result<i64> {
    let count = db_connection(app)
        .await?
        .query(db::sqlx::AssertSqlSafe(format!("SELECT COUNT(*) FROM {table}")))
        .scalar::<i64>()
        .await?;

    Ok(count.unwrap_or_default())
}

async fn count_expired(app: &Application, table: &str) -> laravel::Result<i64> {
    let now = app.scope(async || laravel::now().timestamp()).await;
    let connection = db_connection(app).await?;
    let placeholder = if connection.driver() == Driver::Postgres {
        "$1"
    } else {
        "?"
    };
    let count = connection
        .query(db::sqlx::AssertSqlSafe(format!(
            "SELECT COUNT(*) FROM {table} WHERE expiration <= {placeholder}"
        )))
        .bind(now)
        .scalar::<i64>()
        .await?;

    Ok(count.unwrap_or_default())
}

async fn store_contract(app: &Application) -> laravel::Result<()> {
    let cache = store(app, "database").await?;
    let reports = store(app, "reports").await?;
    crate::cache::store_contract(app, &cache).await?;

    let (removed, stored) = tokio::join!(biased; cache.forget("report"), cache.put("report", 42, MINUTE));
    stored?;
    assert_eq!(cache.get::<i64>("report").await?, (!removed?).then_some(42));

    cache.put("user", 1, MINUTE).await?;
    assert_eq!(
        reports.get::<i64>("user").await?,
        None,
        "stores sharing a connection keep their own tables"
    );
    reports.put("kept", 1, MINUTE).await?;
    cache.flush().await?;
    assert!(!cache.has("user").await?);
    assert!(reports.has("kept").await?, "flushing empties only the store's table");

    assert!(cache.lock("shared", MINUTE).acquire().await?);
    assert!(
        !reports.lock("shared", MINUTE).acquire().await?,
        "stores sharing a lock table share their locks"
    );
    cache.lock("shared", MINUTE).force_release().await?;

    prune_contract(app, &cache).await?;
    app.travel_back();
    Ok(())
}

async fn prune_contract(app: &Application, cache: &Repository) -> laravel::Result<()> {
    let expiring: Vec<(String, i64)> = (0..1500).map(|n| (format!("expiring:{n}"), n)).collect();
    cache.put_many(expiring, Duration::from_secs(1)).await?;
    cache.put("kept", true, HOUR).await?;
    assert!(cache.lock("expiring", Duration::from_secs(1)).acquire().await?);
    app.travel(Duration::from_secs(2));
    assert!(count_expired(app, "laravel_cache").await? >= 1500);

    cache.prune().await?;

    assert_eq!(count_expired(app, "laravel_cache").await?, 0, "every batch was pruned");
    assert_eq!(count_expired(app, "laravel_cache_locks").await?, 0);
    assert_eq!(cache.get::<bool>("kept").await?, Some(true));
    Ok(())
}

#[tokio::test]
async fn sqlite_stores_values_in_their_tables() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite");
    let mut connection = sqlite(&directory);
    connection.max_connections = 1;
    let app = application(connection, DatabaseStore::new().without_pruning()).await?;

    app.scope(async || store_contract(&app).await).await
}

#[tokio::test]
async fn cache_writes_join_a_transaction_on_their_connection_and_roll_back_with_it() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-transaction");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;

    app.scope(async || {
        db::transaction(async |tx| {
            tx.query("SELECT 1").statement().await?;
            cache::put("committed", 1, MINUTE).await?;
            let rows = tx.query("SELECT COUNT(*) FROM laravel_cache").scalar::<i64>().await?;
            assert_eq!(rows, Some(1), "the cache wrote in the transaction");
            Ok(())
        })
        .await?;

        let rolled_back: laravel::Result<()> = db::transaction(async |_| {
            cache::put("rolled-back", 2, MINUTE).await?;
            assert_eq!(cache::get::<i64>("rolled-back").await?, Some(2));
            Err(laravel::abort_with(409, "Roll back"))
        })
        .await;
        assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);

        let cache = cache::store("database")?;
        assert_eq!(cache.get::<i64>("committed").await?, Some(1));
        assert_eq!(cache.get::<i64>("rolled-back").await?, None);
        Ok(())
    })
    .await
}

/// A lock taken inside a transaction is visible outside it straight away, and a rollback keeps it.
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn transaction_lock_contract(app: &Application) -> laravel::Result<()> {
    let cache = store(app, "database").await?;
    let outside = db::default_connection()?.outside_transaction();
    let locks = async || -> laravel::Result<Option<i64>> {
        outside
            .query("SELECT COUNT(*) FROM laravel_cache_locks")
            .scalar::<i64>()
            .await
    };
    let rolled_back: laravel::Result<()> = db::transaction(async |tx| {
        tx.query("SELECT COUNT(*) FROM laravel_cache").select().await?;
        assert!(cache.lock("invoice", MINUTE).acquire().await?);
        assert_eq!(
            locks().await?,
            Some(1),
            "other connections see the lock before the commit"
        );
        Err(laravel::abort_with(409, "Roll back"))
    })
    .await;
    let error = rolled_back.unwrap_err();
    assert_eq!(error.status().as_u16(), 409, "{error:?}");
    assert_eq!(locks().await?, Some(1), "the rollback doesn't release the lock");
    assert!(!cache.lock("invoice", MINUTE).acquire().await?);
    Ok(())
}

/// A counter incremented inside a transaction sees the latest value, even when another connection
/// changed it after the transaction's snapshot. A snapshot read would retry the increment forever.
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
/// MariaDB 11.6+ refuses a locking read of a row changed since the transaction's snapshot, so there
/// the transaction retries, and its second attempt reads the changed row.
async fn transaction_increment_contract() -> laravel::Result<()> {
    let connection = db::default_connection()?;
    let mariadb = matches!(connection.driver(), Driver::MySql | Driver::MariaDb)
        && connection
            .query("SELECT VERSION() LIKE '%MariaDB%'")
            .scalar::<i64>()
            .await?
            == Some(1);
    cache::put("hits", 1, MINUTE).await?;
    let attempts = std::sync::atomic::AtomicU32::new(0);
    connection
        .transaction_with_attempts(2, async |_| {
            let first = attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0;
            assert_eq!(cache::get::<i64>("hits").await?, Some(if first { 1 } else { 5 }));
            if first {
                db::default_connection()?
                    .outside_transaction()
                    .query("UPDATE laravel_cache SET value = '5'")
                    .update()
                    .await?;
            }
            let incremented = tokio::time::timeout(std::time::Duration::from_secs(5), cache::increment("hits", 1))
                .await
                .expect("the increment must not retry a stale read forever")?;
            assert_eq!(incremented, Some(6));
            Ok(())
        })
        .await?;
    assert_eq!(attempts.into_inner(), if mariadb { 2 } else { 1 });
    assert_eq!(cache::get::<i64>("hits").await?, Some(6));
    Ok(())
}

/// SQLite allows one writer, so a lock outside a transaction that has written would wait for that
/// transaction. A lock there joins the transaction instead, and a rollback releases it.
#[tokio::test]
async fn sqlite_locks_join_transactions_instead_of_waiting_for_them() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-locks");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;

    app.scope(async || {
        let cache = store(&app, "database").await?;
        let rolled_back: laravel::Result<()> = db::transaction(async |tx| {
            tx.query(
                "INSERT INTO laravel_cache (key, value, expiration) VALUES ('written', '1', '2000-01-01 00:00:00')",
            )
            .insert()
            .await?;
            let acquired = tokio::time::timeout(
                std::time::Duration::from_secs(2),
                cache.lock("invoice", MINUTE).acquire(),
            )
            .await
            .expect("the lock doesn't wait for the transaction it runs in")?;
            assert!(acquired);
            assert!(
                !cache.lock("invoice", MINUTE).acquire().await?,
                "the lock is held inside the transaction"
            );
            Err(laravel::abort_with(409, "Roll back"))
        })
        .await;
        assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
        assert!(
            cache.lock("invoice", MINUTE).acquire().await?,
            "the rollback released the lock"
        );
        Ok(())
    })
    .await
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn sqlite_counters_and_claims_are_atomic() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-concurrency");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;

    app.scope(crate::cache::concurrency_contract).await
}

#[tokio::test]
async fn rows_hold_prefixed_keys_json_values_and_expirations() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-rows");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
    app.travel_to("2026-10-12T12:00:00Z".parse::<laravel::time::Timestamp>()?);

    let cache = store(&app, "database").await?;
    app.scope(async || {
        cache
            .put("user", serde_json::json!({ "name": "Taylor" }), MINUTE)
            .await?;
        cache.put("hour", 1, HOUR).await
    })
    .await?;

    let rows = db_connection(&app)
        .await?
        .query("SELECT \"key\", \"value\", expiration FROM laravel_cache ORDER BY \"key\"")
        .select()
        .await?;
    let rows: Vec<(String, String, laravel::time::Timestamp)> = rows
        .iter()
        .map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?)))
        .collect::<laravel::Result<_>>()?;

    assert_eq!(
        rows,
        [
            (
                "laravel_cache_hour".to_owned(),
                "1".to_owned(),
                "2026-10-12T13:00:00Z".parse()?
            ),
            (
                "laravel_cache_user".to_owned(),
                r#"{"name":"Taylor"}"#.to_owned(),
                "2026-10-12T12:01:00Z".parse()?
            ),
        ]
    );
    Ok(())
}

#[tokio::test]
async fn the_connection_is_chosen_for_each_operation() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-scoped");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
    let manager = app.resolve::<DatabaseManager>().await;
    let tenant = TempDir::new("cache-sqlite-tenant");
    manager.add_connection("tenant", sqlite(&tenant));
    recreate_tables(&manager.connection("tenant")?, &["laravel_report_cache"]).await?;

    app.scope(async || {
        let reports = store(&app, "reports").await?;
        reports.put("key", "default", MINUTE).await?;
        manager
            .using_connection("tenant", reports.put("key", "tenant", MINUTE))
            .await?;

        assert_eq!(reports.get::<String>("key").await?.as_deref(), Some("default"));
        assert_eq!(
            manager
                .using_connection("tenant", reports.get::<String>("key"))
                .await?
                .as_deref(),
            Some("tenant")
        );
        Ok(())
    })
    .await
}

#[tokio::test]
async fn database_stores_open_nothing_until_used() -> laravel::Result<()> {
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "database")]))
        .with_config(|config, _| {
            config.database.default = "unreachable".into();
            let mut unreachable = ConnectionConfig::new("postgres://laravel@127.0.0.1:1/laravel");
            unreachable.acquire_timeout = Duration::from_millis(100).into();
            config.database.add_connection("unreachable", unreachable);
        })
        .create();

    app.command("route:list --json").await.assert_successful();

    assert!(app.scope(async || cache::get::<i64>("key").await).await.is_err());
    Ok(())
}

#[tokio::test]
async fn missing_tables_and_invalid_table_names_are_errors() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-invalid");
    let connection = sqlite(&directory);
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "database")]))
        .with_config(move |config, _| {
            config.database.add_connection("sqlite", connection);
            config.database.default = "sqlite".into();
            config
                .cache
                .add_store("invalid", DatabaseStore::new().table("cache; DROP TABLE users"));
        })
        .create();
    assert!(app.scope(async || cache::get::<i64>("key").await).await.is_err());
    let invalid = app.resolve::<CacheManager>().await.store("invalid").unwrap_err();
    assert!(invalid.to_string().contains("must be letters, digits and underscores"));
    Ok(())
}

#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_stores_values_in_their_tables() -> laravel::Result<()> {
    let url = std::env::var("LARAVEL_TEST_POSTGRES_URL")?;
    let app = application(ConnectionConfig::new(url), DatabaseStore::new().without_pruning()).await?;

    app.scope(async || store_contract(&app).await).await?;
    app.scope(crate::cache::concurrency_contract).await?;
    recreate_tables(&db_connection(&app).await?, &["laravel_cache_locks"]).await?;
    app.scope(async || transaction_lock_contract(&app).await).await?;
    app.scope(transaction_increment_contract).await
}

#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_stores_values_in_their_tables() -> laravel::Result<()> {
    let url = std::env::var("LARAVEL_TEST_MYSQL_URL")?;
    let app = application(ConnectionConfig::new(url), DatabaseStore::new().without_pruning()).await?;

    app.scope(async || store_contract(&app).await).await?;
    app.scope(crate::cache::concurrency_contract).await?;
    recreate_tables(&db_connection(&app).await?, &["laravel_cache_locks"]).await?;
    app.scope(async || transaction_lock_contract(&app).await).await?;
    app.scope(transaction_increment_contract).await
}

#[tokio::test]
async fn cache_prune_deletes_expired_values_and_locks() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-prune");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
    app.freeze_time();

    app.scope(async || {
        let cache = laravel::cache::store("database")?;
        let expiring: Vec<(String, i64)> = (0..2500).map(|n| (format!("expiring:{n}"), n)).collect();
        cache.put_many(expiring, Duration::from_secs(1)).await?;
        cache.put("kept", 1, HOUR).await?;
        cache.lock("expiring", Duration::from_secs(1)).acquire().await?;
        cache.lock("held", HOUR).acquire().await
    })
    .await?;
    app.travel(Duration::from_secs(2));

    app.command("cache:prune database")
        .await
        .assert_successful()
        .assert_error_output_contains("Expired entries pruned from cache store `database`.");

    assert_eq!(count_rows(&app, "laravel_cache").await?, 1);
    assert_eq!(count_rows(&app, "laravel_cache_locks").await?, 1);
    Ok(())
}

#[tokio::test]
async fn servers_sharing_the_tables_prune_once_per_interval() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-background-prune");
    let first = application(sqlite(&directory), DatabaseStore::new()).await?;
    let second = application(sqlite(&directory), DatabaseStore::new()).await?;
    let connection = db_connection(&first).await?;
    let start = "2026-10-12T12:00:00Z".parse::<laravel::time::Timestamp>()?;
    let travel = |offset: Duration| {
        first.travel_to(start + offset);
        second.travel_to(start + offset);
    };

    connection
        .query(db::sqlx::AssertSqlSafe(format!(
            "INSERT INTO laravel_cache VALUES ('laravel_cache_old', '1', '{}')",
            (start + Duration::from_secs(1)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
        )))
        .statement()
        .await?;
    connection
        .query(db::sqlx::AssertSqlSafe(format!(
            "INSERT INTO laravel_cache_locks VALUES ('laravel:cache:prune:laravel_cache', 'elsewhere', '{}')",
            (start + HOUR).strftime("%Y-%m-%dT%H:%M:%S+00:00")
        )))
        .statement()
        .await?;

    travel(Duration::from_secs(2));
    second
        .scope(async || laravel::cache::put("new", 1, HOUR * 2).await)
        .await?;
    first
        .scope(async || laravel::cache::put("newer", 1, HOUR * 2).await)
        .await?;
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert_eq!(
        count_expired(&first, "laravel_cache").await?,
        1,
        "the expired value is still there"
    );

    travel(HOUR + Duration::from_secs(3));
    first
        .scope(async || laravel::cache::put("latest", 1, HOUR).await)
        .await?;
    assert!(
        eventually(async || Ok(count_expired(&first, "laravel_cache").await? == 0)).await?,
        "the expired value is pruned"
    );
    assert_eq!(count_rows(&first, "laravel_cache").await?, 3);
    Ok(())
}

#[tokio::test]
async fn stores_without_pruning_leave_expired_rows() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-no-prune");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
    app.freeze_time();

    app.scope(async || laravel::cache::put("old", 1, Duration::from_secs(1)).await)
        .await?;
    app.travel(Duration::from_secs(2));
    app.scope(async || laravel::cache::put("new", 1, HOUR).await).await?;
    tokio::time::sleep(Duration::from_millis(50)).await;

    assert_eq!(count_expired(&app, "laravel_cache").await?, 1);
    assert_eq!(count_rows(&app, "laravel_cache_locks").await?, 0);
    Ok(())
}

#[tokio::test]
async fn background_pruning_clears_a_backlog_in_one_pass() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-prune-backlog");
    let app = application(sqlite(&directory), DatabaseStore::new()).await?;
    app.freeze_time();

    app.scope(async || {
        let cache = laravel::cache::store("database")?;
        for batch in 0..5 {
            let expiring: Vec<(String, i64)> = (0..2500).map(|n| (format!("expiring:{batch}:{n}"), n)).collect();
            cache.put_many(expiring, Duration::from_secs(1)).await?;
        }
        Ok::<_, laravel::Error>(())
    })
    .await?;
    app.travel(HOUR + Duration::from_secs(2));
    app.scope(async || laravel::cache::put("new", 1, HOUR).await).await?;

    assert!(
        eventually(async || Ok(count_expired(&app, "laravel_cache").await? == 0)).await?,
        "{} expired values are left after one prune",
        count_expired(&app, "laravel_cache").await?
    );
    Ok(())
}

#[tokio::test]
async fn values_and_locks_last_at_least_their_lifetime() -> laravel::Result<()> {
    let directory = TempDir::new("cache-sqlite-whole-lifetime");
    let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
    let start = "2026-10-28T12:00:00.990Z".parse::<laravel::time::Timestamp>()?;

    app.travel_to(start);
    let first = app
        .scope(async || {
            laravel::cache::put("value", 1, Duration::from_secs(1)).await?;
            laravel::cache::lock("job", Duration::from_secs(1))?.acquire().await
        })
        .await?;
    app.travel_to(start + Duration::from_millis(10));
    let (value, second) = app
        .scope(async || {
            let value = laravel::cache::get::<i64>("value").await?;
            Ok::<_, laravel::Error>((
                value,
                laravel::cache::lock("job", Duration::from_secs(1))?.acquire().await?,
            ))
        })
        .await?;

    assert!(first);
    assert_eq!(value, Some(1), "a one-second value expired after 10 milliseconds");
    assert!(!second, "a second owner took a one-second lock 10 milliseconds later");
    Ok(())
}