1use crate::{ServiceHandle, ServiceHandles, ShutdownReport, StartupError};
2use async_trait::async_trait;
3use std::collections::{BTreeMap, BTreeSet};
4use std::sync::Arc;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum ModulePhase {
8 Starting,
9 Started,
10 Failed,
11 Stopping,
12 Stopped,
13 StopFailed,
14 RollingBack,
15 RolledBack,
16 RollbackFailed,
17}
18
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct ModuleEvent {
21 pub module: String,
22 pub phase: ModulePhase,
23 pub detail: Option<String>,
24}
25
26pub trait ModuleObserver: Send + Sync {
27 fn observe(&self, event: &ModuleEvent);
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct ModuleDescriptor {
32 pub name: &'static str,
33 pub dependencies: &'static [&'static str],
34}
35
36impl ModuleDescriptor {
37 #[must_use]
38 pub const fn new(name: &'static str, dependencies: &'static [&'static str]) -> Self {
39 Self { name, dependencies }
40 }
41}
42
43#[async_trait]
44pub trait ModuleStarter<Context>: Send {
45 fn descriptor(&self) -> ModuleDescriptor;
46
47 async fn start(
48 self: Box<Self>,
49 context: &mut Context,
50 ) -> Result<Option<Box<dyn ServiceHandle>>, StartupError>;
51}
52
53pub struct ModulePlan<Context> {
54 starters: Vec<Box<dyn ModuleStarter<Context>>>,
55 observer: Option<Arc<dyn ModuleObserver>>,
56}
57
58impl<Context> Default for ModulePlan<Context> {
59 fn default() -> Self {
60 Self {
61 starters: Vec::new(),
62 observer: None,
63 }
64 }
65}
66
67impl<Context: Send> ModulePlan<Context> {
68 #[must_use]
69 pub fn new() -> Self {
70 Self::default()
71 }
72
73 pub fn push(&mut self, starter: impl ModuleStarter<Context> + 'static) {
74 self.starters.push(Box::new(starter));
75 }
76
77 #[must_use]
78 pub fn with_observer(mut self, observer: impl ModuleObserver + 'static) -> Self {
79 self.observer = Some(Arc::new(observer));
80 self
81 }
82
83 pub async fn start(self, context: &mut Context) -> Result<ModuleRuntime, StartupError> {
88 let mut runtime = ModuleRuntime::with_observer(self.observer);
89 let mut descriptors = BTreeMap::new();
90 for starter in self.starters {
91 let descriptor = starter.descriptor();
92 runtime.notify(descriptor.name, ModulePhase::Starting, None);
93 if runtime.contains(descriptor.name) {
94 let error = StartupError::configuration(
95 descriptor.name,
96 "module appears more than once in the runtime plan",
97 );
98 runtime.notify(
99 descriptor.name,
100 ModulePhase::Failed,
101 Some(error.to_string()),
102 );
103 return Err(rollback(error, descriptor.name, &descriptors, &mut runtime).await);
104 }
105 descriptors.insert(descriptor.name, descriptor.dependencies);
106 if let Some(dependency) = descriptor
107 .dependencies
108 .iter()
109 .find(|dependency| !runtime.contains(dependency))
110 {
111 let error = StartupError::dependency(descriptor.name, dependency);
112 runtime.notify(
113 descriptor.name,
114 ModulePhase::Failed,
115 Some(error.to_string()),
116 );
117 return Err(rollback(error, descriptor.name, &descriptors, &mut runtime).await);
118 }
119 match starter.start(context).await {
120 Ok(handle) => {
121 runtime.record_started(descriptor.name, handle);
122 runtime.notify(descriptor.name, ModulePhase::Started, None);
123 }
124 Err(error) => {
125 runtime.notify(
126 descriptor.name,
127 ModulePhase::Failed,
128 Some(error.to_string()),
129 );
130 return Err(rollback(error, descriptor.name, &descriptors, &mut runtime).await);
131 }
132 }
133 }
134 Ok(runtime)
135 }
136}
137
138pub struct ModuleRuntime {
139 started: Vec<String>,
140 handles: ServiceHandles,
141 observer: Option<Arc<dyn ModuleObserver>>,
142}
143
144impl Default for ModuleRuntime {
145 fn default() -> Self {
146 Self::with_observer(None)
147 }
148}
149
150impl ModuleRuntime {
151 #[must_use]
152 pub fn started(&self) -> &[String] {
153 &self.started
154 }
155
156 #[must_use]
157 pub fn is_empty(&self) -> bool {
158 self.started.is_empty()
159 }
160
161 pub fn push_service(
162 &mut self,
163 module: impl Into<String>,
164 handle: impl ServiceHandle + 'static,
165 ) {
166 self.started.push(module.into());
167 self.handles.push(handle);
168 }
169
170 pub async fn shutdown_reverse(&mut self) -> ShutdownReport {
171 self.shutdown_with_phases(
172 ModulePhase::Stopping,
173 ModulePhase::Stopped,
174 ModulePhase::StopFailed,
175 )
176 .await
177 }
178
179 pub async fn rollback_reverse(&mut self) -> ShutdownReport {
180 self.shutdown_with_phases(
181 ModulePhase::RollingBack,
182 ModulePhase::RolledBack,
183 ModulePhase::RollbackFailed,
184 )
185 .await
186 }
187
188 async fn shutdown_with_phases(
189 &mut self,
190 before: ModulePhase,
191 after: ModulePhase,
192 failed: ModulePhase,
193 ) -> ShutdownReport {
194 let modules = self.started.iter().rev().cloned().collect::<Vec<_>>();
195 for module in &modules {
196 self.notify(module, before, None);
197 }
198 let mut report = self.handles.shutdown_reverse().await;
199 self.started.clear();
200 for module in &modules {
201 if let Some(failure) = report
202 .failures
203 .iter()
204 .find(|failure| failure.service == *module)
205 {
206 self.notify(module, failed, Some(failure.message.clone()));
207 } else {
208 self.notify(module, after, None);
209 }
210 }
211 report.attempted = modules;
212 report
213 }
214
215 fn contains(&self, module: &str) -> bool {
216 self.started.iter().any(|started| started == module)
217 }
218
219 fn record_started(&mut self, module: &str, handle: Option<Box<dyn ServiceHandle>>) {
220 self.started.push(module.to_owned());
221 if let Some(handle) = handle {
222 self.handles.push_boxed(handle);
223 }
224 }
225
226 fn with_observer(observer: Option<Arc<dyn ModuleObserver>>) -> Self {
227 Self {
228 started: Vec::new(),
229 handles: ServiceHandles::default(),
230 observer,
231 }
232 }
233
234 fn notify(&self, module: &str, phase: ModulePhase, detail: Option<String>) {
235 if let Some(observer) = &self.observer {
236 let event = ModuleEvent {
237 module: module.to_owned(),
238 phase,
239 detail,
240 };
241 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
242 observer.observe(&event);
243 }));
244 }
245 }
246}
247
248impl std::fmt::Debug for ModuleRuntime {
249 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 formatter
251 .debug_struct("ModuleRuntime")
252 .field("started", &self.started)
253 .field("service_handles", &self.handles.len())
254 .field("observed", &self.observer.is_some())
255 .finish()
256 }
257}
258
259async fn rollback(
260 error: StartupError,
261 failed: &str,
262 descriptors: &BTreeMap<&str, &[&str]>,
263 runtime: &mut ModuleRuntime,
264) -> StartupError {
265 let chain = dependency_chain(failed, descriptors);
266 let rollback = runtime.rollback_reverse().await;
267 error.with_runtime_context(chain, rollback)
268}
269
270fn dependency_chain(target: &str, descriptors: &BTreeMap<&str, &[&str]>) -> Vec<String> {
271 fn visit(
272 module: &str,
273 descriptors: &BTreeMap<&str, &[&str]>,
274 visited: &mut BTreeSet<String>,
275 ordered: &mut Vec<String>,
276 ) {
277 if !visited.insert(module.to_owned()) {
278 return;
279 }
280 if let Some(dependencies) = descriptors.get(module) {
281 for dependency in *dependencies {
282 visit(dependency, descriptors, visited, ordered);
283 }
284 }
285 ordered.push(module.to_owned());
286 }
287
288 let mut ordered = Vec::new();
289 visit(target, descriptors, &mut BTreeSet::new(), &mut ordered);
290 ordered
291}
292#[cfg(test)]
293mod tests;