Skip to main content

lenso_kernel/
lifecycle.rs

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