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#[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 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 pub fn is_open(&self) -> bool {
32 self.state.open.get()
33 }
34
35 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#[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 pub fn is_open(&self) -> bool {
86 self.state.open.get()
87 }
88
89 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#[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 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 pub fn is_cancelled(&self) -> bool {
130 self.state.cancelled.get()
131 }
132
133 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 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
201pub type ResourceFuture = LocalBoxFuture<'static, Result<(), RuntimeFailure>>;
203
204pub trait ManagedResource: std::fmt::Debug + 'static {
206 fn release(&self) -> ResourceFuture;
208}
209
210#[derive(Clone, Copy, Debug, Eq, PartialEq)]
212pub enum ResourceRegistrationError {
213 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#[derive(Clone, Debug)]
245pub struct ManagedResourceHandle {
246 pub(super) entry: Rc<ManagedResourceEntry>,
247}
248
249impl ManagedResourceHandle {
250 pub fn is_released(&self) -> bool {
252 matches!(
253 &*self.entry.release.borrow(),
254 ManagedResourceRelease::Complete(_)
255 )
256 }
257
258 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#[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 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 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#[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 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#[derive(Debug)]
435pub enum ManagedTaskError {
436 ScopeClosed,
438 Driver(SpawnError),
440}
441
442impl From<SpawnError> for ManagedTaskError {
443 fn from(error: SpawnError) -> Self {
444 Self::Driver(error)
445 }
446}
447
448#[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 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 pub fn task_count(&self) -> usize {
537 self.state.tasks.borrow().len()
538 }
539
540 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#[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 pub fn instance_key(&self) -> &str {
617 &self.instance_key
618 }
619
620 pub fn entrypoint(&self) -> &str {
622 &self.entrypoint
623 }
624
625 pub fn configuration(&self) -> &str {
627 &self.configuration
628 }
629
630 pub const fn phase(&self) -> ModuleLifecyclePhase {
632 ModuleLifecyclePhase::Prepare
633 }
634
635 pub fn dependencies(&self) -> &ModuleDependencies {
637 &self.dependencies
638 }
639
640 pub fn resources(&self) -> &ManagedResourceScope {
642 &self.resources
643 }
644
645 pub fn cancellation(&self) -> CancellationToken {
647 self.cancellation.clone()
648 }
649
650 pub fn admission(&self) -> AppAdmission {
652 self.admission.clone()
653 }
654}
655
656#[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 pub fn instance_key(&self) -> &str {
671 &self.instance_key
672 }
673
674 pub const fn phase(&self) -> ModuleLifecyclePhase {
676 ModuleLifecyclePhase::Activate
677 }
678
679 pub fn dependencies(&self) -> &ModuleDependencies {
681 &self.dependencies
682 }
683
684 pub fn ready_gate(&self) -> AppReadyGate {
686 self.ready_gate.clone()
687 }
688
689 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 pub fn tasks(&self) -> &ManagedTaskScope {
704 &self.tasks
705 }
706
707 pub fn resources(&self) -> &ManagedResourceScope {
709 &self.resources
710 }
711
712 pub fn cancellation(&self) -> CancellationToken {
714 self.cancellation.clone()
715 }
716
717 pub fn admission(&self) -> AppAdmission {
719 self.admission.clone()
720 }
721}
722
723#[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 pub fn instance_key(&self) -> &str {
738 &self.instance_key
739 }
740
741 pub const fn phase(&self) -> ModuleLifecyclePhase {
743 ModuleLifecyclePhase::Ready
744 }
745
746 pub fn dependencies(&self) -> &ModuleDependencies {
748 &self.dependencies
749 }
750
751 pub fn ready_gate(&self) -> AppReadyGate {
753 self.ready_gate.clone()
754 }
755
756 pub fn wait(&self) -> LocalBoxFuture<'static, ()> {
758 self.ready_gate.wait()
759 }
760
761 pub fn is_open(&self) -> bool {
763 self.ready_gate.is_open()
764 }
765
766 pub fn tasks(&self) -> &ManagedTaskScope {
768 &self.tasks
769 }
770
771 pub fn resources(&self) -> &ManagedResourceScope {
773 &self.resources
774 }
775
776 pub fn cancellation(&self) -> CancellationToken {
778 self.cancellation.clone()
779 }
780
781 pub fn is_accepting(&self) -> bool {
783 self.admission.is_open()
784 }
785
786 pub fn admission(&self) -> AppAdmission {
788 self.admission.clone()
789 }
790}
791
792#[derive(Clone, Copy, Debug, Eq, PartialEq)]
794pub enum DeactivationReason {
795 StartupRollback,
797 Shutdown,
799 SupervisionRestart,
801}
802
803#[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 pub fn instance_key(&self) -> &str {
818 &self.instance_key
819 }
820
821 pub const fn phase(&self) -> ModuleLifecyclePhase {
823 ModuleLifecyclePhase::Deactivate
824 }
825
826 pub fn dependencies(&self) -> &ModuleDependencies {
828 &self.dependencies
829 }
830
831 pub const fn reason(&self) -> DeactivationReason {
833 self.reason
834 }
835
836 pub fn tasks(&self) -> &ManagedTaskScope {
838 &self.tasks
839 }
840
841 pub fn resources(&self) -> &ManagedResourceScope {
843 &self.resources
844 }
845
846 pub fn cancellation(&self) -> CancellationToken {
848 self.cancellation.clone()
849 }
850
851 pub fn admission(&self) -> AppAdmission {
853 self.admission.clone()
854 }
855}
856
857pub type ModuleFuture = LocalBoxFuture<'static, Result<(), RuntimeFailure>>;
859
860pub trait ModuleLifecycle: std::fmt::Debug + 'static {
862 fn prepare(&self, _context: PrepareContext) -> ModuleFuture {
864 Box::pin(futures::future::ready(Ok(())))
865 }
866
867 fn activate(&self, _context: ActivateContext) -> ModuleFuture {
869 Box::pin(futures::future::ready(Ok(())))
870 }
871
872 fn deactivate(&self, _context: DeactivateContext) -> ModuleFuture {
874 Box::pin(futures::future::ready(Ok(())))
875 }
876}
877
878#[derive(Debug, Default)]
880pub struct NoopModuleLifecycle;
881
882impl ModuleLifecycle for NoopModuleLifecycle {}