Skip to main content

tembra_core/
model.rs

1use crate::Error;
2use std::collections::{BTreeMap, BTreeSet};
3
4/// Host-local identities are never reused. Generated IDs fit exactly in a JavaScript Number;
5/// zero is reserved for an absent identity.
6pub type Id = u64;
7/// Largest generated identity, shared by every adapter without JSON precision loss.
8pub const MAX_ID: Id = (1 << 53) - 1;
9pub type Version = u32;
10
11/// Stable identity. Tuple boundaries are preserved; keys are not delimiter-joined.
12#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
13pub struct Address {
14    pub service: String,
15    pub key: Vec<String>,
16    pub principal: String,
17}
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum Lifetime {
21    Referenced,
22    Host,
23}
24
25impl Lifetime {
26    /// Return the stable wire name for this variant.
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Referenced => "referenced",
30            Self::Host => "host",
31        }
32    }
33}
34
35/// The members every reference to a service object has, which the kernel refuses as method names
36/// when it installs an Orb, in the lowerCamelCase spelling of the official JavaScript bindings.
37pub const RESERVED_MEMBERS: [&str; 6] = ["then", "release", "state", "ready", "status", "opaque"];
38
39/// Whether a service method's name is a member every reference has, one of [`RESERVED_MEMBERS`],
40/// which the kernel refuses when it installs an Orb.
41pub fn reserved_member(name: &str) -> bool {
42    RESERVED_MEMBERS.contains(&name)
43}
44
45/// Whether the kernel admits the version of a state or of a resource's contract: versions start
46/// at 1.
47pub const fn valid_version(version: Version) -> bool {
48    version != 0
49}
50
51/// Whether the kernel admits a service's objects of `lifetime` lingering `linger_ms` once
52/// unreferenced: a host-lifetime object lives until the host closes, and never lingers.
53pub const fn admits_linger(lifetime: Lifetime, linger_ms: u32) -> bool {
54    !matches!(lifetime, Lifetime::Host) || linger_ms == 0
55}
56
57/// The principal the host creates host-lifetime objects for itself as, when it installs the Orb.
58pub const HOST_PRINCIPAL: &str = "host";
59
60/// Whether the kernel admits an object of `lifetime` acquired by `principal`: a host-lifetime
61/// object belongs to the host, [`HOST_PRINCIPAL`].
62pub fn admits_principal(lifetime: Lifetime, principal: &str) -> bool {
63    !matches!(lifetime, Lifetime::Host) || principal == HOST_PRINCIPAL
64}
65
66/// Whether the kernel admits an object of `lifetime` at `address`: a host-lifetime object lives
67/// at the key `main` of the host principal (`admits_principal`).
68pub(crate) fn admits_address(lifetime: Lifetime, address: &Address) -> bool {
69    !matches!(lifetime, Lifetime::Host)
70        || (address.key == ["main"] && admits_principal(lifetime, &address.principal))
71}
72
73#[derive(Clone, Debug, Eq, PartialEq)]
74pub struct Service {
75    /// Canonical contract identity when this service participates in typed ABI matching.
76    pub signature: Option<String>,
77    pub name: String,
78    pub methods: BTreeSet<String>,
79    pub lifetime: Lifetime,
80    /// Keeps an unreferenced object and its tasks live until this idle duration expires.
81    pub linger_ms: u32,
82}
83
84impl Service {
85    /// Create a declaration with explicit identity and default options.
86    pub fn new(
87        name: impl Into<String>,
88        methods: impl IntoIterator<Item = impl Into<String>>,
89    ) -> Self {
90        Self {
91            signature: None,
92            name: name.into(),
93            methods: methods.into_iter().map(Into::into).collect(),
94            lifetime: Lifetime::Referenced,
95            linger_ms: 0,
96        }
97    }
98}
99
100#[derive(Clone, Debug, Eq, PartialEq)]
101pub struct Requirement {
102    pub signatures: BTreeMap<String, String>,
103    pub hook_signatures: BTreeMap<String, String>,
104    pub orb: String,
105    pub api_version: Version,
106    pub methods: BTreeMap<String, BTreeSet<String>>,
107    pub hooks: BTreeSet<String>,
108}
109
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub struct Orb {
112    pub name: String,
113    pub api_version: Version,
114    pub services: Vec<Service>,
115    pub requires: Vec<Requirement>,
116    pub hooks: BTreeSet<String>,
117    pub hook_signatures: BTreeMap<String, String>,
118    /// Executor-backed revisions own a private resource realm instead of sharing native values.
119    pub isolated: bool,
120}
121
122impl Orb {
123    /// Create a declaration with explicit identity and default options.
124    pub fn new(name: impl Into<String>, api_version: Version) -> Self {
125        Self {
126            name: name.into(),
127            api_version,
128            services: Vec::new(),
129            requires: Vec::new(),
130            hooks: BTreeSet::new(),
131            hook_signatures: BTreeMap::new(),
132            isolated: false,
133        }
134    }
135}
136
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct InstalledOrb {
139    pub id: Id,
140    pub owner: Id,
141    pub code_version: Version,
142    pub declaration: Orb,
143}
144
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum Status {
147    Loading,
148    Live,
149    Released,
150    Gone,
151}
152
153impl Status {
154    /// Return the stable wire name for this variant.
155    pub const fn as_str(self) -> &'static str {
156        match self {
157            Self::Loading => "loading",
158            Self::Live => "live",
159            Self::Released => "released",
160            Self::Gone => "gone",
161        }
162    }
163}
164
165#[derive(Clone, Debug, Eq, PartialEq)]
166pub struct Acquisition {
167    pub reference: Id,
168    pub object: Id,
169    pub orb: Id,
170    pub code_version: Version,
171    pub activate: bool,
172}
173
174/// An admitted physical invocation. Finishing its observer does not finish this invocation.
175#[derive(Clone, Debug, Eq, PartialEq)]
176pub struct Invocation {
177    pub context: Id,
178    pub id: Id,
179    pub root: Id,
180    pub object: Id,
181    pub orb: Id,
182    pub code_version: Version,
183    pub method: String,
184}
185
186#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
187pub enum Owner {
188    Host,
189    Orb(Id),
190    Object(Id),
191}
192
193#[derive(Clone, Debug, Eq, PartialEq)]
194pub struct Resource {
195    pub id: Id,
196    pub owner: Owner,
197    pub name: String,
198    pub version: Version,
199    /// Kernel-derived execution realm: zero for host and native revisions, otherwise the
200    /// isolated orb revision identity. Values are reused only inside the same realm.
201    pub realm: Id,
202    pub code_version: Version,
203    pub exclusive: bool,
204    pub dependencies: Vec<Id>,
205    pub value: Option<Id>,
206    pub closing: bool,
207}
208
209/// Actions are executed by the adapter after a kernel operation completes.
210#[derive(Clone, Debug, Eq, PartialEq)]
211pub enum Action {
212    Execute {
213        program: Id,
214        effects: Vec<crate::Effect>,
215    },
216    CancelEffects {
217        program: Id,
218        effects: Vec<crate::Effect>,
219    },
220    ProgramPrepared(Id),
221    ProgramComplete {
222        program: Id,
223        error: Option<Error>,
224    },
225    DisposeObject(Id),
226    CloseResource(Id),
227    DropValue(Id),
228    CancelRoot(Id),
229    /// One invocation was cancelled by its caller: only that call and the calls it issued, never
230    /// its root or sibling calls. Physical calls keep running until they finish.
231    CancelCall(Id),
232    CancelTask(Id),
233    RetireOrb(Id),
234    StateChanged {
235        object: Id,
236        revision: u64,
237    },
238    #[cfg(feature = "subscriptions")]
239    SubscriptionFailed(Id),
240    #[cfg(feature = "subscriptions")]
241    DetachSubscription(Id),
242    #[cfg(feature = "subscriptions")]
243    Deliver {
244        subscription: Id,
245        payload: Id,
246        operation: Id,
247    },
248}
249
250#[derive(Clone, Debug, Default, Eq, PartialEq)]
251pub struct Diagnostics {
252    pub objects: usize,
253    pub references: usize,
254    pub roots: usize,
255    pub calls: usize,
256    pub resources: usize,
257    pub tasks: usize,
258    pub orbs: usize,
259    pub closing: bool,
260}
261
262#[derive(Clone, Debug)]
263pub(crate) struct Object {
264    pub address: Address,
265    pub orb: Id,
266    pub phase: Status,
267    pub references: usize,
268    pub calls: usize,
269    pub tasks: usize,
270    pub pinned: bool,
271    pub disposing: bool,
272    pub preparing: bool,
273    pub idle_at: Option<u64>,
274    pub linger_ms: u32,
275    pub gate: Option<BTreeSet<Id>>,
276    pub min_version: Version,
277    pub state: Option<crate::Snapshot>,
278    pub dependencies: BTreeSet<Id>,
279}
280
281#[derive(Clone, Debug)]
282pub(crate) struct Reference {
283    pub object: Id,
284    pub released: bool,
285    pub expected_api: Version,
286    pub methods: BTreeSet<String>,
287    #[cfg(feature = "views")]
288    pub allowed: Option<BTreeSet<String>>,
289}
290
291#[derive(Clone, Debug)]
292pub(crate) struct Root {
293    pub contexts: BTreeSet<Id>,
294    pub version: Version,
295    pub principal: String,
296    pub active: bool,
297    pub cancelled: bool,
298    pub calls: usize,
299    pub touched: BTreeSet<Id>,
300    pub orbs: BTreeSet<Id>,
301    pub cleanup: bool,
302}
303
304#[derive(Clone, Debug)]
305pub(crate) struct Task {
306    pub owner: Owner,
307    pub cancelled: bool,
308    pub version: Version,
309}
310
311#[derive(Clone, Debug, Eq, PartialEq)]
312pub struct Reload {
313    pub id: Id,
314    pub code_version: Version,
315    pub orbs: Vec<InstalledOrb>,
316    pub objects: Vec<Id>,
317    /// Candidate providers for affected service identities, shared with language adapters.
318    pub providers: BTreeMap<String, Id>,
319}
320
321#[derive(Clone, Debug, Eq, PartialEq)]
322pub struct Migration {
323    pub object: Id,
324    pub expected_revision: u64,
325    pub value: Id,
326    pub state_version: Version,
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn a_host_lifetime_object_lives_at_main_of_the_host() {
335        let address = |key: &str, principal: &str| Address {
336            service: "ledger".into(),
337            key: vec![key.into()],
338            principal: principal.into(),
339        };
340        assert!(admits_address(Lifetime::Host, &address("main", "host")));
341        assert!(!admits_address(Lifetime::Host, &address("other", "host")));
342        assert!(!admits_address(Lifetime::Host, &address("main", "alice")));
343        assert!(admits_address(
344            Lifetime::Referenced,
345            &address("other", "alice")
346        ));
347    }
348}