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
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use laravel::Application;
use laravel::cache::{self, CacheManager, LockTimeout, MemoryStore, Repository, Store};
use laravel::config::Env;
use laravel::config::cache::StoreConfig;
use laravel::container::Inject;
use laravel::http::middleware::Timeout;
use laravel::testing::{MakesConsoleRequests, MakesHttpRequests};
use laravel::time::ToSpan;
use serde::{Deserialize, Serialize};

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

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
}

fn taylor() -> User {
    User {
        id: 42,
        name: "Taylor".into(),
    }
}

fn app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.cache.add_store("other", StoreConfig::Memory);
        })
        .create()
}

pub(crate) async fn eventually(mut done: impl AsyncFnMut() -> laravel::Result<bool>) -> laravel::Result<bool> {
    for _ in 0..200 {
        if done().await? {
            return Ok(true);
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }

    Ok(false)
}

/// What every store with locks keeps, checked here on the memory store and in `cache_database` on
/// each database. Run it inside a scope of `app`.
pub(crate) async fn store_contract(app: &Application, cache: &Repository) -> laravel::Result<()> {
    // Database rows expire on whole seconds, so start on one to keep each lifetime exact...
    app.travel_to("2026-10-12T12:00:00Z".parse::<laravel::time::Timestamp>()?);

    cache.put("user", vec!["Taylor", "Abigail"], MINUTE).await?;
    cache.put("user", vec!["Taylor"], MINUTE).await?;
    assert_eq!(cache.get::<Vec<String>>("user").await?, Some(vec!["Taylor".to_owned()]));
    assert!(cache.get::<i64>("user").await.is_err(), "another type is an error");
    cache.put("long", true, HOUR).await?;

    assert!(cache.add("claim", "first", MINUTE).await?);
    assert!(!cache.add("claim", "second", MINUTE).await?);
    assert_eq!(cache.get::<String>("claim").await?.as_deref(), Some("first"));

    assert_eq!(cache.increment("visits", 1).await?, None);
    assert!(!cache.has("visits").await?, "a missing counter stays missing");
    cache.add("visits", 0, MINUTE).await?;
    assert_eq!(cache.increment("visits", 5).await?, Some(5));
    assert_eq!(cache.decrement("visits", 2).await?, Some(3));
    assert_eq!(cache.increment("visits", 0).await?, Some(3));
    assert!(cache.increment("user", 1).await.is_err());
    cache.put("max", i64::MAX, MINUTE).await?;
    assert!(cache.increment("max", 1).await.is_err());
    assert!(cache.decrement("max", i64::MIN).await.is_err());
    assert_eq!(cache.get::<i64>("max").await?, Some(i64::MAX));

    app.travel(Duration::from_secs(59));
    assert!(cache.has("user").await?);
    app.travel(Duration::from_secs(1));
    assert_eq!(
        cache.get::<Vec<String>>("user").await?,
        None,
        "values expire on the application's clock"
    );
    assert_eq!(cache.increment("visits", 1).await?, None, "counters keep their expiry");
    assert!(
        cache.add("claim", "third", MINUTE).await?,
        "an expired value can be replaced"
    );
    assert_eq!(cache.get::<String>("claim").await?.as_deref(), Some("third"));
    assert_eq!(cache.get::<bool>("long").await?, Some(true));

    cache.put("expired", 1, Duration::from_secs(1)).await?;
    app.travel(Duration::from_secs(1));
    assert!(
        !cache.forget("expired").await?,
        "an expired value wasn't there to remove"
    );
    assert!(cache.forget("long").await?);
    assert!(!cache.has("long").await?);

    assert_eq!(cache.increment_or_add("hits", 1, MINUTE).await?, 1);
    assert_eq!(cache.increment_or_add("hits", 2, HOUR).await?, 3);
    assert_eq!(cache.increment_or_add("stock", -1, MINUTE).await?, -1);
    assert_eq!(cache.increment_or_add("zero", 1, Duration::ZERO).await?, 1);
    assert!(!cache.has("zero").await?, "a zero lifetime adds nothing");
    cache.put("name", "Taylor", MINUTE).await?;
    assert!(cache.increment_or_add("name", 1, MINUTE).await.is_err());
    app.travel(MINUTE);
    assert_eq!(
        cache.increment_or_add("hits", 1, MINUTE).await?,
        1,
        "the counter kept its first lifetime, then started again"
    );

    cache.put("report", "ready", MINUTE).await?;
    app.travel(Duration::from_secs(50));
    assert!(cache.touch("report", MINUTE).await?);
    app.travel(Duration::from_secs(50));
    assert!(cache.has("report").await?, "the value outlives its first lifetime");
    app.travel(Duration::from_secs(10));
    assert!(!cache.has("report").await?);
    assert!(!cache.touch("report", MINUTE).await?, "an expired value isn't revived");
    assert!(!cache.touch("missing", MINUTE).await?);
    cache.put("removed", 1, MINUTE).await?;
    assert!(cache.touch("removed", Duration::ZERO).await?);
    assert!(!cache.has("removed").await?, "a zero lifetime removes the key");

    cache.put_many([("a", 1), ("b", 2), ("a", 3)], MINUTE).await?;
    cache.put_many([("b", 4)], MINUTE).await?;
    assert_eq!(
        cache.many::<i64>(["a", "missing", "b"]).await?,
        [Some(3), None, Some(4)],
        "a repeated key keeps its last value, and existing keys are replaced"
    );
    assert!(cache.many::<i64>(Vec::<String>::new()).await?.is_empty());
    cache.put_many([("a", 1)], Duration::ZERO).await?;
    assert_eq!(cache.many::<i64>(["a", "b"]).await?, [None, Some(4)]);
    app.travel(MINUTE);
    assert_eq!(cache.many::<i64>(["b"]).await?, [None]);

    let first = cache.lock("reports", Duration::from_secs(10));
    let second = cache.lock("reports", Duration::from_secs(10));
    assert_ne!(first.owner(), second.owner());
    assert!(first.acquire().await?);
    assert!(!second.acquire().await?);
    assert!(
        !first.acquire().await?,
        "a held lock isn't taken again, even by its owner"
    );
    assert!(first.is_owned().await? && !second.is_owned().await?);
    assert!(second.is_locked().await?);
    assert!(!second.release().await?, "only the owner releases a lock");
    assert!(first.release().await?);
    assert!(!first.is_locked().await?);
    assert!(second.acquire().await?);

    app.travel(Duration::from_secs(9));
    assert!(second.refresh().await?);
    app.travel(Duration::from_secs(9));
    assert!(!first.acquire().await?, "a refreshed lock is still held");
    app.travel(Duration::from_secs(1));
    assert!(first.acquire().await?, "an expired lock can be taken");
    assert!(!second.refresh().await?, "an expired lock can't be refreshed");

    cache.put("value", 1, MINUTE).await?;
    cache.flush().await?;
    assert!(!cache.has("value").await?);
    assert!(first.is_owned().await?, "flushing keeps locks");

    let restored = cache.restore_lock("reports", first.owner());
    assert!(restored.refresh_for(MINUTE).await?);
    assert!(restored.release().await?);
    assert!(!first.is_locked().await?);
    assert!(second.acquire().await?);
    first.force_release().await?;
    assert!(!second.is_locked().await?);
    assert_eq!(cache.lock("reports", MINUTE).get(|| async { Ok(1) }).await?, Some(1));
    assert!(!first.is_locked().await?, "get releases the lock");

    let calls = Arc::new(AtomicUsize::new(0));
    let flexible = || {
        let calls = Arc::clone(&calls);
        cache.flexible(
            "stats",
            Duration::from_secs(5),
            Duration::from_secs(10),
            move || async move { Ok(calls.fetch_add(1, Ordering::SeqCst) + 1) },
        )
    };
    assert_eq!(flexible().await?, 1, "a miss computes the value");
    app.travel(Duration::from_secs(4));
    assert_eq!(flexible().await?, 1, "a fresh value is served");
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    app.travel(Duration::from_secs(2));
    assert_eq!(flexible().await?, 1, "a stale value is served while it refreshes");
    assert!(eventually(async || Ok(cache.get::<usize>("stats").await? == Some(2))).await?);
    assert_eq!(flexible().await?, 2, "the refreshed value is fresh again");
    app.travel(Duration::from_secs(11));
    assert_eq!(flexible().await?, 3, "an expired value is computed before returning");

    Ok(())
}

#[tokio::test]
async fn helpers_keep_typed_values_in_the_default_store() -> laravel::Result<()> {
    let app = app();

    app.scope(async || {
        assert_eq!(cache::manager().default_store_name(), "memory");
        assert_eq!(cache::get::<User>("user:42").await?, None);

        cache::put("user:42", taylor(), MINUTE).await?;
        assert_eq!(cache::get("user:42").await?, Some(taylor()));
        assert!(cache::has("user:42").await?);
        assert!(
            cache::get::<Vec<String>>("user:42").await.is_err(),
            "another type is an error"
        );

        assert_eq!(cache::pull("user:42").await?, Some(taylor()));
        assert!(!cache::has("user:42").await?);
        assert!(!cache::forget("user:42").await?);

        cache::put("greeting", "Hello", MINUTE).await?;
        assert!(cache::forget("greeting").await?);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn the_memory_store_keeps_the_store_contract() -> laravel::Result<()> {
    let app = app();

    app.scope(async || store_contract(&app, &cache::store("memory")?).await)
        .await
}

#[tokio::test]
async fn null_values_are_cached_rather_than_missing() -> laravel::Result<()> {
    app()
        .scope(async || {
            cache::put("nobody", None::<User>, MINUTE).await?;

            assert_eq!(cache::get::<Option<User>>("nobody").await?, Some(None));
            assert!(cache::has("nobody").await?);
            Ok(())
        })
        .await
}

#[tokio::test]
async fn zero_ttls_store_nothing() -> laravel::Result<()> {
    app()
        .scope(async || {
            cache::put("key", 1, MINUTE).await?;
            cache::put("key", 2, Duration::ZERO).await?;
            assert!(!cache::has("key").await?);

            assert!(!cache::add("key", 3, Duration::ZERO).await?);
            assert!(!cache::has("key").await?);
            Ok(())
        })
        .await
}

#[tokio::test]
async fn remember_stores_what_the_callback_returns() -> laravel::Result<()> {
    let calls = AtomicUsize::new(0);
    let compute = || async {
        calls.fetch_add(1, Ordering::SeqCst);
        Ok(taylor())
    };

    app()
        .scope(async || {
            assert_eq!(cache::remember("user", MINUTE, compute).await?, taylor());
            assert_eq!(cache::remember("user", MINUTE, compute).await?, taylor());
            assert_eq!(calls.load(Ordering::SeqCst), 1);

            let failed = cache::remember("failing", MINUTE, || async {
                Err::<User, _>(laravel::abort_with(503, "unavailable"))
            })
            .await;
            assert_eq!(failed.unwrap_err().status(), 503);
            assert!(!cache::has("failing").await?, "errors aren't cached");

            Ok(())
        })
        .await
}

/// A deploy that changes a cached type, while values of the old type are still cached.
#[tokio::test]
async fn remember_and_flexible_replace_a_value_cached_as_another_type() -> laravel::Result<()> {
    app()
        .scope(async || {
            cache::put("user", "Taylor", MINUTE).await?;
            assert_eq!(cache::remember("user", MINUTE, async || Ok(taylor())).await?, taylor());
            assert_eq!(cache::get::<User>("user").await?, Some(taylor()));

            let name = cache::flexible("stats", MINUTE, HOUR, async || Ok(String::from("Taylor"))).await?;
            assert_eq!(name, "Taylor");
            let stats: User = cache::flexible("stats", MINUTE, HOUR, async || Ok(taylor())).await?;
            assert_eq!(stats, taylor());
            assert_eq!(cache::get::<User>("stats").await?, Some(taylor()));

            cache::put("visits", "many", MINUTE).await?;
            let unreadable = cache::get::<u64>("visits").await.unwrap_err();
            assert_eq!(
                unreadable.to_string(),
                "the cached value of `visits` in cache store `memory` can't be read: \
                 invalid type: string \"many\", expected u64 at line 1 column 6"
            );
            let unreadable = cache::many::<u64>(["user:42", "visits"]).await.unwrap_err();
            assert!(
                unreadable
                    .to_string()
                    .starts_with("the cached value of `visits` in cache store `memory`"),
                "{unreadable}"
            );
            Ok(())
        })
        .await
}

#[tokio::test]
async fn named_stores_are_created_once_and_kept_apart() -> laravel::Result<()> {
    app()
        .scope(async || {
            let manager = cache::manager();
            assert_eq!(
                manager.store_names(),
                ["database", "discard", "failover", "memory", "other", "redis"]
            );
            manager.store("memory")?.put("key", "default", MINUTE).await?;
            manager.store("other")?.put("key", "other", MINUTE).await?;

            assert_eq!(
                manager.store("memory")?.get::<String>("key").await?.as_deref(),
                Some("default")
            );
            assert_eq!(
                manager.store("other")?.get::<String>("key").await?.as_deref(),
                Some("other")
            );
            assert_eq!(manager.store("other")?.name(), "other");

            let missing = manager.store("dynamodb").unwrap_err();
            assert!(missing.to_string().contains("cache store `dynamodb` isn't defined"));

            Ok(())
        })
        .await
}

#[tokio::test]
async fn an_undefined_default_store_stops_the_application_booting() {
    async fn boot_error(store: &str) -> String {
        let app = Application::configure()
            .replace_env(Env::from_iter([("CACHE_STORE", store)]))
            .create();

        app.boot().await.unwrap_err().to_string()
    }

    let file = boot_error("file").await;
    assert!(file.contains("default cache store `file` isn't defined"), "{file}");

    let array = boot_error("array").await;
    assert!(
        array.contains("default cache store `array` isn't defined; use `memory` for the in-memory store"),
        "{array}"
    );
}

#[tokio::test]
async fn a_default_store_added_while_booting_keeps_keys_under_the_apps_prefix() -> laravel::Result<()> {
    let shared = MemoryStore::default();
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_NAME", "My App"), ("CACHE_STORE", "shared")]))
        .booted({
            let shared = shared.clone();
            move |app| async move {
                app.resolve::<CacheManager>().await?.add_store("shared", shared);
                Ok(())
            }
        })
        .create();

    app.scope(async || cache::put("key", "value", MINUTE).await).await?;

    assert_eq!(
        Store::get(&shared, "my_app_cache_key").await?.as_deref(),
        Some("\"value\"")
    );
    assert_eq!(Store::get(&shared, "key").await?, None);
    Ok(())
}

#[tokio::test]
async fn the_discard_store_keeps_nothing() -> laravel::Result<()> {
    app()
        .scope(async || {
            let discard = cache::store("discard")?;

            discard.put("key", 1, MINUTE).await?;
            assert_eq!(discard.get::<i64>("key").await?, None);
            assert!(!discard.add("key", 1, MINUTE).await?);
            assert_eq!(discard.increment("key", 1).await?, None);
            assert_eq!(discard.increment_or_add("key", 1, MINUTE).await?, 1);
            assert!(!discard.forget("key").await?);
            assert_eq!(discard.remember("key", MINUTE, || async { Ok(7) }).await?, 7);

            let lock = discard.lock("reports", MINUTE);
            assert!(lock.acquire().await?);
            assert!(
                discard.lock("reports", MINUTE).acquire().await?,
                "locks exclude nothing"
            );
            assert!(!lock.is_locked().await?);
            assert!(lock.release().await?);

            Ok(())
        })
        .await
}

#[tokio::test]
async fn each_application_has_its_own_memory_store() -> laravel::Result<()> {
    let (first, second) = (app(), app());

    first.scope(async || cache::put("key", 1, MINUTE).await).await?;

    assert_eq!(second.scope(async || cache::get::<i64>("key").await).await?, None);
    Ok(())
}

#[tokio::test]
async fn handlers_use_the_cache_through_the_manager_or_the_helpers() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route.post("/visits", |cache: Inject<CacheManager>| async move {
                    let cache = cache.default_store()?;
                    cache.add("visits", 0, MINUTE).await?;
                    Ok::<_, laravel::Error>(cache.increment("visits", 1).await?.unwrap_or_default().to_string())
                });
                route.get("/visits", || async {
                    Ok::<_, laravel::Error>(cache::get::<i64>("visits").await?.unwrap_or_default().to_string())
                });
            });
        })
        .create();

    app.post("/visits").await.assert_ok().assert_see("1");
    app.post("/visits").await.assert_ok().assert_see("2");
    app.get("/visits").await.assert_ok().assert_see("2");
}

#[tokio::test]
async fn cache_clear_flushes_the_default_or_a_named_store() -> laravel::Result<()> {
    let app = app();
    app.scope(async || {
        cache::store("memory")?.put("key", 1, MINUTE).await?;
        cache::store("other")?.put("key", 1, MINUTE).await
    })
    .await?;

    app.command("cache:clear")
        .await
        .assert_successful()
        .assert_error_output_contains("Cache store `memory` cleared.");
    assert!(!app.scope(async || cache::has("key").await).await?);
    assert!(app.scope(async || { cache::store("other")?.has("key").await }).await?);

    let cleared = app.command("cache:clear other").await;
    cleared.assert_successful();
    assert_eq!(cleared.output(), "");
    assert_eq!(
        cleared.error_output(),
        "Cache store `other` only reaches this process, so other processes keep their entries.\n\
         Cache store `other` cleared.\n"
    );
    assert!(!app.scope(async || { cache::store("other")?.has("key").await }).await?);

    Ok(())
}

#[tokio::test]
async fn cache_clear_fails_for_an_unknown_or_unreachable_store() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config
                .cache
                .add_store("unreachable", StoreConfig::custom("unreachable"));
        })
        .with_services(|app| {
            app.cache().extend("unreachable", |_app, _definition| async {
                Err::<MemoryStore, _>(laravel::abort_with(503, "the cache server is down"))
            });
        })
        .create();

    app.command("cache:clear missing")
        .await
        .assert_failed()
        .assert_error_output_contains("cache store `missing` isn't defined");
    app.command("cache:clear unreachable")
        .await
        .assert_failed()
        .assert_error_output_contains("the cache server is down");
}

/// Concurrent writes to the default store, each of which must be atomic. Run it inside an application's scope.
pub(crate) async fn concurrency_contract() -> laravel::Result<()> {
    cache::put("counter", 0, MINUTE).await?;

    let tasks: Vec<_> = (0..50)
        .map(|_| {
            laravel::task::spawn(async {
                let (incremented, hit, claimed, locked) = tokio::join!(
                    cache::increment("counter", 1),
                    cache::increment_or_add("hits", 1, MINUTE),
                    cache::add("claim", "mine", MINUTE),
                    async { cache::lock("reports", MINUTE)?.acquire().await },
                );
                incremented?;
                hit?;
                Ok::<_, laravel::Error>((claimed?, locked?))
            })
        })
        .collect();
    let (mut claimed, mut acquired) = (0, 0);
    for task in tasks {
        let (claim, lock) = task.await.expect("the task doesn't panic")?;
        claimed += usize::from(claim);
        acquired += usize::from(lock);
    }

    assert_eq!(cache::get::<i64>("counter").await?, Some(50));
    assert_eq!(
        cache::get::<i64>("hits").await?,
        Some(50),
        "concurrent first hits are all counted"
    );
    assert_eq!(claimed, 1);
    assert_eq!(acquired, 1);

    // Concurrent attempts swap the same bucket, and exactly the limit succeed...
    let limit = laravel::rate_limit::Limit::per_minute(3);
    let tasks =
        (0..10).map(|_| laravel::task::spawn(async move { laravel::rate_limit::attempt("imports", limit).await }));
    let mut allowed = 0;
    for task in tasks {
        allowed += usize::from(task.await.expect("the task doesn't panic")?.is_ok());
    }
    assert_eq!(allowed, 3);
    let too_many = laravel::rate_limit::check("imports", limit).await?.unwrap_err();
    let wait = *too_many.retry_after();
    assert!(
        wait > Duration::from_secs(19) && wait <= Duration::from_secs(20),
        "one attempt back every 20 seconds: {wait:?}"
    );
    Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_counters_claims_locks_and_rate_limits_are_atomic() -> laravel::Result<()> {
    app().scope(concurrency_contract).await
}

#[tokio::test]
async fn get_runs_the_callback_holding_the_lock_and_releases_it() -> laravel::Result<()> {
    app()
        .scope(async || {
            let lock = cache::lock("invoices", MINUTE)?;
            let other = cache::lock("invoices", MINUTE)?;

            let sent = lock
                .get(|| async {
                    assert_eq!(other.get(|| async { Ok(()) }).await?, None, "a held lock doesn't run");
                    Ok(3)
                })
                .await?;
            assert_eq!(sent, Some(3));
            assert!(!lock.is_locked().await?);

            let failed = lock
                .get(|| async { Err::<(), _>(laravel::abort_with(503, "unavailable")) })
                .await;
            assert_eq!(failed.unwrap_err().status(), 503);
            assert!(!lock.is_locked().await?, "a failing callback still releases the lock");
            Ok(())
        })
        .await
}

#[tokio::test]
async fn get_releases_the_lock_when_its_caller_is_cancelled() -> laravel::Result<()> {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route
                    .get("/invoices", || async {
                        cache::lock("invoices", MINUTE)?
                            .get(|| async {
                                tokio::time::sleep(Duration::from_secs(5)).await;
                                Ok(())
                            })
                            .await?;
                        Ok::<_, laravel::Error>("sent")
                    })
                    .middleware(Timeout::after(Duration::from_millis(20)));
            });
        })
        .create();
    let is_locked = |name: &'static str| app.scope(async move || cache::lock(name, MINUTE)?.is_locked().await);

    app.get("/invoices").await.assert_status(503);
    assert!(
        eventually(async || Ok(!is_locked("invoices").await?)).await?,
        "a timed-out request releases its lock"
    );

    let cancelled = app
        .scope(async || {
            let lock = cache::lock("reports", MINUTE)?;
            let report = lock.block(Duration::from_secs(1)).get(|| async {
                tokio::time::sleep(Duration::from_secs(5)).await;
                Ok("generated")
            });
            Ok::<_, laravel::Error>(tokio::time::timeout(Duration::from_millis(20), report).await.is_err())
        })
        .await?;
    assert!(cancelled);
    assert!(
        eventually(async || Ok(!is_locked("reports").await?)).await?,
        "a cancelled wait releases the lock it took"
    );
    Ok(())
}

/// Memory locks whose store answers slowly after taking the lock, like a remote store whose reply
/// is still in flight.
#[derive(Default)]
struct SlowLocks(MemoryStore);

impl Store for SlowLocks {
    async fn get(&self, key: &str) -> laravel::Result<Option<String>> {
        self.0.get(key).await
    }
    async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {
        self.0.put(key, value, ttl).await
    }
    async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {
        self.0.add(key, value, ttl).await
    }
    async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {
        self.0.increment(key, by).await
    }
    async fn forget(&self, key: &str) -> laravel::Result<bool> {
        self.0.forget(key).await
    }
    async fn flush(&self) -> laravel::Result<()> {
        self.0.flush().await
    }
    async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {
        let taken = self.0.acquire_lock(name, owner, ttl).await?;
        tokio::time::sleep(Duration::from_secs(5)).await;
        Ok(taken)
    }
    async fn release_lock(&self, name: &str, owner: &str) -> laravel::Result<bool> {
        self.0.release_lock(name, owner).await
    }
    async fn force_release_lock(&self, name: &str) -> laravel::Result<()> {
        self.0.force_release_lock(name).await
    }
    async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {
        self.0.refresh_lock(name, owner, ttl).await
    }
    async fn lock_owner(&self, name: &str) -> laravel::Result<Option<String>> {
        self.0.lock_owner(name).await
    }
}

#[tokio::test]
async fn get_releases_a_lock_taken_while_its_caller_stopped_waiting_for_the_store() -> laravel::Result<()> {
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "slow")]))
        .with_config(|config, _| {
            config.cache.add_store("slow", StoreConfig::custom("slow"));
        })
        .with_services(|app| {
            app.cache()
                .extend("slow", |_app, _definition| async { Ok(SlowLocks::default()) });
        })
        .create();

    app.scope(async || {
        let lock = cache::lock("invoices", MINUTE)?;
        let sent = lock.get(|| async { Ok("sent") });
        assert!(tokio::time::timeout(Duration::from_millis(20), sent).await.is_err());

        let lock = cache::lock("reports", MINUTE)?;
        let report = lock.block(Duration::from_secs(1)).get(|| async { Ok("generated") });
        assert!(tokio::time::timeout(Duration::from_millis(20), report).await.is_err());

        for name in ["invoices", "reports"] {
            let lock = cache::lock(name, MINUTE)?;
            assert!(
                eventually(async || Ok(!lock.is_locked().await?)).await?,
                "`{name}` is released after its caller stopped waiting"
            );
        }
        Ok(())
    })
    .await
}

#[tokio::test]
async fn block_waits_for_the_lock_or_times_out() -> laravel::Result<()> {
    app()
        .scope(async || {
            let store = cache::manager().default_store()?;
            let holder = store.lock("reports", MINUTE);
            let waiter = store.lock("reports", MINUTE).between_attempts(Duration::from_millis(5));
            assert!(holder.acquire().await?);

            let timeout = waiter.block(Duration::from_millis(20)).await.unwrap_err();
            assert!(timeout.is::<LockTimeout>());
            assert_eq!(timeout.status(), 423);
            assert_eq!(timeout.to_string(), "This resource is busy. Please try again.");
            let details = timeout.downcast_ref::<LockTimeout>().expect("a lock timeout");
            assert_eq!(details.name(), "reports");
            assert_eq!(details.wait(), 20.milliseconds());

            let release = async {
                tokio::time::sleep(Duration::from_millis(20)).await;
                holder.release().await
            };
            let (released, report) = tokio::join!(
                release,
                waiter.block(Duration::from_secs(5)).get(|| async { Ok("generated") })
            );

            assert!(released?);
            assert_eq!(report?, "generated");
            assert!(!waiter.is_locked().await?);
            Ok(())
        })
        .await
}

#[tokio::test]
async fn a_lock_that_timed_out_can_be_taken_again_and_stays_held() -> laravel::Result<()> {
    app()
        .scope(async || {
            let store = cache::manager().default_store()?;
            let holder = store.lock("reports", MINUTE);
            let waiter = store.lock("reports", MINUTE);
            assert!(holder.acquire().await?);

            let timeout = waiter.block(Duration::ZERO).get(|| async { Ok(()) }).await.unwrap_err();
            assert!(timeout.is::<LockTimeout>());

            assert!(holder.release().await?);
            assert!(waiter.acquire().await?);
            tokio::time::sleep(Duration::from_millis(20)).await;

            assert!(waiter.is_owned().await?, "the timed-out wait released nothing");
            Ok(())
        })
        .await
}

#[tokio::test]
async fn restored_locks_are_released_by_their_owner_token() -> laravel::Result<()> {
    app()
        .scope(async || {
            let lock = cache::lock("processing", MINUTE)?;
            assert!(lock.acquire().await?);

            let restored = cache::restore_lock("processing", lock.owner())?;
            assert!(restored.is_owned().await?);
            assert!(
                restored.acquire().await.is_err(),
                "a restored lock has no duration to take it for"
            );
            assert!(restored.refresh().await.is_err());
            assert!(restored.refresh_for(MINUTE).await?);

            assert!(restored.release().await?);
            assert!(!lock.is_locked().await?);
            Ok(())
        })
        .await
}

#[tokio::test]
async fn lock_names_carry_the_prefix_and_stores_without_locks_fail() -> laravel::Result<()> {
    struct Plain(MemoryStore);

    impl Store for Plain {
        async fn get(&self, key: &str) -> laravel::Result<Option<String>> {
            self.0.get(key).await
        }
        async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {
            self.0.put(key, value, ttl).await
        }
        async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {
            self.0.add(key, value, ttl).await
        }
        async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {
            self.0.increment(key, by).await
        }
        async fn forget(&self, key: &str) -> laravel::Result<bool> {
            self.0.forget(key).await
        }
        async fn flush(&self) -> laravel::Result<()> {
            self.0.flush().await
        }
    }

    let shared = MemoryStore::default();
    let app = app();
    let manager = app.resolve::<CacheManager>().await;
    manager.add_store("shared", shared.clone());
    manager.add_store("plain", Plain(MemoryStore::default()));

    app.scope(async || {
        let lock = cache::store("shared")?.lock("reports", MINUTE);
        assert!(lock.acquire().await?);
        assert_eq!(
            Store::lock_owner(&shared, "laravel_cache_reports").await?.as_deref(),
            Some(lock.owner())
        );

        let plain = cache::store("plain")?;
        plain.put_many([("a", 1), ("b", 2)], MINUTE).await?;
        assert_eq!(
            plain.many::<i64>(["a", "b"]).await?,
            [Some(1), Some(2)],
            "many works key by key"
        );
        assert!(
            plain.touch("a", MINUTE).await?,
            "touch works by storing the value again"
        );
        assert!(!plain.touch("missing", MINUTE).await?);
        assert_eq!(plain.increment_or_add("count", 2, MINUTE).await?, 2);
        assert_eq!(plain.increment_or_add("count", 2, MINUTE).await?, 4);
        let unsupported = plain.lock("reports", MINUTE).acquire().await.unwrap_err();
        assert!(unsupported.to_string().contains("doesn't support locks"));
        Ok(())
    })
    .await
}

#[tokio::test]
async fn locks_need_a_duration() {
    let error = app()
        .scope(async || cache::lock("reports", Duration::ZERO)?.acquire().await)
        .await
        .unwrap_err();

    assert!(error.to_string().contains("needs a duration longer than zero"));
}

#[tokio::test]
async fn outside_the_application_stores_and_locks_panic_before_changing_anything() -> laravel::Result<()> {
    let app = app();
    let (store, lock) = app
        .scope(async || {
            cache::put("count", 1, MINUTE).await?;
            Ok::<_, laravel::Error>((cache::store("memory")?, cache::lock("reports", MINUTE)?))
        })
        .await?;

    let increment = tokio::spawn(async move { store.increment("count", 1).await.map(drop) });
    let acquire = tokio::spawn(async move { lock.acquire().await.map(drop) });
    for task in [increment, acquire] {
        let panicked = task
            .await
            .expect_err("a task spawned without the context has no application");
        let message = panicked.into_panic();
        let message = message.downcast_ref::<String>().expect("a formatted message");
        assert!(
            message.contains("`laravel::cache` can only be used inside the application"),
            "{message}"
        );
    }

    app.scope(async || {
        assert_eq!(cache::get::<i64>("count").await?, Some(1));
        assert!(
            !cache::lock("reports", MINUTE)?.is_locked().await?,
            "the lock wasn't taken"
        );
        Ok(())
    })
    .await
}

#[tokio::test]
async fn lifetimes_can_be_spans() -> laravel::Result<()> {
    let app = app();
    app.freeze_time();

    app.scope(async || {
        cache::put("daily", 1, 1.day()).await?;
        cache::put("past", 1, (-5).seconds()).await?;
        assert!(!cache::has("past").await?, "a negative lifetime stores nothing");

        let lock = cache::lock("reports", 10.seconds())?.between_attempts(5.milliseconds());
        assert!(lock.acquire().await?);
        assert!(lock.refresh_for(1.minute()).await?);
        let waiting = cache::lock("reports", 10.seconds())?.between_attempts(5.milliseconds());
        assert!(waiting.block(20.milliseconds()).await.unwrap_err().is::<LockTimeout>());
        Ok::<_, laravel::Error>(())
    })
    .await?;

    app.travel(Duration::from_secs(24 * 60 * 60 - 1));
    assert!(app.scope(async || cache::has("daily").await).await?);
    app.travel(Duration::from_secs(1));
    assert!(!app.scope(async || cache::has("daily").await).await?);
    Ok(())
}

#[tokio::test]
async fn handlers_that_time_out_on_a_lock_respond_423() -> laravel::Result<()> {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route.get("/reports", || async {
                    cache::lock("reports", MINUTE)?
                        .between_attempts(Duration::from_millis(5))
                        .block(Duration::from_millis(20))
                        .get(|| async { Ok("generated") })
                        .await
                });
            });
        })
        .create();
    let holder = app.scope(async || cache::lock("reports", MINUTE)).await?;
    assert!(app.scope(async || holder.acquire().await).await?);

    app.get("/reports")
        .await
        .assert_status(423)
        .assert_see("Locked")
        .assert_dont_see("reports`");

    app.scope(async || holder.release().await).await?;
    app.get("/reports").await.assert_ok().assert_see("generated");
    Ok(())
}

#[tokio::test]
async fn cache_prune_runs_on_any_store() -> laravel::Result<()> {
    let app = app();
    app.freeze_time();
    app.scope(async || {
        cache::put("old", 1, Duration::from_secs(1)).await?;
        cache::put("kept", 1, MINUTE).await
    })
    .await?;
    app.travel(Duration::from_secs(2));

    app.command("cache:prune")
        .await
        .assert_successful()
        .assert_error_output_contains("Expired entries pruned from cache store `memory`.");
    let pruned = app.command("cache:prune discard").await;
    pruned.assert_successful();
    assert_eq!(pruned.output(), "");
    assert_eq!(
        pruned.error_output(),
        "Expired entries pruned from cache store `discard`.\n"
    );
    assert_eq!(app.scope(async || cache::get::<i64>("kept").await).await?, Some(1));
    Ok(())
}