tembra-runtime 0.3.0

Shared Rust host implementation for Tembra
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! A logical root stays pinned until physical work settles.

use super::*;

impl Host {
    /// Issue a context for an active root and matching invocation.
    pub fn context(&self, root: core::Id, invocation: Option<core::Invocation>) -> Result<Context> {
        self.kernel().check_root(root)?;
        if invocation.as_ref().is_some_and(|call| call.root != root) {
            return Err(Error::invalid(
                Reason::Context,
                "invocation belongs to another root",
            ));
        }
        Ok(Context {
            host: self.clone(),
            root,
            frame: invocation.as_ref().map_or(0, |call| call.context),
            call: invocation,
            signal: self.context_signal(root),
            owner: None,
        })
    }

    /// Run an operation while a guard retains its root lifetime.
    pub async fn root<T>(
        &self,
        principal: &str,
        operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>>,
    ) -> Result<T> {
        let root = self.kernel().begin_root(principal)?;
        let context = self.context(root, None)?;
        let _guard = RootGuard {
            host: self.clone(),
            root,
        };
        operation(context).await
    }
}

impl Host {
    /// Run a root operation as a task of this host instead of the caller's future.
    ///
    /// The root lives until the operation itself completes, whoever (if anyone) awaits the
    /// returned receiver: dropping it neither ends the root nor stops the operation. The task is
    /// tracked like every callback, so [`Host::close`] waits for it. Use it when work admitted
    /// under the root must outlive the caller's own wait, for example a response that keeps
    /// streaming after its headers were handed to the application.
    pub fn spawn_root<T: 'static>(
        &self,
        principal: &str,
        operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>> + 'static,
    ) -> Result<futures::channel::oneshot::Receiver<Result<T>>> {
        let host = self.clone();
        let principal = principal.to_owned();
        self.spawn(async move { host.root(&principal, operation).await })
    }
}

pub(super) struct RootGuard {
    pub(super) host: Host,
    pub(super) root: core::Id,
}

impl Drop for RootGuard {
    /// End the root's logical lifetime and dispatch pending cleanup.
    fn drop(&mut self) {
        if let Err(error) = self.host.kernel().end_root(self.root) {
            self.host.0.errors.borrow_mut().push(error);
        }
        self.host.end_context(self.root);
        self.host
            .notify_foreign(super::signals::ForeignNotification::RootEnded(self.root));
        self.host.flush();
    }
}

/// Contexts are issued by a host, and become unusable when their root or invocation ends.
#[derive(Clone)]
pub struct Context {
    frame: core::Id,
    pub(crate) host: Host,
    pub root: core::Id,
    call: Option<core::Invocation>,
    /// The root's signal, which every context of the root holds: a signal of the root or of its
    /// calls, first read once the kernel has forgotten the root, still finds whether it was
    /// cancelled.
    signal: Cancellation,
    /// The owner of the resource whose opener or closer runs with this context, which has no
    /// invocation: the Orb the record of a `log` is attributed to, and the object whose address
    /// `address` answers, for a resource of an object.
    owner: Option<Owner>,
}

/// The owner of a resource, as the context of its opener or closer knows it: the name of the Orb,
/// read when the resource is declared, since the opener of a resource a reload adds runs before
/// the kernel commits the new revision, and the closer of one a reload keeps runs after it has
/// forgotten the revision that declared it; none for a resource of the host, which no Orb owns.
#[derive(Clone)]
pub(super) struct Owner {
    pub(super) orb: Option<String>,
    pub(super) object: Option<core::Id>,
}

impl Context {
    /// This context as a resource's opener or closer gets it: attributed to the resource's owner,
    /// and, for an opener, cancelled with the resource's own signal.
    pub(super) fn owned(mut self, owner: Owner, signal: Option<Cancellation>) -> Self {
        self.owner = Some(owner);
        if let Some(signal) = signal {
            self.signal = signal;
        }
        self
    }
}

impl Context {
    /// Read the frame identity for local adapter calls.
    pub fn frame(&self) -> core::Id {
        self.frame
    }

    /// Derive values without extending identity or invocation lifetime.
    pub fn with<T: core::ContextDatum>(&self, key: &core::ContextKey<T>, value: T) -> Result<Self> {
        self.check()?;
        let frame = self.host.kernel().derive_context(
            self.root,
            self.frame,
            self.call.as_ref().map(|call| call.id),
            key.contract(),
            value.into_value(),
        )?;
        Ok(Self {
            host: self.host.clone(),
            root: self.root,
            call: self.call.clone(),
            frame,
            signal: self.signal.clone(),
            owner: self.owner.clone(),
        })
    }

    /// Retain the admitted isolated revision in this invocation's private execution ancestry.
    pub fn enter_execution(&self) -> Result<Self> {
        let call = self.invocation()?;
        let frame = self.host.kernel().enter_execution(call.id, self.frame)?;
        Ok(Self {
            host: self.host.clone(),
            root: self.root,
            call: self.call.clone(),
            frame,
            signal: self.signal.clone(),
            owner: self.owner.clone(),
        })
    }

    /// Read typed metadata while this invocation remains valid.
    pub fn value<T: core::ContextDatum>(&self, key: &core::ContextKey<T>) -> Result<Option<T>> {
        self.check()?;
        if self.frame == 0 {
            return Ok(None);
        }
        self.host
            .kernel()
            .context_value(self.root, self.frame, &key.contract())?
            .map(T::from_value)
            .transpose()
    }

    /// Reject an expired root, or a completed invocation or one its caller cancelled.
    pub fn check(&self) -> Result<()> {
        self.host.kernel().check_root(self.root)?;
        if let Some(call) = &self.call {
            self.host.kernel().check_call(call.id)?;
        }
        Ok(())
    }

    /// Signal root cancellation without releasing physical ownership.
    pub fn cancel(&self) -> Result<()> {
        self.host.kernel().cancel_root(self.root)?;
        self.host.cancel_context(self.root);
        self.host.flush();
        Ok(())
    }

    /// Read the identity retained by this root.
    pub fn principal(&self) -> Result<String> {
        self.host.kernel().root_principal(self.root)
    }

    /// Read the canonical address of the object running this invocation, as
    /// [`Declaration::address`] reads it while the object declares; in the opener or closer of an
    /// object's resource, the address of that object.
    pub fn address(&self) -> Result<core::Address> {
        let object = match (&self.call, &self.owner) {
            (Some(call), _) => call.object,
            (
                None,
                Some(Owner {
                    object: Some(object),
                    ..
                }),
            ) => *object,
            (None, _) => self.invocation()?.object,
        };
        self.host.kernel().object_address(object)
    }

    /// The name of the Orb a record of this context is attributed to: the one running the
    /// invocation, or the one owning the resource whose opener or closer runs, as it was named
    /// when the resource was declared.
    pub(super) fn attributed(&self) -> Result<String> {
        match (&self.call, &self.owner) {
            (Some(call), _) => Ok(self.host.kernel().orb(call.orb)?.declaration.name),
            (None, Some(Owner { orb: Some(orb), .. })) => Ok(orb.clone()),
            (None, _) => {
                let call = self.invocation()?;
                Ok(self.host.kernel().orb(call.orb)?.declaration.name)
            }
        }
    }

    /// The entered invocation that issues calls made from this context, if any.
    pub(crate) fn issuer(&self) -> Option<core::Id> {
        self.call.as_ref().map(|call| call.id)
    }

    /// Require an admitted call context for owner operations.
    pub fn invocation(&self) -> Result<core::Invocation> {
        self.call
            .clone()
            .ok_or_else(|| Error::invalid(Reason::Context, "an entered invocation is required"))
    }
}

impl Context {
    /// Observe cancellation of this operation's root, including host shutdown. An entered
    /// invocation's signal also fires when its caller cancels that invocation (or one it
    /// descends from); that never cancels the root or sibling calls.
    pub fn signal(&self) -> Cancellation {
        match &self.call {
            Some(call) => self.host.call_signal(self.root, &self.signal, call.id),
            None => self.signal.clone(),
        }
    }
}

impl Host {
    /// One shared signal per entered invocation, created when first observed: cancelled at once
    /// if its root or the invocation itself already was. The root's signal answers for the root,
    /// as a signal read earlier would: its normal end cancels nothing of the call.
    fn call_signal(
        &self,
        root: core::Id,
        root_signal: &Cancellation,
        call: core::Id,
    ) -> Cancellation {
        let mut signals = self.0.call_signals.borrow_mut();
        signals.retain(|_, (_, signal)| signal.strong_count() != 0);
        if let Some(signal) = signals.get(&call).and_then(|(_, signal)| signal.upgrade()) {
            return Cancellation(signal);
        }
        let signal = Cancellation::new("root");
        if root_signal.is_cancelled() {
            signal.cancel();
        } else if self.kernel().call_cancelled(call) {
            signal.cancel_because("call");
        }
        signals.insert(call, (root, Rc::downgrade(&signal.0)));
        signal
    }

    /// Mirror a kernel call cancellation into that invocation's signal, if it is observed.
    pub fn cancel_call_signal(&self, call: core::Id) {
        let signal = self
            .0
            .call_signals
            .borrow()
            .get(&call)
            .and_then(|(_, signal)| signal.upgrade());
        if let Some(signal) = signal {
            Cancellation(signal).cancel_because("call");
        }
    }

    /// The signal of a root, for a context of it: the one its other contexts hold, or a new one.
    /// A context is issued only for a root neither ended nor cancelled, so a new signal starts
    /// uncancelled, and the root's cancellation reaches it while a context holds it.
    fn context_signal(&self, root: core::Id) -> Cancellation {
        let mut signals = self.0.context_signals.borrow_mut();
        // Each context of a root asks for its signal: only a new one sweeps the released ones.
        if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
            return Cancellation(signal);
        }
        signals.retain(|_, signal| signal.strong_count() != 0);
        let signal = Cancellation::new("root");
        signals.insert(root, Rc::downgrade(&signal.0));
        signal
    }

    /// Private lifecycle notification for waiting acquisition, never exposed as Context::signal.
    /// Normal root completion must not cancel admitted or streaming physical work.
    fn root_end_signal(&self, root: core::Id) -> Cancellation {
        let mut signals = self.0.root_end_signals.borrow_mut();
        signals.retain(|_, signal| signal.strong_count() != 0);
        if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
            return Cancellation(signal);
        }
        let signal = Cancellation::new("root_end");
        if self.kernel().check_root(root).is_err() {
            signal.cancel();
        }
        signals.insert(root, Rc::downgrade(&signal.0));
        signal
    }

    /// Mirror a shared kernel cancellation action into native context signals, and cancel the
    /// stream ends delivered to this root at once.
    pub fn cancel_context(&self, root: core::Id) {
        if let Some(signal) = self
            .0
            .context_signals
            .borrow()
            .get(&root)
            .and_then(std::rc::Weak::upgrade)
        {
            Cancellation(signal).cancel();
        }
        // Signals of the root's entered invocations observe the root too.
        let calls: Vec<_> = self
            .0
            .call_signals
            .borrow()
            .values()
            .filter(|(owner, _)| *owner == root)
            .filter_map(|(_, signal)| signal.upgrade())
            .collect();
        for signal in calls {
            Cancellation(signal).cancel_because("root");
        }
        for stream in self.root_streams(root, false) {
            stream.cancel_root();
        }
    }

    /// Bind a delivered stream end to the root that received it.
    pub(crate) fn bind_root_stream(
        &self,
        root: core::Id,
        stream: std::rc::Weak<dyn crate::portable::RootStream>,
    ) -> Result<()> {
        self.kernel().check_root(root)?;
        let mut claims = self.0.root_references.borrow_mut();
        let streams = &mut claims.entry(root).or_default().streams;
        streams.retain(|stream| stream.strong_count() != 0);
        streams.push(stream);
        Ok(())
    }

    /// The live stream ends of a root, taken out of the registry when the root ends. Collected
    /// first, so a stream's close never runs while the registry is borrowed.
    fn root_streams(&self, root: core::Id, take: bool) -> Vec<Rc<dyn crate::portable::RootStream>> {
        let mut claims = self.0.root_references.borrow_mut();
        let Some(claims) = claims.get_mut(&root) else {
            return Vec::new();
        };
        let streams = if take {
            std::mem::take(&mut claims.streams)
        } else {
            claims.streams.clone()
        };
        streams.iter().filter_map(std::rc::Weak::upgrade).collect()
    }
}

impl Context {
    /// Acquire a reference whose claim is revoked when this operation's root ends.
    pub fn get(
        &self,
        service: &str,
        key: Vec<String>,
        options: crate::AcquisitionOptions,
    ) -> Result<Rc<Reference>> {
        self.check()?;
        let reference =
            Rc::new(
                self.host
                    .get_with_options(service, key, &self.principal()?, options)?,
            );
        self.host
            .0
            .root_references
            .borrow_mut()
            .entry(self.root)
            .or_default()
            .references
            .push(reference.clone());
        Ok(reference)
    }
}

impl Context {
    /// Acquire under this root after the exact previous instance physically closes.
    /// Cancellation or root expiry ends only this wait; it never interrupts the old cleanup.
    /// The principal, context and admission requirements are checked again on every attempt.
    /// Use [`Reference::ready`] separately to await the new instance's activation.
    pub async fn get_wait(
        &self,
        service: &str,
        key: Vec<String>,
        options: crate::AcquisitionOptions,
    ) -> Result<Rc<Reference>> {
        let signal = self.signal();
        loop {
            match self.get(service, key.clone(), options.clone()) {
                Ok(reference) => return Ok(reference),
                Err(error) => {
                    let wait = self
                        .host
                        .closing(service, &key, &self.principal()?, error)?;
                    let root_signal = self.host.root_end_signal(self.root);
                    let cancelled = std::pin::pin!(async {
                        let call = std::pin::pin!(signal.cancelled());
                        let root = std::pin::pin!(root_signal.cancelled());
                        futures::future::select(call, root).await;
                    });
                    let wait = std::pin::pin!(wait);
                    if let futures::future::Either::Left(_) =
                        futures::future::select(cancelled, wait).await
                    {
                        self.check()?;
                        signal.check()?;
                        root_signal.check()?;
                    }
                }
            }
        }
    }

    /// Access the native environment shared by the currently entered orb.
    pub fn orb<T: 'static>(&self) -> Result<Rc<T>> {
        self.check()?;
        let call = self.invocation()?;
        self.host
            .0
            .orb_values
            .borrow()
            .get(&call.orb)
            .cloned()
            .ok_or_else(|| Error::invalid(Reason::Orb, "orb environment unavailable"))?
            .downcast::<T>()
            .map_err(|_| type_error())
    }

    /// Access a host-owned resource during an active operation.
    pub fn resource<T: 'static>(&self, name: &str) -> Result<Resource<T>> {
        self.check()?;
        self.host.resource(name)
    }
}

impl Host {
    /// Revoke native claims acquired inside a root whose logical wait has ended.
    /// Shared drivers call this for roots they issue themselves.
    /// Stream ends delivered to the root are closed first, so their producers stop before the
    /// root's claims are revoked; a retained end then refuses every read.
    pub fn end_context(&self, root: core::Id) {
        let ended = self
            .0
            .root_end_signals
            .borrow_mut()
            .remove(&root)
            .and_then(|signal| signal.upgrade());
        if let Some(ended) = ended {
            Cancellation(ended).cancel();
        }
        for stream in self.root_streams(root, true) {
            stream.end_root();
        }
        let references = self
            .0
            .root_references
            .borrow_mut()
            .remove(&root)
            .unwrap_or_default()
            .references;
        for reference in references {
            if let Err(error) = reference.release() {
                self.0.errors.borrow_mut().push(error);
            }
        }
    }
}