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
//! Route composition and application-owned task registrations.
use std::{
future::Future,
sync::{Arc, OnceLock},
};
use axum::{Router, handler::Handler, routing};
use super::Role;
use crate::{
AppConfig,
task::{self, Cleanup, Worker, WorkerContext},
};
type ConfigOverride = Box<dyn FnOnce(&mut AppConfig) + Send>;
pub(crate) struct Registration {
pub name: String,
pub role: Role,
pub component_name: Option<String>,
pub metrics: crate::metrics::Registry,
pub config: AppConfig,
pub environment: bool,
pub overrides: Vec<ConfigOverride>,
pub workers: Vec<Worker>,
pub cleanups: Vec<Cleanup>,
pub checks: Vec<crate::health::Check>,
pub http: bool,
pub http_wrapper: Option<crate::web::HttpWrapper>,
pub streaming: Vec<crate::web::StreamingGroup>,
pub startup_error: Option<crate::Error>,
pub rejection_formatter: Option<crate::web::RejectionFormatter>,
pub setup: Option<crate::setup::Factory>,
}
/// Builds an application whose routes still need state `S`.
///
/// Only `App<()>` can start. Route collisions retain Axum's construction-time
/// panic behavior. Construction installs no signal handlers or global logging.
pub struct App<S = ()> {
pub(crate) router: Router<S>,
pub(crate) registration: Registration,
pub(super) task_state: Option<Arc<OnceLock<S>>>,
}
impl<S> App<S>
where
S: Clone + Send + Sync + 'static,
{
/// Begin assembling an application with a diagnostic name.
pub fn new(name: impl Into<String>) -> Self {
Self {
router: Router::new(),
task_state: None,
registration: Registration {
name: name.into(),
role: Role::default(),
component_name: None,
metrics: crate::metrics::Registry::owned(),
config: AppConfig::default(),
environment: true,
overrides: Vec::new(),
workers: Vec::new(),
cleanups: Vec::new(),
checks: Vec::new(),
http: false,
http_wrapper: None,
streaming: Vec::new(),
startup_error: None,
rejection_formatter: None,
setup: None,
},
}
}
/// Select the application work to start. The default is [Role::All].
///
/// Setup can read the role to initialize the resources this process needs.
/// The configured admin listener is available in every role.
pub fn with_role(mut self, role: Role) -> Self {
self.registration.role = role;
self
}
/// Attach an application-owned registry for prebuilt state and setup instruments.
///
/// Attaching the same registry (including a clone) to another builder fails
/// startup. Attachment is permanent even if this builder is later dropped.
/// Registration closes when setup ends; instrument handles remain usable.
pub fn metrics(mut self, metrics: crate::metrics::Registry) -> Self {
match metrics.attach() {
Ok(()) => self.registration.metrics = metrics,
Err(error) => {
self.registration.startup_error =
Some(crate::Error::Registration(error.to_string()));
}
}
self
}
/// Supply a complete explicit configuration, bypassing environment loading.
pub fn config(mut self, config: AppConfig) -> Self {
self.registration.config = config;
self.registration.environment = false;
self
}
/// Apply field overrides after environment loading, at startup.
pub fn configure(
mut self,
override_config: impl FnOnce(&mut AppConfig) + Send + 'static,
) -> Self {
self.registration.overrides.push(Box::new(override_config));
self
}
/// Format Servlet's pre-handler HTTP rejections as application problem JSON.
///
/// The callback receives safe rejection facts and returns an optional
/// serialized problem body, up to 16 KiB. It must return promptly. Servlet
/// owns the status, correlation header, transport, and metrics. Returning
/// no body, exceeding the limit, or panicking uses the default problem.
pub fn format_runtime_rejections(
mut self,
formatter: impl for<'a> Fn(crate::web::RuntimeRejection<'a>) -> Option<crate::web::Bytes>
+ Send
+ Sync
+ 'static,
) -> Self {
self.registration.rejection_formatter = Some(Arc::new(formatter));
self
}
/// Register a GET route using Axum's native handler types.
pub fn get<H, T>(mut self, path: &str, handler: H) -> Self
where
H: Handler<T, S>,
T: 'static,
{
self.router = self.router.route(path, routing::get(handler));
self.registration.http = true;
self
}
/// Register a POST route using Axum's native handler types.
pub fn post<H, T>(mut self, path: &str, handler: H) -> Self
where
H: Handler<T, S>,
T: 'static,
{
self.router = self.router.route(path, routing::post(handler));
self.registration.http = true;
self
}
/// Merge an ordinary Axum router with the same missing state.
pub fn http(mut self, router: Router<S>) -> Self {
self.router = self.router.merge(router);
self.registration.http = true;
self
}
/// Wrap the complete application router after setup binds state.
///
/// Use this for middleware that needs the final Axum response, including
/// routing headers. The callback runs once, before workers start and the
/// application listener admits requests. It must return promptly.
/// Only the application listener uses this wrapper. Registering another
/// wrapper replaces the previous one.
pub fn wrap_http(
mut self,
wrap: impl FnOnce(Router) -> std::result::Result<Router, task::BoxError> + Send + 'static,
) -> Self {
self.registration.http_wrapper = Some(Box::new(wrap));
self
}
/// Mount a native Axum router at a dedicated streaming prefix.
///
/// The prefix reserves the whole subtree, including unmatched requests.
/// The router's paths are relative to the prefix, following Axum nesting.
/// Register any middleware the streaming routes need on that router.
/// Prefixes are disjoint, static, absolute paths such as `"/api/sync"`.
///
/// This group's exchange slots are separate from ordinary request slots.
/// All HTTP connections still share the application's connection ceiling.
/// Leave headroom below that ceiling across the enabled streaming groups
/// so active streams alone cannot occupy every connection.
///
/// The group uses its policy from admission onward, including route
/// handling and response transfer. The listener's header deadline and the
/// application's request body limit still apply.
///
/// ```
/// use servlet::{App, web::{Router, StreamPolicy, routing::get}};
/// use std::time::Duration;
///
/// let app: App = App::new("events").streaming_routes(
/// "/events",
/// StreamPolicy {
/// max_in_flight: 32,
/// max_duration: Duration::from_secs(120),
/// idle_timeout: Duration::from_secs(15),
/// },
/// Router::new().route("/", get(|| async { "mounted at /events" })),
/// );
/// ```
pub fn streaming_routes(
mut self,
prefix: &str,
policy: crate::web::StreamPolicy,
router: Router<S>,
) -> Self {
let group = match crate::web::StreamingGroup::new(prefix, policy) {
Ok(group) => group,
Err(error) => {
self.registration.startup_error.get_or_insert(error);
return self;
}
};
if self
.registration
.streaming
.iter()
.any(|other| group.overlaps(other))
{
self.registration.startup_error.get_or_insert_with(|| {
crate::Error::Registration("streaming prefixes must not overlap".into())
});
return self;
}
self.router = self.router.nest(prefix, router);
self.registration.streaming.push(group);
self.registration.http = true;
self
}
/// Supply state for routes and state-aware tasks so the application can start.
pub fn state(self, state: S) -> App<()> {
App {
router: Self::router_with_state(self.router, self.task_state, state),
registration: self.registration,
task_state: None,
}
}
pub(super) fn router_with_state(
router: Router<S>,
task_state: Option<Arc<OnceLock<S>>>,
state: S,
) -> Router {
if let Some(task_state) = task_state {
task_state.get_or_init(|| state.clone());
}
router.with_state(state)
}
/// Register a required, long-running worker for [`Role::All`] and [`Role::Worker`].
/// Returning early is a failure.
pub fn worker<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
where
F: FnOnce(WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.register_task(name, factory, false)
}
/// Register a worker that receives a clone of the initialized state.
///
/// Register before [`Self::setup`] or [`Self::state`] to receive typed state.
/// The factory runs after successful setup in the same roles as [`Self::worker`].
pub fn worker_with_state<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
where
F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.register_stateful_task(name, factory, false)
}
/// Register a required, long-running service that starts in every role.
///
/// Services start after setup. They share task names, startup readiness,
/// failure handling, and shutdown with [`Self::worker`]. Call
/// [`WorkerContext::ready`] when a service is ready. Returning early is a
/// failure.
pub fn service<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
where
F: FnOnce(WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.register_task(name, factory, true)
}
/// Register a service that receives a clone of the initialized state.
///
/// Register before [`Self::setup`] or [`Self::state`] to receive typed state.
/// The factory runs after successful setup in every role, like [`Self::service`].
pub fn service_with_state<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
where
F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.register_stateful_task(name, factory, true)
}
fn register_stateful_task<F, Fut>(
mut self,
name: impl Into<String>,
factory: F,
runs_in_api: bool,
) -> Self
where
F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
let task_state = self
.task_state
.get_or_insert_with(|| Arc::new(OnceLock::new()))
.clone();
self.register_task(
name,
move |context| {
let state = task_state
.get()
.expect("application state is initialized before tasks start")
.clone();
factory(state, context)
},
runs_in_api,
)
}
fn register_task<F, Fut>(
mut self,
name: impl Into<String>,
factory: F,
runs_in_api: bool,
) -> Self
where
F: FnOnce(WorkerContext) -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.registration.workers.push(Worker {
name: name.into(),
factory: Box::new(move |context| Box::pin(factory(context))),
runs_in_api,
});
self
}
/// Register a cached dependency check. Startup waits for its first success.
/// Readiness reflects its latest result, which can fail before startup ends.
pub fn readiness<F, Fut>(
mut self,
name: impl Into<String>,
policy: crate::health::CheckPolicy,
check: F,
) -> Self
where
F: Fn() -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.registration
.checks
.push(crate::health::Check::new(name.into(), policy, check));
self
}
/// Register cleanup, run in reverse order after drain and cancellation.
pub fn cleanup<F, Fut>(mut self, name: impl Into<String>, factory: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = task::Result> + Send + 'static,
{
self.registration.cleanups.push(Cleanup {
name: name.into(),
factory: Box::new(move || Box::pin(factory())),
});
self
}
}