renox 1.0.0

A batteries-included web framework for Rust, inspired by Laravel: Axum, HTMX and Alpine.js, SQLite or PostgreSQL, deployed as one binary.
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
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use renox::Kernel;
use renox::db::Dialect;
use renox::prelude::*;
use serde::{Deserialize, Serialize};

async fn log(state: &AppState, message: &str) -> Result {
    renox::db::sql("INSERT INTO log (message) VALUES (?)")
        .bind(message.to_owned())
        .execute(&state.db)
        .await?;
    Ok(())
}

async fn logged(kernel: &Kernel) -> Vec<String> {
    renox::db::sql("SELECT message FROM log ORDER BY id")
        .scalars(kernel.db())
        .await
        .unwrap()
}

#[derive(Serialize, Deserialize)]
struct Greet {
    name: String,
}

impl Job for Greet {
    const NAME: &'static str = "greet";

    async fn handle(self, ctx: JobContext) -> Result {
        log(&ctx.state, &format!("hello {}", self.name)).await
    }
}

/// Fails until its third attempt.
#[derive(Serialize, Deserialize)]
struct Flaky;

impl Job for Flaky {
    const NAME: &'static str = "flaky";

    fn backoff(_: u32) -> Duration {
        Duration::ZERO
    }

    async fn handle(self, ctx: JobContext) -> Result {
        log(&ctx.state, &format!("attempt {}", ctx.attempt)).await?;
        if ctx.attempt < 3 {
            return Err(anyhow_error("not yet"));
        }
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
struct Broken;

impl Job for Broken {
    const NAME: &'static str = "broken";
    const MAX_ATTEMPTS: u32 = 2;

    fn backoff(_: u32) -> Duration {
        Duration::ZERO
    }

    async fn handle(self, _: JobContext) -> Result {
        Err(anyhow_error("the printer is on fire"))
    }
}

#[derive(Serialize, Deserialize)]
struct Slow;

impl Job for Slow {
    const NAME: &'static str = "slow";
    const MAX_ATTEMPTS: u32 = 1;
    const TIMEOUT: Duration = Duration::from_millis(50);

    async fn handle(self, _: JobContext) -> Result {
        tokio::time::sleep(Duration::from_secs(5)).await;
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
struct Email;

impl Job for Email {
    const NAME: &'static str = "email";
    const QUEUE: &'static str = "emails";

    async fn handle(self, ctx: JobContext) -> Result {
        log(&ctx.state, "email sent").await
    }
}

/// A job whose name no handler is registered for.
#[derive(Serialize, Deserialize)]
struct Orphan;

impl Job for Orphan {
    const NAME: &'static str = "orphan";

    async fn handle(self, _: JobContext) -> Result {
        Ok(())
    }
}

fn anyhow_error(message: &str) -> Error {
    Error::Internal(renox_anyhow(message))
}

fn renox_anyhow(message: &str) -> anyhow::Error {
    anyhow::anyhow!(message.to_owned())
}

#[derive(Clone)]
struct OrderPlaced {
    id: i64,
}

impl Event for OrderPlaced {}

struct Shop;

impl Module for Shop {
    fn name(&self) -> &'static str {
        "shop"
    }

    fn register(&self, app: &mut Registry) {
        app.job::<Email>()
            .listen(|e: OrderPlaced, state| async move {
                log(&state, &format!("shop saw order {}", e.id)).await
            });
    }
}

fn config() -> Config {
    {
        let mut c = Config::default();
        c.env = Environment::Testing;
        c.key = Some(renox::generate_key());
        c
    }
}

async fn kernel_with(app: impl FnOnce(App) -> App) -> Kernel {
    let kernel = app(App::with_config(config())
        .module(Shop)
        .job::<Greet>()
        .job::<Flaky>()
        .job::<Broken>()
        .job::<Slow>())
    .boot()
    .await
    .unwrap();
    kernel.migrate().await.unwrap();
    renox::db::sql(match kernel.db().dialect() {
        Dialect::Sqlite => "CREATE TABLE log (id INTEGER PRIMARY KEY, message TEXT NOT NULL)",
        Dialect::Postgres => {
            "CREATE TABLE log (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, \
             message TEXT NOT NULL)"
        }
    })
    .execute(kernel.db())
    .await
    .unwrap();
    kernel
}

async fn kernel() -> Kernel {
    kernel_with(|app| app).await
}

#[tokio::test]
async fn dispatched_jobs_run() {
    let kernel = kernel().await;
    let queue = &kernel.state().queue;
    kernel
        .state()
        .dispatch(Greet {
            name: "Alex".into(),
        })
        .await
        .unwrap();
    queue.dispatch(Greet { name: "Ben".into() }).await.unwrap();
    assert_eq!(queue.pending().await.unwrap(), 2);

    assert_eq!(kernel.run_jobs().await.unwrap(), 2);
    assert_eq!(logged(&kernel).await, ["hello Alex", "hello Ben"]);
    assert_eq!(queue.pending().await.unwrap(), 0);
}

#[tokio::test]
async fn failing_jobs_are_retried() {
    let kernel = kernel().await;
    kernel.state().dispatch(Flaky).await.unwrap();
    kernel.run_jobs().await.unwrap();
    assert_eq!(
        logged(&kernel).await,
        ["attempt 1", "attempt 2", "attempt 3"]
    );
    assert!(kernel.state().queue.failed().await.unwrap().is_empty());
}

#[tokio::test]
async fn jobs_that_keep_failing_can_be_retried_later() {
    let kernel = kernel().await;
    let queue = &kernel.state().queue;
    queue.dispatch(Broken).await.unwrap();
    kernel.run_jobs().await.unwrap();

    let failed = queue.failed().await.unwrap();
    assert_eq!(failed.len(), 1);
    assert_eq!(failed[0].job, "broken");
    assert!(
        failed[0].error.contains("the printer is on fire"),
        "{}",
        failed[0].error
    );
    assert_eq!(queue.pending().await.unwrap(), 0);

    assert!(queue.retry(failed[0].id).await.unwrap());
    assert_eq!(queue.pending().await.unwrap(), 1);
    let attempts: i64 = renox::db::sql("SELECT max_attempts FROM jobs")
        .scalar(kernel.db())
        .await
        .unwrap();
    assert_eq!(attempts, 2, "a retried job gets its own attempts back");

    kernel.run_jobs().await.unwrap();
    assert_eq!(queue.flush_failed().await.unwrap(), 1);
    assert!(queue.failed().await.unwrap().is_empty());
}

#[tokio::test]
async fn slow_and_unknown_jobs_fail() {
    let kernel = kernel().await;
    let queue = &kernel.state().queue;
    queue.dispatch(Slow).await.unwrap();
    queue.dispatch(Orphan).await.unwrap();
    kernel.run_jobs().await.unwrap();
    let errors: Vec<String> = queue
        .failed()
        .await
        .unwrap()
        .into_iter()
        .map(|f| f.error)
        .collect();
    assert!(errors[0].contains("timed out"), "{errors:?}");
    assert_eq!(errors[1], "no handler registered for job `orphan`");
}

#[tokio::test]
async fn delayed_jobs_wait() {
    let kernel = kernel().await;
    let queue = &kernel.state().queue;
    queue
        .dispatch_after(
            Greet {
                name: "later".into(),
            },
            Duration::from_secs(3600),
        )
        .await
        .unwrap();
    assert_eq!(kernel.run_jobs().await.unwrap(), 0);
    assert_eq!(queue.pending().await.unwrap(), 1);
}

#[tokio::test]
async fn workers_can_be_limited_to_queues() {
    let kernel = kernel().await;
    kernel.state().dispatch(Email).await.unwrap();
    kernel
        .state()
        .dispatch(Greet {
            name: "Alex".into(),
        })
        .await
        .unwrap();

    assert_eq!(
        kernel.worker(vec!["emails".into()]).drain().await.unwrap(),
        1
    );
    assert_eq!(logged(&kernel).await, ["email sent"]);
    assert_eq!(kernel.state().queue.pending().await.unwrap(), 1);
}

#[tokio::test]
async fn events_reach_every_listener() {
    let calls = Arc::new(AtomicUsize::new(0));
    let counter = calls.clone();
    let kernel = kernel_with(move |app| {
        app.listen(move |e: OrderPlaced, state| {
            let counter = counter.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
                log(&state, &format!("app saw order {}", e.id)).await?;
                Err(anyhow_error("listener broke"))
            }
        })
    })
    .await;

    let result = kernel.state().emit(OrderPlaced { id: 7 }).await;
    assert!(format!("{:?}", result.unwrap_err()).contains("listener broke"));
    // App-level listeners first, then modules' (registered at boot); all of them run.
    assert_eq!(
        logged(&kernel).await,
        ["app saw order 7", "shop saw order 7"]
    );
    assert_eq!(calls.load(Ordering::SeqCst), 1);

    #[derive(Clone)]
    struct Nobody;
    impl Event for Nobody {}
    assert!(kernel.state().emit(Nobody).await.is_ok());
}

#[tokio::test]
async fn background_workers_pick_up_jobs_and_stop_cleanly() {
    let kernel = kernel().await;
    let (stop, stopped) = tokio::sync::watch::channel(false);
    let worker = tokio::spawn(kernel.worker(Vec::new()).run(2, stopped));

    kernel
        .state()
        .dispatch(Greet {
            name: "background".into(),
        })
        .await
        .unwrap();
    // Within the 1s poll interval, so this checks the wake-up. A PostgreSQL
    // server shared by the whole parallel suite can be slower than that.
    let tries = match kernel.db().dialect() {
        Dialect::Sqlite => 50,
        Dialect::Postgres => 150,
    };
    for _ in 0..tries {
        if !logged(&kernel).await.is_empty() {
            break;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    assert_eq!(
        logged(&kernel).await,
        ["hello background"],
        "woken without waiting for the poll"
    );
    stop.send(true).unwrap();
    tokio::time::timeout(Duration::from_secs(3), worker)
        .await
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn misconfiguration_fails_at_boot() {
    let twice = App::with_config(config())
        .job::<Greet>()
        .job::<Greet>()
        .boot()
        .await;
    assert!(format!("{:?}", twice.err().unwrap()).contains("job `greet` is registered twice"));

    let bad_time = App::with_config(config())
        .schedule(|s| {
            s.daily_at("25:00", "nope", |_| async { Ok(()) });
        })
        .boot()
        .await;
    assert!(format!("{:?}", bad_time.err().unwrap()).contains("task `nope`"));

    // An unknown APP_TIMEZONE is refused when the config is read (the config tests).
}

#[tokio::test]
async fn scheduled_tasks_run_on_demand_with_their_hooks() {
    static RUNS: AtomicUsize = AtomicUsize::new(0);
    let kernel = kernel_with(|app| {
        app.schedule(|s| {
            s.cron("0 3 * * *", "report", |state| async move {
                RUNS.fetch_add(1, Ordering::SeqCst);
                assert!(renox::context::app().is_some(), "runs in the app's context");
                state.cache.put("report.ran", &true, None).await
            })
            .timezone("Asia/Jakarta")
            .on_success(|state| async move {
                let _ = state.cache.put("report.ok", &true, None).await;
            });
            s.daily_at("04:00", "broken", |_| async {
                Err(abort(StatusCode::INTERNAL_SERVER_ERROR, "disk full"))
            })
            .on_failure(|err, state| async move {
                let _ = state
                    .cache
                    .put("broken.error", &format!("{err:?}"), None)
                    .await;
            });
            s.hourly("panics", |_| async { panic!("boom") })
                .on_failure(|_, state| async move {
                    let _ = state.cache.put("panics.caught", &true, None).await;
                });
        })
    })
    .await;
    let cache = &kernel.state().cache;
    kernel.run_scheduled("report").await.unwrap();
    assert_eq!(RUNS.load(Ordering::SeqCst), 1);
    assert_eq!(cache.get::<bool>("report.ok").await.unwrap(), Some(true));

    assert!(kernel.run_scheduled("broken").await.is_err());
    let error = cache.get::<String>("broken.error").await.unwrap().unwrap();
    assert!(error.contains("disk full"), "{error}");

    assert!(kernel.run_scheduled("panics").await.is_err());
    assert_eq!(
        cache.get::<bool>("panics.caught").await.unwrap(),
        Some(true)
    );
    assert!(kernel.run_scheduled("nope").await.is_err());
}

#[tokio::test]
async fn each_scheduled_run_is_claimed_once() {
    let kernel = kernel().await;
    let state = kernel.state();
    // Two processes sharing the database reach the same slot: one runs it.
    assert!(renox::schedule::claim(state, "report", 1_800_000_000, 120).await);
    assert!(!renox::schedule::claim(state, "report", 1_800_000_000, 120).await);
    assert!(renox::schedule::claim(state, "report", 1_800_000_060, 120).await);
    assert!(renox::schedule::claim(state, "backup", 1_800_000_000, 120).await);
}