1mod lifecycle;
4mod supervisor;
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use std::error::Error;
9use std::fmt;
10use std::time::Duration;
11
12#[doc(hidden)]
14pub mod __source {
15 pub const LIB: &str = include_str!("lib.rs");
16 pub const LIFECYCLE: &str = include_str!("lifecycle.rs");
17 pub const SUPERVISOR: &str = include_str!("supervisor.rs");
18}
19
20pub use lifecycle::{
21 ModuleDescriptor, ModuleEvent, ModuleObserver, ModulePhase, ModulePlan, ModuleRuntime,
22 ModuleStarter,
23};
24pub use supervisor::{
25 BackgroundTaskExit, BackgroundTaskExitKind, BackgroundTaskObserver, SupervisedTaskHandle,
26};
27
28pub const RUNTIME_API_VERSION: u32 = appstruct_contracts::RUNTIME_API.current;
30
31pub const DEFAULT_SERVICE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
32
33#[must_use]
34pub const fn supports_runtime_api(version: u32) -> bool {
35 appstruct_contracts::RUNTIME_API.supports(version)
36}
37
38pub type TenantId = uuid::Uuid;
39
40#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub struct Actor {
42 pub id: uuid::Uuid,
43 pub email: String,
44 pub roles: Vec<String>,
45}
46
47impl Actor {
48 #[must_use]
49 pub fn has_role(&self, role: &str) -> bool {
50 self.roles.iter().any(|candidate| candidate == role)
51 }
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct StartupError {
56 service: String,
57 message: String,
58 dependency_chain: Vec<String>,
59 rolled_back: Vec<String>,
60 rollback_failures: Vec<ShutdownFailure>,
61}
62
63impl StartupError {
64 #[must_use]
65 pub fn configuration(service: impl Into<String>, error: impl fmt::Display) -> Self {
66 Self {
67 service: service.into(),
68 message: error.to_string(),
69 dependency_chain: Vec::new(),
70 rolled_back: Vec::new(),
71 rollback_failures: Vec::new(),
72 }
73 }
74
75 #[must_use]
76 pub fn dependency(service: impl Into<String>, dependency: impl fmt::Display) -> Self {
77 Self::configuration(
78 service,
79 format_args!("runtime dependency `{dependency}` was not started"),
80 )
81 }
82
83 #[must_use]
84 pub fn service(&self) -> &str {
85 &self.service
86 }
87
88 #[must_use]
89 pub fn dependency_chain(&self) -> &[String] {
90 &self.dependency_chain
91 }
92
93 #[must_use]
94 pub fn rolled_back(&self) -> &[String] {
95 &self.rolled_back
96 }
97
98 #[must_use]
99 pub fn rollback_failures(&self) -> &[ShutdownFailure] {
100 &self.rollback_failures
101 }
102
103 #[must_use]
104 pub fn with_runtime_context(
105 mut self,
106 dependency_chain: Vec<String>,
107 rollback: ShutdownReport,
108 ) -> Self {
109 self.dependency_chain = dependency_chain;
110 self.rolled_back = rollback.attempted;
111 self.rollback_failures = rollback.failures;
112 self
113 }
114}
115
116impl fmt::Display for StartupError {
117 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
118 write!(
119 formatter,
120 "failed to initialize {}: {}",
121 self.service, self.message
122 )?;
123 if !self.dependency_chain.is_empty() {
124 write!(
125 formatter,
126 "; dependency chain: {}",
127 self.dependency_chain.join(" -> ")
128 )?;
129 }
130 if !self.rolled_back.is_empty() {
131 write!(formatter, "; rolled back: {}", self.rolled_back.join(", "))?;
132 }
133 if !self.rollback_failures.is_empty() {
134 write!(
135 formatter,
136 "; rollback failures: {}",
137 self.rollback_failures
138 .iter()
139 .map(ToString::to_string)
140 .collect::<Vec<_>>()
141 .join(", ")
142 )?;
143 }
144 Ok(())
145 }
146}
147
148impl Error for StartupError {}
149
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct ShutdownError {
152 message: String,
153}
154
155impl ShutdownError {
156 #[must_use]
157 pub fn new(error: impl fmt::Display) -> Self {
158 Self {
159 message: error.to_string(),
160 }
161 }
162}
163
164impl fmt::Display for ShutdownError {
165 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166 formatter.write_str(&self.message)
167 }
168}
169
170impl Error for ShutdownError {}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum ShutdownFailureKind {
174 Error,
175 Timeout,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub struct ShutdownFailure {
180 pub service: String,
181 pub kind: ShutdownFailureKind,
182 pub message: String,
183}
184
185impl fmt::Display for ShutdownFailure {
186 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(formatter, "{}: {}", self.service, self.message)
188 }
189}
190
191#[derive(Clone, Debug, Default, PartialEq, Eq)]
192pub struct ShutdownReport {
193 pub attempted: Vec<String>,
194 pub failures: Vec<ShutdownFailure>,
195}
196
197impl ShutdownReport {
198 #[must_use]
199 pub fn is_success(&self) -> bool {
200 self.failures.is_empty()
201 }
202}
203
204impl fmt::Display for ShutdownReport {
205 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
206 if self.failures.is_empty() {
207 formatter.write_str("shutdown completed")
208 } else {
209 write!(
210 formatter,
211 "shutdown failed: {}",
212 self.failures
213 .iter()
214 .map(ToString::to_string)
215 .collect::<Vec<_>>()
216 .join(", ")
217 )
218 }
219 }
220}
221
222#[async_trait]
223pub trait ServiceHandle: Send {
224 fn service(&self) -> &'static str;
225 async fn shutdown(self: Box<Self>) -> Result<(), ShutdownError>;
226}
227
228#[derive(Default)]
229pub struct ServiceHandles {
230 handles: Vec<Box<dyn ServiceHandle>>,
231}
232
233impl ServiceHandles {
234 #[must_use]
235 pub fn new() -> Self {
236 Self::default()
237 }
238
239 pub fn push(&mut self, handle: impl ServiceHandle + 'static) {
240 self.handles.push(Box::new(handle));
241 }
242
243 pub fn push_boxed(&mut self, handle: Box<dyn ServiceHandle>) {
244 self.handles.push(handle);
245 }
246
247 #[must_use]
248 pub fn len(&self) -> usize {
249 self.handles.len()
250 }
251
252 #[must_use]
253 pub fn is_empty(&self) -> bool {
254 self.handles.is_empty()
255 }
256
257 pub async fn shutdown_reverse(&mut self) -> ShutdownReport {
258 self.shutdown_reverse_with_timeout(DEFAULT_SERVICE_SHUTDOWN_TIMEOUT)
259 .await
260 }
261
262 pub async fn shutdown_reverse_with_timeout(&mut self, timeout: Duration) -> ShutdownReport {
263 let mut report = ShutdownReport {
264 attempted: Vec::with_capacity(self.handles.len()),
265 failures: Vec::new(),
266 };
267 while let Some(handle) = self.handles.pop() {
268 let service = handle.service().to_owned();
269 report.attempted.push(service.clone());
270 match tokio::time::timeout(timeout, handle.shutdown()).await {
271 Ok(Ok(())) => {}
272 Ok(Err(error)) => report.failures.push(ShutdownFailure {
273 service,
274 kind: ShutdownFailureKind::Error,
275 message: error.to_string(),
276 }),
277 Err(_) => report.failures.push(ShutdownFailure {
278 service,
279 kind: ShutdownFailureKind::Timeout,
280 message: format!("did not stop within {} ms", timeout.as_millis()),
281 }),
282 }
283 }
284 report
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::{
291 RUNTIME_API_VERSION, ServiceHandle, ServiceHandles, ShutdownError, ShutdownFailureKind,
292 supports_runtime_api,
293 };
294 use async_trait::async_trait;
295 use std::sync::{Arc, Mutex};
296
297 struct RecordingHandle {
298 service: &'static str,
299 stopped: Arc<Mutex<Vec<&'static str>>>,
300 }
301
302 #[async_trait]
303 impl ServiceHandle for RecordingHandle {
304 fn service(&self) -> &'static str {
305 self.service
306 }
307
308 async fn shutdown(self: Box<Self>) -> Result<(), ShutdownError> {
309 self.stopped.lock().unwrap().push(self.service);
310 Ok(())
311 }
312 }
313
314 #[tokio::test]
315 async fn stops_services_in_reverse_startup_order() {
316 let stopped = Arc::new(Mutex::new(Vec::new()));
317 let mut handles = ServiceHandles::new();
318 for service in ["auth", "jobs", "web"] {
319 handles.push(RecordingHandle {
320 service,
321 stopped: Arc::clone(&stopped),
322 });
323 }
324 let report = handles.shutdown_reverse().await;
325 assert_eq!(report.attempted, ["web", "jobs", "auth"]);
326 assert!(report.is_success());
327 assert_eq!(*stopped.lock().unwrap(), ["web", "jobs", "auth"]);
328 assert!(handles.is_empty());
329 }
330
331 struct FailingHandle {
332 service: &'static str,
333 hangs: bool,
334 }
335
336 #[async_trait]
337 impl ServiceHandle for FailingHandle {
338 fn service(&self) -> &'static str {
339 self.service
340 }
341
342 async fn shutdown(self: Box<Self>) -> Result<(), ShutdownError> {
343 if self.hangs {
344 std::future::pending().await
345 } else {
346 Err(ShutdownError::new("injected shutdown error"))
347 }
348 }
349 }
350
351 #[tokio::test]
352 async fn reports_shutdown_errors_and_timeouts_without_skipping_services() {
353 let mut handles = ServiceHandles::new();
354 handles.push(FailingHandle {
355 service: "failure",
356 hangs: false,
357 });
358 handles.push(FailingHandle {
359 service: "timeout",
360 hangs: true,
361 });
362
363 let report = handles
364 .shutdown_reverse_with_timeout(std::time::Duration::from_millis(1))
365 .await;
366 assert_eq!(report.attempted, ["timeout", "failure"]);
367 assert_eq!(report.failures.len(), 2);
368 assert_eq!(report.failures[0].kind, ShutdownFailureKind::Timeout);
369 assert_eq!(report.failures[1].kind, ShutdownFailureKind::Error);
370 }
371
372 #[test]
373 fn runtime_api_compatibility_is_explicit() {
374 assert!(supports_runtime_api(RUNTIME_API_VERSION));
375 assert!(!supports_runtime_api(RUNTIME_API_VERSION + 1));
376 }
377}