Skip to main content

tembra_runtime/host/
mod.rs

1use crate::core::Reason;
2use crate::{
3    Error, Orb, Result, State, core,
4    orb::{Data, Implementation, type_error},
5};
6use futures::{
7    FutureExt,
8    channel::oneshot,
9    future::{LocalBoxFuture, Shared},
10    task::{LocalSpawn, LocalSpawnExt},
11};
12use serde::Serialize;
13use serde_json::Value;
14use std::{
15    cell::{Cell, RefCell},
16    collections::{BTreeMap, BTreeSet},
17    future::Future,
18    rc::Rc,
19};
20
21mod acquisition;
22mod activation;
23mod clock;
24mod context;
25mod declaration;
26#[cfg(feature = "subscriptions")]
27mod events;
28mod execution;
29#[cfg(feature = "hooks")]
30mod hooks;
31mod log;
32#[cfg(feature = "hooks")]
33mod observation;
34mod reference;
35mod reload;
36mod resources;
37#[cfg(feature = "rpc")]
38mod rpc;
39mod scopes;
40mod signals;
41mod tasks;
42mod values;
43
44pub use acquisition::AcquisitionOptions;
45pub use context::Context;
46pub use declaration::Declaration;
47pub use log::LogRecord;
48pub use reference::{IssuedCall, Reference};
49pub use resources::{Cancellation, Resource, ResourceKey, ResourceSignal};
50pub use signals::ForeignNotification;
51pub use tasks::TaskScope;
52
53type ForeignNotifier = Rc<dyn Fn(ForeignNotification)>;
54type LogObserver = Rc<dyn Fn(&LogRecord)>;
55type ForeignDispatcher = Rc<dyn Fn(Value) -> LocalBoxFuture<'static, Result<Value>>>;
56type Encoder = Rc<dyn Fn() -> Result<Value>>;
57struct ValueRecord {
58    value: Data,
59    portable: Option<Encoder>,
60}
61
62struct Environment {
63    environment: Data,
64    implementation: Implementation,
65    scope: core::Id,
66    /// The owner of the native resources this version issues; its drop, with the version,
67    /// closes those still held.
68    issuer: Rc<crate::portable::Issuer>,
69}
70
71struct Object {
72    versions: BTreeMap<core::Id, Environment>,
73    activation: Option<Shared<LocalBoxFuture<'static, Result<()>>>>,
74}
75type Opener = Box<dyn FnOnce(Context) -> LocalBoxFuture<'static, Result<()>>>;
76type Closer = Box<dyn FnOnce(Context) -> LocalBoxFuture<'static, Result<()>>>;
77/// Physical work a call keeps doing after its logical result was published.
78pub(crate) type Physical = LocalBoxFuture<'static, Result<()>>;
79
80/// What a root owns natively: claims acquired through [`Context::get`], which its end releases,
81/// and stream ends delivered to it, which its end closes and its cancellation cancels.
82#[derive(Default)]
83struct RootClaims {
84    references: Vec<Rc<Reference>>,
85    streams: Vec<std::rc::Weak<dyn crate::portable::RootStream>>,
86}
87
88struct Inner {
89    #[cfg(feature = "hooks")]
90    hooks: hooks::Hooks,
91    #[cfg(feature = "subscriptions")]
92    listeners: RefCell<BTreeMap<core::Id, Rc<events::Listener>>>,
93    scopes: RefCell<BTreeMap<core::Id, scopes::NativeScope>>,
94    host_scopes: RefCell<Vec<core::Id>>,
95    scope_activations: RefCell<BTreeMap<core::Id, Shared<LocalBoxFuture<'static, Result<()>>>>>,
96    orb_scopes: RefCell<BTreeMap<core::Id, core::Id>>,
97    orb_factories: RefCell<BTreeMap<core::Id, crate::orb::Factory>>,
98    pending_orbs: RefCell<BTreeMap<core::Id, core::InstalledOrb>>,
99    orb_declaring: RefCell<BTreeSet<core::Id>>,
100    orb_values: RefCell<BTreeMap<core::Id, Data>>,
101    host_resources: RefCell<BTreeMap<String, ResourceKey>>,
102    root_references: RefCell<BTreeMap<core::Id, RootClaims>>,
103    task_signals: RefCell<BTreeMap<core::Id, Cancellation>>,
104    clock: Rc<dyn crate::Clock>,
105    clock_offset: Cell<u64>,
106    orb_errors: RefCell<BTreeMap<core::Id, Error>>,
107    deadline: RefCell<Option<(u64, futures::future::AbortHandle)>>,
108    kernel: core::Host,
109    executor: Rc<dyn LocalSpawn>,
110    orbs: RefCell<BTreeMap<core::Id, BTreeMap<String, Implementation>>>,
111    objects: RefCell<BTreeMap<core::Id, Object>>,
112    scope_objects: RefCell<BTreeMap<core::Id, (core::Id, core::Id)>>,
113    observers: RefCell<BTreeMap<core::Id, Vec<std::rc::Weak<crate::readable::Observer>>>>,
114    values: RefCell<BTreeMap<core::Id, ValueRecord>>,
115    closers: RefCell<BTreeMap<core::Id, Closer>>,
116    openers: RefCell<BTreeMap<core::Id, Opener>>,
117    cancellations: RefCell<BTreeMap<core::Id, ResourceSignal>>,
118    context_signals: RefCell<BTreeMap<core::Id, std::rc::Weak<resources::CancellationState>>>,
119    /// Logical root completion observed only by acquisitions waiting for an address.
120    /// Kept separate from cancellation: admitted physical work may outlive its root's wait.
121    root_end_signals: RefCell<BTreeMap<core::Id, std::rc::Weak<resources::CancellationState>>>,
122    /// Signals of entered invocations, by call, with their root; created when first observed.
123    call_signals:
124        RefCell<BTreeMap<core::Id, (core::Id, std::rc::Weak<resources::CancellationState>)>>,
125    errors: RefCell<Vec<Error>>,
126    external_actions: Cell<bool>,
127    driver_wake: RefCell<Option<Rc<dyn Fn()>>>,
128    foreign_dispatcher: RefCell<Option<ForeignDispatcher>>,
129    foreign_notifier: RefCell<Option<ForeignNotifier>>,
130    log_observer: RefCell<Option<LogObserver>>,
131    flushing: Cell<bool>,
132    active: Cell<usize>,
133    settled_waker: futures::task::AtomicWaker,
134    settled: RefCell<Vec<oneshot::Sender<()>>>,
135    programs: RefCell<BTreeMap<core::Id, oneshot::Sender<Result<()>>>>,
136    prepared_programs: RefCell<BTreeMap<core::Id, oneshot::Sender<Result<()>>>>,
137}
138
139/// Runs native callbacks on the supplied executor.
140/// Keep the executor running until callbacks and cleanup settle.
141#[derive(Clone)]
142pub struct Host(Rc<Inner>);
143
144impl Host {
145    /// Create a native host driven by the supplied local executor.
146    pub fn new(executor: impl LocalSpawn + 'static) -> Self {
147        Self::with_kernel(core::Host::new(), executor)
148    }
149
150    /// Attach native callbacks to an existing shared kernel.
151    pub fn with_kernel(kernel: core::Host, executor: impl LocalSpawn + 'static) -> Self {
152        Self::with_clock(kernel, executor, crate::clock::SystemClock::default())
153    }
154
155    /// Create a host with an embedding-supplied monotonic clock and timer.
156    pub fn with_clock(
157        kernel: core::Host,
158        executor: impl LocalSpawn + 'static,
159        clock: impl crate::Clock + 'static,
160    ) -> Self {
161        Self(Rc::new(Inner {
162            #[cfg(feature = "hooks")]
163            hooks: hooks::Hooks::default(),
164            #[cfg(feature = "subscriptions")]
165            listeners: RefCell::new(BTreeMap::new()),
166            scopes: RefCell::new(BTreeMap::new()),
167            host_scopes: RefCell::new(Vec::new()),
168            scope_activations: RefCell::new(BTreeMap::new()),
169            orb_scopes: RefCell::new(BTreeMap::new()),
170            orb_factories: RefCell::new(BTreeMap::new()),
171            pending_orbs: RefCell::new(BTreeMap::new()),
172            orb_declaring: RefCell::new(BTreeSet::new()),
173            orb_values: RefCell::new(BTreeMap::new()),
174            host_resources: RefCell::new(BTreeMap::new()),
175            root_references: RefCell::new(BTreeMap::new()),
176            task_signals: RefCell::new(BTreeMap::new()),
177            clock: Rc::new(clock),
178            clock_offset: Cell::new(0),
179            orb_errors: RefCell::new(BTreeMap::new()),
180            deadline: RefCell::new(None),
181            kernel,
182            executor: Rc::new(executor),
183            orbs: RefCell::new(BTreeMap::new()),
184            objects: RefCell::new(BTreeMap::new()),
185            scope_objects: RefCell::new(BTreeMap::new()),
186            observers: RefCell::new(BTreeMap::new()),
187            values: RefCell::new(BTreeMap::new()),
188            closers: RefCell::new(BTreeMap::new()),
189            openers: RefCell::new(BTreeMap::new()),
190            cancellations: RefCell::new(BTreeMap::new()),
191            context_signals: RefCell::new(BTreeMap::new()),
192            root_end_signals: RefCell::new(BTreeMap::new()),
193            call_signals: RefCell::new(BTreeMap::new()),
194            errors: RefCell::new(Vec::new()),
195            external_actions: Cell::new(false),
196            driver_wake: RefCell::new(None),
197            foreign_dispatcher: RefCell::new(None),
198            foreign_notifier: RefCell::new(None),
199            log_observer: RefCell::new(None),
200            flushing: Cell::new(false),
201            active: Cell::new(0),
202            settled_waker: futures::task::AtomicWaker::new(),
203            settled: RefCell::new(Vec::new()),
204            programs: RefCell::new(BTreeMap::new()),
205            prepared_programs: RefCell::new(BTreeMap::new()),
206        }))
207    }
208
209    /// Clone the shared kernel handle without copying its storage.
210    pub fn kernel(&self) -> core::Host {
211        self.0.kernel.clone()
212    }
213
214    /// Check whether two handles refer to the same native host.
215    pub(crate) fn same(&self, other: &Self) -> bool {
216        Rc::ptr_eq(&self.0, &other.0)
217    }
218
219    /// Check whether this adapter retains the orb implementation.
220    pub fn has_orb(&self, id: core::Id) -> bool {
221        self.0.orbs.borrow().contains_key(&id)
222    }
223
224    /// Give the shared JS adapter exclusive ownership of action dispatch.
225    pub fn delegate_actions(&self) {
226        self.0.external_actions.set(true);
227        if let Some((_, timer)) = self.0.deadline.borrow_mut().take() {
228            timer.abort();
229        }
230    }
231
232    /// Install compiled native orbs without replacing existing implementations.
233    pub fn install(&self, orbs: Vec<Orb>) -> Result<()> {
234        let current = self.kernel().installed_orbs();
235        if orbs.iter().any(|orb| {
236            current
237                .iter()
238                .any(|installed| installed.declaration.name == orb.metadata.name)
239        }) {
240            return Err(Error::invalid(
241                Reason::OrbInstalled,
242                "compiled native orbs cannot be replaced",
243            ));
244        }
245        #[cfg(feature = "hooks")]
246        self.validate_hooks(&orbs)?;
247        let reload = self.kernel().prepare(
248            orbs.iter().map(|orb| orb.metadata.clone()).collect(),
249            Vec::new(),
250        )?;
251        self.kernel().commit(reload.id, Vec::new())?;
252        let mut factories = Vec::new();
253        for (orb, info) in orbs.into_iter().zip(reload.orbs) {
254            factories.push(info.id);
255            self.0
256                .orb_factories
257                .borrow_mut()
258                .insert(info.id, orb.factory);
259            #[cfg(feature = "hooks")]
260            self.install_hooks(info.id, orb.hooks, orb.contributions)?;
261            self.0.orbs.borrow_mut().insert(info.id, orb.services);
262        }
263        for orb in factories {
264            self.ensure_orb(orb)?;
265        }
266        let pinned = self
267            .kernel()
268            .installed_orbs()
269            .into_iter()
270            .filter(|info| self.has_orb(info.id))
271            .flat_map(|info| info.declaration.services)
272            .filter(|service| service.lifetime == core::Lifetime::Host)
273            .collect::<Vec<_>>();
274        for service in pinned {
275            self.get(&service.name, vec!["main".into()], "host")?
276                .release()?;
277        }
278        Ok(())
279    }
280
281    /// Acquire an object reference and schedule its native activation.
282    pub fn get(&self, service: &str, key: Vec<String>, principal: &str) -> Result<Reference> {
283        self.get_with_options(
284            service,
285            key,
286            principal,
287            crate::AcquisitionOptions::default(),
288        )
289    }
290
291    /// Drain errors collected during callback execution and cleanup.
292    pub fn errors(&self) -> Vec<Error> {
293        std::mem::take(&mut *self.0.errors.borrow_mut())
294    }
295
296    /// Waits for physical callbacks and all resource closers; cancellation cannot force termination.
297    pub async fn close(&self) -> Result<()> {
298        if self.0.external_actions.get() {
299            return Err(Error::invalid(
300                Reason::Driver,
301                "the shared JS adapter owns host shutdown",
302            ));
303        }
304        self.kernel().close();
305        self.flush();
306        while self.0.active.get() != 0 {
307            let (send, receive) = oneshot::channel();
308            self.0.settled.borrow_mut().push(send);
309            let _ = receive.await;
310            self.flush();
311        }
312        self.finish_close()
313    }
314
315    /// Release native callback storage after the shared driver has physically settled shutdown.
316    /// The kernel refuses premature completion without discarding active owners.
317    pub fn finish_close(&self) -> Result<()> {
318        self.kernel().finish_close()?;
319        self.0.observers.borrow_mut().clear();
320        self.0.scopes.borrow_mut().clear();
321        self.0.driver_wake.borrow_mut().take();
322        self.0.foreign_dispatcher.borrow_mut().take();
323        self.0.root_references.borrow_mut().clear();
324        self.0.values.borrow_mut().clear();
325        self.0.orbs.borrow_mut().clear();
326        self.0.orb_values.borrow_mut().clear();
327        self.0.orb_errors.borrow_mut().clear();
328        self.0.orb_factories.borrow_mut().clear();
329        self.0.pending_orbs.borrow_mut().clear();
330        self.0.prepared_programs.borrow_mut().clear();
331        self.0.orb_scopes.borrow_mut().clear();
332        self.0.scope_activations.borrow_mut().clear();
333        self.0.host_resources.borrow_mut().clear();
334        self.0.foreign_notifier.borrow_mut().take();
335        self.0.log_observer.borrow_mut().take();
336        #[cfg(feature = "hooks")]
337        self.clear_hooks();
338        self.0.scope_objects.borrow_mut().clear();
339        if let Some(error) = self.errors().into_iter().next() {
340            return Err(error);
341        }
342        Ok(())
343    }
344}