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

use laravel::Application;
use laravel::cache::{MemoryStore, Store};
use laravel::config::Env;
use laravel::config::cache::StoreConfig;
use laravel::container::Inject;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, IntoMiddleware, Next, job, middleware};
use laravel::time::ToSpan;

use crate::queue::Records;

#[derive(Queueable)]
struct Reindex {
    product: u32,
    revision: String,
}

impl Reindex {
    fn new(product: u32, revision: &str) -> Self {
        Self {
            product,
            revision: revision.into(),
        }
    }
}

#[job(debounce_for = 30.seconds())]
impl Reindex {
    fn debounce_id(&self) -> u32 {
        self.product
    }

    async fn handle(self, records: Inject<Records>) {
        records.push(format!("reindexed {} at {}", self.product, self.revision));
    }
}

#[derive(Queueable)]
struct RebuildSitemap(u32);

#[job(debounce_for = 30.seconds())]
impl RebuildSitemap {
    async fn handle(self, records: Inject<Records>) {
        records.push(format!("sitemap {}", self.0));
    }
}

/// A store whose writes give way to other tasks once they're done, as a shared store's round
/// trips do.
#[derive(Default)]
struct SharedStore(MemoryStore);

impl Store for SharedStore {
    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?;
        tokio::task::yield_now().await;
        Ok(())
    }
    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
    }
}

#[tokio::test]
async fn concurrent_dispatches_on_the_sync_connection_all_run() {
    let app = Application::configure()
        .replace_env(Env::from_iter([("CACHE_STORE", "shared")]))
        .with_config(|config, _| {
            config.queue.default = "sync".into();
            config.cache.add_store("shared", StoreConfig::custom("shared"));
        })
        .with_services(|services| {
            services.instance(Records::default());
            services
                .cache()
                .extend("shared", |_app, _definition| async { Ok(SharedStore::default()) });
        })
        .create();

    app.scope(async || {
        let (first, second) = tokio::join!(
            Reindex::new(1, "first").dispatch(),
            Reindex::new(1, "second").dispatch()
        );
        first.and(second)?;
        Reindex::new(1, "third").dispatch_sync().await
    })
    .await
    .unwrap();

    let mut records = app.resolve::<Records>().await.all();
    records[..2].sort();
    assert_eq!(
        records,
        ["reindexed 1 at first", "reindexed 1 at second", "reindexed 1 at third"]
    );
}

#[derive(Queueable)]
struct Recount {
    revision: u32,
    hold: bool,
}

#[middleware]
async fn hold_back(attempt: &Attempt, _next: Next) -> laravel::Result<()> {
    attempt.release(1.hours());
    Ok(())
}

#[job(debounce_for = 30.seconds(), max_wait = 1.minutes())]
impl Recount {
    fn middleware(&self) -> impl IntoMiddleware {
        self.hold.then_some(hold_back)
    }

    async fn handle(self, records: Inject<Records>) {
        records.push(format!("recount {}", self.revision));
    }
}

#[tokio::test]
async fn fakes_record_the_debounced_delay() {
    let app = Application::configure().replace_env(Env::default()).create();

    let delays = app
        .scope(async || {
            let queue = queue::fake();
            Reindex::new(1, "first").dispatch().await?;
            Reindex::new(1, "second").dispatch().delay(5.seconds()).await?;
            Recount {
                revision: 1,
                hold: false,
            }
            .dispatch()
            .await?;
            app.travel(50.seconds());
            Recount {
                revision: 2,
                hold: false,
            }
            .dispatch()
            .await?;
            app.travel(11.seconds());
            Recount {
                revision: 3,
                hold: false,
            }
            .dispatch()
            .await?;
            Recount {
                revision: 4,
                hold: false,
            }
            .dispatch()
            .await?;

            queue.assert_pushed_times::<Reindex>(2);
            let reindexed: Vec<_> = queue.pushed::<Reindex>().iter().map(|job| job.delay()).collect();
            let recounted: Vec<_> = queue.pushed::<Recount>().iter().map(|job| job.delay()).collect();
            Ok::<_, laravel::Error>((reindexed, recounted))
        })
        .await
        .unwrap();

    let seconds = Duration::from_secs;
    assert_eq!(delays.0, [seconds(30), seconds(5)], "a dispatch's own delay wins");
    assert_eq!(
        delays.1,
        [seconds(30), seconds(30), Duration::ZERO, seconds(30)],
        "the dispatch a minute after the first runs without waiting, and the next starts a new wait"
    );
}

#[derive(Queueable)]
struct Resync(u32);

#[job(debounce_for = 10.seconds(), max_wait = 10.minutes())]
impl Resync {
    async fn handle(self) {}
}

#[tokio::test]
async fn max_wait_holds_when_it_outlasts_the_debounce_id() {
    let app = Application::configure().replace_env(Env::default()).create();

    let delays = app
        .scope(async || {
            let queue = queue::fake();
            for minute in 0..12 {
                Resync(minute).dispatch().await?;
                app.travel(1.minutes());
            }

            Ok::<_, laravel::Error>(
                queue
                    .pushed::<Resync>()
                    .iter()
                    .map(|job| job.delay())
                    .collect::<Vec<_>>(),
            )
        })
        .await
        .unwrap();

    let mut expected = vec![Duration::from_secs(10); 12];
    expected[10] = Duration::ZERO;
    assert_eq!(
        delays, expected,
        "the dispatch ten minutes after the first doesn't wait"
    );
}

#[cfg(feature = "database-sqlite")]
mod database {
    use laravel::cache;
    use laravel::config::database::ConnectionConfig;
    use laravel::config::queue::DatabaseQueue;
    use laravel::db;
    use laravel::event::Event;
    use laravel::queue::events::JobProcessed;
    use laravel::testing::{MakesConsoleRequests, TestCommandResult};
    use laravel::time::Timestamp;

    use super::*;
    use crate::queue::database::create_table;

    #[derive(Queueable)]
    struct Note(String);

    #[job]
    impl Note {
        async fn handle(self, records: Inject<Records>) {
            records.push(self.0);
        }
    }

    #[derive(Default)]
    struct Seen(Records);

    const NOW: i64 = 1_800_000_000;

    async fn application(directory: &crate::support::TempDir) -> Application {
        let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());
        let app = Application::configure()
            .replace_env(Env::default())
            .with_config(move |config, _| {
                config.queue.default = "database".into();
                config
                    .queue
                    .add_connection("broken", DatabaseQueue::new().table("missing_jobs"));
                config.database.default = "primary".into();
                config
                    .database
                    .connections
                    .insert("primary".into(), ConnectionConfig::new(url));
            })
            .with_services(|services| {
                services.instance(Records::default());
                services.instance(Seen::default());
            })
            .with_events(|events, _| {
                events.listen(|event: Event<JobProcessed>, seen: Inject<Seen>| async move {
                    seen.0.push(format!("{} {}", event.job.name, event.outcome));
                });
            })
            .create();
        app.scope(async || {
            let connection = db::default_connection()?;
            connection.query(create_table(connection.driver())).statement().await
        })
        .await
        .unwrap();
        app.travel_to(Timestamp::from_second(NOW).unwrap());

        app
    }

    async fn work(app: &Application) -> TestCommandResult {
        tokio::time::timeout(Duration::from_secs(30), app.command("queue:work --stop-when-empty"))
            .await
            .expect("the worker should stop once no job is available")
    }

    #[derive(db::FromRow)]
    struct Row {
        available_at: Timestamp,
    }

    async fn available_at(app: &Application) -> Vec<i64> {
        let rows: Vec<Row> = app
            .scope(async || {
                db::default_connection()?
                    .query("SELECT available_at FROM jobs ORDER BY id")
                    .select_as()
                    .await
            })
            .await
            .unwrap();

        rows.into_iter().map(|row| row.available_at.as_second() - NOW).collect()
    }

    async fn records(app: &Application) -> Vec<String> {
        app.resolve::<Records>().await.all()
    }

    #[tokio::test]
    async fn the_worker_runs_only_the_latest_dispatch_of_each_debounce_id() {
        let directory = crate::support::TempDir::new("queue-debounce-worker");
        let app = application(&directory).await;
        app.scope(async || {
            Reindex::new(1, "first").dispatch().await?;
            Reindex::new(2, "only").dispatch().await?;
            Reindex::new(1, "second").dispatch().await?;
            RebuildSitemap(1).dispatch().await?;
            app.travel(10.seconds());
            RebuildSitemap(2).dispatch().delay(5.seconds()).await?;
            Ok::<_, laravel::Error>(())
        })
        .await
        .unwrap();
        assert_eq!(available_at(&app).await, [30, 30, 30, 30, 15]);

        app.travel(5.seconds());
        let result = work(&app).await;
        result.assert_successful();
        assert_eq!(records(&app).await, ["sitemap 2"], "{}", result.output());

        app.travel(15.seconds());
        let result = work(&app).await;
        result.assert_successful();
        assert_eq!(
            result.error_output().matches(" debounced  ").count(),
            2,
            "{}",
            result.error_output()
        );
        assert_eq!(
            records(&app).await,
            ["sitemap 2", "reindexed 2 at only", "reindexed 1 at second"]
        );
        assert_eq!(
            app.resolve::<Seen>().await.0.all(),
            [
                "integration::queue_debounce::RebuildSitemap succeeded",
                "integration::queue_debounce::Reindex debounced",
                "integration::queue_debounce::Reindex succeeded",
                "integration::queue_debounce::Reindex succeeded",
                "integration::queue_debounce::RebuildSitemap debounced",
            ]
        );
        assert!(available_at(&app).await.is_empty());
    }

    #[tokio::test]
    async fn a_dispatch_runs_without_waiting_once_the_first_has_waited_max_wait() {
        let directory = crate::support::TempDir::new("queue-debounce-max-wait");
        let app = application(&directory).await;
        let dispatch = |revision, hold| app.scope(async move || Recount { revision, hold }.dispatch().await.map(drop));

        dispatch(1, false).await.unwrap();
        app.travel(50.seconds());
        dispatch(2, false).await.unwrap();
        app.travel(11.seconds());
        dispatch(3, false).await.unwrap();
        dispatch(33, false).await.unwrap();
        assert_eq!(available_at(&app).await, [30, 80, 61, 91]);
        work(&app).await.assert_successful();
        app.travel(20.seconds());
        work(&app).await.assert_successful();
        assert_eq!(
            records(&app).await,
            ["recount 3"],
            "the dispatch that ended the wait runs, though a later dispatch started a new one"
        );

        app.travel(10.minutes());
        dispatch(4, false).await.unwrap();
        app.travel(30.seconds());
        work(&app).await.assert_successful();
        app.travel(31.seconds());
        dispatch(5, true).await.unwrap();
        assert_eq!(available_at(&app).await, [742 + 30]);

        app.travel(30.seconds());
        work(&app).await.assert_successful();
        app.travel(31.seconds());
        dispatch(6, false).await.unwrap();
        assert_eq!(available_at(&app).await, [772 + 3600, 803]);
        assert_eq!(records(&app).await, ["recount 3", "recount 4"]);
    }

    #[tokio::test]
    async fn replaced_chains_rolled_back_dispatches_failed_pushes_and_lost_keys() {
        let directory = crate::support::TempDir::new("queue-debounce-edges");
        let app = application(&directory).await;

        app.scope(async || {
            queue::chain(Reindex::new(1, "chained"))
                .then(Note("after the chained job".into()))
                .await?;
            queue::chain(Note("first link".into()))
                .then(Reindex::new(1, "latest"))
                .await?;
            Ok::<_, laravel::Error>(())
        })
        .await
        .unwrap();
        work(&app).await.assert_successful();
        assert_eq!(available_at(&app).await, [30, 30]);
        app.travel(30.seconds());
        work(&app).await.assert_successful();
        assert_eq!(records(&app).await, ["first link", "reindexed 1 at latest"]);
        app.resolve::<Records>().await.clear();

        app.scope(async || {
            Reindex::new(2, "committed").dispatch().await?;
            let rolled_back = db::default_connection()?
                .transaction(async |_| {
                    Reindex::new(2, "rolled back").dispatch().await?;
                    Err::<(), _>(laravel::abort_with(500, "rolled back"))
                })
                .await;
            assert!(rolled_back.is_err());
            let refused = Reindex::new(2, "refused").dispatch().on_connection("broken").await;
            assert!(refused.is_err());
            Ok::<_, laravel::Error>(())
        })
        .await
        .unwrap();
        app.travel(30.seconds());
        work(&app).await.assert_successful();
        assert_eq!(records(&app).await, ["reindexed 2 at committed"]);
        app.resolve::<Records>().await.clear();

        app.scope(async || {
            Reindex::new(3, "first").dispatch().await?;
            Reindex::new(3, "second").dispatch().await?;
            cache::flush().await
        })
        .await
        .unwrap();
        app.travel(30.seconds());
        work(&app).await.assert_successful();
        assert_eq!(records(&app).await, ["reindexed 3 at first", "reindexed 3 at second"]);
    }
}