Skip to main content

lenso_kernel/
lifecycle.rs

1use super::{
2    AbortHandle, AssertUnwindSafe, Cell, Context, DriverControl, DriverTask, Duration, Future,
3    FutureExt, LocalBoxFuture, LocalTask, ModuleDependencies, ModuleLifecyclePhase, Pin, Poll, Rc,
4    RefCell, RuntimeDriver, RuntimeFailure, SpawnError, TaskOutcome, oneshot, wait_until,
5};
6
7/// A shared App-wide signal that opens exactly once after every Module activates.
8#[derive(Clone, Debug)]
9pub struct AppReadyGate {
10    pub(super) state: Rc<AppReadyState>,
11}
12
13#[derive(Debug)]
14pub(super) struct AppReadyState {
15    pub(super) open: Cell<bool>,
16    pub(super) waiters: RefCell<Vec<oneshot::Sender<()>>>,
17}
18
19impl AppReadyGate {
20    /// Creates a closed App Ready Gate.
21    pub fn new() -> Self {
22        Self {
23            state: Rc::new(AppReadyState {
24                open: Cell::new(false),
25                waiters: RefCell::new(Vec::new()),
26            }),
27        }
28    }
29
30    /// Returns whether the App Ready Gate has opened.
31    pub fn is_open(&self) -> bool {
32        self.state.open.get()
33    }
34
35    /// Waits until the whole App has completed activation.
36    pub fn wait(&self) -> LocalBoxFuture<'static, ()> {
37        if self.is_open() {
38            return Box::pin(futures::future::ready(()));
39        }
40
41        let (wakeup, waiter) = oneshot::channel();
42        self.state.waiters.borrow_mut().push(wakeup);
43        Box::pin(async move {
44            let _ = waiter.await;
45        })
46    }
47
48    pub(super) fn open(&self) {
49        if self.state.open.replace(true) {
50            return;
51        }
52        for waiter in self.state.waiters.borrow_mut().drain(..) {
53            let _ = waiter.send(());
54        }
55    }
56}
57
58impl Default for AppReadyGate {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64/// App-wide admission for externally triggered work.
65#[derive(Clone, Debug)]
66pub struct AppAdmission {
67    pub(super) state: Rc<AppAdmissionState>,
68}
69
70#[derive(Debug)]
71pub(super) struct AppAdmissionState {
72    pub(super) open: Cell<bool>,
73}
74
75impl AppAdmission {
76    pub(super) fn new() -> Self {
77        Self {
78            state: Rc::new(AppAdmissionState {
79                open: Cell::new(false),
80            }),
81        }
82    }
83
84    /// Returns whether new externally triggered work may be admitted.
85    pub fn is_open(&self) -> bool {
86        self.state.open.get()
87    }
88
89    /// Returns whether new externally triggered work is rejected.
90    pub fn is_closed(&self) -> bool {
91        !self.is_open()
92    }
93
94    pub(super) fn open(&self) {
95        self.state.open.set(true);
96    }
97
98    pub(super) fn close(&self) {
99        self.state.open.set(false);
100    }
101}
102
103/// Cooperative cancellation shared by one Module Instance generation.
104#[derive(Clone, Debug)]
105pub struct CancellationToken {
106    pub(super) state: Rc<CancellationState>,
107}
108
109#[derive(Debug)]
110pub(super) struct CancellationState {
111    pub(super) cancelled: Cell<bool>,
112    pub(super) next_waiter_id: Cell<usize>,
113    pub(super) waiters: RefCell<Vec<(usize, oneshot::Sender<()>)>>,
114}
115
116impl CancellationToken {
117    /// Creates a token that has not been cancelled.
118    pub fn new() -> Self {
119        Self {
120            state: Rc::new(CancellationState {
121                cancelled: Cell::new(false),
122                next_waiter_id: Cell::new(0),
123                waiters: RefCell::new(Vec::new()),
124            }),
125        }
126    }
127
128    /// Returns whether cancellation has been requested.
129    pub fn is_cancelled(&self) -> bool {
130        self.state.cancelled.get()
131    }
132
133    /// Waits until cancellation is requested.
134    pub fn cancelled(&self) -> LocalBoxFuture<'static, ()> {
135        if self.is_cancelled() {
136            return Box::pin(futures::future::ready(()));
137        }
138        let (wakeup, waiter) = oneshot::channel();
139        let waiter_id = self.state.next_waiter_id.get();
140        self.state.next_waiter_id.set(waiter_id.saturating_add(1));
141        self.state.waiters.borrow_mut().push((waiter_id, wakeup));
142        Box::pin(CancellationWaiter {
143            state: self.state.clone(),
144            waiter_id,
145            receiver: waiter,
146            registered: true,
147        })
148    }
149
150    /// Requests cooperative cancellation and wakes every current waiter.
151    pub fn cancel(&self) {
152        if self.state.cancelled.replace(true) {
153            return;
154        }
155        for (_, waiter) in self.state.waiters.borrow_mut().drain(..) {
156            let _ = waiter.send(());
157        }
158    }
159}
160
161#[derive(Debug)]
162pub(super) struct CancellationWaiter {
163    pub(super) state: Rc<CancellationState>,
164    pub(super) waiter_id: usize,
165    pub(super) receiver: oneshot::Receiver<()>,
166    pub(super) registered: bool,
167}
168
169impl Future for CancellationWaiter {
170    type Output = ();
171
172    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
173        match Pin::new(&mut self.receiver).poll(context) {
174            Poll::Ready(_) => {
175                self.registered = false;
176                Poll::Ready(())
177            }
178            Poll::Pending => Poll::Pending,
179        }
180    }
181}
182
183impl Drop for CancellationWaiter {
184    fn drop(&mut self) {
185        if !self.registered {
186            return;
187        }
188        self.state
189            .waiters
190            .borrow_mut()
191            .retain(|(waiter_id, _)| *waiter_id != self.waiter_id);
192    }
193}
194
195impl Default for CancellationToken {
196    fn default() -> Self {
197        Self::new()
198    }
199}
200
201/// A future used to release one Driver-backed managed resource.
202pub type ResourceFuture = LocalBoxFuture<'static, Result<(), RuntimeFailure>>;
203
204/// A resource whose release is owned by one Module Instance generation.
205pub trait ManagedResource: std::fmt::Debug + 'static {
206    /// Releases the resource exactly once when its generation is cleaned up.
207    fn release(&self) -> ResourceFuture;
208}
209
210/// Error returned when a resource cannot be registered in a closed scope.
211#[derive(Clone, Copy, Debug, Eq, PartialEq)]
212pub enum ResourceRegistrationError {
213    /// The Module generation has begun shutdown or rollback cleanup.
214    ScopeClosed,
215}
216
217pub(super) struct ManagedResourceEntry {
218    pub(super) resource: Rc<dyn ManagedResource>,
219    pub(super) release: RefCell<ManagedResourceRelease>,
220}
221
222pub(super) enum ManagedResourceRelease {
223    Pending,
224    Running(ResourceFuture),
225    Complete(Result<(), RuntimeFailure>),
226}
227
228impl std::fmt::Debug for ManagedResourceEntry {
229    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        let state = match &*self.release.borrow() {
231            ManagedResourceRelease::Pending => "pending",
232            ManagedResourceRelease::Running(_) => "running",
233            ManagedResourceRelease::Complete(Ok(())) => "released",
234            ManagedResourceRelease::Complete(Err(_)) => "failed",
235        };
236        formatter
237            .debug_struct("ManagedResourceEntry")
238            .field("release", &state)
239            .finish_non_exhaustive()
240    }
241}
242
243/// A handle that releases one managed resource at most once.
244#[derive(Clone, Debug)]
245pub struct ManagedResourceHandle {
246    pub(super) entry: Rc<ManagedResourceEntry>,
247}
248
249impl ManagedResourceHandle {
250    /// Returns whether this resource's release future completed.
251    pub fn is_released(&self) -> bool {
252        matches!(
253            &*self.entry.release.borrow(),
254            ManagedResourceRelease::Complete(_)
255        )
256    }
257
258    /// Releases this resource once; repeated calls are successful no-ops.
259    pub async fn release(&self) -> Result<(), RuntimeFailure> {
260        ManagedResourceReleaseOperation {
261            entry: self.entry.clone(),
262        }
263        .await
264    }
265}
266
267pub(super) struct ManagedResourceReleaseOperation {
268    pub(super) entry: Rc<ManagedResourceEntry>,
269}
270
271impl Future for ManagedResourceReleaseOperation {
272    type Output = Result<(), RuntimeFailure>;
273
274    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
275        let mut release = self.entry.release.borrow_mut();
276        if matches!(*release, ManagedResourceRelease::Pending) {
277            *release = ManagedResourceRelease::Running(self.entry.resource.release());
278        }
279        match &mut *release {
280            ManagedResourceRelease::Running(future) => match future.as_mut().poll(context) {
281                Poll::Ready(result) => {
282                    *release = ManagedResourceRelease::Complete(result.clone());
283                    Poll::Ready(result)
284                }
285                Poll::Pending => Poll::Pending,
286            },
287            ManagedResourceRelease::Complete(result) => Poll::Ready(result.clone()),
288            ManagedResourceRelease::Pending => unreachable!("pending release was started"),
289        }
290    }
291}
292
293/// A Module-generation resource scope backed by Driver-polled cleanup futures.
294#[derive(Clone)]
295pub struct ManagedResourceScope {
296    pub(super) state: Rc<ManagedResourceScopeState>,
297}
298
299#[derive(Debug, Default)]
300pub(super) struct ManagedResourceScopeState {
301    pub(super) resources: RefCell<Vec<ManagedResourceHandle>>,
302    pub(super) closed: Cell<bool>,
303}
304
305impl std::fmt::Debug for ManagedResourceScope {
306    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        formatter
308            .debug_struct("ManagedResourceScope")
309            .field("resource_count", &self.resource_count())
310            .finish()
311    }
312}
313
314impl ManagedResourceScope {
315    pub(super) fn new() -> Self {
316        Self {
317            state: Rc::new(ManagedResourceScopeState::default()),
318        }
319    }
320
321    /// Registers a resource owned by this Module Instance generation.
322    pub fn register(
323        &self,
324        resource: impl ManagedResource,
325    ) -> Result<ManagedResourceHandle, ResourceRegistrationError> {
326        if self.state.closed.get() {
327            return Err(ResourceRegistrationError::ScopeClosed);
328        }
329        let handle = ManagedResourceHandle {
330            entry: Rc::new(ManagedResourceEntry {
331                resource: Rc::new(resource),
332                release: RefCell::new(ManagedResourceRelease::Pending),
333            }),
334        };
335        self.state.resources.borrow_mut().push(handle.clone());
336        Ok(handle)
337    }
338
339    /// Returns the number of resources that still need cleanup.
340    pub fn resource_count(&self) -> usize {
341        self.state
342            .resources
343            .borrow()
344            .iter()
345            .filter(|resource| !resource.is_released())
346            .count()
347    }
348
349    pub(super) fn close(&self) {
350        self.state.closed.set(true);
351    }
352
353    pub(super) async fn release_all(&self) -> Option<RuntimeFailure> {
354        let resources = std::mem::take(&mut *self.state.resources.borrow_mut());
355        let mut first_error = None;
356        for resource in resources {
357            if let Err(error) = resource.release().await
358                && first_error.is_none()
359            {
360                first_error = Some(error);
361            }
362        }
363        first_error
364    }
365
366    pub(super) async fn release_all_until(
367        &self,
368        driver: &DriverControl,
369        deadline: Duration,
370    ) -> Result<Option<RuntimeFailure>, ()> {
371        let resources = std::mem::take(&mut *self.state.resources.borrow_mut());
372        let mut first_error = None;
373        for (index, resource) in resources.iter().enumerate() {
374            match wait_until(driver, deadline, resource.release()).await {
375                Some(Ok(())) => {}
376                Some(Err(error)) => {
377                    if first_error.is_none() {
378                        first_error = Some(error);
379                    }
380                }
381                None => {
382                    self.state
383                        .resources
384                        .borrow_mut()
385                        .extend(resources.into_iter().skip(index));
386                    return Err(());
387                }
388            }
389        }
390        Ok(first_error)
391    }
392}
393
394/// A Kernel-owned task handle that is cleaned up with its Module generation.
395#[derive(Clone, Debug)]
396pub struct ManagedTask {
397    pub(super) task: Rc<RefCell<Option<DriverTask>>>,
398    pub(super) abort: AbortHandle,
399    pub(super) failed: Rc<Cell<bool>>,
400}
401
402impl ManagedTask {
403    pub(super) fn from_driver_task(task: DriverTask) -> Self {
404        Self {
405            abort: task.abort_handle(),
406            task: Rc::new(RefCell::new(Some(task))),
407            failed: Rc::new(Cell::new(false)),
408        }
409    }
410
411    /// Requests cancellation of the underlying task.
412    pub fn cancel(&self) {
413        self.abort.abort();
414    }
415
416    pub(super) async fn join(&self) -> TaskOutcome {
417        let task = self.task.borrow_mut().take();
418        if let Some(task) = task {
419            let outcome = task.await;
420            if self.failed.get() {
421                TaskOutcome::Failed
422            } else {
423                outcome
424            }
425        } else if self.failed.get() {
426            TaskOutcome::Failed
427        } else {
428            TaskOutcome::Completed
429        }
430    }
431}
432
433/// Error returned when a managed task cannot be admitted to its scope.
434#[derive(Debug)]
435pub enum ManagedTaskError {
436    /// The Module generation has begun shutdown or rollback cleanup.
437    ScopeClosed,
438    /// The Runtime Driver rejected the local task.
439    Driver(SpawnError),
440}
441
442impl From<SpawnError> for ManagedTaskError {
443    fn from(error: SpawnError) -> Self {
444        Self::Driver(error)
445    }
446}
447
448/// A Module-generation task scope backed by the selected Runtime Driver.
449#[derive(Clone)]
450pub struct ManagedTaskScope {
451    pub(super) spawn: Rc<dyn Fn(LocalTask) -> Result<DriverTask, SpawnError>>,
452    pub(super) state: Rc<ManagedTaskScopeState>,
453}
454
455pub(super) struct ManagedTaskScopeState {
456    pub(super) tasks: RefCell<Vec<ManagedTask>>,
457    pub(super) closed: Cell<bool>,
458    pub(super) cancellation: CancellationToken,
459    pub(super) failure_handler: RefCell<Option<Rc<dyn Fn()>>>,
460    pub(super) unreported_failure: Cell<bool>,
461}
462
463impl Default for ManagedTaskScopeState {
464    fn default() -> Self {
465        Self {
466            tasks: RefCell::new(Vec::new()),
467            closed: Cell::new(false),
468            cancellation: CancellationToken::new(),
469            failure_handler: RefCell::new(None),
470            unreported_failure: Cell::new(false),
471        }
472    }
473}
474
475impl std::fmt::Debug for ManagedTaskScopeState {
476    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477        formatter
478            .debug_struct("ManagedTaskScopeState")
479            .field("task_count", &self.tasks.borrow().len())
480            .field("closed", &self.closed.get())
481            .field("unreported_failure", &self.unreported_failure.get())
482            .finish_non_exhaustive()
483    }
484}
485
486impl std::fmt::Debug for ManagedTaskScope {
487    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
488        formatter
489            .debug_struct("ManagedTaskScope")
490            .field("task_count", &self.task_count())
491            .finish()
492    }
493}
494
495impl ManagedTaskScope {
496    pub(super) fn new<D: RuntimeDriver>(driver: &D) -> Self {
497        let spawner = driver.clone();
498        Self {
499            spawn: Rc::new(move |task| spawner.spawn_local(task)),
500            state: Rc::new(ManagedTaskScopeState::default()),
501        }
502    }
503
504    pub(super) fn new_from_driver_control(driver: &DriverControl) -> Self {
505        let spawn = driver.spawn_local.clone();
506        Self {
507            spawn,
508            state: Rc::new(ManagedTaskScopeState::default()),
509        }
510    }
511
512    /// Spawns work owned by this Module Instance generation.
513    pub fn spawn_local(&self, task: LocalTask) -> Result<ManagedTask, ManagedTaskError> {
514        if self.state.closed.get() {
515            return Err(ManagedTaskError::ScopeClosed);
516        }
517        let failed = Rc::new(Cell::new(false));
518        let task_failed = failed.clone();
519        let state = self.state.clone();
520        let monitored = Box::pin(async move {
521            if AssertUnwindSafe(task).catch_unwind().await.is_err() {
522                task_failed.set(true);
523                state.report_failure();
524            }
525        });
526        let driver_task = (self.spawn)(monitored)?;
527        let handle = ManagedTask {
528            failed,
529            ..ManagedTask::from_driver_task(driver_task)
530        };
531        self.state.tasks.borrow_mut().push(handle.clone());
532        Ok(handle)
533    }
534
535    /// Returns the number of tasks still tracked by this scope.
536    pub fn task_count(&self) -> usize {
537        self.state.tasks.borrow().len()
538    }
539
540    /// Returns the cooperative cancellation token for this generation.
541    pub fn cancellation(&self) -> CancellationToken {
542        self.state.cancellation.clone()
543    }
544
545    pub(super) fn close(&self) {
546        self.state.closed.set(true);
547        self.state.cancellation.cancel();
548    }
549
550    pub(super) fn set_failure_handler(&self, handler: &Rc<dyn Fn()>) {
551        self.state.failure_handler.replace(Some(handler.clone()));
552        if self.state.unreported_failure.replace(false) {
553            handler();
554        }
555    }
556
557    pub(super) fn cancel(&self) {
558        self.state.cancellation.cancel();
559    }
560
561    pub(super) fn abort_all(&self) {
562        for task in self.state.tasks.borrow().iter() {
563            task.cancel();
564        }
565    }
566
567    pub(super) async fn cancel_all(&self) {
568        self.close();
569        let tasks = std::mem::take(&mut *self.state.tasks.borrow_mut());
570        for task in tasks {
571            task.cancel();
572            let _ = task.join().await;
573        }
574    }
575
576    pub(super) async fn drain_until(&self, driver: &DriverControl, deadline: Duration) -> bool {
577        self.cancel();
578        let tasks = std::mem::take(&mut *self.state.tasks.borrow_mut());
579        for (index, task) in tasks.iter().enumerate() {
580            if wait_until(driver, deadline, task.join()).await.is_none() {
581                for pending in tasks.iter().skip(index) {
582                    pending.cancel();
583                }
584                return false;
585            }
586        }
587        true
588    }
589}
590
591impl ManagedTaskScopeState {
592    pub(super) fn report_failure(&self) {
593        let handler = self.failure_handler.borrow().clone();
594        if let Some(handler) = handler {
595            handler();
596        } else {
597            self.unreported_failure.set(true);
598        }
599    }
600}
601
602/// Context supplied while a Module reserves reversible resources.
603#[derive(Clone, Debug)]
604pub struct PrepareContext {
605    pub(super) instance_key: String,
606    pub(super) entrypoint: String,
607    pub(super) configuration: String,
608    pub(super) dependencies: ModuleDependencies,
609    pub(super) resources: ManagedResourceScope,
610    pub(super) cancellation: CancellationToken,
611    pub(super) admission: AppAdmission,
612}
613
614impl PrepareContext {
615    /// Returns the App-local Module Instance key.
616    pub fn instance_key(&self) -> &str {
617        &self.instance_key
618    }
619
620    /// Returns the exact package entrypoint selected by the immutable Plan.
621    pub fn entrypoint(&self) -> &str {
622        &self.entrypoint
623    }
624
625    /// Returns opaque Module-owned configuration selected by the immutable Plan.
626    pub fn configuration(&self) -> &str {
627        &self.configuration
628    }
629
630    /// Returns the phase represented by this context.
631    pub const fn phase(&self) -> ModuleLifecyclePhase {
632        ModuleLifecyclePhase::Prepare
633    }
634
635    /// Returns the explicit dependencies selected for this Instance.
636    pub fn dependencies(&self) -> &ModuleDependencies {
637        &self.dependencies
638    }
639
640    /// Returns the generation-owned resource scope.
641    pub fn resources(&self) -> &ManagedResourceScope {
642        &self.resources
643    }
644
645    /// Returns the generation-owned cooperative cancellation token.
646    pub fn cancellation(&self) -> CancellationToken {
647        self.cancellation.clone()
648    }
649
650    /// Returns the App admission state, which remains closed until readiness.
651    pub fn admission(&self) -> AppAdmission {
652        self.admission.clone()
653    }
654}
655
656/// Context supplied while a Module initializes against prepared dependencies.
657#[derive(Clone, Debug)]
658pub struct ActivateContext {
659    pub(super) instance_key: String,
660    pub(super) dependencies: ModuleDependencies,
661    pub(super) ready_gate: AppReadyGate,
662    pub(super) tasks: ManagedTaskScope,
663    pub(super) resources: ManagedResourceScope,
664    pub(super) cancellation: CancellationToken,
665    pub(super) admission: AppAdmission,
666}
667
668impl ActivateContext {
669    /// Returns the App-local Module Instance key.
670    pub fn instance_key(&self) -> &str {
671        &self.instance_key
672    }
673
674    /// Returns the phase represented by this context.
675    pub const fn phase(&self) -> ModuleLifecyclePhase {
676        ModuleLifecyclePhase::Activate
677    }
678
679    /// Returns the explicit dependencies selected for this Instance.
680    pub fn dependencies(&self) -> &ModuleDependencies {
681        &self.dependencies
682    }
683
684    /// Returns the closed-until-fully-active App Ready Gate.
685    pub fn ready_gate(&self) -> AppReadyGate {
686        self.ready_gate.clone()
687    }
688
689    /// Returns the readiness context a Module may pass to managed work.
690    pub fn readiness(&self) -> ReadinessContext {
691        ReadinessContext {
692            instance_key: self.instance_key.clone(),
693            dependencies: self.dependencies.clone(),
694            ready_gate: self.ready_gate.clone(),
695            tasks: self.tasks.clone(),
696            resources: self.resources.clone(),
697            cancellation: self.cancellation.clone(),
698            admission: self.admission.clone(),
699        }
700    }
701
702    /// Returns the generation-owned task scope.
703    pub fn tasks(&self) -> &ManagedTaskScope {
704        &self.tasks
705    }
706
707    /// Returns the generation-owned resource scope.
708    pub fn resources(&self) -> &ManagedResourceScope {
709        &self.resources
710    }
711
712    /// Returns the generation-owned cooperative cancellation token.
713    pub fn cancellation(&self) -> CancellationToken {
714        self.cancellation.clone()
715    }
716
717    /// Returns the App admission state, which remains closed until readiness.
718    pub fn admission(&self) -> AppAdmission {
719        self.admission.clone()
720    }
721}
722
723/// Context supplied after the App Ready Gate has opened.
724#[derive(Clone, Debug)]
725pub struct ReadinessContext {
726    pub(super) instance_key: String,
727    pub(super) dependencies: ModuleDependencies,
728    pub(super) ready_gate: AppReadyGate,
729    pub(super) tasks: ManagedTaskScope,
730    pub(super) resources: ManagedResourceScope,
731    pub(super) cancellation: CancellationToken,
732    pub(super) admission: AppAdmission,
733}
734
735impl ReadinessContext {
736    /// Returns the App-local Module Instance key.
737    pub fn instance_key(&self) -> &str {
738        &self.instance_key
739    }
740
741    /// Returns the phase represented by this context.
742    pub const fn phase(&self) -> ModuleLifecyclePhase {
743        ModuleLifecyclePhase::Ready
744    }
745
746    /// Returns the explicit dependencies selected for this Instance.
747    pub fn dependencies(&self) -> &ModuleDependencies {
748        &self.dependencies
749    }
750
751    /// Returns the opened App Ready Gate.
752    pub fn ready_gate(&self) -> AppReadyGate {
753        self.ready_gate.clone()
754    }
755
756    /// Waits for the App Ready Gate to open.
757    pub fn wait(&self) -> LocalBoxFuture<'static, ()> {
758        self.ready_gate.wait()
759    }
760
761    /// Returns whether the App Ready Gate has opened.
762    pub fn is_open(&self) -> bool {
763        self.ready_gate.is_open()
764    }
765
766    /// Returns the generation-owned task scope.
767    pub fn tasks(&self) -> &ManagedTaskScope {
768        &self.tasks
769    }
770
771    /// Returns the generation-owned resource scope.
772    pub fn resources(&self) -> &ManagedResourceScope {
773        &self.resources
774    }
775
776    /// Returns the generation-owned cooperative cancellation token.
777    pub fn cancellation(&self) -> CancellationToken {
778        self.cancellation.clone()
779    }
780
781    /// Returns whether new externally triggered work may be admitted.
782    pub fn is_accepting(&self) -> bool {
783        self.admission.is_open()
784    }
785
786    /// Returns the App admission state.
787    pub fn admission(&self) -> AppAdmission {
788        self.admission.clone()
789    }
790}
791
792/// The reason a Module generation is being deactivated.
793#[derive(Clone, Copy, Debug, Eq, PartialEq)]
794pub enum DeactivationReason {
795    /// Startup failed and prepared work is being rolled back.
796    StartupRollback,
797    /// The embedding App requested a graceful stop.
798    Shutdown,
799    /// Supervision is releasing a failed generation before recreation.
800    SupervisionRestart,
801}
802
803/// Context supplied while a Module releases one generation.
804#[derive(Clone, Debug)]
805pub struct DeactivateContext {
806    pub(super) instance_key: String,
807    pub(super) dependencies: ModuleDependencies,
808    pub(super) reason: DeactivationReason,
809    pub(super) tasks: ManagedTaskScope,
810    pub(super) resources: ManagedResourceScope,
811    pub(super) cancellation: CancellationToken,
812    pub(super) admission: AppAdmission,
813}
814
815impl DeactivateContext {
816    /// Returns the App-local Module Instance key.
817    pub fn instance_key(&self) -> &str {
818        &self.instance_key
819    }
820
821    /// Returns the phase represented by this context.
822    pub const fn phase(&self) -> ModuleLifecyclePhase {
823        ModuleLifecyclePhase::Deactivate
824    }
825
826    /// Returns the explicit dependencies selected for this Instance.
827    pub fn dependencies(&self) -> &ModuleDependencies {
828        &self.dependencies
829    }
830
831    /// Returns why this generation is being deactivated.
832    pub const fn reason(&self) -> DeactivationReason {
833        self.reason
834    }
835
836    /// Returns the generation-owned task scope.
837    pub fn tasks(&self) -> &ManagedTaskScope {
838        &self.tasks
839    }
840
841    /// Returns the generation-owned resource scope.
842    pub fn resources(&self) -> &ManagedResourceScope {
843        &self.resources
844    }
845
846    /// Returns the generation-owned cooperative cancellation token.
847    pub fn cancellation(&self) -> CancellationToken {
848        self.cancellation.clone()
849    }
850
851    /// Returns the App admission state, which is closed during deactivation.
852    pub fn admission(&self) -> AppAdmission {
853        self.admission.clone()
854    }
855}
856
857/// The result type returned by prepare, activate, and deactivate hooks.
858pub type ModuleFuture = LocalBoxFuture<'static, Result<(), RuntimeFailure>>;
859
860/// Adapter-facing lifecycle Interface for one Module Instance generation.
861pub trait ModuleLifecycle: std::fmt::Debug + 'static {
862    /// Reserves reversible resources without exposing external work.
863    fn prepare(&self, _context: PrepareContext) -> ModuleFuture {
864        Box::pin(futures::future::ready(Ok(())))
865    }
866
867    /// Initializes the generation against already prepared dependencies.
868    fn activate(&self, _context: ActivateContext) -> ModuleFuture {
869        Box::pin(futures::future::ready(Ok(())))
870    }
871
872    /// Releases resources and work owned by this generation.
873    fn deactivate(&self, _context: DeactivateContext) -> ModuleFuture {
874        Box::pin(futures::future::ready(Ok(())))
875    }
876}
877
878/// Default no-op lifecycle used by endpoint-only native fixtures.
879#[derive(Debug, Default)]
880pub struct NoopModuleLifecycle;
881
882impl ModuleLifecycle for NoopModuleLifecycle {}