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
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use laravel::Application;
use laravel::cache::{self, MemoryStore, Store};
use laravel::config::Env;
use laravel::config::cache::{CustomStore, StoreConfig};
use laravel::container::Registrar;
use laravel::foundation::{ApplicationBuilder, ServiceProvider, StartupError};
use laravel::testing::MakesHttpRequests;

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

#[derive(Clone, Default)]
struct StubStore {
    values: MemoryStore,
    reads: Arc<Mutex<Vec<String>>>,
}

impl StubStore {
    fn reads(&self) -> Vec<String> {
        self.reads.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }

    fn record(&self, keys: &[String]) {
        self.reads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .extend(keys.iter().cloned());
    }
}

impl Store for StubStore {
    async fn get(&self, key: &str) -> laravel::Result<Option<String>> {
        self.record(&[key.to_owned()]);
        self.values.get(key).await
    }
    async fn many(&self, keys: &[String]) -> laravel::Result<Vec<Option<String>>> {
        self.record(keys);
        self.values.many(keys).await
    }
    async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {
        self.values.put(key, value, ttl).await
    }
    async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {
        self.values.add(key, value, ttl).await
    }
    async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {
        self.values.increment(key, by).await
    }
    async fn forget(&self, key: &str) -> laravel::Result<bool> {
        self.values.forget(key).await
    }
    async fn flush(&self) -> laravel::Result<()> {
        self.values.flush().await
    }
}

#[derive(Debug)]
struct StubSettings {
    label: &'static str,
}

#[tokio::test]
async fn stores_use_drivers_registered_by_name() -> laravel::Result<()> {
    let created = Arc::new(Mutex::new(Vec::new()));
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "stub")]))
        .with_config(|config, _| {
            config
                .cache
                .add_store(
                    "stub",
                    StoreConfig::custom("stub").settings(StubSettings { label: "first" }),
                )
                .add_store(
                    "other",
                    StoreConfig::custom("Stub").settings(StubSettings { label: "second" }),
                );
        })
        .with_services({
            let created = Arc::clone(&created);
            move |app| {
                app.cache().extend("STUB", move |_app, definition| {
                    let created = Arc::clone(&created);
                    async move {
                        let label = definition.settings::<StubSettings>()?.label;
                        created
                            .lock()
                            .unwrap_or_else(PoisonError::into_inner)
                            .push((definition.name().to_owned(), label));
                        Ok(StubStore::default())
                    }
                });
            }
        })
        .create();

    app.scope(async || {
        cache::put("user", "Taylor", MINUTE).await?;
        assert_eq!(cache::get::<String>("user").await?.as_deref(), Some("Taylor"));
        assert_eq!(
            cache::store("other")?.get::<String>("user").await?,
            None,
            "each store is its own"
        );
        Ok::<_, laravel::Error>(())
    })
    .await?;

    let mut created = created.lock().unwrap_or_else(PoisonError::into_inner).clone();
    created.sort();
    assert_eq!(
        created,
        [("other".to_owned(), "second"), ("stub".to_owned(), "first")],
        "each store is created once, on first use, with its own settings, whatever the driver name's case"
    );
    Ok(())
}

#[test]
fn stores_with_unregistered_drivers_stop_the_application_from_starting() {
    let error = Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.cache.add_store("dynamodb", StoreConfig::custom("dynamodb"));
        })
        .try_create()
        .unwrap_err();

    assert!(matches!(error, StartupError::Cache(_)));
    assert!(
        error
            .to_string()
            .contains("cache store `dynamodb` uses driver `dynamodb`, which isn't registered")
    );
}

async fn first_use_error(store: CustomStore) -> String {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config.cache.add_store("stub", store);
        })
        .with_services(|app| {
            app.cache().extend("stub", |_app, definition| async move {
                definition.settings::<StubSettings>()?;
                Ok(StubStore::default())
            });
        })
        .create();

    app.boot().await.unwrap();
    app.scope(async || cache::store("stub")?.get::<i64>("key").await)
        .await
        .unwrap_err()
        .to_string()
}

#[tokio::test]
async fn missing_settings_or_settings_of_another_type_fail_the_first_operation() {
    let wrong = first_use_error(StoreConfig::custom("stub").settings("not the settings")).await;
    assert!(wrong.contains("failed to create cache store `stub`"), "{wrong}");
    assert!(wrong.contains("has settings of type `&str`"), "{wrong}");

    let missing = first_use_error(StoreConfig::custom("stub")).await;
    assert!(missing.contains("cache store `stub` has no settings"), "{missing}");
}

#[tokio::test]
async fn a_driver_that_fails_to_build_keeps_its_status_and_headers() {
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "unavailable")]))
        .with_config(|config, _| {
            config
                .cache
                .add_store("unavailable", StoreConfig::custom("unavailable"));
        })
        .with_services(|app| {
            app.cache().extend("unavailable", |_app, _definition| async {
                Err::<MemoryStore, _>(laravel::abort(503).with_header("retry-after", "30"))
            });
        })
        .with_routing(|routing, _| {
            routing.api(|route| {
                route.get("/visits", async || {
                    cache::get::<i64>("visits")
                        .await
                        .map(|visits| visits.unwrap_or(0).to_string())
                });
            });
        })
        .create();

    app.get("/api/visits")
        .await
        .assert_status(503)
        .assert_header("retry-after", "30");
}

fn with_stub_store() -> ApplicationBuilder {
    Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "stub")]))
        .with_config(|config, _| {
            config.cache.add_store("stub", StoreConfig::custom("stub"));
        })
}

#[tokio::test]
async fn failing_or_panicking_drivers_fail_their_operations_and_are_tried_again() -> laravel::Result<()> {
    let attempts = Arc::new(AtomicUsize::new(0));
    let app = with_stub_store()
        .with_services({
            let attempts = Arc::clone(&attempts);
            move |app| {
                app.cache().extend("stub", move |_app, _definition| {
                    let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                    async move {
                        match attempt {
                            0 => Err(std::io::Error::other("the cache server is unreachable").into()),
                            1 => panic!("the cache server is unreachable"),
                            _ => Ok(MemoryStore::default()),
                        }
                    }
                });
            }
        })
        .create();

    app.boot().await?;
    assert_eq!(attempts.load(Ordering::SeqCst), 0, "booting creates no store");

    app.scope(async || {
        let store = cache::store("stub")?;
        let error = store.put("key", 1, MINUTE).await.unwrap_err();
        assert!(error.is::<std::io::Error>(), "{error}");
        assert!(
            error.to_string().contains("failed to create cache store `stub`"),
            "{error}"
        );

        let error = store.put("key", 1, MINUTE).await.unwrap_err().to_string();
        assert!(error.contains("failed to create cache store `stub`"), "{error}");
        assert!(error.contains("panic at tests/cache_extensions.rs:"), "{error}");
        assert!(error.ends_with(": the cache server is unreachable"), "{error}");

        store.put("key", 1, MINUTE).await?;
        assert_eq!(cache::get::<i64>("key").await?, Some(1));
        assert!(
            cache::lock("report", MINUTE)?.acquire().await?,
            "locks reach the created store"
        );
        Ok::<_, laravel::Error>(())
    })
    .await?;

    assert_eq!(attempts.load(Ordering::SeqCst), 3, "created once it succeeds");
    Ok(())
}

#[tokio::test]
async fn an_operation_that_stops_waiting_doesnt_cancel_its_stores_creation() -> laravel::Result<()> {
    let attempts = Arc::new(AtomicUsize::new(0));
    let app = with_stub_store()
        .with_services({
            let attempts = Arc::clone(&attempts);
            move |app| {
                app.cache().extend("stub", move |_app, _definition| {
                    attempts.fetch_add(1, Ordering::SeqCst);
                    async {
                        tokio::time::sleep(Duration::from_millis(200)).await;
                        Ok(MemoryStore::default())
                    }
                });
            }
        })
        .create();

    app.scope(async || {
        let abandoned = tokio::time::timeout(Duration::from_millis(20), cache::put("key", 1, MINUTE)).await;
        assert!(
            abandoned.is_err(),
            "the first operation stopped waiting while its store was created"
        );

        cache::put("key", 1, MINUTE).await?;
        Ok::<_, laravel::Error>(())
    })
    .await?;

    assert_eq!(
        attempts.load(Ordering::SeqCst),
        1,
        "the next operation finished the creation rather than starting another"
    );
    Ok(())
}

struct Warmed;

#[tokio::test]
async fn a_driver_and_transient_service_cycle_fails_rather_than_hangs() {
    let app = with_stub_store()
        .with_services(|services| {
            services.bind(|_| async {
                cache::get::<i64>("warm").await?;
                Ok(Warmed)
            });
        })
        .with_services(|app| {
            app.cache().extend("stub", |app, _definition| async move {
                app.resolve::<Warmed>().await?;
                Ok(MemoryStore::default())
            });
        })
        .create();

    let error = tokio::time::timeout(
        Duration::from_secs(5),
        app.scope(async || laravel::resolve::<Warmed>().await.map(drop)),
    )
    .await
    .expect("the cycle through the shared store must fail rather than hang")
    .unwrap_err()
    .to_string();
    assert!(error.contains("the cache store `stub` depends on itself"), "{error}");
}

#[tokio::test]
async fn a_driver_needing_a_service_that_uses_its_store_fails_rather_than_hangs() {
    let app = with_stub_store()
        .with_services(|services| {
            services.singleton(|_| async {
                cache::get::<i64>("warm").await?;
                Ok(Warmed)
            });
        })
        .with_services(|app| {
            app.cache().extend("stub", |app, _definition| async move {
                app.resolve::<Warmed>().await?;
                Ok(MemoryStore::default())
            });
        })
        .create();
    let cycle = "`integration::cache_extensions::Warmed` depends on itself: integration::cache_extensions::Warmed \
                 → the cache store `stub` → integration::cache_extensions::Warmed";

    let from_the_service = app.scope(async || laravel::resolve::<Warmed>().await.map(drop));
    let error = tokio::time::timeout(Duration::from_secs(5), from_the_service)
        .await
        .expect("the cycle is found when the service's factory creates the store")
        .unwrap_err()
        .to_string();
    assert!(error.contains(cycle), "{error}");

    let from_the_store = app.scope(async || cache::get::<i64>("key").await);
    let error = tokio::time::timeout(Duration::from_secs(5), from_the_store)
        .await
        .expect("the cycle is found when the store's creation builds the service")
        .unwrap_err()
        .to_string();
    assert!(error.contains(cycle), "{error}");
}

struct StubPackage;

impl ServiceProvider for StubPackage {
    fn register(&self, app: &mut Registrar) {
        app.singleton(|_| async { Ok(StubStore::default()) });
        app.cache().extend(
            "memory",
            |app, _definition| async move { app.resolve::<StubStore>().await },
        );
    }
}

#[tokio::test]
async fn packages_register_drivers_and_the_application_replaces_them() -> laravel::Result<()> {
    let packaged = Application::configure()
        .replace_env(Env::default())
        .with_providers(|providers| {
            providers.add(StubPackage);
        })
        .create();
    let store = packaged.resolve::<StubStore>().await;
    packaged.scope(async || cache::get::<i64>("key").await).await?;
    assert_eq!(
        store.reads(),
        ["laravel_cache_key"],
        "the package's factory replaced the built-in memory driver"
    );

    let replaced = Application::configure()
        .replace_env(Env::default())
        .with_providers(|providers| {
            providers.add(StubPackage);
        })
        .with_services(|app| {
            app.cache().extend("memory", |_app, definition| async move {
                assert_eq!(definition.config(), &StoreConfig::Memory);
                Ok(MemoryStore::default())
            });
        })
        .create();
    let store = replaced.resolve::<StubStore>().await;
    replaced.scope(async || cache::get::<i64>("key").await).await?;
    assert!(store.reads().is_empty(), "the application's registration won");
    Ok(())
}

fn memo_app() -> (Application, StubStore) {
    let stub = StubStore::default();
    let app = with_stub_store()
        .with_services({
            let stub = stub.clone();
            move |app| {
                app.cache().extend("stub", move |_app, _definition| {
                    let stub = stub.clone();
                    async move { Ok(stub) }
                });
            }
        })
        .create();

    (app, stub)
}

#[tokio::test]
async fn memoized_reads_reach_the_store_once_per_scope() -> laravel::Result<()> {
    let (app, stub) = memo_app();
    app.scope(async || cache::put("user", "Taylor", MINUTE).await).await?;

    app.scope(async || {
        let memo = cache::memo()?;
        assert_eq!(memo.get::<String>("user").await?.as_deref(), Some("Taylor"));
        assert_eq!(memo.get::<String>("user").await?.as_deref(), Some("Taylor"));
        assert!(memo.has("user").await?);
        assert_eq!(memo.get::<String>("missing").await?, None);
        assert_eq!(memo.get::<String>("missing").await?, None, "misses are remembered too");
        Ok::<_, laravel::Error>(())
    })
    .await?;
    assert_eq!(stub.reads(), ["laravel_cache_user", "laravel_cache_missing"]);

    app.scope(async || cache::memo()?.get::<String>("user").await).await?;
    assert_eq!(stub.reads().len(), 3, "another scope reads the store again");
    Ok(())
}

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

    app.scope(async || {
        let memo = cache::memo()?;
        assert_eq!(memo.get::<i64>("count").await?, None);

        cache::put("count", 1, MINUTE).await?;
        assert_eq!(memo.get::<i64>("count").await?, Some(1), "a write elsewhere is seen");

        cache::increment("count", 1).await?;
        assert_eq!(memo.get::<i64>("count").await?, Some(2));

        memo.forget("count").await?;
        assert_eq!(memo.get::<i64>("count").await?, None);

        cache::put("count", 3, MINUTE).await?;
        memo.get::<i64>("count").await?;
        cache::flush().await?;
        assert_eq!(memo.get::<i64>("count").await?, None, "flushing forgets everything");
        Ok::<_, laravel::Error>(())
    })
    .await?;

    assert_eq!(stub.reads().len(), 6, "every read after a write went to the store");
    Ok(())
}

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

    app.scope(async || {
        cache::put_many([("a", 1), ("b", 2)], MINUTE).await?;
        let memo = cache::memo()?;
        memo.get::<i64>("a").await?;

        assert_eq!(memo.many::<i64>(["a", "b", "c"]).await?, [Some(1), Some(2), None]);
        assert_eq!(memo.many::<i64>(["a", "b", "c"]).await?, [Some(1), Some(2), None]);
        Ok::<_, laravel::Error>(())
    })
    .await?;

    assert_eq!(stub.reads(), ["laravel_cache_a", "laravel_cache_b", "laravel_cache_c"]);
    Ok(())
}

#[tokio::test]
async fn memoized_values_are_logged_when_read_from_the_store() -> laravel::Result<()> {
    let (app, _stub) = memo_app();
    let (lines, _guard) = crate::logging::Lines::capture();

    app.scope(async || {
        cache::put("user", "Taylor", MINUTE).await?;
        let memo = cache::memo()?;

        memo.get::<String>("user").await?;
        memo.get::<String>("user").await?;
        Ok::<_, laravel::Error>(())
    })
    .await?;

    assert_eq!(crate::cache_logging::logged(&lines, "Cache hit").len(), 1);
    Ok(())
}

#[tokio::test]
async fn an_abandoned_store_build_lets_go_of_the_application() {
    use std::sync::atomic::AtomicBool;

    use tokio::sync::Notify;

    struct Witness(Arc<AtomicBool>);

    impl Drop for Witness {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    let dropped = Arc::new(AtomicBool::new(false));
    let (entered, release) = (Arc::new(Notify::new()), Arc::new(Notify::new()));
    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({
            let dropped = Arc::clone(&dropped);
            move |services| {
                services.instance(Witness(dropped));
            }
        })
        .with_services({
            let (entered, release) = (Arc::clone(&entered), Arc::clone(&release));
            move |app| {
                app.cache().extend("slow", move |_app, _definition| {
                    let (entered, release) = (Arc::clone(&entered), Arc::clone(&release));
                    async move {
                        entered.notify_one();
                        release.notified().await;
                        Ok(MemoryStore::default())
                    }
                });
            }
        })
        .create();

    tokio::select! {
        _ = app.scope(async || cache::has("key").await) => panic!("the store's driver is still waiting"),
        () = entered.notified() => {}
    }
    release.notify_one();
    drop(app);

    for _ in 0..100 {
        if dropped.load(Ordering::SeqCst) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    panic!("the application outlived the store build nobody awaited");
}