Skip to main content

tembra_runtime/host/
signals.rs

1//! Small adapter notifications consumed by the shared action driver.
2use super::*;
3
4/// Metadata notifications carry claim and root cleanup across an attached language adapter.
5#[derive(Clone, Copy)]
6pub enum ForeignNotification {
7    RootEnded(core::Id),
8    ReferenceReleased(core::Id),
9}
10
11impl Host {
12    /// Deliver a kernel action owned by native callback storage.
13    /// Returns true when the native adapter exclusively consumes the action.
14    pub fn notify(&self, action: &core::Action) -> bool {
15        match action {
16            #[cfg(feature = "subscriptions")]
17            core::Action::Deliver {
18                subscription,
19                operation,
20                payload,
21            } => return self.deliver(*subscription, *operation, *payload),
22            #[cfg(feature = "subscriptions")]
23            core::Action::DetachSubscription(subscription)
24            | core::Action::SubscriptionFailed(subscription) => {
25                return self.detach_listener(*subscription);
26            }
27            core::Action::StateChanged { object, .. } => self.publish_state(*object),
28            core::Action::DisposeObject(object) => {
29                self.0.observers.borrow_mut().remove(object);
30            }
31            core::Action::CancelRoot(root) => self.cancel_context(*root),
32            core::Action::CancelCall(call) => self.cancel_call_signal(*call),
33            core::Action::CancelTask(task) => self.cancel_task(*task),
34            core::Action::ProgramComplete { program, error } => {
35                if let Some(send) = self.0.programs.borrow_mut().remove(program) {
36                    let _ = send.send(error.clone().map_or(Ok(()), Err));
37                    return true;
38                }
39            }
40            _ => {}
41        }
42        false
43    }
44}
45
46impl Host {
47    pub(crate) fn observe(
48        &self,
49        object: core::Id,
50        observer: std::rc::Weak<crate::readable::Observer>,
51    ) {
52        self.0
53            .observers
54            .borrow_mut()
55            .entry(object)
56            .or_default()
57            .push(observer);
58    }
59
60    /// Remove detached observations while their state object can remain live and quiet.
61    pub(crate) fn prune_observers(&self, object: core::Id) {
62        let mut indexed = self.0.observers.borrow_mut();
63        if let Some(observers) = indexed.get_mut(&object) {
64            observers.retain(|observer| {
65                observer
66                    .upgrade()
67                    .is_some_and(|observer| observer.active.get())
68            });
69            if observers.is_empty() {
70                indexed.remove(&object);
71            }
72        }
73    }
74
75    /// Publish a shared kernel state-change notification to native observers.
76    pub fn publish_state(&self, object: core::Id) {
77        let observers = {
78            let mut indexed = self.0.observers.borrow_mut();
79            let Some(observers) = indexed.get_mut(&object) else {
80                return;
81            };
82            observers.retain(|observer| {
83                observer
84                    .upgrade()
85                    .is_some_and(|observer| observer.active.get())
86            });
87            observers
88                .iter()
89                .filter_map(std::rc::Weak::upgrade)
90                .collect::<Vec<_>>()
91        };
92        for observer in observers {
93            if observer.active.get()
94                && let Err(error) = (observer.invoke)()
95            {
96                self.0.errors.borrow_mut().push(error);
97            }
98        }
99    }
100}
101
102impl Host {
103    /// Attach the shared driver's wake callback. Native settlement requests another action drain.
104    pub fn set_driver_wake(&self, wake: impl Fn() + 'static) {
105        *self.0.driver_wake.borrow_mut() = Some(Rc::new(wake));
106    }
107
108    /// Attach metadata-only notifications for foreign root and reference cleanup.
109    pub fn set_foreign_notifier(&self, notify: impl Fn(ForeignNotification) + 'static) {
110        *self.0.foreign_notifier.borrow_mut() = Some(Rc::new(notify));
111    }
112
113    pub(super) fn notify_foreign(&self, notification: ForeignNotification) {
114        let notify = self.0.foreign_notifier.borrow().clone();
115        if let Some(notify) = notify {
116            notify(notification);
117        }
118    }
119
120    /// Attach the codec-bound service callback path provided by a foreign execution adapter.
121    pub fn set_foreign_dispatcher(
122        &self,
123        dispatch: impl Fn(Value) -> LocalBoxFuture<'static, Result<Value>> + 'static,
124    ) {
125        *self.0.foreign_dispatcher.borrow_mut() = Some(Rc::new(dispatch));
126    }
127
128    pub(super) async fn foreign(&self, request: Value) -> Result<Value> {
129        let dispatch = self
130            .0
131            .foreign_dispatcher
132            .borrow()
133            .clone()
134            .ok_or_else(|| Error::invalid(Reason::Driver, "no foreign callback adapter"))?;
135        dispatch(request).await
136    }
137
138    /// Wake an attached driver when native work settles without keeping idle infrastructure alive.
139    pub fn poll_settled(&self, cx: &mut std::task::Context<'_>) -> std::task::Poll<()> {
140        self.0.settled_waker.register(cx.waker());
141        if self.0.active.get() == 0 {
142            std::task::Poll::Ready(())
143        } else {
144            std::task::Poll::Pending
145        }
146    }
147
148    /// Wait for native physical callbacks while the shared adapter continues driving kernel actions.
149    pub async fn settled(&self) {
150        while self.0.active.get() != 0 {
151            let (send, receive) = oneshot::channel();
152            self.0.settled.borrow_mut().push(send);
153            let _ = receive.await;
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use futures::executor::LocalPool;
162
163    #[test]
164    fn released_and_detached_observations_leave_no_index_on_a_quiet_live_object() {
165        let mut pool = LocalPool::new();
166        let host = Host::new(pool.spawner());
167        host.install(vec![
168            Orb::new("state", 1).service(
169                crate::Service::new("state", |declaration| {
170                    declaration.state(0_u32, 1, |_| Ok(()))
171                })
172                .lifetime(core::Lifetime::Host, 0),
173            ),
174        ])
175        .unwrap();
176        for explicit_detach in [false, true] {
177            for _ in 0..100 {
178                let reference = host.get("state", vec!["main".into()], "host").unwrap();
179                pool.run_until(reference.ready()).unwrap();
180                let observation = reference
181                    .state::<u32>()
182                    .unwrap()
183                    .subscribe(|_| Ok(()))
184                    .unwrap();
185                assert_eq!(host.0.observers.borrow()[&reference.object()].len(), 1);
186                if explicit_detach {
187                    observation.detach();
188                }
189                reference.release().unwrap();
190                assert!(host.0.observers.borrow().is_empty());
191                assert_eq!(host.kernel().diagnostics().objects, 1);
192                drop(observation);
193            }
194        }
195        pool.run_until(host.close()).unwrap();
196    }
197}