tembra-runtime 0.4.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
use crate::core::Reason;
use crate::{
    Context, Declaration, Error, Result, core,
    portable::{Outcome, Payload},
};
use futures::{FutureExt, future::LocalBoxFuture};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
#[cfg(feature = "views")]
use std::collections::BTreeSet;
use std::{any::Any, collections::BTreeMap, future::Future, rc::Rc};

pub(crate) type Data = Rc<dyn Any>;
pub(crate) type Factory = Rc<dyn Fn(Declaration) -> Result<Data>>;
pub(crate) type LocalMethod =
    Rc<dyn Fn(Data, Context, Box<dyn Any>) -> LocalBoxFuture<'static, Result<Box<dyn Any>>>>;
pub(crate) type PortableMethod =
    Rc<dyn Fn(Data, Context, Payload) -> LocalBoxFuture<'static, Result<Outcome>>>;
pub(crate) type BeforeCreate = Rc<dyn Fn() -> LocalBoxFuture<'static, Result<Data>>>;
#[cfg(feature = "views")]
type Access = Rc<dyn Fn(&str) -> BTreeSet<String>>;

#[derive(Clone)]
pub(crate) struct Implementation {
    pub factory: Factory,
    pub local: BTreeMap<String, LocalMethod>,
    pub portable: BTreeMap<String, PortableMethod>,
    pub before_create: Option<BeforeCreate>,
    #[cfg(feature = "rpc")]
    pub contract: Option<Result<(String, tembra_contracts::PreparedContract, String)>>,
    #[cfg(feature = "views")]
    pub access: Option<Access>,
}

/// A typed service. Methods execute once; only the portable entrypoint invokes serde.
pub struct Service<E> {
    pub(crate) metadata: core::Service,
    pub(crate) implementation: Implementation,
    marker: std::marker::PhantomData<E>,
}

/// How a method bound with [`Service::method_with`] reads its portable arguments and writes its
/// result, in place of serde, so its Rust types need no serde implementation.
pub struct Codec<A, R> {
    /// Read the arguments' JSON, or refuse it with a message: the call then fails with
    /// [`Reason::Arguments`] before its callback runs.
    pub decode: fn(Value) -> std::result::Result<A, String>,
    /// Write the result as JSON, or refuse it with a message: the call then fails with
    /// [`Reason::Result`].
    pub encode: fn(R) -> std::result::Result<Value, String>,
}

impl<E: 'static> Service<E> {
    /// Create a native declaration with explicit identity and default options.
    pub fn new(
        name: impl Into<String>,
        create: impl Fn(Declaration) -> Result<E> + 'static,
    ) -> Self {
        Self {
            metadata: core::Service::new(name, std::iter::empty::<String>()),
            implementation: Implementation {
                factory: Rc::new(move |declaration| Ok(Rc::new(create(declaration)?) as Data)),
                local: BTreeMap::new(),
                portable: BTreeMap::new(),
                before_create: None,
                #[cfg(feature = "rpc")]
                contract: None,
                #[cfg(feature = "views")]
                access: None,
            },
            marker: std::marker::PhantomData,
        }
    }

    /// Wait for an adapter's executor before running the synchronous declaration factory.
    pub fn before_create<P, F, Fut>(mut self, prepare: F) -> Self
    where
        P: 'static,
        F: Fn() -> Fut + 'static,
        Fut: Future<Output = Result<P>> + 'static,
    {
        self.implementation.before_create = Some(Rc::new(move || {
            let ready = prepare();
            async move { Ok(Rc::new(ready.await?) as Data) }.boxed_local()
        }));
        self
    }

    /// Declare the canonical ABI signature used by typed dependency admission.
    pub fn signature(mut self, signature: Option<String>) -> Self {
        self.metadata.signature = signature;
        self
    }

    /// Decode the service's immutable WIT once for RPC validation before provider execution.
    pub fn contract(self, binding: impl Into<String>, prepared: &[u8]) -> Self {
        let binding = binding.into();
        #[cfg(feature = "rpc")]
        {
            let mut service = self;
            service.implementation.contract = Some((|| {
                let contract = tembra_contracts::PreparedContract::decode(prepared)
                    .map_err(|error| Error::invalid("contract", error.to_string()))?;
                let signature = contract
                    .service_signatures()
                    .map_err(|error| Error::invalid("contract", error.to_string()))?
                    .remove(&binding)
                    .ok_or_else(|| Error::invalid("contract", "missing service signature"))?;
                Ok((binding, contract, signature))
            })());
            service
        }
        #[cfg(not(feature = "rpc"))]
        {
            let _ = (binding, prepared);
            self
        }
    }

    /// Set the ownership policy and optional idle retention period.
    pub fn lifetime(mut self, lifetime: core::Lifetime, linger_ms: u32) -> Self {
        self.metadata.lifetime = lifetime;
        self.metadata.linger_ms = linger_ms;
        self
    }

    /// Bind one callback to typed local and portable entrypoints.
    pub fn method<A, R, F, Fut>(mut self, name: impl Into<String>, handle: F) -> Self
    where
        A: DeserializeOwned + 'static,
        R: Serialize + 'static,
        F: Fn(Rc<E>, Context, A) -> Fut + 'static,
        Fut: Future<Output = Result<R>> + 'static,
    {
        let name = name.into();
        let handle = Rc::new(handle);
        let portable = handle.clone();
        self.implementation.local.insert(
            name.clone(),
            Rc::new(move |environment, context, arguments| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .and_then(|environment| {
                        let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
                        Ok(handle(environment, context, *arguments))
                    });
                async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
            }),
        );
        self.implementation.portable.insert(
            name.clone(),
            Rc::new(move |environment, context, arguments: Payload| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .and_then(|environment| {
                        // Serde methods take data only; capabilities are refused and closed.
                        let arguments =
                            serde_json::from_value(arguments.data_only()?).map_err(|error| {
                                Error::invalid(Reason::Arguments, error.to_string())
                            })?;
                        Ok(portable(environment, context, arguments))
                    });
                async move {
                    serde_json::to_value(result?.await?)
                        .map(|value| Payload::data(value).into())
                        .map_err(|error| Error::invalid(Reason::Result, error.to_string()))
                }
                .boxed_local()
            }),
        );
        self.metadata.methods.insert(name);
        self
    }

    /// Bind one callback to a typed local entrypoint, as [`Service::method`] does, and to a
    /// portable entrypoint that reads the arguments and writes the result with `codec` instead
    /// of serde. Local calls never run the codec.
    pub fn method_with<A, R, F, Fut>(
        mut self,
        name: impl Into<String>,
        handle: F,
        codec: Codec<A, R>,
    ) -> Self
    where
        A: 'static,
        R: 'static,
        F: Fn(Rc<E>, Context, A) -> Fut + 'static,
        Fut: Future<Output = Result<R>> + 'static,
    {
        let name = name.into();
        let handle = Rc::new(handle);
        let portable = handle.clone();
        let Codec { decode, encode } = codec;
        self.implementation.local.insert(
            name.clone(),
            Rc::new(move |environment, context, arguments| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .and_then(|environment| {
                        let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
                        Ok(handle(environment, context, *arguments))
                    });
                async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
            }),
        );
        self.implementation.portable.insert(
            name.clone(),
            Rc::new(move |environment, context, arguments: Payload| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .and_then(|environment| {
                        // Codec methods take data only; capabilities are refused and closed.
                        let arguments = decode(arguments.data_only()?)
                            .map_err(|message| Error::invalid(Reason::Arguments, message))?;
                        Ok(portable(environment, context, arguments))
                    });
                async move {
                    encode(result?.await?)
                        .map(|value| Payload::data(value).into())
                        .map_err(|message| Error::invalid(Reason::Result, message))
                }
                .boxed_local()
            }),
        );
        self.metadata.methods.insert(name);
        self
    }
}

impl<E: 'static> Service<E> {
    /// Bind a host-local callback with typed Rust values and no portable entrypoint.
    ///
    /// The method exists only for callers in this process that hold the exact argument type, such
    /// as an executor's lifecycle adapter carrying owned host resources. Every portable access
    /// (`call_portable`, `Host::invoke_portable`, foreign hosts and isolated Orb references) is refused with
    /// [`Reason::LocalValue`] before the callback runs; no serde conversion is ever attempted.
    pub fn local_method<A, R, F, Fut>(mut self, name: impl Into<String>, handle: F) -> Self
    where
        A: 'static,
        R: 'static,
        F: Fn(Rc<E>, Context, A) -> Fut + 'static,
        Fut: Future<Output = Result<R>> + 'static,
    {
        let name = name.into();
        let handle = Rc::new(handle);
        self.implementation.local.insert(
            name.clone(),
            Rc::new(move |environment, context, arguments| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .and_then(|environment| {
                        let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
                        Ok(handle(environment, context, *arguments))
                    });
                async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
            }),
        );
        self.implementation.portable.remove(&name);
        self.metadata.methods.insert(name);
        self
    }
}

impl<E: 'static> Service<E> {
    /// Bind a portable-only callback that receives and returns the whole [`Payload`], including
    /// host-issued capabilities. It is the entrypoint for executors that issue resources. It has
    /// no typed local entrypoint, so [`crate::Reference::call`] refuses it.
    ///
    /// The callback returns a [`Payload`], or an [`Outcome`] when the call keeps physically
    /// working after its result (a stream's producer, for example).
    pub fn payload_method<F, Fut, R>(mut self, name: impl Into<String>, handle: F) -> Self
    where
        F: Fn(Rc<E>, Context, Payload) -> Fut + 'static,
        Fut: Future<Output = Result<R>> + 'static,
        R: Into<Outcome> + 'static,
    {
        let name = name.into();
        let handle = Rc::new(handle);
        self.implementation.portable.insert(
            name.clone(),
            Rc::new(move |environment, context, payload| {
                let result = environment
                    .downcast::<E>()
                    .map_err(|_| type_error())
                    .map(|environment| handle(environment, context, payload));
                async move { result?.await.map(Into::into) }.boxed_local()
            }),
        );
        self.implementation.local.remove(&name);
        self.metadata.methods.insert(name);
        self
    }
}

impl Implementation {
    /// Whether a method has only a typed local entrypoint.
    pub(crate) fn local_only(&self, method: &str) -> bool {
        self.local.contains_key(method) && !self.portable.contains_key(method)
    }
}

/// Report an argument or result type mismatch at native dispatch.
pub(crate) fn type_error() -> Error {
    Error::invalid(
        Reason::RustType,
        "native argument or result type does not match the method",
    )
}

/// The Orb that answers what a native Orb consumes from another: the name and API version it is
/// installed under. An Orb that `#[tembra::orb]` generates takes one per imported interface and
/// per hook it contributes to, as the fields of its `Providers`, which `orb(..)` requires.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Provider {
    /// The provider's Orb name.
    pub name: String,
    /// The API version the provider is installed at.
    pub api_version: u32,
}

impl Provider {
    /// The Orb `name` at `api_version`.
    pub fn new(name: impl Into<String>, api_version: u32) -> Self {
        Self {
            name: name.into(),
            api_version,
        }
    }
}

/// Native Orb declarations compile with the application and dispatch typed Rust callbacks.
pub struct Orb {
    pub(crate) metadata: core::Orb,
    pub(crate) factory: Factory,
    pub(crate) services: BTreeMap<String, Implementation>,
    #[cfg(feature = "hooks")]
    pub(crate) hooks: BTreeMap<String, crate::hooks::Signature>,
    #[cfg(feature = "hooks")]
    pub(crate) contributions: Vec<crate::hooks::Contribution>,
}

impl Orb {
    /// Create a native declaration with explicit identity and default options.
    pub fn new(name: impl Into<String>, api_version: u32) -> Self {
        Self {
            metadata: core::Orb::new(name, api_version),
            factory: Rc::new(|_| Ok(Rc::new(()) as Data)),
            services: BTreeMap::new(),
            #[cfg(feature = "hooks")]
            hooks: BTreeMap::new(),
            #[cfg(feature = "hooks")]
            contributions: Vec::new(),
        }
    }

    /// Inspect this Orb's declared services, signatures and requirements without installing it
    /// or running factories. Executable callbacks remain private.
    pub fn declaration(&self) -> &core::Orb {
        &self.metadata
    }

    /// Add an explicit versioned orb dependency.
    pub fn requires(mut self, requirement: core::Requirement) -> Self {
        self.metadata.requires.push(requirement);
        #[cfg(feature = "hooks")]
        self.bind_hook_requirements();
        self
    }

    /// Mark an executor-backed orb whose every revision owns a private resource realm.
    pub fn isolated(mut self) -> Self {
        self.metadata.isolated = true;
        self
    }

    /// Attach a typed service and its callback implementation.
    pub fn service<E>(mut self, service: Service<E>) -> Self {
        self.services
            .insert(service.metadata.name.clone(), service.implementation);
        self.metadata.services.push(service.metadata);
        self
    }
}

#[cfg(feature = "hooks")]
impl Orb {
    /// Declare an orb-owned hook contract.
    pub fn hook<A: 'static, R: 'static>(mut self, hook: crate::Hook<A, R>) -> Self {
        if let Some(signature) = &hook.wit {
            self.metadata
                .hook_signatures
                .insert(hook.name.clone(), signature.clone());
        }
        self.hooks.insert(hook.name.clone(), hook.identity());
        self.metadata.hooks.insert(hook.name);
        self
    }

    /// Register a WIT-checked executor callback in the ordinary contribution plan.
    #[doc(hidden)]
    pub fn contribute_portable<F, Fut>(
        mut self,
        target: impl Into<String>,
        hook: impl Into<String>,
        signature: impl Into<String>,
        priority: i32,
        handle: F,
    ) -> Self
    where
        F: Fn(Context, Value) -> Fut + 'static,
        Fut: Future<Output = Result<Option<Value>>> + 'static,
    {
        self.contributions.push(crate::hooks::Contribution {
            target: target.into(),
            hook: hook.into(),
            priority,
            signature: crate::hooks::Signature {
                native: None,
                wit: Some(signature.into()),
            },
            local: None,
            portable: Rc::new(move |context, value| handle(context, value).boxed_local()),
        });
        self.bind_hook_requirements();
        self
    }

    /// Contribute a typed callback. External targets must also be listed in `requires`.
    /// Lower priorities run first; ties retain contribution registration order.
    pub fn contribute<A, R, F, Fut>(
        mut self,
        target: impl Into<String>,
        hook: &crate::Hook<A, R>,
        priority: i32,
        handle: F,
    ) -> Self
    where
        A: DeserializeOwned + 'static,
        R: 'static,
        F: Fn(Context, A) -> Fut + 'static,
        Fut: Future<Output = Result<R>> + 'static,
    {
        self.contributions
            .push(hook.contribution(target.into(), priority, handle));
        self.bind_hook_requirements();
        self
    }

    /// Keep WIT requirements in the kernel graph regardless of the builder's declaration order.
    fn bind_hook_requirements(&mut self) {
        for contribution in &self.contributions {
            let Some(signature) = &contribution.signature.wit else {
                continue;
            };
            for requirement in &mut self.metadata.requires {
                if requirement.orb == contribution.target
                    && requirement.hooks.contains(&contribution.hook)
                {
                    requirement
                        .hook_signatures
                        .entry(contribution.hook.clone())
                        .or_insert_with(|| signature.clone());
                }
            }
        }
    }
}

impl Orb {
    /// Create one shared environment for this orb and declare orb-owned resources and work.
    pub fn create<T: 'static>(
        mut self,
        create: impl Fn(Declaration) -> Result<T> + 'static,
    ) -> Self {
        self.factory = Rc::new(move |declaration| Ok(Rc::new(create(declaration)?) as Data));
        self
    }
}

#[cfg(feature = "views")]
impl<E: 'static> Service<E> {
    /// Restrict acquired references to the methods permitted for their principal.
    pub fn access(mut self, policy: impl Fn(&str) -> BTreeSet<String> + 'static) -> Self {
        self.implementation.access = Some(Rc::new(policy));
        self
    }
}