Repository navigation
Expand file tree
/
Copy pathwrap.rs
More file actions
98 lines (83 loc) · 2.14 KB
/
Copy pathwrap.rs
File metadata and controls
98 lines (83 loc) · 2.14 KB
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
//! Wrapper constructors for cross-cutting concerns — the Rust alternative to a
//! `decorate` API.
//!
//! Each type can only be `provide`d once. Compose wrappers in one constructor,
//! or expose a newtype / service struct from a module (`provide_private` raw value
//! + public wrapper returning a different type).
//!
//! ```bash
//! cargo run --example wrap
//! ```
use modrun::logging::init;
use modrun::{Modrun, Module, Result};
#[derive(Clone, Debug, PartialEq, Eq)]
struct Logger {
name: &'static str,
metrics: bool,
}
impl Logger {
fn with_name(self, name: &'static str) -> Self {
Self { name, ..self }
}
fn with_metrics(self) -> Self {
Self {
metrics: true,
..self
}
}
}
/// Public face of the logging module — distinct from the private [`Logger`] binding.
#[derive(Clone, PartialEq, Eq)]
struct AppLogger(Logger);
fn new_logger() -> Logger {
Logger {
name: "default",
metrics: false,
}
}
fn named_logger(log: Logger) -> Logger {
log.with_name("myapp")
}
fn metrics_logger(log: Logger) -> Logger {
log.with_metrics()
}
fn new_app_logger(log: Logger) -> AppLogger {
AppLogger(metrics_logger(named_logger(log)))
}
fn logging_domain() -> Module {
Module::builder("logging")
.provide_private(new_logger)
.provide(new_app_logger)
.invoke(|log: AppLogger| {
assert_eq!(log.0.name, "myapp");
assert!(log.0.metrics);
})
}
/// At the composition root, a single constructor is enough when you do not need a
/// private binding:
fn app_logger() -> Logger {
metrics_logger(named_logger(new_logger()))
}
fn boot(log: Logger) {
assert_eq!(log.name, "myapp");
assert!(log.metrics);
}
#[tokio::main]
async fn main() -> Result<()> {
init();
println!("-- module + newtype wrapper --");
Modrun::builder()
.module(logging_domain())
.start()
.await?
.stop()
.await?;
println!("-- root + composed ctor --");
Modrun::builder()
.provide(app_logger)
.invoke(boot)
.start()
.await?
.stop()
.await
}