ulo 0.1.0-alpha.3

Fast and modular web framework for scalable applications
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
//! Section 10.1 step 6, the environment: a `Timer` wherever a wait is written (section 3.9), and
//! no zero bound on any item `resolve_bound` resolves.
//!
//! Capabilities pinned: 42 (readiness bounds and backoff need a clock), 44 (reported by `wire()`
//! at the call that wrote the wait: `.timeout(..)`, `.attempt_timeout(..)` or `.backoff(..)`, and
//! the registration for a trait const), 45. `Default` and `Unbounded` need no clock.

#[macro_use]
mod common;

use std::time::Duration;

use common::*;
use ulo::{App, Bound, BoundItem, Dep, HookKind, Key, Timer, WiringError};

struct A;
struct Svc;

const SECOND: Duration = Duration::from_secs(1);

fn check() -> impl Fn() -> std::future::Ready<Result<(), Boom>> + Send + Sync + 'static {
    || std::future::ready(Ok(()))
}

/// The `BoundWithoutTimer` entries as `(item, line)`.
fn bounds(errors: &ulo::WiringErrors) -> Vec<(String, u32)> {
    entries!(errors, WiringError::BoundWithoutTimer { item, at } => (item.clone(), at.line()))
}

#[test]
fn a_construction_timeout_on_an_app_with_no_timer() {
    // The registration and the bound on two lines, so the entry tells them apart.
    let registered = line!() + 3;
    let timeout = line!() + 3;
    let errors = wire_err(Mod::<A>::new(|m| {
        m.singleton(|| async { Svc })
            .timeout(SECOND);
    }));
    let found = bounds(&errors);
    assert_eq!(found.len(), 1, "{errors}");
    assert!(found[0].0.contains("Svc"), "the item names the binding: {}", found[0].0);
    assert_eq!(found[0].1, timeout, "the entry points at the `.timeout(..)`, not the registration on line {registered}");
}

#[test]
fn a_constructs_after_bound_on_an_app_with_no_timer() {
    struct Slow;
    impl ulo::Construct for Slow {
        type Scope = ulo::scope::Singleton;
        const CONSTRUCT_TIMEOUT: Bound = Bound::After(SECOND);

        fn dependencies(_d: &mut ulo::Dependencies) {}

        async fn construct(_r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
            Ok(Slow)
        }
    }
    let registered = line!() + 2;
    let errors = wire_err(Mod::<A>::new(|m| {
        m.provide::<Slow>();
    }));
    let found = bounds(&errors);
    assert_eq!(found.len(), 1, "{errors}");
    assert!(found[0].0.contains("Slow"), "{}", found[0].0);
    assert_eq!(found[0].1, registered, "a trait const has no call: the registration that brought the type in");
}

#[test]
fn a_readiness_timeout_and_attempt_timeout_on_an_app_with_no_timer() {
    // One call per line, so the registration, the `.ready` and the bound are three lines.
    let ready = line!() + 5;
    let whole = line!() + 5;
    let attempt = line!() + 7;
    let errors = wire_err(Mod::<A>::new(|m| {
        m.singleton(|| async { Svc })
            .ready(check())
            .timeout(SECOND);
        m.singleton(|| async { A })
            .ready(check())
            .attempt_timeout(SECOND);
    }));
    let mut found = bounds(&errors);
    found.sort_by_key(|(_, line)| *line);
    assert_eq!(found.len(), 2, "{errors}");
    assert!(found[0].0.contains("readiness `.timeout`") && found[0].0.contains("Svc"), "{}", found[0].0);
    assert_eq!(found[0].1, whole, "the entry points at the `.timeout(..)`, not the `.ready(..)` on line {ready}");
    assert!(found[1].0.contains("readiness `.attempt_timeout`") && found[1].0.contains("A"), "{}", found[1].0);
    assert_eq!(found[1].1, attempt, "the `.attempt_timeout(..)` line");
}

#[test]
fn a_hook_timeout_and_a_module_hook_timeout_on_an_app_with_no_timer() {
    let hook = line!() + 5;
    let module_hook = line!() + 6;
    let errors = wire_err(Mod::<A>::new(|m| {
        m.singleton(|| async { Svc })
            .on_init(check())
            .timeout(SECOND);
        m.on_init(check())
            .timeout(SECOND);
    }));
    let found = bounds(&errors);
    assert_eq!(found.len(), 2, "{errors}");
    let line_of = |needle: &str| found.iter().find(|(item, _)| item.contains(needle)).map(|&(_, line)| line);
    assert_eq!(line_of("`Svc`"), Some(hook), "the binding's hook, at its `.timeout(..)`: {found:?}");
    assert_eq!(line_of(&mod_name::<A>()), Some(module_hook), "the module's hook, at its `.timeout(..)`: {found:?}");
}

#[test]
fn a_trait_hooks_after_bound_on_an_app_with_no_timer() {
    struct Hooked;
    impl ulo::Construct for Hooked {
        type Scope = ulo::scope::Singleton;

        fn dependencies(_d: &mut ulo::Dependencies) {}

        async fn construct(_r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
            Ok(Hooked)
        }

        fn hooks(h: &mut ulo::Hooks<Self>) {
            h.on_module_init();
        }
    }
    impl ulo::OnModuleInit for Hooked {
        const TIMEOUT: Bound = Bound::After(SECOND);

        async fn on_module_init(&self) -> Result<(), ulo::BoxError> {
            Ok(())
        }
    }
    let registered = line!() + 2;
    let errors = wire_err(Mod::<A>::new(|m| {
        m.provide::<Hooked>();
    }));
    let found = bounds(&errors);
    assert_eq!(found.len(), 1, "{errors}");
    assert!(found[0].0.contains("OnModuleInit") && found[0].0.contains("Hooked"), "{}", found[0].0);
    assert_eq!(found[0].1, registered, "a trait const has no call: the registration that brought the type in");
}

#[test]
fn default_and_unbounded_need_no_timer() {
    wires(Mod::<A>::new(|m| {
        m.singleton(|| async { Svc });
        m.singleton(|| async { A }).unbounded();
        m.singleton(|| async { SECOND }).ready(check()).unbounded();
        m.singleton(|| async { 1_u8 }).on_init(check()).unbounded();
        m.on_init(check()).unbounded();
    }));
}

#[test]
fn the_same_bounds_wire_on_an_app_with_a_timer() {
    wires_with(
        App::builder(Mod::<A>::new(|m| {
            m.singleton(|| async { Svc }).timeout(SECOND);
            m.singleton(|| async { A }).ready(check()).timeout(SECOND);
            m.singleton(|| async { SECOND }).ready(check()).attempt_timeout(SECOND).backoff(SECOND);
            m.singleton(|| async { 1_u8 }).on_init(check()).timeout(SECOND);
            m.on_init(check()).timeout(SECOND);
        }))
        .timer(Frozen::new()),
    );
}

#[test]
fn backoff_reports_its_own_line() {
    let ready = line!() + 3;
    let backoff = line!() + 3;
    let errors = wire_err(Mod::<A>::new(|m| {
        let handle = m.singleton(|| async { Svc }).ready(check());
        handle.backoff(SECOND);
    }));

    let (binding, line) = entry!(errors, WiringError::BackoffWithoutTimer { binding, at } => (binding.clone(), at.line()));
    assert!(binding.contains("Svc"), "{binding}");
    assert_eq!(line, backoff, "the `.backoff(..)` line, not the `.ready(..)` line {ready}");
    assert!(bounds(&errors).is_empty(), "a backoff is not a bound: {errors}");
}

#[test]
fn a_zero_backoff_waits_for_nothing_and_needs_no_timer() {
    wires(Mod::<A>::new(|m| {
        let handle = m.singleton(|| async { Svc }).ready(check());
        handle.backoff(Duration::ZERO);
    }));
}

#[test]
fn a_builder_knob_on_an_app_with_no_timer() {
    type Knob = fn(ulo::AppBuilder) -> ulo::AppBuilder;
    let knobs: [(&str, Knob); 4] = [
        ("drain_timeout", |b| b.drain_timeout(SECOND)),
        ("shutdown_timeout", |b| b.shutdown_timeout(SECOND)),
        ("hook_timeout", |b| b.hook_timeout(SECOND)),
        ("construct_timeout", |b| b.construct_timeout(SECOND)),
    ];
    for (name, set) in knobs {
        let errors = wire_err_with(set(App::builder(Empty)));
        let knob = entry!(errors, WiringError::KnobWithoutTimer { knob } => *knob);
        assert_eq!(knob, name);
        assert_eq!(errors.len(), 1, "{errors}");

        wires_with(set(App::builder(Empty)).timer(Frozen::new()));
    }

    let all = App::builder(Empty).construct_timeout(SECOND).hook_timeout(SECOND).shutdown_timeout(SECOND).drain_timeout(SECOND);
    let errors = wire_err_with(all);
    assert_eq!(
        entries!(errors, WiringError::KnobWithoutTimer { knob } => *knob),
        ["drain_timeout", "shutdown_timeout", "hook_timeout", "construct_timeout"],
        "every knob set is reported, in one fixed order"
    );
}

#[test]
fn a_module_binding_dyn_timer_is_a_second_source() {
    struct MyTimer(Frozen);
    impl Timer for MyTimer {
        fn sleep(&self, d: Duration) -> ulo::BoxFuture<'static, ()> {
            self.0.sleep(d)
        }

        fn now(&self) -> std::time::Instant {
            self.0.now()
        }

        fn try_sleep(&self, d: Duration) -> ulo::BoxFuture<'static, Result<(), ulo::Refused>> {
            Timer::try_sleep(&self.0, d)
        }
    }
    let root = Mod::<A>::new(|m| {
        m.import(Mod::<Svc>::new(|m| {
            m.singleton(|| async { MyTimer(Frozen::new()) }).also_as::<dyn Timer>(|a| a);
            m.export::<dyn Timer>();
        }));
        m.singleton(|_t: Dep<dyn Timer>| async { Svc });
    });
    let errors = wire_err_with(App::builder(root).timer(Frozen::new()));

    let (key, sources) = entry!(errors, WiringError::Ambiguous { key, sources, .. } => (key.key(), sources.len()));
    assert_eq!(key, Key::of::<dyn Timer, ()>());
    assert_eq!(sources, 2, "the app's clock and the module's");
}

// ---- Zero bounds (A3): refused on every item `resolve_bound` resolves, whatever the clock. ----

const ZERO: Duration = Duration::ZERO;

/// The `ZeroBound` entries as `(item, binding key, module, line)`.
fn zeros(errors: &ulo::WiringErrors) -> Vec<(BoundItem, Option<Key>, String, u32)> {
    entries!(errors, WiringError::ZeroBound { item, binding, module, at } => (*item, binding.as_ref().map(|b| b.key()), module.to_string(), at.line()))
}

/// `root` wired with no clock and with one: the same zero bounds refused both times, and on the app
/// with no clock as `ZeroBound` alone, never also as `BoundWithoutTimer`.
fn refused_either_way(root: impl Fn() -> Mod<A>) -> Vec<(BoundItem, Option<Key>, String, u32)> {
    let untimed = wire_err(root());
    assert!(bounds(&untimed).is_empty(), "a zero bound is reported once, as `ZeroBound`: {untimed}");
    let timed = wire_err_with(App::builder(root()).timer(Frozen::new()));
    let found = zeros(&timed);
    assert_eq!(zeros(&untimed), found, "the clock plays no part");
    assert_eq!(found.len(), timed.len(), "nothing else is reported: {timed}");
    found
}

trait Plugin: Send + Sync {}

impl Plugin for Svc {}

#[test]
fn a_zero_construction_timeout_is_refused_at_its_timeout_call() {
    struct Inner;
    let timeout = line!() + 6;
    let contribution = line!() + 8;
    let found = refused_either_way(|| {
        Mod::<A>::new(|m| {
            m.import(Mod::<Inner>::new(|m| {
                m.singleton(|| async { Svc })
                    .timeout(ZERO);
                m.contribute::<dyn Plugin>()
                    .singleton(|| async { Svc }, |p| p)
                    .timeout(ZERO);
            }));
        })
    });
    assert_eq!(
        found,
        [
            (BoundItem::Construction, Some(Key::of::<Svc, ()>()), mod_name::<Inner>(), timeout),
            (BoundItem::Construction, Some(Key::of::<dyn Plugin, ()>()), mod_name::<Inner>(), contribution),
        ],
        "the module that binds each, and a contribution's own `.timeout(..)` line"
    );
}

#[test]
fn a_zero_readiness_timeout_and_attempt_timeout_are_refused_at_their_calls() {
    let whole = line!() + 6;
    let attempt = line!() + 8;
    let found = refused_either_way(|| {
        Mod::<A>::new(|m| {
            m.singleton(|| async { Svc })
                .ready(check())
                .timeout(ZERO);
            m.singleton(|| async { SECOND })
                .ready(check())
                .attempt_timeout(ZERO);
        })
    });
    assert_eq!(
        found,
        [
            (BoundItem::ReadinessWhole, Some(Key::of::<Svc, ()>()), mod_name::<A>(), whole),
            (BoundItem::ReadinessAttempt, Some(Key::of::<Duration, ()>()), mod_name::<A>(), attempt),
        ]
    );
}

#[test]
fn a_zero_hook_timeout_on_a_binding_and_on_a_module_is_refused_at_its_call() {
    struct Hooks;
    let hook = line!() + 6;
    let module_hook = line!() + 8;
    let found = refused_either_way(|| {
        Mod::<A>::new(|m| {
            m.singleton(|| async { Svc })
                .on_destroy(|| async {})
                .timeout(ZERO);
            m.import(Mod::<Hooks>::new(|m| {
                m.on_init(check())
                    .timeout(ZERO);
            }));
        })
    });
    assert_eq!(
        found,
        [
            (BoundItem::Hook(HookKind::OnModuleDestroy), Some(Key::of::<Svc, ()>()), mod_name::<A>(), hook),
            (BoundItem::Hook(HookKind::OnModuleInit), None, mod_name::<Hooks>(), module_hook),
        ]
    );
}

#[test]
fn a_zero_trait_const_is_refused_at_the_registration_that_brought_the_type_in() {
    struct Instant0;
    impl ulo::Construct for Instant0 {
        type Scope = ulo::scope::Singleton;
        const CONSTRUCT_TIMEOUT: Bound = Bound::After(ZERO);

        fn dependencies(_d: &mut ulo::Dependencies) {}

        async fn construct(_r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
            Ok(Instant0)
        }

        fn hooks(h: &mut ulo::Hooks<Self>) {
            h.on_application_shutdown();
        }
    }
    impl ulo::OnApplicationShutdown for Instant0 {
        const TIMEOUT: Bound = Bound::After(ZERO);

        async fn on_application_shutdown(&self, _signal: &ulo::Signal) {}
    }
    let registered = line!() + 3;
    let found = refused_either_way(|| {
        Mod::<A>::new(|m| {
            m.provide::<Instant0>();
        })
    });
    let key = Some(Key::of::<Instant0, ()>());
    assert_eq!(
        found,
        [
            (BoundItem::Construction, key, mod_name::<A>(), registered),
            (BoundItem::Hook(HookKind::OnApplicationShutdown), key, mod_name::<A>(), registered),
        ]
    );
}

#[test]
fn a_bound_above_zero_and_unbounded_are_not_zero_bounds() {
    wires_with(
        App::builder(Mod::<A>::new(|m| {
            m.singleton(|| async { Svc }).timeout(Duration::from_nanos(1));
            m.singleton(|| async { A }).ready(check()).attempt_timeout(Duration::from_nanos(1));
            m.singleton(|| async { SECOND }).ready(check()).unbounded();
            m.on_init(check()).unbounded();
        }))
        .timer(Frozen::new()),
    );
}

#[test]
fn a_zero_construct_or_hook_default_is_refused_at_the_call_that_set_it() {
    let construct = line!() + 3;
    let hook = line!() + 3;
    let builder = App::builder(Empty).timer(Frozen::new())
        .construct_timeout(ZERO)
        .hook_timeout(ZERO);
    let errors = wire_err_with(builder);
    let found = entries!(errors, WiringError::ZeroDefault { knob, at } => (*knob, at.line()));
    assert_eq!(found, [("hook_timeout", hook), ("construct_timeout", construct)], "each knob with the line that set it, in one fixed order");
    assert_eq!(errors.len(), 2, "{errors}");
    let text = errors.to_string();
    assert!(text.contains("`construct_timeout` is zero") && text.contains(".unbounded()"), "{text}");

    // Refused whatever the clock; with none, the missing `Timer` is reported beside it.
    let errors = wire_err_with(App::builder(Empty).hook_timeout(ZERO));
    assert_eq!(entries!(errors, WiringError::ZeroDefault { knob, .. } => *knob), ["hook_timeout"]);
    assert_eq!(entries!(errors, WiringError::KnobWithoutTimer { knob } => *knob), ["hook_timeout"]);
    assert_eq!(errors.len(), 2, "{errors}");
}

#[test]
fn a_zero_drain_or_shutdown_window_is_accepted() {
    wires_with(App::builder(Empty).timer(Frozen::new()).drain_timeout(ZERO).shutdown_timeout(ZERO));
}

#[test]
fn a_zero_default_set_through_test_app_is_refused_at_the_tests_call() {
    let construct = line!() + 1;
    let app = ulo::testing::TestApp::of(Empty).timer(Frozen::new()).construct_timeout(ZERO);
    let hook = line!() + 1;
    let app = app.hook_timeout(ZERO);
    let errors = wiring_errors(app.wire());
    let found = entries!(errors, WiringError::ZeroDefault { knob, at } => (*knob, at.file(), at.line()));
    assert_eq!(found, [("hook_timeout", file!(), hook), ("construct_timeout", file!(), construct)], "the test's own lines, not `TestApp`'s");
}