Skip to main content

tembra_runtime/host/
tasks.rs

1//! Scope-owned background work remains pinned until actual callback settlement.
2use super::context::RootGuard;
3use super::*;
4
5/// Authority for one declared in-memory background task.
6#[derive(Clone)]
7pub struct TaskScope {
8    host: Host,
9    task: core::Id,
10    orb: core::Id,
11    object: Option<core::Id>,
12    operation: core::Id,
13    principal: String,
14    signal: Cancellation,
15}
16
17impl TaskScope {
18    /// Observe task cancellation without treating it as physical completion.
19    pub fn signal(&self) -> Cancellation {
20        self.signal.clone()
21    }
22
23    /// Run a managed operation with the owner's identity and the current published code version.
24    pub async fn root<T: 'static>(
25        &self,
26        operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>>,
27    ) -> Result<T> {
28        self.signal.check()?;
29        let root = self.host.kernel().task_root(self.task, &self.principal)?;
30        let _root = RootGuard {
31            host: self.host.clone(),
32            root,
33        };
34        let call =
35            self.host
36                .kernel()
37                .begin_operation(self.orb, root, self.operation, self.object)?;
38        let context = self.host.context(root, Some(call.clone()))?;
39        let future = operation(context);
40        let receive = self.host.spawn_managed(call.id, future)?;
41        receive
42            .await
43            .map_err(|_| Error::invalid(Reason::Executor, "task operation executor stopped"))?
44    }
45}
46
47impl Declaration {
48    /// Declare background work to start after this scope is activated.
49    pub fn task(
50        &self,
51        start: impl FnOnce(TaskScope) -> LocalBoxFuture<'static, Result<()>> + 'static,
52    ) -> Result<()> {
53        self.check_declaration()?;
54        if self.orb == 0 {
55            return Err(Error::invalid(
56                Reason::Task,
57                "host tasks require an orb owner",
58            ));
59        }
60        self.draft.tasks.borrow_mut().push(Box::new(start));
61        Ok(())
62    }
63}
64
65impl Host {
66    pub(super) fn start_scope(&self, scope: core::Id) -> Result<()> {
67        let (owner, orb, starts) = {
68            let scopes = self.0.scopes.borrow();
69            let Some(scope) = scopes.get(&scope) else {
70                return Ok(());
71            };
72            (scope.owner, scope.orb, scope.draft.tasks.take())
73        };
74        for start in starts {
75            let task = self.kernel().begin_task(owner)?;
76            let object = match owner {
77                core::Owner::Object(object) => Some(object),
78                _ => None,
79            };
80            let principal = object
81                .map(|object| {
82                    self.kernel()
83                        .object_address(object)
84                        .map(|address| address.principal)
85                })
86                .transpose()?
87                .unwrap_or_else(|| "host".into());
88            let signal = Cancellation::new("task");
89            let authority = TaskScope {
90                host: self.clone(),
91                task,
92                orb,
93                object,
94                operation: self.kernel().allocate_handle()?,
95                principal,
96                signal: signal.clone(),
97            };
98            self.0
99                .task_signals
100                .borrow_mut()
101                .insert(task, signal.clone());
102            self.0
103                .scopes
104                .borrow_mut()
105                .get_mut(&scope)
106                .expect("declared scope")
107                .tasks
108                .push(task);
109            let guard = TaskGuard {
110                host: self.clone(),
111                task,
112            };
113            let host = self.clone();
114            let receive = self.spawn(async move {
115                let _guard = guard;
116                // A task that panics fails as one that returns an error does.
117                let ended = std::panic::AssertUnwindSafe(async move { start(authority).await })
118                    .catch_unwind()
119                    .await
120                    .unwrap_or_else(|_| {
121                        Err(Error::new(
122                            core::Code::Unavailable,
123                            "callback",
124                            "native callback panicked",
125                        ))
126                    });
127                if let Err(error) = ended
128                    && !signal.is_cancelled()
129                {
130                    host.0.errors.borrow_mut().push(error);
131                }
132                Ok(())
133            })?;
134            drop(receive);
135        }
136        Ok(())
137    }
138
139    pub(super) fn stop_scope(&self, scope: core::Id) -> Result<()> {
140        let tasks = self
141            .0
142            .scopes
143            .borrow()
144            .get(&scope)
145            .map(|scope| scope.tasks.clone())
146            .unwrap_or_default();
147        for task in tasks {
148            if self.0.task_signals.borrow().contains_key(&task) {
149                self.kernel().stop_task(task)?;
150                self.cancel_task(task);
151            }
152        }
153        Ok(())
154    }
155
156    /// Mirror a shared kernel task-cancellation action into its native signal.
157    pub fn cancel_task(&self, task: core::Id) {
158        if let Some(signal) = self.0.task_signals.borrow().get(&task) {
159            signal.cancel();
160        }
161    }
162
163    pub(crate) fn spawn_managed<T: 'static>(
164        &self,
165        call: core::Id,
166        operation: impl Future<Output = Result<T>> + 'static,
167    ) -> Result<oneshot::Receiver<Result<T>>> {
168        self.spawn_managed_settling(call, async move { (operation.await, None) })
169    }
170
171    /// Run an admitted call whose logical result may be published before its physical work
172    /// ends. The invocation stays admitted until that work ends: the call's one guard moves
173    /// into the remaining work, so `finish_call` runs exactly when it settles. An ordinary call
174    /// finishes before its result is sent, as always.
175    pub(crate) fn spawn_managed_settling<T: 'static>(
176        &self,
177        call: core::Id,
178        operation: impl Future<Output = (Result<T>, Option<Physical>)> + 'static,
179    ) -> Result<oneshot::Receiver<Result<T>>> {
180        let guard = InvocationGuard {
181            host: self.clone(),
182            call,
183        };
184        self.spawn_settling(async move {
185            let (result, physical) = operation.await;
186            let physical = physical.map(|physical| {
187                async move {
188                    let settled = physical.await;
189                    drop(guard);
190                    settled
191                }
192                .boxed_local()
193            });
194            (result, physical)
195        })
196    }
197}
198
199struct TaskGuard {
200    host: Host,
201    task: core::Id,
202}
203impl Drop for TaskGuard {
204    fn drop(&mut self) {
205        if !self.host.0.external_actions.get() {
206            self.host.tick();
207        }
208        if let Err(error) = self.host.kernel().finish_task(self.task) {
209            self.host.0.errors.borrow_mut().push(error);
210        }
211        self.host.0.task_signals.borrow_mut().remove(&self.task);
212        self.host.flush();
213    }
214}
215
216struct InvocationGuard {
217    host: Host,
218    call: core::Id,
219}
220impl Drop for InvocationGuard {
221    fn drop(&mut self) {
222        if !self.host.0.external_actions.get() {
223            self.host.tick();
224        }
225        if let Err(error) = self.host.kernel().finish_call(self.call) {
226            self.host.0.errors.borrow_mut().push(error);
227        }
228        self.host.flush();
229    }
230}