Skip to main content

rustia/
extension_api.rs

1use crate::function::IntoHostFunction;
2use crate::{
3    Error, GuestSurface, HostSchema, OpCapability, Profile, Result, Rustia, Settings, VmError,
4    VmErrorKind,
5};
6use rustia_compiler::{compile_with_options, CompileOptions};
7use rustia_vm::{
8    ClockProvider, EntropyProvider, HostFunctionOp, ModuleResolver, Program, ResolvedModule,
9    StdoutSink, VmSettings,
10};
11#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
12use std::time::{Instant, SystemTime, UNIX_EPOCH};
13#[cfg(all(
14    target_arch = "wasm32",
15    target_os = "unknown",
16    feature = "platform-adapters"
17))]
18use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
19
20#[cfg(all(
21    target_arch = "wasm32",
22    target_os = "unknown",
23    feature = "platform-adapters"
24))]
25#[wasm_bindgen]
26extern "C" {
27    #[wasm_bindgen(js_namespace = console, js_name = log)]
28    fn web_console_log(text: &str);
29}
30
31/// Chooses a script environment, resource limits, and host services.
32///
33/// Start with [`Rustia::builder`] for reproducible defaults, or use
34/// [`live`](Self::live) for real clocks, entropy, and `loadstring`.
35/// [`deterministic`](Self::deterministic) rejects nondeterministic input providers
36/// and host capabilities. None of these presets sets a fuel or memory limit.
37///
38/// ```
39/// use rustia::Rustia;
40///
41/// let mut lua = Rustia::builder()
42///     .fuel(100_000)
43///     .memory_limit_bytes(4 * 1024 * 1024)
44///     .build()?;
45/// assert_eq!(lua.load("return 6 * 7").eval::<i64>()?, 42);
46/// # Ok::<(), rustia::Error>(())
47/// ```
48///
49/// Use [`build_for_host`](Self::build_for_host) when callbacks need borrowed
50/// per-invocation state. The more restricted
51/// [`deterministic_leaf`](Self::deterministic_leaf) preset is for stateless
52/// decisions and requires a typed host plus an explicit memory limit.
53pub struct RustiaBuilder {
54    profile: Profile,
55    settings: VmSettings,
56    extensions: Vec<RustiaExtension>,
57    live_requested: bool,
58}
59
60/// Stable, typed description of the core profile and guest surface selected by
61/// a builder.
62///
63/// The descriptor deliberately covers the core [`Profile`] and guest-visible
64/// [`GuestSurface`] together. Its canonical bytes are one component of an
65/// embedder's package or replay identity; settings, budgets, host ABI, and any
66/// permitted services must be bound separately. Unlike a caller-maintained
67/// label, the value can also be read back from the built [`Rustia`] VM.
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct RustiaExecutionProfile {
70    profile: Profile,
71    guest_surface: GuestSurface,
72}
73
74impl RustiaExecutionProfile {
75    /// Ordinary sealed deterministic execution.
76    pub const DETERMINISTIC_STANDARD: Self =
77        Self::new(Profile::DeterministicSim, GuestSurface::Standard);
78
79    /// Stateless authoritative-leaf execution.
80    pub const DETERMINISTIC_HARDENED_LEAF: Self =
81        Self::new(Profile::DeterministicSim, GuestSurface::HardenedLeaf);
82
83    pub(crate) const fn new(profile: Profile, guest_surface: GuestSurface) -> Self {
84        Self {
85            profile,
86            guest_surface,
87        }
88    }
89
90    pub(crate) const fn from_vm(
91        profile: rustia_vm::Profile,
92        guest_surface: rustia_vm::GuestSurface,
93    ) -> Self {
94        Self::new(
95            Profile::from_core(profile),
96            GuestSurface::from_core(guest_surface),
97        )
98    }
99
100    /// Constructs a builder whose core VM semantics exactly match this
101    /// descriptor. Further builder methods may add budgets or services; the
102    /// final descriptor remains readable through
103    /// [`RustiaBuilder::execution_profile`].
104    pub fn builder(self) -> RustiaBuilder {
105        RustiaBuilder::from_execution_profile(self)
106    }
107
108    /// Stable compact code for fixed-width host protocol fields.
109    ///
110    /// Codes name the complete `(Profile, GuestSurface)` pair rather than
111    /// relying on Rust enum discriminants.
112    pub const fn compatibility_id(self) -> u32 {
113        match (self.profile, self.guest_surface) {
114            (Profile::DeterministicSim, GuestSurface::HardenedLeaf) => 1,
115            (Profile::LuauCompat, GuestSurface::Standard) => 2,
116            (Profile::ReproducibleStandard, GuestSurface::Standard) => 3,
117            (Profile::DeterministicSim, GuestSurface::Standard) => 4,
118            (Profile::LuauCompat, GuestSurface::HardenedLeaf) => 5,
119            (Profile::ReproducibleStandard, GuestSurface::HardenedLeaf) => 6,
120            (Profile::Puc51Compat, GuestSurface::Standard) => 7,
121            (Profile::Puc51Compat, GuestSurface::HardenedLeaf) => 8,
122        }
123    }
124
125    /// Canonical versioned bytes for package and replay identity components.
126    ///
127    /// Each field is an explicitly assigned little-endian `u32`: encoding
128    /// version, core-profile tag, then guest-surface tag.
129    pub const fn identity_bytes(self) -> [u8; 12] {
130        let encoding = 1u32.to_le_bytes();
131        let profile = match self.profile {
132            Profile::LuauCompat => 1u32,
133            Profile::ReproducibleStandard => 2,
134            Profile::DeterministicSim => 3,
135            Profile::Puc51Compat => 4,
136        }
137        .to_le_bytes();
138        let surface = match self.guest_surface {
139            GuestSurface::Standard => 1u32,
140            GuestSurface::HardenedLeaf => 2,
141        }
142        .to_le_bytes();
143        [
144            encoding[0],
145            encoding[1],
146            encoding[2],
147            encoding[3],
148            profile[0],
149            profile[1],
150            profile[2],
151            profile[3],
152            surface[0],
153            surface[1],
154            surface[2],
155            surface[3],
156        ]
157    }
158}
159
160impl RustiaBuilder {
161    pub(crate) fn new() -> Self {
162        Self {
163            profile: Profile::ReproducibleStandard,
164            settings: VmSettings::default(),
165            extensions: Vec::new(),
166            live_requested: false,
167        }
168    }
169
170    fn from_execution_profile(execution_profile: RustiaExecutionProfile) -> Self {
171        let mut builder = Self::new();
172        builder.profile = execution_profile.profile;
173        builder.settings.guest_surface = execution_profile.guest_surface.to_core();
174        builder
175    }
176
177    /// Returns the typed core execution semantics currently selected by this
178    /// builder.
179    pub const fn execution_profile(&self) -> RustiaExecutionProfile {
180        RustiaExecutionProfile::new(
181            self.profile,
182            GuestSurface::from_core(self.settings.guest_surface),
183        )
184    }
185
186    /// Returns the effective limits and service declarations selected so far.
187    ///
188    /// Use [`Settings::identity_bytes`] when configuration is part of a replay
189    /// or package identity. Provider data and application code remain separate
190    /// identity inputs.
191    pub fn settings(&self) -> Settings {
192        Settings::from_core(self.profile, &self.settings)
193    }
194
195    #[cfg(test)]
196    pub(crate) const fn vm_settings(&self) -> &VmSettings {
197        &self.settings
198    }
199
200    /// Starts with reproducible inputs and the standard script environment.
201    ///
202    /// This uses [`Profile::ReproducibleStandard`]: clocks use deterministic
203    /// defaults, the random seed is zero, and `loadstring` is disabled. Script
204    /// `print` writes to stdout on native/WASI targets and is silent on browser
205    /// Wasm until a sink is supplied. Real clocks and other nondeterministic
206    /// providers remain available when explicitly configured.
207    /// [`Rustia::builder`] starts with this preset.
208    pub fn standard() -> Self {
209        let builder = Self::new();
210        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
211        let builder = builder.stdout(|text| print!("{text}"));
212        builder
213    }
214
215    /// Starts with [`Profile::DeterministicSim`] and no host services.
216    ///
217    /// Nondeterministic input providers and host capabilities are rejected.
218    /// Replay-stable providers and a `print` sink can still be added explicitly.
219    pub fn deterministic() -> Self {
220        RustiaExecutionProfile::DETERMINISTIC_STANDARD.builder()
221    }
222
223    /// Starts a restricted environment for independent, stateless decisions.
224    ///
225    /// Uses [`GuestSurface::HardenedLeaf`] with [`Profile::DeterministicSim`].
226    /// Set an explicit [`memory_limit_bytes`](Self::memory_limit_bytes) and use
227    /// [`build_for_host`](Self::build_for_host). Execute host-owned decision
228    /// bodies with [`Rustia::compile_entry`] and [`Rustia::invoke_entry_into`].
229    pub fn deterministic_leaf() -> Self {
230        RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF.builder()
231    }
232
233    /// Starts with real clocks, a fresh random seed, output, and `loadstring`.
234    ///
235    /// Uses [`Profile::ReproducibleStandard`] with nondeterministic services;
236    /// results are not guaranteed to repeat. `loadstring` lets scripts compile
237    /// additional code at runtime, so choose this preset deliberately for
238    /// untrusted scripts.
239    ///
240    /// Native and WASI targets use their system services. On `wasm32-unknown-unknown`,
241    /// the default `platform-adapters` feature connects to JavaScript’s `console`,
242    /// `Date`, `performance`, and `crypto`. To run without JavaScript imports, disable
243    /// default features and give [`build`](Self::build) a [`wall_clock`](Self::wall_clock),
244    /// a [`monotonic_clock`](Self::monotonic_clock), and an [`entropy`](Self::entropy) provider.
245    pub fn live() -> Self {
246        let builder = Self::standard();
247        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
248        let builder = builder
249            .wall_clock(ServiceClock::system())
250            .monotonic_clock(ServiceClock::monotonic())
251            .entropy(ServiceEntropy::system());
252        #[cfg(all(
253            target_arch = "wasm32",
254            target_os = "unknown",
255            feature = "platform-adapters"
256        ))]
257        let builder = builder
258            .stdout(web_console_log)
259            .wall_clock(ServiceClock::system())
260            .monotonic_clock(ServiceClock::monotonic())
261            .entropy(ServiceEntropy::system());
262        let mut builder = builder;
263        builder.live_requested = true;
264        builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
265        builder
266    }
267
268    /// Starts a Lua 5.1 compatibility environment with `loadstring` enabled.
269    ///
270    /// The profile alone reproduces PUC 5.1.5 table layout, number
271    /// formatting, and `table.sort`; this preset adds `loadstring` so PUC-era
272    /// code that compiles chunks at runtime works out of the box. Runtime
273    /// compilation is an extra capability for untrusted scripts; enable it
274    /// where Lua 5.1 source compatibility requires it. Host services otherwise
275    /// use the defaults from [`standard`](Self::standard).
276    pub fn puc51_compat() -> Self {
277        let mut builder = Self::standard().profile(Profile::Puc51Compat);
278        builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
279        builder
280    }
281
282    /// Selects the core compatibility and capability policy.
283    /// Existing settings and services are retained and checked when building.
284    pub fn profile(mut self, profile: Profile) -> Self {
285        self.profile = profile;
286        self
287    }
288
289    #[cfg(test)]
290    pub(crate) fn raw_settings(mut self, settings: VmSettings) -> Self {
291        self.settings = settings;
292        self
293    }
294
295    /// Configures host-side reports independently of guest heap and fuel limits.
296    pub fn diagnostic_limits(mut self, limits: crate::DiagnosticLimits) -> Self {
297        self.settings.diagnostic_limits = limits.to_core();
298        self
299    }
300
301    /// Limits the instruction work allowed during execution.
302    ///
303    /// Direct `Rustia<()>` entry points use this as their top-level budget. A
304    /// typed invocation uses the lower of this ceiling and its explicit
305    /// [`crate::InvocationLimits`] fuel, across every guest call in that
306    /// invocation. Fuel measures deterministic work rather than elapsed time;
307    /// script `pcall` cannot catch fuel exhaustion. The default is unlimited.
308    pub fn fuel(mut self, fuel: u64) -> Self {
309        self.settings.initial_fuel = Some(fuel);
310        self
311    }
312
313    /// Limits nested script calls. The default and maximum are 512.
314    ///
315    /// Larger values are clamped to the engine maximum. Exhaustion returns a
316    /// distinct error that script `pcall` cannot catch.
317    pub fn recursion_limit(mut self, limit: usize) -> Self {
318        self.settings.recursion_limit = limit.min(rustia_vm::MAX_RECURSION_LIMIT);
319        self
320    }
321
322    /// Limits the VM's accounted live memory. The default is unlimited.
323    ///
324    /// Some charges depend on pointer width, so a script near its limit can run
325    /// out of memory at different points on native and Wasm targets. The limit
326    /// covers VM-accounted memory and excludes allocator capacity, total process
327    /// memory and memory captured by Rust callbacks.
328    pub fn memory_limit_bytes(mut self, bytes: usize) -> Self {
329        self.settings.memory_limit_bytes = Some(bytes);
330        self
331    }
332
333    /// Enables tracking of live and reserved memory peaks at instruction boundaries.
334    pub fn memory_tracking(mut self, enabled: bool) -> Self {
335        self.settings.enable_memory_tracking = enabled;
336        self
337    }
338
339    /// Adds a group of Rust callbacks to install when the VM is built.
340    /// For a typed host, use [`crate::HostModule`] after building instead.
341    pub fn extension(mut self, extension: RustiaExtension) -> Self {
342        self.extensions.push(extension);
343        self
344    }
345
346    /// Chooses where script `print` output goes.
347    ///
348    /// Each call sends one string, with arguments joined by tabs and a trailing
349    /// newline. The closure cannot return an error. Output sinks are allowed in
350    /// every ordinary profile, including [`Profile::DeterministicSim`].
351    #[cfg(not(feature = "send"))]
352    pub fn stdout(mut self, sink: impl FnMut(&str) + 'static) -> Self {
353        self.settings.services.stdout = Some(StdoutSink::new(sink));
354        self
355    }
356
357    /// Chooses a transferable sink for script `print` output.
358    #[cfg(feature = "send")]
359    pub fn stdout(mut self, sink: impl FnMut(&str) + Send + 'static) -> Self {
360        self.settings.services.stdout = Some(StdoutSink::new(sink));
361        self
362    }
363
364    /// Discards script `print` output by removing the configured sink.
365    pub fn without_stdout(mut self) -> Self {
366        self.settings.services.stdout = None;
367        self
368    }
369
370    /// Installs the host-owned resolver behind script-visible `require`.
371    ///
372    /// The resolver chooses a canonical module identity and source for every
373    /// request. Successful results are cached by identity within the calling
374    /// function's module cohort: the cache shared by a module and its dependencies.
375    /// Each installation starts a fresh cohort; retained functions keep using
376    /// their original cohort. A module can therefore execute again in a new
377    /// installation before [`Rustia::reset_decision`] clears all guest state.
378    /// See [`ServiceModuleResolver`] for loading, failure, and suspension rules.
379    pub fn module_resolver(mut self, resolver: ServiceModuleResolver) -> Self {
380        self.settings.module_resolver = Some(resolver.into_provider());
381        self
382    }
383
384    /// Supplies the clock for no-argument `os.time()` and the default `os.date`
385    /// timestamp. A nondeterministic provider is rejected at [`build`](Self::build) on
386    /// `DeterministicSim`.
387    pub fn wall_clock(mut self, clock: ServiceClock) -> Self {
388        self.settings.services.wall_clock = Some(clock.into_provider());
389        self
390    }
391
392    /// Supplies the clock for `os.clock()`, overriding the VM's built-in
393    /// logical clock. Same `DeterministicSim` validation as [`wall_clock`](Self::wall_clock).
394    pub fn monotonic_clock(mut self, clock: ServiceClock) -> Self {
395        self.settings.services.monotonic_clock = Some(clock.into_provider());
396        self
397    }
398
399    /// Supplies the seed read once at VM construction for the initial `math.random`
400    /// sequence. Calling `math.randomseed` later still replaces that state. A nondeterministic
401    /// provider is rejected by [`deterministic`](Self::deterministic).
402    pub fn entropy(mut self, entropy: ServiceEntropy) -> Self {
403        self.settings.services.entropy = Some(entropy.into_provider());
404        self
405    }
406
407    /// Validates the configuration and builds a VM without a typed host context.
408    ///
409    /// Returns an error for incompatible services, invalid extensions, or a
410    /// hardened-leaf preset, which requires [`build_for_host`](Self::build_for_host).
411    pub fn build(self) -> Result<Rustia> {
412        self.validate()?;
413        if self.settings.guest_surface.is_hardened_leaf() {
414            return Err(Error::from(VmError::new(
415                VmErrorKind::HardenedLeafViolation {
416                    feature: "context-free facade",
417                },
418            )));
419        }
420        let mut rustia = Rustia::from_settings(self.profile, self.settings);
421        for extension in self.extensions {
422            rustia.install_extension(extension)?;
423        }
424        Ok(rustia)
425    }
426
427    /// Builds a typed VM while preserving this builder's profile, settings,
428    /// and host services.
429    ///
430    /// Legacy [`RustiaExtension`] values deliberately do not cross into the
431    /// typed capability surface; install a [`crate::HostModule<H>`] after
432    /// building instead.
433    pub fn build_for_host<H>(self) -> Result<Rustia<H>>
434    where
435        H: HostSchema,
436    {
437        self.validate()?;
438        if !self.extensions.is_empty() {
439            return Err(Error::embed(
440                "legacy RustiaExtension values cannot be installed into a typed VM; \
441                 use HostModule instead"
442                    .to_owned(),
443            ));
444        }
445        Ok(Rustia::<H>::from_settings(self.profile, self.settings))
446    }
447
448    fn validate(&self) -> Result<()> {
449        if self.live_requested
450            && (self.settings.services.wall_clock.is_none()
451                || self.settings.services.monotonic_clock.is_none()
452                || self.settings.services.entropy.is_none())
453        {
454            return Err(Error::from(VmError::new(VmErrorKind::Unsupported {
455                feature: "live() without a complete platform adapter (plug \
456                          .wall_clock/.monotonic_clock/.entropy providers, or enable the \
457                          default platform-adapters feature for browser/JavaScript wasm hosts)",
458            })));
459        }
460        if self.profile.is_deterministic_sim() {
461            for (feature, clock) in [
462                (
463                    "non-deterministic wall clock provider",
464                    &self.settings.services.wall_clock,
465                ),
466                (
467                    "non-deterministic monotonic clock provider",
468                    &self.settings.services.monotonic_clock,
469                ),
470            ] {
471                if clock.as_ref().is_some_and(|clock| !clock.deterministic()) {
472                    return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
473                        feature,
474                        operation: None,
475                        profile: self.profile,
476                    })));
477                }
478            }
479            if self
480                .settings
481                .services
482                .entropy
483                .as_ref()
484                .is_some_and(|entropy| !entropy.deterministic())
485            {
486                return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
487                    feature: "non-deterministic entropy provider",
488                    operation: None,
489                    profile: self.profile,
490                })));
491            }
492            if self
493                .settings
494                .module_resolver
495                .as_ref()
496                .is_some_and(|resolver| !resolver.deterministic())
497            {
498                return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
499                    feature: "non-deterministic module resolver",
500                    operation: Some("require".to_owned()),
501                    profile: self.profile,
502                })));
503            }
504        }
505        if self.settings.guest_surface.is_hardened_leaf() {
506            if !self.profile.is_deterministic_sim() {
507                return Err(Error::from(VmError::new(
508                    VmErrorKind::HardenedLeafViolation {
509                        feature: "non-DeterministicSim profile",
510                    },
511                )));
512            }
513            if self.settings.memory_limit_bytes.is_none() {
514                return Err(Error::from(VmError::new(
515                    VmErrorKind::HardenedLeafViolation {
516                        feature: "missing logical-live memory limit",
517                    },
518                )));
519            }
520            if self.settings.services.stdout.is_some()
521                || self.settings.services.wall_clock.is_some()
522                || self.settings.services.monotonic_clock.is_some()
523                || self.settings.services.entropy.is_some()
524            {
525                return Err(Error::from(VmError::new(
526                    VmErrorKind::HardenedLeafViolation {
527                        feature: "host output, clock, or entropy services",
528                    },
529                )));
530            }
531            if self.settings.loadstring_compiler.is_some()
532                || self.settings.module_resolver.is_some()
533                || self.settings.enable_conformance_coverage
534                || self.settings.enable_opcode_census
535                || self.settings.enable_conformance_top_level_yield
536                || self.settings.enable_conformance_int64_userdata
537                || self.settings.enable_conformance_native_userdata
538                || self.settings.enable_conformance_native_type_checks
539                || self.settings.enable_conformance_pcall_helpers
540            {
541                return Err(Error::from(VmError::new(
542                    VmErrorKind::HardenedLeafViolation {
543                        feature: "dynamic-code or conformance-only facilities",
544                    },
545                )));
546            }
547        }
548        Ok(())
549    }
550}
551
552/// Host-supplied source returned by a [`ServiceModuleResolver`].
553#[derive(Clone, Debug, Eq, PartialEq)]
554pub struct ModuleSource {
555    identity: String,
556    source_name: String,
557    source: Vec<u8>,
558}
559
560impl ModuleSource {
561    /// Creates a module whose diagnostic and resolver-referrer source name
562    /// matches its canonical cache identity.
563    pub fn new(identity: impl Into<String>, source: impl AsRef<[u8]>) -> Self {
564        let identity = identity.into();
565        Self {
566            source_name: identity.clone(),
567            identity,
568            source: source.as_ref().to_vec(),
569        }
570    }
571
572    /// Creates a module with a separate canonical cache identity and source
573    /// name. The source name is used for diagnostics and nested `require`
574    /// resolver referrers.
575    pub fn with_source_name(
576        identity: impl Into<String>,
577        source_name: impl Into<String>,
578        source: impl AsRef<[u8]>,
579    ) -> Self {
580        Self {
581            identity: identity.into(),
582            source_name: source_name.into(),
583            source: source.as_ref().to_vec(),
584        }
585    }
586
587    pub fn identity(&self) -> &str {
588        &self.identity
589    }
590
591    pub fn source_name(&self) -> &str {
592        &self.source_name
593    }
594
595    pub fn source(&self) -> &[u8] {
596        &self.source
597    }
598}
599
600/// Host-owned resolver for script-visible `require`.
601///
602/// Resolution is performed on demand with the requested path and the current
603/// chunk's source name. The host must return a stable canonical identity when
604/// it labels the resolver deterministic. Because the canonical identity is a
605/// resolver result, the resolver is called before every cache lookup; a host
606/// with expensive I/O or compilation should keep its own source cache. A cache
607/// hit skips module execution and discards the newly resolved program.
608///
609/// A module may return zero or one value. Successful results are cached within
610/// the calling function's module cohort; failures can be retried. Module code
611/// running in a guest coroutine may yield and resume before its result is
612/// cached. Recursive loading is an error, as is requesting an identity that a
613/// different coroutine is still loading.
614///
615/// Ordinary `require` keeps completed writes when a module fails. An enclosing
616/// [`Chunk::install`](crate::Chunk::install) still rolls back guest state when
617/// the installation fails; external Rust effects remain outside that rollback.
618///
619/// ```
620/// use rustia::{ModuleSource, RustiaBuilder, ServiceModuleResolver};
621///
622/// # fn main() -> rustia::Result<()> {
623/// let resolver = ServiceModuleResolver::from_fn(|name, _referrer| {
624///     match name {
625///         "answer" => Ok(ModuleSource::new("answer", "return 42")),
626///         _ => Err(rustia::Error::embed(format!("unknown module {name}"))),
627///     }
628/// });
629/// let mut lua = RustiaBuilder::deterministic().module_resolver(resolver).build()?;
630/// assert_eq!(lua.load("return require('answer')").eval::<i64>()?, 42);
631/// # Ok(())
632/// # }
633/// ```
634#[derive(Clone, Debug)]
635pub struct ServiceModuleResolver {
636    provider: ModuleResolver,
637}
638
639impl ServiceModuleResolver {
640    /// Host-supplied replay-stable resolver. The determinism assertion is
641    /// trusted, not verified.
642    #[cfg(not(feature = "send"))]
643    pub fn from_fn(
644        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
645    ) -> Self {
646        Self::from_fn_with_determinism(resolver, true)
647    }
648
649    /// Host-supplied replay-stable transferable resolver.
650    #[cfg(feature = "send")]
651    pub fn from_fn(
652        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
653    ) -> Self {
654        Self::from_fn_with_determinism(resolver, true)
655    }
656
657    /// Host-supplied live resolver explicitly labeled nondeterministic.
658    #[cfg(not(feature = "send"))]
659    pub fn from_nondeterministic_fn(
660        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
661    ) -> Self {
662        Self::from_fn_with_determinism(resolver, false)
663    }
664
665    /// Host-supplied live transferable resolver.
666    #[cfg(feature = "send")]
667    pub fn from_nondeterministic_fn(
668        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
669    ) -> Self {
670        Self::from_fn_with_determinism(resolver, false)
671    }
672
673    #[cfg(not(feature = "send"))]
674    fn from_fn_with_determinism(
675        mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
676        deterministic: bool,
677    ) -> Self {
678        let provider = ModuleResolver::new_with_profile(
679            move |requested, referrer, profile| {
680                let module =
681                    resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
682                compile_module_source(module, profile)
683            },
684            deterministic,
685        );
686        Self { provider }
687    }
688
689    #[cfg(feature = "send")]
690    fn from_fn_with_determinism(
691        mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
692        deterministic: bool,
693    ) -> Self {
694        let provider = ModuleResolver::new_with_profile(
695            move |requested, referrer, profile| {
696                let module =
697                    resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
698                compile_module_source(module, profile)
699            },
700            deterministic,
701        );
702        Self { provider }
703    }
704
705    fn into_provider(self) -> ModuleResolver {
706        self.provider
707    }
708}
709
710fn compile_module_source(
711    module: ModuleSource,
712    profile: rustia_vm::Profile,
713) -> rustia_vm::Result<ResolvedModule> {
714    if module.identity.is_empty() {
715        return Err(crate::value::embed_to_vm_error(Error::embed(
716            "module identity must not be empty",
717        )));
718    }
719    let chunk = rustia_parser::parse_source_bytes(&module.source).map_err(|error| {
720        module_compile_error(
721            Error::from_engine(error),
722            &module.source_name,
723            &module.source,
724        )
725    })?;
726    let options = CompileOptions {
727        puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
728        ..CompileOptions::default()
729    }
730    .with_source_bytes(module.source_name.clone(), &module.source);
731    let mut program = compile_with_options(&chunk, options).map_err(|error| {
732        module_compile_error(
733            Error::from_engine(error),
734            &module.source_name,
735            &module.source,
736        )
737    })?;
738    program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
739        &module.source,
740        crate::DiagnosticLimits::default().source_bytes,
741    );
742    Ok(ResolvedModule::new(module.identity, program))
743}
744
745fn module_compile_error(error: Error, name: &str, source: &[u8]) -> rustia_vm::Error {
746    let message = format!("{name}:1: {error}");
747    let mut error = error.with_source(name, source, crate::DiagnosticLimits::default());
748    // Keep a single snapshot lease at the outer diagnostic, not an unbudgeted
749    // copy hidden in the typed cause chain.
750    let mut diagnostic = error.diagnostic.take();
751    let mut error = crate::value::embed_to_vm_error(error);
752    if let Some(diagnostic) = &mut diagnostic {
753        std::sync::Arc::make_mut(diagnostic).host_cause = error
754            .diagnostic
755            .as_ref()
756            .and_then(|diagnostic| diagnostic.host_cause.clone());
757    }
758    error.diagnostic = diagnostic.map(|diagnostic| std::sync::Arc::new(diagnostic.to_core()));
759    if let rustia_vm::ErrorKind::RuntimeError { message: raw } = &mut error.kind {
760        *raw = message;
761    }
762    error
763}
764
765/// A clock supplied to [`RustiaBuilder::wall_clock`] or
766/// [`RustiaBuilder::monotonic_clock`].
767///
768/// Every constructor declares whether readings repeat during replay.
769/// [`Profile::DeterministicSim`] rejects nondeterministic providers when built;
770/// other profiles accept either kind.
771/// Cloning shares the underlying provider.
772#[non_exhaustive]
773#[derive(Clone, Debug)]
774pub struct ServiceClock {
775    provider: ClockProvider,
776}
777
778impl ServiceClock {
779    /// Real system time in seconds since the Unix epoch, anchored to a monotonic instant at
780    /// construction so readings never move backwards. Labeled nondeterministic: usable on
781    /// `ReproducibleStandard`/`LuauCompat`, rejected on `DeterministicSim`.
782    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
783    pub fn system() -> Self {
784        let epoch = SystemTime::now()
785            .duration_since(UNIX_EPOCH)
786            .map_or(0.0, |duration| duration.as_secs_f64());
787        let start = Instant::now();
788        Self {
789            provider: ClockProvider::new(move || epoch + start.elapsed().as_secs_f64(), false),
790        }
791    }
792
793    /// Monotonic elapsed time in seconds. Labeled nondeterministic.
794    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
795    pub fn monotonic() -> Self {
796        let start = Instant::now();
797        Self {
798            provider: ClockProvider::new(move || start.elapsed().as_secs_f64(), false),
799        }
800    }
801
802    /// JavaScript host wall time in seconds since the Unix epoch. Labeled nondeterministic.
803    #[cfg(all(
804        target_arch = "wasm32",
805        target_os = "unknown",
806        feature = "platform-adapters"
807    ))]
808    pub fn system() -> Self {
809        Self {
810            provider: ClockProvider::new(|| js_sys::Date::now() / 1_000.0, false),
811        }
812    }
813
814    /// JavaScript host monotonic time in seconds. Uses `performance.now()` when available and
815    /// falls back to `Date.now()`. Labeled nondeterministic.
816    #[cfg(all(
817        target_arch = "wasm32",
818        target_os = "unknown",
819        feature = "platform-adapters"
820    ))]
821    pub fn monotonic() -> Self {
822        Self {
823            provider: ClockProvider::new(web_monotonic_seconds, false),
824        }
825    }
826
827    /// Constant clock that always reads `t` seconds. Labeled deterministic.
828    pub fn fixed(t: f64) -> Self {
829        Self {
830            provider: ClockProvider::new(move || t, true),
831        }
832    }
833
834    /// Supplies a clock whose readings the host promises to reproduce during replay.
835    /// Rustia trusts this declaration and does not verify it.
836    #[cfg(not(feature = "send"))]
837    pub fn from_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
838        Self {
839            provider: ClockProvider::new(clock, true),
840        }
841    }
842
843    /// Supplies a transferable clock whose readings the host promises to reproduce.
844    #[cfg(feature = "send")]
845    pub fn from_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
846        Self {
847            provider: ClockProvider::new(clock, true),
848        }
849    }
850
851    /// Host-supplied live clock. The provider is explicitly labeled nondeterministic.
852    #[cfg(not(feature = "send"))]
853    pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
854        Self {
855            provider: ClockProvider::new(clock, false),
856        }
857    }
858
859    /// Host-supplied transferable live clock.
860    #[cfg(feature = "send")]
861    pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
862        Self {
863            provider: ClockProvider::new(clock, false),
864        }
865    }
866
867    pub(crate) fn into_provider(self) -> ClockProvider {
868        self.provider
869    }
870}
871
872/// Host entropy used to select the VM's initial `math.random` sequence.
873///
874/// Like [`ServiceClock`], every constructor carries a determinism label. The provider is read
875/// once while the VM is built; `math.randomseed` remains available afterward.
876#[non_exhaustive]
877#[derive(Clone, Debug)]
878pub struct ServiceEntropy {
879    provider: EntropyProvider,
880}
881
882impl ServiceEntropy {
883    /// System entropy where Rustia has a default platform adapter. If the platform random
884    /// source is temporarily unavailable, a time-varying fallback still preserves `live()`'s
885    /// no-replay-guarantee contract. Labeled nondeterministic.
886    #[cfg(any(
887        not(all(target_arch = "wasm32", target_os = "unknown")),
888        all(
889            target_arch = "wasm32",
890            target_os = "unknown",
891            feature = "platform-adapters"
892        )
893    ))]
894    pub fn system() -> Self {
895        let fallback_counter = std::sync::atomic::AtomicU64::new(0);
896        Self {
897            provider: EntropyProvider::new(
898                move || {
899                    system_entropy().unwrap_or_else(|| {
900                        let counter = fallback_counter
901                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
902                            .wrapping_add(1);
903                        fallback_entropy(counter)
904                    })
905                },
906                false,
907            ),
908        }
909    }
910
911    /// Constant replay-stable seed.
912    pub fn fixed(seed: u64) -> Self {
913        Self {
914            provider: EntropyProvider::new(move || seed, true),
915        }
916    }
917
918    /// Host-supplied replay-stable seed provider.
919    #[cfg(not(feature = "send"))]
920    pub fn from_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
921        Self {
922            provider: EntropyProvider::new(entropy, true),
923        }
924    }
925
926    /// Host-supplied transferable replay-stable seed provider.
927    #[cfg(feature = "send")]
928    pub fn from_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
929        Self {
930            provider: EntropyProvider::new(entropy, true),
931        }
932    }
933
934    /// Host-supplied live seed provider, explicitly labeled nondeterministic.
935    #[cfg(not(feature = "send"))]
936    pub fn from_nondeterministic_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
937        Self {
938            provider: EntropyProvider::new(entropy, false),
939        }
940    }
941
942    /// Host-supplied transferable live seed provider.
943    #[cfg(feature = "send")]
944    pub fn from_nondeterministic_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
945        Self {
946            provider: EntropyProvider::new(entropy, false),
947        }
948    }
949
950    pub(crate) fn into_provider(self) -> EntropyProvider {
951        self.provider
952    }
953}
954
955#[cfg(feature = "platform-adapters")]
956fn system_entropy() -> Option<u64> {
957    getrandom::u64().ok()
958}
959
960#[cfg(all(
961    not(feature = "platform-adapters"),
962    not(all(target_arch = "wasm32", target_os = "unknown"))
963))]
964fn system_entropy() -> Option<u64> {
965    None
966}
967
968#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
969fn fallback_entropy(counter: u64) -> u64 {
970    let wall = SystemTime::now()
971        .duration_since(UNIX_EPOCH)
972        .map_or(0_u128, |duration| duration.as_nanos());
973    (wall as u64) ^ ((wall >> 64) as u64) ^ counter.rotate_left(29)
974}
975
976#[cfg(all(
977    target_arch = "wasm32",
978    target_os = "unknown",
979    feature = "platform-adapters"
980))]
981fn fallback_entropy(counter: u64) -> u64 {
982    js_sys::Date::now().to_bits() ^ web_monotonic_seconds().to_bits() ^ counter.rotate_left(29)
983}
984
985#[cfg(all(
986    target_arch = "wasm32",
987    target_os = "unknown",
988    feature = "platform-adapters"
989))]
990fn web_monotonic_seconds() -> f64 {
991    let global = js_sys::global();
992    let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance"));
993    let Ok(performance) = performance else {
994        return js_sys::Date::now() / 1_000.0;
995    };
996    let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now"))
997        .ok()
998        .and_then(|value| value.dyn_into::<js_sys::Function>().ok())
999        .and_then(|now| now.call0(&performance).ok())
1000        .and_then(|value| value.as_f64());
1001    now.unwrap_or_else(js_sys::Date::now) / 1_000.0
1002}
1003
1004/// Stock `loadstring` compiler installed by [`RustiaBuilder::live`]: the same parse + compile
1005/// pipeline the facade uses for ahead-of-time source (public builtin environment), with
1006/// Luau's `[string "..."]` chunk naming when the script passes no chunk name.
1007///
1008/// The VM supplies its active [`Profile`] so profile-dependent codegen stays
1009/// consistent between ahead-of-time and runtime-compiled chunks (currently the
1010/// PUC 5.1 table-constructor write order under `Profile::Puc51Compat`).
1011fn stock_loadstring_compiler(
1012    source: &[u8],
1013    source_name: Option<&[u8]>,
1014    profile: rustia_vm::Profile,
1015) -> std::result::Result<Program, String> {
1016    let source_name = source_name.map_or_else(
1017        || loadstring_chunk_name(source),
1018        |name| String::from_utf8_lossy(name).into_owned(),
1019    );
1020    let chunk = rustia_parser::parse_source_bytes(source)
1021        .map_err(|error| format!("{source_name}:1: {error}"))?;
1022    let options = CompileOptions {
1023        puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
1024        ..CompileOptions::default()
1025    }
1026    .with_source_bytes(source_name.clone(), source);
1027    let mut program = compile_with_options(&chunk, options)
1028        .map_err(|error| format!("{source_name}:1: {error}"))?;
1029    program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
1030        source,
1031        crate::DiagnosticLimits::default().source_bytes,
1032    );
1033    Ok(program)
1034}
1035
1036fn loadstring_chunk_name(source: &[u8]) -> String {
1037    let mut preview = String::new();
1038    for byte in source.iter().copied().take(60) {
1039        match byte {
1040            b'\\' => preview.push_str("\\\\"),
1041            b'"' => preview.push_str("\\\""),
1042            b'\n' => break,
1043            0x20..=0x7e => preview.push(byte as char),
1044            _ => preview.push('?'),
1045        }
1046    }
1047    if source.len() > 60 {
1048        preview.push_str("...");
1049    }
1050    format!("[string \"{preview}\"]")
1051}
1052
1053/// A group of Rust callbacks installed together, optionally in a named table.
1054///
1055/// Add it with [`RustiaBuilder::extension`] or [`Rustia::install_extension`].
1056/// For callbacks that borrow per-invocation host state, use [`crate::HostModule`]
1057/// instead. The capability labels here describe captured host state; they do
1058/// not provide a borrowed host context or make captured mutations transactional.
1059#[derive(Clone, Debug)]
1060pub struct RustiaExtension {
1061    namespace: Option<String>,
1062    functions: Vec<HostFunctionOp>,
1063}
1064
1065/// Version for the public host-function fuel-cost schedule.
1066///
1067/// Bump this when a rustia release changes the meaning of declared host fuel costs.
1068pub const RUSTIA_HOST_FUEL_ABI_VERSION: u32 = 1;
1069
1070/// Default fuel cost assigned by capability-specific host-function helpers.
1071pub const RUSTIA_DEFAULT_HOST_FUNCTION_FUEL: u32 = 1;
1072
1073/// Minimum accepted host-function fuel cost.
1074pub const RUSTIA_MIN_HOST_FUNCTION_FUEL: u32 = 1;
1075
1076/// Public host-function fuel policy for extension metadata.
1077#[non_exhaustive]
1078#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1079pub struct RustiaHostFuelPolicy {
1080    /// ABI version for interpreting host-function fuel costs.
1081    pub abi_version: u32,
1082    /// Fuel cost used when the helper API does not take an explicit cost.
1083    pub default_function_fuel: u32,
1084    /// Smallest fuel cost accepted by VM registration.
1085    pub minimum_function_fuel: u32,
1086}
1087
1088/// The fuel policy used by extension registration helpers.
1089pub const RUSTIA_HOST_FUEL_POLICY: RustiaHostFuelPolicy = RustiaHostFuelPolicy {
1090    abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1091    default_function_fuel: RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1092    minimum_function_fuel: RUSTIA_MIN_HOST_FUNCTION_FUEL,
1093};
1094
1095/// Public pre-install metadata for a registered host function.
1096#[non_exhaustive]
1097#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1098pub struct RustiaHostFunctionInfo<'a> {
1099    /// The binding name inside the extension's namespace, or a global name.
1100    pub name: &'a str,
1101    /// ABI version used to interpret `fuel_cost`.
1102    pub fuel_abi_version: u32,
1103    /// Fuel charged per call.
1104    pub fuel_cost: u32,
1105    /// The callback's declared access to host state and effects.
1106    pub capability: OpCapability,
1107    /// The number of typed Rust parameters.
1108    pub parameter_count: u8,
1109    /// Rust type names for the callback parameters.
1110    pub parameter_types: &'a [&'static str],
1111    /// Rust type names for the callback results.
1112    pub return_types: &'a [&'static str],
1113    /// Whether the callback returns a Rustia `Result`.
1114    pub fallible: bool,
1115}
1116
1117impl RustiaExtension {
1118    /// Creates callbacks to install under a named table. An empty name selects globals.
1119    pub fn new(namespace: impl Into<String>) -> Self {
1120        let namespace = namespace.into();
1121        Self {
1122            namespace: (!namespace.is_empty()).then_some(namespace),
1123            functions: Vec::new(),
1124        }
1125    }
1126
1127    /// Creates callbacks to install directly as globals.
1128    pub fn global() -> Self {
1129        Self {
1130            namespace: None,
1131            functions: Vec::new(),
1132        }
1133    }
1134
1135    /// Returns the table name, or `None` for global callbacks.
1136    pub fn namespace(&self) -> Option<&str> {
1137        self.namespace.as_deref()
1138    }
1139
1140    /// Returns the fuel policy used by these registration helpers.
1141    pub fn fuel_policy(&self) -> RustiaHostFuelPolicy {
1142        RUSTIA_HOST_FUEL_POLICY
1143    }
1144
1145    /// Describes the callbacks before installation.
1146    pub fn functions(&self) -> impl Iterator<Item = RustiaHostFunctionInfo<'_>> + '_ {
1147        self.functions
1148            .iter()
1149            .map(|function| RustiaHostFunctionInfo {
1150                name: &function.name,
1151                fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1152                fuel_cost: function.fuel_cost,
1153                capability: OpCapability::from_core(function.capability),
1154                parameter_count: function.parameter_count,
1155                parameter_types: &function.parameter_types,
1156                return_types: &function.return_types,
1157                fallible: function.fallible,
1158            })
1159    }
1160
1161    /// Adds a callback declared free of external mutable state, at the default fuel cost.
1162    pub fn fn_pure<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1163    where
1164        Func: IntoHostFunction<Args, Return>,
1165    {
1166        self.fn_with(
1167            name,
1168            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1169            OpCapability::Pure,
1170            function,
1171        )
1172    }
1173
1174    /// Adds a callback declared to read deterministic input, at the default fuel cost.
1175    pub fn fn_input<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1176    where
1177        Func: IntoHostFunction<Args, Return>,
1178    {
1179        self.fn_with(
1180            name,
1181            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1182            OpCapability::ReadsDeterministicInput,
1183            function,
1184        )
1185    }
1186
1187    /// Adds a callback declared to read slot state, at the default fuel cost.
1188    pub fn fn_slot_read<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1189    where
1190        Func: IntoHostFunction<Args, Return>,
1191    {
1192        self.fn_with(
1193            name,
1194            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1195            OpCapability::ReadsSlotState,
1196            function,
1197        )
1198    }
1199
1200    /// Adds a callback declared to write slot effects, at the default fuel cost.
1201    pub fn fn_slot_write<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1202    where
1203        Func: IntoHostFunction<Args, Return>,
1204    {
1205        self.fn_with(
1206            name,
1207            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1208            OpCapability::WritesSlotEffect,
1209            function,
1210        )
1211    }
1212
1213    /// Adds a callback declared to emit deterministic effects, at the default fuel cost.
1214    pub fn fn_effect<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1215    where
1216        Func: IntoHostFunction<Args, Return>,
1217    {
1218        self.fn_with(
1219            name,
1220            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1221            OpCapability::EmitsDeterministicEffect,
1222            function,
1223        )
1224    }
1225
1226    /// Adds a callback that reads external mutable state. Deterministic profiles reject it.
1227    pub fn fn_external_state<Func, Args, Return>(
1228        self,
1229        name: impl Into<String>,
1230        function: Func,
1231    ) -> Self
1232    where
1233        Func: IntoHostFunction<Args, Return>,
1234    {
1235        self.fn_with(
1236            name,
1237            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1238            OpCapability::ReadsExternalMutableState,
1239            function,
1240        )
1241    }
1242
1243    /// Adds a nondeterministic callback. Deterministic profiles reject it.
1244    pub fn fn_nondeterministic<Func, Args, Return>(
1245        self,
1246        name: impl Into<String>,
1247        function: Func,
1248    ) -> Self
1249    where
1250        Func: IntoHostFunction<Args, Return>,
1251    {
1252        self.fn_with(
1253            name,
1254            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1255            OpCapability::NondeterministicEffect,
1256            function,
1257        )
1258    }
1259
1260    /// Adds a callback with an explicit capability and nonzero fuel cost.
1261    /// Invalid costs and disallowed capabilities are rejected during installation.
1262    pub fn fn_with<Func, Args, Return>(
1263        mut self,
1264        name: impl Into<String>,
1265        fuel_cost: u32,
1266        capability: OpCapability,
1267        function: Func,
1268    ) -> Self
1269    where
1270        Func: IntoHostFunction<Args, Return>,
1271    {
1272        self.functions.push(
1273            crate::HostFunction::<()>::with_capability(capability, function)
1274                .fuel_cost(fuel_cost)
1275                .into_op(name.into()),
1276        );
1277        self
1278    }
1279
1280    pub(crate) fn install(self, rustia: &mut Rustia) -> Result<()> {
1281        let Some(namespace) = self.namespace else {
1282            return rustia
1283                .vm_mut()
1284                .install_host_functions(self.functions)
1285                .map_err(Error::from_engine);
1286        };
1287
1288        rustia
1289            .vm_mut()
1290            .install_host_module(namespace, self.functions)
1291            .map_err(Error::from_engine)
1292    }
1293}