Skip to main content

appstruct_runtime/
lib.rs

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