1pub use super::runtime::OwnerPhase;
6use super::{
7 ordinary::{
8 BackendError, OrdinaryAgent, OrdinaryBinder, OrdinaryBinding, OrdinaryClient,
9 OrdinaryLimits, ReclaimClock,
10 },
11 runtime::{HostRuntime, OwnerEntry},
12 AgentId, AgentState, CatalogError, CatalogGuard, HostCatalog, RequestId, RunId,
13};
14use futures::{future::BoxFuture, stream::FuturesUnordered, FutureExt, StreamExt};
15use rpi_harness::agent_harness::HostAdmissionStatus;
16#[cfg(unix)]
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::{
19 collections::BTreeMap,
20 future::Future,
21 io::Write,
22 panic::AssertUnwindSafe,
23 sync::{Arc, MutexGuard, Weak},
24 time::Duration,
25};
26use tokio::{
27 sync::{watch, RwLockReadGuard, RwLockWriteGuard},
28 time::Instant,
29};
30
31type Result<T> = std::result::Result<T, ServiceError>;
32
33#[derive(Clone, Debug, thiserror::Error)]
36pub enum ServiceError {
37 #[error("shared Host is draining or stopped")]
38 Stopping,
39 #[error("Agent already has a Host owner")]
40 AlreadyOwned,
41 #[error("Agent has no loaded Host owner")]
42 NotLoaded,
43 #[error("Agent owner is starting or closing")]
44 Busy,
45 #[error("Agent backend operation failed")]
46 Backend(#[from] BackendError),
47 #[error("Host catalog operation failed")]
48 Catalog(#[source] Arc<CatalogError>),
49 #[error("Host shutdown retained {owners} unsettled owner(s); reconcile and retry")]
50 ShutdownIncomplete { owners: usize },
51 #[error("Host service task panicked or stopped; inspect state before retrying")]
52 TaskStopped,
53}
54
55enum NativeOwner {
56 Ordinary(OrdinaryAgent),
57 Mini(super::mini::MiniAgent),
58}
59impl NativeOwner {
60 fn ordinary(&self) -> std::result::Result<&OrdinaryAgent, BackendError> {
61 match self {
62 Self::Ordinary(owner) => Ok(owner),
63 Self::Mini(_) => Err(BackendError::Binding(
64 "Mini has no persistent admission authority",
65 )),
66 }
67 }
68 async fn close(&self) -> std::result::Result<(), BackendError> {
69 match self {
70 Self::Ordinary(owner) => owner.close().await,
71 Self::Mini(owner) => owner.close().await,
72 }
73 }
74}
75type Entry = OwnerEntry<NativeOwner, super::NativeExtensionCustody>;
76#[cfg(unix)]
77pub(super) type AreaAttachment = (super::area_rpc::Events, super::ordinary::AreaPeer);
78
79struct OrdinaryLoad {
80 client: OrdinaryClient,
81 #[cfg(unix)]
82 attachment: Option<std::result::Result<AreaAttachment, BackendError>>,
83}
84
85enum CloseIntent<'a> {
86 Close,
87 Guarded(CatalogGuard),
88 Idle(&'a Weak<NativeOwner>),
89}
90struct Inner {
91 catalog: HostCatalog,
92 runtime: HostRuntime<NativeOwner, super::NativeExtensionCustody>,
93 empty_since: Option<watch::Sender<Option<Instant>>>,
94 #[cfg(unix)]
95 administration_claimed: AtomicBool,
96}
97impl Inner {
98 fn entries(&self) -> MutexGuard<'_, BTreeMap<AgentId, Entry>> {
99 self.runtime.entries()
100 }
101
102 fn update_empty_since(&self, entries: &BTreeMap<AgentId, Entry>) {
105 if let Some(idle) = &self.empty_since {
106 idle.send_if_modified(|since| match (entries.is_empty(), since.is_some()) {
107 (true, false) => {
108 *since = Some(Instant::now());
109 true
110 }
111 (false, true) => {
112 *since = None;
113 true
114 }
115 _ => false,
116 });
117 }
118 }
119}
120
121#[derive(Clone)]
125pub struct HostService {
126 inner: Arc<Inner>,
127}
128
129pub(crate) struct ServiceReservation<'a> {
134 service: &'a HostService,
135 _guard: RwLockReadGuard<'a, ()>,
136}
137impl ServiceReservation<'_> {
138 pub(crate) fn catalog(&self) -> &HostCatalog {
139 self.service.catalog()
140 }
141 pub(crate) async fn restore_bound(
142 &self,
143 id: AgentId,
144 guard: CatalogGuard,
145 limits: OrdinaryLimits,
146 binding: OrdinaryBinding,
147 ) -> Result<OrdinaryClient> {
148 self.service
149 .restore_inner(id, guard, limits, binding, false)
150 .await
151 .map(|loaded| loaded.client)
152 }
153
154 #[cfg(unix)]
155 pub(super) async fn restore_for_attach(
156 &self,
157 prepared: super::PreparedProfile,
158 guard: CatalogGuard,
159 ) -> Result<(OrdinaryClient, AreaAttachment)> {
160 let loaded = self
161 .service
162 .restore_inner(
163 prepared.spec.id,
164 guard,
165 prepared.limits,
166 prepared.binding,
167 true,
168 )
169 .await?;
170 Ok((
171 loaded.client,
172 loaded.attachment.ok_or(ServiceError::TaskStopped)??,
173 ))
174 }
175 pub(crate) async fn cancel_guarded(
176 &self,
177 id: AgentId,
178 guard: CatalogGuard,
179 ticket: RunId,
180 ) -> Result<bool> {
181 self.service
182 .client_inner(id)?
183 .cancel_guarded(guard, ticket)
184 .await
185 .map_err(ServiceError::Backend)
186 }
187 pub(crate) async fn cancel_submitted_guarded(
188 &self,
189 id: AgentId,
190 guard: CatalogGuard,
191 submitted_request_id: RequestId,
192 ) -> Result<bool> {
193 self.service
194 .client_inner(id)?
195 .cancel_submitted_guarded(guard, &submitted_request_id.to_string())
196 .await
197 .map_err(ServiceError::Backend)
198 }
199 #[cfg(unix)]
200 pub(crate) fn mini_client(&self, id: AgentId) -> Result<super::mini::MiniClient> {
201 self.service.mini_client(id)
202 }
203 #[cfg(unix)]
204 pub(crate) async fn close_mini(&self, id: AgentId) -> Result<()> {
205 {
208 let entries = self.service.inner.entries();
209 let entry = entries.get(&id).ok_or(ServiceError::NotLoaded)?;
210 if !matches!(entry.owner.as_deref(), Some(NativeOwner::Mini(_))) {
211 return Err(
212 BackendError::Binding("Mini control cannot close a Persistent owner").into(),
213 );
214 }
215 }
216 self.service.close_inner(id, CloseIntent::Close).await
217 }
218 pub(crate) async fn close_guarded(&self, id: AgentId, guard: CatalogGuard) -> Result<()> {
219 match self
220 .service
221 .close_inner(id, CloseIntent::Guarded(guard))
222 .await
223 {
224 Err(ServiceError::NotLoaded) => {
225 let record = self.catalog().get(id).await.map_err(BackendError::from)?;
226 if record.state != AgentState::Unloaded {
227 return Err(ServiceError::NotLoaded);
228 }
229 self.catalog()
232 .transition(id, guard, AgentState::Closed)
233 .await
234 .map_err(|error| match error {
235 CatalogError::EpochConflict | CatalogError::RevisionConflict { .. } => {
236 BackendError::GuardRejected(Arc::new(error))
237 }
238 error => BackendError::from(error),
239 })?;
240 Ok(())
241 }
242 result => result,
243 }
244 }
245}
246
247pub(crate) struct StopReservation<'a> {
250 service: &'a HostService,
251 _guard: RwLockWriteGuard<'a, ()>,
252 settled: bool,
253}
254impl<'a> StopReservation<'a> {
255 pub(crate) fn catalog(&self) -> &HostCatalog {
256 self.service.catalog()
257 }
258 pub(crate) fn is_closed(&self) -> bool {
259 self.service.is_closed()
260 }
261 pub(crate) async fn settle(&mut self) -> Result<()> {
264 self.service.inner.runtime.begin_stopping();
265 self.service.drain_inner().await?;
266 self.settled = true;
267 Ok(())
268 }
269 pub(crate) async fn drain(mut self) -> Result<DrainedService<'a>> {
270 if !self.settled {
271 self.settle().await?;
272 }
273 Ok(DrainedService { reservation: self })
274 }
275}
276
277pub(crate) struct DrainedService<'a> {
281 reservation: StopReservation<'a>,
282}
283impl DrainedService<'_> {
284 pub(crate) fn catalog(&self) -> &HostCatalog {
285 self.reservation.catalog()
286 }
287 pub(crate) async fn close_storage(self) -> Result<()> {
288 self.catalog()
289 .shutdown()
290 .await
291 .map_err(|error| ServiceError::Catalog(Arc::new(error)))?;
292 self.reservation.service.inner.runtime.mark_closed();
293 Ok(())
294 }
295}
296
297impl HostService {
298 pub fn new(catalog: HostCatalog) -> Self {
301 let empty_since = catalog
302 .idle_timeout()
303 .map(|_| watch::channel(Some(Instant::now())).0);
304 Self {
305 inner: Arc::new(Inner {
306 catalog,
307 runtime: HostRuntime::new(),
308 empty_since,
309 #[cfg(unix)]
310 administration_claimed: AtomicBool::new(false),
311 }),
312 }
313 }
314
315 pub(crate) fn catalog(&self) -> &HostCatalog {
318 &self.inner.catalog
319 }
320
321 #[cfg(unix)]
324 pub(crate) fn claim_administration(&self) -> bool {
325 self.inner
326 .administration_claimed
327 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
328 .is_ok()
329 }
330
331 pub fn owner_count(&self) -> usize {
332 self.inner.runtime.owner_count()
333 }
334 pub fn phase(&self, id: AgentId) -> Option<OwnerPhase> {
335 self.inner.runtime.phase(id)
336 }
337 pub fn is_stopping(&self) -> bool {
338 self.inner.runtime.is_stopping()
339 }
340 pub fn is_closed(&self) -> bool {
341 self.inner.runtime.is_closed()
342 }
343
344 pub(crate) async fn with_administration<T, F>(&self, operation: F) -> Result<T>
348 where
349 T: Send + 'static,
350 F: for<'a> FnOnce(ServiceReservation<'a>) -> BoxFuture<'a, Result<T>> + Send + 'static,
351 {
352 if self.is_stopping() {
353 return Err(ServiceError::Stopping);
354 }
355 let service = self.clone();
356 supervised(async move {
357 let guard = service.inner.runtime.lifecycle.read().await;
358 if service.is_stopping() {
359 return Err(ServiceError::Stopping);
360 }
361 operation(ServiceReservation {
362 service: &service,
363 _guard: guard,
364 })
365 .await
366 })
367 .await
368 }
369
370 pub(crate) async fn with_stop_reservation<T, F>(
374 &self,
375 unconditional: bool,
376 operation: F,
377 ) -> Result<T>
378 where
379 T: Send + 'static,
380 F: for<'a> FnOnce(StopReservation<'a>) -> BoxFuture<'a, Result<T>> + Send + 'static,
381 {
382 if !unconditional && self.is_stopping() {
383 return Err(ServiceError::Stopping);
384 }
385 let service = self.clone();
386 supervised(async move {
387 if unconditional {
388 service.inner.runtime.begin_stopping();
389 }
390 let guard = service.inner.runtime.lifecycle.write().await;
391 if !unconditional && (service.is_stopping() || service.is_closed()) {
392 return Err(ServiceError::Stopping);
393 }
394 operation(StopReservation {
395 service: &service,
396 _guard: guard,
397 settled: false,
398 })
399 .await
400 })
401 .await
402 }
403
404 pub async fn restore_ordinary(
408 &self,
409 id: AgentId,
410 guard: CatalogGuard,
411 limits: OrdinaryLimits,
412 binder: OrdinaryBinder,
413 ) -> Result<OrdinaryClient> {
414 self.restore_bound(id, guard, limits, OrdinaryBinding::legacy(binder))
415 .await
416 }
417
418 pub async fn restore_bound(
421 &self,
422 id: AgentId,
423 guard: CatalogGuard,
424 limits: OrdinaryLimits,
425 binding: OrdinaryBinding,
426 ) -> Result<OrdinaryClient> {
427 self.with_administration(move |reservation| {
428 Box::pin(async move { reservation.restore_bound(id, guard, limits, binding).await })
429 })
430 .await
431 }
432
433 async fn restore_inner(
434 &self,
435 id: AgentId,
436 guard: CatalogGuard,
437 limits: OrdinaryLimits,
438 binding: OrdinaryBinding,
439 attach: bool,
440 ) -> Result<OrdinaryLoad> {
441 {
442 let mut entries = self.inner.entries();
443 if entries.contains_key(&id) {
444 return Err(ServiceError::AlreadyOwned);
445 }
446 entries.insert(
447 id,
448 Entry {
449 phase: OwnerPhase::Starting,
450 owner: None,
451 failed_start: None,
452 },
453 );
454 self.inner.update_empty_since(&entries);
455 }
456 let result = OrdinaryAgent::restore_bound_with_intent(
457 self.catalog().clone(),
458 id,
459 guard,
460 limits,
461 binding,
462 attach,
463 )
464 .await;
465 #[cfg(unix)]
468 let attachment = match &result {
469 Ok(owner) if attach => Some(attach_area_peer(&owner.client()).await),
470 _ => None,
471 };
472 let safe_failure = result.is_err()
473 && !matches!(&result, Err(BackendError::ExtensionUnsettled(_)))
474 && self.failed_start_is_inactive(id).await;
475 let mut entries = self.inner.entries();
476 match result {
477 Ok(owner) => {
478 let client = owner.client();
479 let clock = owner.reclaim_clock();
480 let owner = Arc::new(NativeOwner::Ordinary(owner));
481 if let Some(clock) = clock {
482 tokio::spawn(watch_idle(
483 Arc::downgrade(&self.inner),
484 id,
485 Arc::downgrade(&owner),
486 clock,
487 ));
488 }
489 entries.insert(
490 id,
491 Entry {
492 phase: OwnerPhase::Live,
493 owner: Some(owner),
494 failed_start: None,
495 },
496 );
497 Ok(OrdinaryLoad {
498 client,
499 #[cfg(unix)]
500 attachment,
501 })
502 }
503 Err(error) => {
504 if safe_failure {
507 entries.remove(&id);
508 self.inner.update_empty_since(&entries);
509 } else {
510 entries.insert(
511 id,
512 Entry {
513 phase: OwnerPhase::StartFailed,
514 owner: None,
515 failed_start: match &error {
516 BackendError::ExtensionUnsettled(custody) => Some(custody.clone()),
517 _ => None,
518 },
519 },
520 );
521 }
522 Err(error.into())
523 }
524 }
525 }
526
527 pub async fn start_mini(
531 &self,
532 id: AgentId,
533 guard: CatalogGuard,
534 profile: super::bindings::NativeBindingProfile,
535 limits: super::mini::MiniLimits,
536 ) -> Result<super::mini::MiniClient> {
537 self.with_administration(move |reservation| {
538 Box::pin(async move {
539 reservation
540 .service
541 .start_mini_inner(id, guard, profile, limits)
542 .await
543 })
544 })
545 .await
546 }
547
548 async fn start_mini_inner(
549 &self,
550 id: AgentId,
551 guard: CatalogGuard,
552 profile: super::bindings::NativeBindingProfile,
553 limits: super::mini::MiniLimits,
554 ) -> Result<super::mini::MiniClient> {
555 let record = self
556 .inner
557 .catalog
558 .get(id)
559 .await
560 .map_err(|error| ServiceError::Catalog(Arc::new(error)))?;
561 if record.spec.mode != super::AgentMode::Mini {
562 return Err(
563 BackendError::Binding("Mini requires explicit Session-free metadata").into(),
564 );
565 }
566 let custody = super::NativeExtensionCustody::new();
567 {
568 let mut entries = self.inner.entries();
569 if entries.contains_key(&id) {
570 return Err(ServiceError::AlreadyOwned);
571 }
572 entries.insert(
573 id,
574 Entry {
575 phase: OwnerPhase::Starting,
576 owner: None,
577 failed_start: Some(custody.clone()),
578 },
579 );
580 self.inner.update_empty_since(&entries);
581 }
582 let result = AssertUnwindSafe(super::mini::MiniAgent::start(
583 self.inner.catalog.clone(),
584 id,
585 guard,
586 profile,
587 limits,
588 custody.clone(),
589 self.inner.runtime.stopping_signal(),
590 ))
591 .catch_unwind()
592 .await;
593 let safe_failure = matches!(result, Ok(Err(_))) && self.failed_start_is_inactive(id).await;
595 let mut entries = self.inner.entries();
596 match result {
597 Ok(Ok(owner)) => {
598 let client = owner.client();
599 entries.insert(
600 id,
601 Entry {
602 phase: OwnerPhase::Live,
603 owner: Some(Arc::new(NativeOwner::Mini(owner))),
604 failed_start: None,
605 },
606 );
607 Ok(client)
608 }
609 failure => {
610 if safe_failure {
611 entries.remove(&id);
612 self.inner.update_empty_since(&entries);
613 } else {
614 entries.insert(
615 id,
616 Entry {
617 phase: OwnerPhase::StartFailed,
618 owner: None,
619 failed_start: Some(custody),
620 },
621 );
622 }
623 match failure {
624 Ok(Err(error)) => Err(error.into()),
625 Err(_) => Err(ServiceError::TaskStopped),
626 Ok(Ok(_)) => unreachable!(),
627 }
628 }
629 }
630 }
631
632 pub fn mini_client(&self, id: AgentId) -> Result<super::mini::MiniClient> {
635 if self.is_stopping() {
636 return Err(ServiceError::Stopping);
637 }
638 let entries = self.inner.entries();
639 let entry = entries.get(&id).ok_or(ServiceError::NotLoaded)?;
640 if entry.phase != OwnerPhase::Live {
641 return Err(ServiceError::Busy);
642 }
643 match entry.owner.as_deref().ok_or(ServiceError::TaskStopped)? {
644 NativeOwner::Mini(owner) => Ok(owner.client()),
645 NativeOwner::Ordinary(_) => {
646 Err(BackendError::Binding("persistent owner has no Mini authority").into())
647 }
648 }
649 }
650
651 pub fn ordinary_client(&self, id: AgentId) -> Result<OrdinaryClient> {
655 if self.is_stopping() {
656 return Err(ServiceError::Stopping);
657 }
658 self.client_inner(id)
659 }
660 fn client_inner(&self, id: AgentId) -> Result<OrdinaryClient> {
661 let entries = self.inner.entries();
662 let entry = entries.get(&id).ok_or(ServiceError::NotLoaded)?;
663 match entry.phase {
664 OwnerPhase::Live => Ok(entry
665 .owner
666 .as_ref()
667 .ok_or(ServiceError::TaskStopped)?
668 .ordinary()?
669 .client()),
670 OwnerPhase::Starting | OwnerPhase::Closing => Err(ServiceError::Busy),
671 OwnerPhase::StartFailed | OwnerPhase::CloseFailed => {
672 Err(ServiceError::Backend(BackendError::Faulted))
673 }
674 }
675 }
676
677 async fn failed_start_is_inactive(&self, id: AgentId) -> bool {
678 match self.inner.catalog.get(id).await {
679 Ok(record) => !record.state.is_resident(),
680 Err(CatalogError::UnknownAgent) => true,
681 Err(_) => false,
682 }
683 }
684
685 pub async fn admission(
688 &self,
689 id: AgentId,
690 request_id: &str,
691 ) -> Result<Option<HostAdmissionStatus>> {
692 self.ordinary_client(id)?
693 .admission(request_id)
694 .await
695 .map_err(ServiceError::Backend)
696 }
697
698 pub async fn admissions(&self, id: AgentId) -> Result<Vec<HostAdmissionStatus>> {
700 self.ordinary_client(id)?
701 .admissions()
702 .await
703 .map_err(ServiceError::Backend)
704 }
705
706 pub async fn cancel_ordinary_guarded(
711 &self,
712 id: AgentId,
713 guard: CatalogGuard,
714 ticket: RunId,
715 ) -> Result<bool> {
716 self.with_administration(move |reservation| {
717 Box::pin(async move { reservation.cancel_guarded(id, guard, ticket).await })
718 })
719 .await
720 }
721
722 pub async fn cancel_submitted_ordinary_guarded(
726 &self,
727 id: AgentId,
728 guard: CatalogGuard,
729 submitted_request_id: RequestId,
730 ) -> Result<bool> {
731 self.with_administration(move |reservation| {
732 Box::pin(async move {
733 reservation
734 .cancel_submitted_guarded(id, guard, submitted_request_id)
735 .await
736 })
737 })
738 .await
739 }
740
741 pub async fn close_ordinary_guarded(&self, id: AgentId, guard: CatalogGuard) -> Result<()> {
746 self.with_administration(move |reservation| {
747 Box::pin(async move { reservation.close_guarded(id, guard).await })
748 })
749 .await
750 }
751
752 pub async fn close_ordinary(&self, id: AgentId) -> Result<()> {
755 self.close_agent(id).await
756 }
757
758 pub async fn close_agent(&self, id: AgentId) -> Result<()> {
761 let service = self.clone();
762 supervised(async move {
763 let _reservation = service.inner.runtime.lifecycle.read().await;
764 service.close_inner(id, CloseIntent::Close).await
765 })
766 .await
767 }
768 async fn close_inner(&self, id: AgentId, intent: CloseIntent<'_>) -> Result<()> {
769 if self.phase(id) == Some(OwnerPhase::StartFailed) {
770 if !matches!(intent, CloseIntent::Close) {
773 return Err(ServiceError::Backend(BackendError::Faulted));
774 }
775 let custody = {
776 let mut entries = self.inner.entries();
777 let entry = entries.get_mut(&id).ok_or(ServiceError::NotLoaded)?;
778 if entry.phase != OwnerPhase::StartFailed {
779 return Err(ServiceError::Busy);
780 }
781 let custody = entry.failed_start.clone();
782 if custody.is_some() {
783 entry.phase = OwnerPhase::Closing;
786 }
787 custody
788 };
789 if let Some(custody) = custody {
790 let result = AssertUnwindSafe(async {
791 custody.close().await?;
792 custody.release_storage().await;
793 let record = self
794 .inner
795 .catalog
796 .get(id)
797 .await
798 .map_err(BackendError::from)?;
799 if record.state.is_resident() {
800 self.inner
801 .catalog
802 .transition(
803 id,
804 self.inner.catalog.guard(&record),
805 if record.spec.mode == super::AgentMode::Mini {
806 super::AgentState::Lost
807 } else {
808 super::AgentState::Closed
809 },
810 )
811 .await
812 .map_err(BackendError::from)?;
813 }
814 Ok::<(), ServiceError>(())
815 })
816 .catch_unwind()
817 .await
818 .unwrap_or(Err(ServiceError::TaskStopped));
819 let mut entries = self.inner.entries();
820 match &result {
821 Ok(()) => {
822 entries.remove(&id);
823 self.inner.update_empty_since(&entries);
824 }
825 Err(_) => {
826 if let Some(entry) = entries.get_mut(&id) {
827 entry.phase = OwnerPhase::StartFailed;
828 }
829 }
830 }
831 return result;
832 }
833 if !self.failed_start_is_inactive(id).await {
834 return Err(ServiceError::Backend(BackendError::Faulted));
835 }
836 let mut entries = self.inner.entries();
837 if entries.get(&id).map(|entry| entry.phase) != Some(OwnerPhase::StartFailed) {
840 return Err(ServiceError::Busy);
841 }
842 entries.remove(&id);
843 self.inner.update_empty_since(&entries);
844 return Ok(());
845 }
846 let (owner, previous_phase) = {
847 let mut entries = self.inner.entries();
848 let entry = entries.get_mut(&id).ok_or(ServiceError::NotLoaded)?;
849 if matches!(entry.phase, OwnerPhase::Starting | OwnerPhase::Closing) {
850 return Err(ServiceError::Busy);
851 }
852 let owner = entry.owner.clone().ok_or(ServiceError::TaskStopped)?;
853 if let CloseIntent::Idle(expected) = intent {
854 if entry.phase != OwnerPhase::Live || expected.as_ptr() != Arc::as_ptr(&owner) {
855 return Err(ServiceError::NotLoaded);
856 }
857 }
858 if !matches!(intent, CloseIntent::Close) {
859 owner.ordinary()?;
862 }
863 let previous_phase = entry.phase;
864 entry.phase = OwnerPhase::Closing;
865 (owner, previous_phase)
866 };
867 let result = AssertUnwindSafe(async {
870 match intent {
871 CloseIntent::Guarded(guard) => owner.ordinary()?.close_guarded(guard).await,
872 CloseIntent::Idle(_) => owner.ordinary()?.unload_idle().await,
873 CloseIntent::Close => owner.close().await,
874 }
875 })
876 .catch_unwind()
877 .await;
878 let rejected = !matches!(intent, CloseIntent::Close)
882 && matches!(
883 &result,
884 Ok(Err(BackendError::GuardRejected(_) | BackendError::Busy))
885 );
886 let mut entries = self.inner.entries();
887 match result {
888 Ok(Ok(())) => {
889 entries.remove(&id);
890 self.inner.update_empty_since(&entries);
891 Ok(())
892 }
893 result => {
894 if let Some(entry) = entries.get_mut(&id) {
895 entry.phase = if rejected {
896 previous_phase
897 } else {
898 OwnerPhase::CloseFailed
899 };
900 }
901 match result {
902 Ok(Err(error)) => Err(error.into()),
903 Err(_) => Err(ServiceError::TaskStopped),
904 Ok(Ok(())) => unreachable!(),
905 }
906 }
907 }
908 }
909
910 pub async fn shutdown(&self) -> Result<()> {
914 self.with_stop_reservation(true, |reservation| {
915 Box::pin(async move {
916 if reservation.is_closed() {
917 return Ok(());
918 }
919 reservation.drain().await?.close_storage().await
920 })
921 })
922 .await
923 }
924
925 #[cfg(unix)]
926 pub(super) fn empty_since(&self) -> Option<watch::Receiver<Option<Instant>>> {
927 self.inner
928 .empty_since
929 .as_ref()
930 .map(watch::Sender::subscribe)
931 }
932
933 #[cfg(unix)]
936 pub(super) async fn shutdown_if_idle(&self, timeout: std::time::Duration) -> Result<bool> {
937 let Ok(guard) = self.inner.runtime.lifecycle.try_write() else {
938 return Ok(false);
939 };
940 let Some(since) = self
941 .inner
942 .empty_since
943 .as_ref()
944 .and_then(|value| *value.borrow())
945 else {
946 return Ok(false);
947 };
948 if self.is_stopping() || since.elapsed() < timeout {
949 return Ok(false);
950 }
951 let status = self
952 .catalog()
953 .status()
954 .await
955 .map_err(|error| ServiceError::Catalog(Arc::new(error)))?;
956 if status.resident != 0 || self.is_stopping() {
957 return Ok(false);
958 }
959 self.inner.runtime.begin_stopping();
960 DrainedService {
961 reservation: StopReservation {
962 service: self,
963 _guard: guard,
964 settled: true,
965 },
966 }
967 .close_storage()
968 .await?;
969 Ok(true)
970 }
971
972 async fn drain_inner(&self) -> Result<()> {
975 let ids: Vec<_> = self.inner.entries().keys().copied().collect();
976 let mut closes = FuturesUnordered::new();
977 for id in ids {
978 closes.push(self.close_during_shutdown(id));
979 }
980 while closes.next().await.is_some() {}
981 let owners = self.owner_count();
982 if owners != 0 {
983 return Err(ServiceError::ShutdownIncomplete { owners });
984 }
985 let status = self
986 .inner
987 .catalog
988 .status()
989 .await
990 .map_err(|error| ServiceError::Catalog(Arc::new(error)))?;
991 if status.resident != 0 {
992 return Err(ServiceError::ShutdownIncomplete {
993 owners: status.resident,
994 });
995 }
996 Ok(())
997 }
998
999 async fn close_during_shutdown(&self, id: AgentId) -> Result<()> {
1000 let grace = self
1001 .inner
1002 .entries()
1003 .get(&id)
1004 .and_then(|entry| entry.owner.as_ref()?.ordinary().ok()?.shutdown_grace());
1005 let closing = self.close_inner(id, CloseIntent::Close);
1006 let Some(grace) = grace else {
1007 return closing.await;
1008 };
1009 tokio::pin!(closing);
1010 tokio::select! {
1011 biased;
1012 result = &mut closing => return result,
1013 () = tokio::time::sleep(grace) => (),
1014 }
1015 let _ = writeln!(
1018 std::io::stderr().lock(),
1019 "Host Agent {id} exceeded shutdown grace ({} ms) and is still settling",
1020 grace.as_millis()
1021 );
1022 closing.await
1023 }
1024}
1025
1026#[cfg(unix)]
1027pub(super) async fn attach_area_peer(
1028 client: &OrdinaryClient,
1029) -> std::result::Result<AreaAttachment, BackendError> {
1030 let (events, peer) = client.area_session(true).await?;
1031 Ok((events, peer.ok_or(BackendError::TaskStopped)?))
1032}
1033
1034async fn watch_idle(
1037 service: Weak<Inner>,
1038 id: AgentId,
1039 owner: Weak<NativeOwner>,
1040 mut clock: watch::Receiver<ReclaimClock>,
1041) {
1042 let mut retry_at = None;
1043 loop {
1044 let deadline = clock.borrow_and_update().deadline();
1045 if let Some(deadline) = deadline {
1046 let deadline = deadline.max(retry_at.unwrap_or(deadline));
1047 tokio::select! {
1048 biased;
1049 changed = clock.changed() => {
1050 if changed.is_err() { return; }
1051 retry_at = None;
1052 continue;
1053 }
1054 () = tokio::time::sleep_until(deadline) => (),
1055 }
1056 let Some(inner) = service.upgrade() else {
1057 return;
1058 };
1059 let service = HostService { inner };
1060 let expected = owner.clone();
1061 let result = service
1062 .with_administration(move |reservation| {
1063 Box::pin(async move {
1064 reservation
1065 .service
1066 .close_inner(id, CloseIntent::Idle(&expected))
1067 .await
1068 })
1069 })
1070 .await;
1071 match result {
1072 Err(ServiceError::Busy | ServiceError::Backend(BackendError::Busy)) => {
1073 retry_at = Some(Instant::now() + Duration::from_millis(100));
1074 }
1075 Err(ServiceError::NotLoaded | ServiceError::Stopping) | Ok(()) => return,
1076 Err(error) => {
1077 let _ = writeln!(
1078 std::io::stderr().lock(),
1079 "Host Agent {id} idle unload failed: {error}"
1080 );
1081 return;
1082 }
1083 }
1084 } else if clock.changed().await.is_err() {
1085 return;
1086 } else {
1087 retry_at = None;
1088 }
1089 }
1090}
1091
1092async fn supervised<T: Send + 'static>(
1093 future: impl Future<Output = Result<T>> + Send + 'static,
1094) -> Result<T> {
1095 tokio::spawn(AssertUnwindSafe(future).catch_unwind())
1097 .await
1098 .map_err(|_| ServiceError::TaskStopped)?
1099 .map_err(|_| ServiceError::TaskStopped)?
1100}