Skip to main content

blitz_script/
native_host.rs

1//! Engine-neutral contracts for native guest values and retained callbacks.
2//!
3//! These traits describe an opt-in boundary only. They do not provide a guest
4//! runtime or imply that a document backend executes through this interface.
5
6/// The active identity of a guest realm.
7///
8/// A generation distinguishes successive guest instances that use the same
9/// realm identifier. Hosts should advance it when an instance is replaced.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct RealmScope<R> {
12    realm: R,
13    generation: u64,
14}
15
16impl<R> RealmScope<R> {
17    /// Create a scope for the currently active guest instance.
18    pub const fn new(realm: R, generation: u64) -> Self {
19        Self { realm, generation }
20    }
21
22    /// The identifier of the realm.
23    pub const fn realm(&self) -> &R {
24        &self.realm
25    }
26
27    /// The generation of the guest instance in this realm.
28    pub const fn generation(&self) -> u64 {
29        self.generation
30    }
31}
32
33/// A retained callback identifier scoped to the guest instance that created it.
34///
35/// The token is opaque to this crate. Its identifier type belongs to the guest
36/// implementation and should identify a callback retained by that instance.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct RetainedCallback<R, C> {
39    realm: R,
40    generation: u64,
41    callback: C,
42}
43
44impl<R, C> RetainedCallback<R, C> {
45    /// Create a token for a callback retained in the given realm generation.
46    pub const fn new(realm: R, generation: u64, callback: C) -> Self {
47        Self {
48            realm,
49            generation,
50            callback,
51        }
52    }
53
54    /// The identifier of the realm that retained this callback.
55    pub const fn realm(&self) -> &R {
56        &self.realm
57    }
58
59    /// The generation that retained this callback.
60    pub const fn generation(&self) -> u64 {
61        self.generation
62    }
63
64    /// The guest-defined callback identifier.
65    pub const fn callback(&self) -> &C {
66        &self.callback
67    }
68
69    /// Whether this token belongs to the active realm generation.
70    pub fn is_current_in(&self, scope: &RealmScope<R>) -> bool
71    where
72        R: PartialEq,
73    {
74        self.realm == scope.realm && self.generation == scope.generation
75    }
76}
77
78/// A guest implementation that exposes typed values and retained callbacks.
79///
80/// `Value`, `RealmId`, `CallbackId`, and `Error` remain implementation-defined.
81/// In particular, this interface does not impose a shared host value enum.
82pub trait NativeGuest {
83    /// The guest's native value representation.
84    type Value;
85    /// An identifier for one realm owned by this guest.
86    type RealmId: Clone + PartialEq;
87    /// An identifier for a callback retained by this guest.
88    type CallbackId: Clone;
89    /// Errors produced while invoking a callback.
90    type Error;
91
92    /// Return this guest's current realm and generation, rather than accepting
93    /// a caller-supplied scope as authority to enter the guest.
94    fn scope(&self) -> RealmScope<Self::RealmId>;
95
96    /// Root an executable guest callback until release or realm teardown.
97    /// Reject values that are not callable without evaluating their source.
98    fn retain_callback(
99        &mut self,
100        callback: &Self::Value,
101    ) -> Result<RetainedCallback<Self::RealmId, Self::CallbackId>, Self::Error>;
102
103    /// Revoke dispatch and release the guest root. Other token clones must
104    /// become unusable. Unknown, released and stale tokens must be rejected.
105    fn release_callback(
106        &mut self,
107        callback: &RetainedCallback<Self::RealmId, Self::CallbackId>,
108    ) -> Result<(), Self::Error>;
109
110    /// Install a compiled typed host entry point before page scripts execute.
111    /// Guest-to-host conversions belong to the backend and must preserve value
112    /// identity, UTF-16 code units and buffer ownership without serializing JS.
113    fn register_intrinsic(
114        &mut self,
115        name: &'static str,
116        arity: u8,
117        callback: NativeIntrinsic<Self>,
118    ) -> Result<(), Self::Error>
119    where
120        Self: Sized;
121
122    /// Invoke a retained callback with typed arguments.
123    ///
124    /// Implementations must check that `callback` is current in `self.scope()` before
125    /// executing it, and reject an unknown callback identifier. This method's
126    /// contract does not claim that any particular guest currently enforces
127    /// those checks.
128    fn invoke_retained_callback(
129        &mut self,
130        callback: &RetainedCallback<Self::RealmId, Self::CallbackId>,
131        arguments: &[Self::Value],
132    ) -> Result<Self::Value, Self::Error>;
133}
134
135/// A native entry point that executes on the guest's owning realm thread.
136pub type NativeIntrinsic<G> = fn(
137    &mut G,
138    &[<G as NativeGuest>::Value],
139) -> Result<<G as NativeGuest>::Value, <G as NativeGuest>::Error>;
140
141/// Failure returned by the host callback dispatch boundary.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum NativeCallbackError<E> {
144    /// The callback token belongs to another realm or guest generation.
145    StaleCallback,
146    /// The guest rejected the callback or its execution failed.
147    Guest(E),
148}
149
150/// A host-side owner that can dispatch calls to a native guest.
151pub trait NativeHost {
152    /// The guest implementation owned by this host.
153    type Guest: NativeGuest;
154
155    /// Borrow the guest immutably.
156    fn guest(&self) -> &Self::Guest;
157
158    /// Borrow the guest for an invocation.
159    fn guest_mut(&mut self) -> &mut Self::Guest;
160
161    /// Dispatch a typed call to a retained callback.
162    ///
163    /// Rejects mismatched realm or generation metadata before entering the
164    /// guest. The guest implementation remains responsible for rejecting an
165    /// unknown callback identifier before callback code runs.
166    fn invoke_retained_callback(
167        &mut self,
168        callback: &RetainedCallback<
169            <Self::Guest as NativeGuest>::RealmId,
170            <Self::Guest as NativeGuest>::CallbackId,
171        >,
172        arguments: &[<Self::Guest as NativeGuest>::Value],
173    ) -> Result<
174        <Self::Guest as NativeGuest>::Value,
175        NativeCallbackError<<Self::Guest as NativeGuest>::Error>,
176    > {
177        let guest = self.guest_mut();
178        if !callback.is_current_in(&guest.scope()) {
179            return Err(NativeCallbackError::StaleCallback);
180        }
181        guest
182            .invoke_retained_callback(callback, arguments)
183            .map_err(NativeCallbackError::Guest)
184    }
185}