diff --git a/Justfile b/Justfile index de10ebf5..68e86366 100644 --- a/Justfile +++ b/Justfile @@ -161,26 +161,30 @@ clean: -rm -f src/js-host-api/index.d.ts # TESTING +# On Windows, create surrogates on demand rather than pre-creating the pool in +# every test process. This leaves the maximum surrogate pool size unchanged. +test-env-command := if os() == "windows" { "$env:HYPERLIGHT_INITIAL_SURROGATES='0'; " } else { "" } + # Metrics tests cannot run with other tests they are marked as ignored so that cargo test works # There may be tests that we really want to ignore so we cant just use --ignored and run then we have to # specify the test name of the ignored tests that we want to run # NOTE: If features is non-empty, the test will be ran with no-default-features + the given features test target=default-target features="": (build target) - cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} --profile={{ if target == "debug" {"dev"} else { target } }} - cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} handle_termination --profile={{ if target == "debug" {"dev"} else { target } }} -- --ignored --nocapture - cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} test_metrics --profile={{ if target == "debug" {"dev"} else { target } }} -- --ignored --nocapture - cargo test --manifest-path=./src/hyperlight-js-runtime/Cargo.toml --test=native_cli --profile={{ if target == "debug" {"dev"} else { target } }} + {{ test-env-command }}cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} --profile={{ if target == "debug" {"dev"} else { target } }} + {{ test-env-command }}cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} handle_termination --profile={{ if target == "debug" {"dev"} else { target } }} -- --ignored --nocapture + {{ test-env-command }}cd src/hyperlight-js && cargo test {{ if features =="" {''} else if features=="no-default-features" {"--no-default-features" } else {"--no-default-features -F " + features } }} test_metrics --profile={{ if target == "debug" {"dev"} else { target } }} -- --ignored --nocapture + {{ test-env-command }}cargo test --manifest-path=./src/hyperlight-js-runtime/Cargo.toml --test=native_cli --profile={{ if target == "debug" {"dev"} else { target } }} just test-native-modules {{ target }} # Test with monitor features enabled (wall-clock and CPU time monitors) # Note: We exclude test_metrics (requires process isolation, already run by `test`) # and native_modules (requires custom guest runtime, run by `test-native-modules`) test-monitors target=default-target: - cd src/hyperlight-js && cargo test --features monitor-wall-clock,monitor-cpu-time --profile={{ if target == "debug" {"dev"} else { target } }} -- --include-ignored --skip test_metrics --skip custom_native_module --skip builtin_modules_work_with_custom --skip console_log_works_with_custom --skip custom_globals_and_host_clock + {{ test-env-command }}cd src/hyperlight-js && cargo test --features monitor-wall-clock,monitor-cpu-time --profile={{ if target == "debug" {"dev"} else { target } }} -- --include-ignored --skip test_metrics --skip custom_native_module --skip builtin_modules_work_with_custom --skip console_log_works_with_custom --skip custom_globals_and_host_clock test-js-host-api target=default-target features="": (build-js-host-api target features) - cargo test --manifest-path src/js-host-api/Cargo.toml --profile={{ if target == "debug" {"dev"} else { target } }} - cd src/js-host-api && npm test + {{ test-env-command }}cargo test --manifest-path src/js-host-api/Cargo.toml --profile={{ if target == "debug" {"dev"} else { target } }} + {{ test-env-command }}cd src/js-host-api && npm test # Test custom native modules: # 1. Runs the runtime crate's native_modules unit/pipeline tests (native binary) @@ -191,11 +195,11 @@ test-native-modules target=default-target: (check-fixture-lock) (_test-native-mo [private] _test-native-modules-unit target=default-target: - cargo test --manifest-path=./src/hyperlight-js-runtime/Cargo.toml --test=native_modules --profile={{ if target == "debug" {"dev"} else { target } }} + {{ test-env-command }}cargo test --manifest-path=./src/hyperlight-js-runtime/Cargo.toml --test=native_modules --profile={{ if target == "debug" {"dev"} else { target } }} [private] _test-native-modules-manifest target=default-target: - {{ set-env-command }}HYPERLIGHT_JS_RUNTIME_MANIFEST_PATH="{{PWD}}/src/hyperlight-js-runtime/tests/fixtures/extended_runtime/Cargo.toml" {{ if os() == "windows" { ";" } else { "&&" } }} cargo test -p hyperlight-js --test native_modules --test runtime_build --profile={{ if target == "debug" {"dev"} else { target } }} -- --include-ignored --nocapture + {{ test-env-command }}{{ set-env-command }}HYPERLIGHT_JS_RUNTIME_MANIFEST_PATH="{{PWD}}/src/hyperlight-js-runtime/tests/fixtures/extended_runtime/Cargo.toml" {{ if os() == "windows" { ";" } else { "&&" } }} cargo test -p hyperlight-js --test native_modules --test runtime_build --profile={{ if target == "debug" {"dev"} else { target } }} -- --include-ignored --nocapture [private] _test-native-modules-restore target=default-target: diff --git a/docs/execution-monitors.md b/docs/execution-monitors.md index adc32669..e95023c1 100644 --- a/docs/execution-monitors.md +++ b/docs/execution-monitors.md @@ -276,7 +276,7 @@ loaded.handle_event_with_monitor("handler", "{}".into(), &monitor, None)?; When a handler is terminated by a monitor: 1. `handle_event_with_monitor()` returns an error -2. The sandbox becomes "poisoned" (`sandbox.poisoned() == true`) +2. The sandbox becomes "poisoned" (`sandbox.status().is_poisoned()`) 3. To reuse the sandbox, call `sandbox.restore(&snapshot)` ```rust @@ -289,7 +289,7 @@ let result = loaded_sandbox.handle_event_with_monitor( None, ); -if result.is_err() && loaded_sandbox.poisoned() { +if result.is_err() && loaded_sandbox.status().is_poisoned() { // Handler was killed - restore to continue using sandbox loaded_sandbox.restore(&snapshot)?; } diff --git a/src/hyperlight-js/src/sandbox/host_fn.rs b/src/hyperlight-js/src/sandbox/host_fn.rs index 4fd831dd..72b1c68d 100644 --- a/src/hyperlight-js/src/sandbox/host_fn.rs +++ b/src/hyperlight-js/src/sandbox/host_fn.rs @@ -159,9 +159,9 @@ pub(crate) fn decode_binaries(data: Vec) -> crate::Result>> { .map_err(|e| crate::HyperlightError::Error(e.to_string())) } -/// A module containing host functions that can be called from the guest JavaScript code. +/// Internal callback storage for a [`HostFunctionModule`]. #[derive(Default)] -pub struct HostModule { +pub(crate) struct HostModule { functions: HashMap, } @@ -182,22 +182,8 @@ impl HostModule { self.functions.keys().map(String::as_str) } - /// Register a typed host function that can be called from the guest - /// JavaScript code. - /// - /// Arguments are deserialized from JSON via serde and the return value - /// is serialized back to JSON automatically. - /// - /// This variant does **not** support `Uint8Array`/`Buffer` arguments. - /// For binary data support, use the JS bridge API instead. - /// - /// ```text - /// module.register("add", |a: i32, b: i32| a + b); - /// ``` - /// - /// Registering a function with the same `name` as an existing function - /// overwrites the previous registration. - pub fn register( + /// Store a typed callback supplied through [`HostFunctionModule::register`]. + pub(crate) fn register( &mut self, name: impl Into, func: impl Function + Send + Sync + 'static, @@ -207,16 +193,8 @@ impl HostModule { self } - /// Register a host function for the JavaScript bridge (NAPI layer). - /// - /// This is an internal API used by the `js-host-api` NAPI bridge. - /// Rust users should use [`register`](Self::register) instead, which - /// handles binary data transparently via serde. - /// - /// The closure receives parsed `JsonValue` args and decoded binary - /// blobs directly. Return [`FnReturn::Json`] or [`FnReturn::Binary`]. - #[doc(hidden)] - pub fn register_js( + /// Store a callback supplied through [`HostFunctionModule::register_js`]. + pub(crate) fn register_js( &mut self, name: impl Into, func: impl Fn(JsonValue, Vec>) -> crate::Result + Send + Sync + 'static, @@ -316,6 +294,19 @@ impl HostFunctionModule { } /// Register a typed host function on this module. + /// + /// Arguments are deserialized from JSON via serde and the return value + /// is serialized back to JSON automatically. + /// + /// This variant does **not** support `Uint8Array`/`Buffer` arguments. + /// For binary data support, use the JS bridge API instead. + /// + /// ```text + /// module.register("add", |a: i32, b: i32| a + b); + /// ``` + /// + /// Registering a function with the same `name` as an existing function + /// overwrites the previous registration. pub fn register( &mut self, name: impl Into, @@ -326,6 +317,9 @@ impl HostFunctionModule { } /// Register a JavaScript-bridge host function on this module. + /// + /// The closure receives parsed JSON arguments and decoded binary blobs. + /// Return [`FnReturn::Json`] or [`FnReturn::Binary`]. #[doc(hidden)] pub fn register_js( &mut self, diff --git a/src/hyperlight-js/src/sandbox/js_sandbox.rs b/src/hyperlight-js/src/sandbox/js_sandbox.rs index b158e4a4..ba53dc3c 100644 --- a/src/hyperlight-js/src/sandbox/js_sandbox.rs +++ b/src/hyperlight-js/src/sandbox/js_sandbox.rs @@ -43,7 +43,7 @@ pub const DEFAULT_MODULE_NAMESPACE: &str = "user"; /// Reserved namespaces that cannot be used for user modules. /// /// The `host` namespace is reserved for host-function modules registered via -/// [`ProtoJSSandbox::host_module`]. +/// [`SandboxBuilder::with_host_function_modules`](crate::SandboxBuilder::with_host_function_modules). pub const RESERVED_NAMESPACES: &[&str] = &["host"]; /// Validates a module identifier (name or namespace). @@ -375,12 +375,6 @@ impl JSSandbox { self.modules.clear(); } - /// Returns whether the sandbox is currently poisoned. - #[deprecated(since = "0.4.0", note = "use status().is_poisoned()")] - pub fn poisoned(&self) -> bool { - self.inner.status().is_poisoned() - } - /// Returns the sandbox lifecycle status. pub fn status(&self) -> SandboxStatus { self.inner.status() diff --git a/src/hyperlight-js/src/sandbox/loaded_js_sandbox.rs b/src/hyperlight-js/src/sandbox/loaded_js_sandbox.rs index 1bb47cae..8a341b2b 100644 --- a/src/hyperlight-js/src/sandbox/loaded_js_sandbox.rs +++ b/src/hyperlight-js/src/sandbox/loaded_js_sandbox.rs @@ -248,12 +248,6 @@ impl LoadedJSSandbox { self.inner.interrupt_handle() } - /// Returns whether the sandbox is currently poisoned. - #[deprecated(since = "0.4.0", note = "use status().is_poisoned()")] - pub fn poisoned(&self) -> bool { - self.inner.status().is_poisoned() - } - /// Returns the sandbox lifecycle status. pub fn status(&self) -> SandboxStatus { self.inner.status() diff --git a/src/hyperlight-js/src/sandbox/proto_js_sandbox.rs b/src/hyperlight-js/src/sandbox/proto_js_sandbox.rs index 683d9fc5..0499c5e8 100644 --- a/src/hyperlight-js/src/sandbox/proto_js_sandbox.rs +++ b/src/hyperlight-js/src/sandbox/proto_js_sandbox.rs @@ -14,21 +14,16 @@ See the License for the specific language governing permissions and limitations under the License. */ use std::collections::HashMap; -use std::fmt::Debug; use std::time::SystemTime; use anyhow::Context; use hyperlight_host::sandbox::SandboxConfiguration; use hyperlight_host::{GuestBinary, Result, UninitializedSandbox}; -use serde::de::DeserializeOwned; -use serde::Serialize; use tracing::{instrument, Level}; use super::js_sandbox::JSSandbox; use super::sandbox_builder::SandboxBuilder; -use crate::sandbox::host_fn::{ - host_function_dispatch, host_function_manifest, Function, HostModule, -}; +use crate::sandbox::host_fn::{host_function_dispatch, host_function_manifest, HostModule}; use crate::sandbox::metrics::SandboxMetricsGuard; use crate::sandbox::module_loader::ExternalModuleLoader; use crate::HostPrintFn; @@ -42,8 +37,8 @@ pub(super) fn current_time_micros() -> hyperlight_host::Result { /// A fresh Hyperlight sandbox before the JavaScript runtime is loaded. /// -/// Register host resources, then call [`Self::load_runtime`] to create a -/// [`JSSandbox`]. Restore snapshots with [`crate::SandboxBuilder::from_snapshot`]. +/// Configure host resources on [`SandboxBuilder`], then call [`Self::load_runtime`] +/// to create a [`JSSandbox`]. Restore snapshots with [`crate::SandboxBuilder::from_snapshot`]. pub struct ProtoJSSandbox { inner: UninitializedSandbox, host_modules: HashMap, @@ -79,21 +74,6 @@ impl ProtoJSSandbox { }) } - /// Install a custom file system for module resolution and loading. - /// - /// Enables JavaScript module imports using the provided ~FileSystem~ implementation. - #[deprecated( - note = "Use SandboxBuilder::with_module_loader, which also works when restoring snapshots" - )] - #[instrument(err(Debug), skip_all, level=Level::INFO)] - pub fn set_module_loader( - mut self, - file_system: Fs, - ) -> Result { - ExternalModuleLoader::new(file_system).register(&mut self.inner)?; - Ok(self) - } - /// Load the JavaScript runtime into the sandbox. #[instrument(err(Debug), skip(self), level=Level::INFO)] pub fn load_runtime(mut self) -> Result { @@ -113,67 +93,6 @@ impl ProtoJSSandbox { JSSandbox::new(multi_use_sandbox, host_functions) } - - /// Register a host module that can be called from the guest JavaScript code. - /// - /// This method should be called **before** [`ProtoJSSandbox::load_runtime`], while - /// the sandbox is still in its "proto" (uninitialized) state. After - /// [`load_runtime`](Self::load_runtime) is called, the set of host modules and - /// functions is fixed for the resulting [`JSSandbox`]. - /// - /// Calling this method multiple times with the same `name` refers to the same - /// module; additional calls will reuse the existing module instance and allow - /// you to register more functions on it. The first call creates the module and - /// subsequent calls return the previously created module. - /// - /// Module names are matched by exact string equality from the guest - /// JavaScript environment. They should be valid UTF‑8 strings and while there is - /// no explicit restriction on special characters, using simple, ASCII identifiers - /// (e.g. `"fs"`, `"net"`, `"my_module"`) is recommended for portability and clarity. - /// - /// # Example - /// - /// ``` - /// # #![allow(deprecated)] - /// use hyperlight_js::SandboxBuilder; - /// - /// // Create a proto sandbox and register a host function. - /// let mut sbox = SandboxBuilder::new().build()?; - /// - /// // Register a module and a function on it before loading the runtime. - /// sbox.host_module("math").register("add", |a: i32, b: i32| a + b); - /// - /// // Once all host modules/functions are registered, load the JS runtime. - /// let js_sandbox = sbox.load_runtime()?; - /// # Ok::<(), hyperlight_host::HyperlightError>(()) - /// ``` - #[deprecated( - note = "Use SandboxBuilder::with_host_function_modules, which also works when restoring snapshots" - )] - #[instrument(skip(self), level=Level::INFO)] - pub fn host_module(&mut self, name: impl Into + Debug) -> &mut HostModule { - self.host_modules.entry(name.into()).or_default() - } - - /// Register a host function that can be called from the guest JavaScript code. - /// This is equivalent to calling `sbox.host_module(module).register(name, func)`. - /// - /// Registering a function with the same `module` and `name` as an existing function - /// overwrites the previous registration. - #[deprecated( - note = "Use SandboxBuilder::with_host_function_modules, which also works when restoring snapshots" - )] - #[instrument(err(Debug), skip(self, func), level=Level::INFO)] - pub fn register( - &mut self, - module: impl Into + Debug, - name: impl Into + Debug, - func: impl Function + Send + Sync + 'static, - ) -> Result<()> { - #[allow(deprecated)] - self.host_module(module).register(name, func); - Ok(()) - } } impl std::fmt::Debug for ProtoJSSandbox { diff --git a/src/hyperlight-js/src/sandbox/sandbox_builder.rs b/src/hyperlight-js/src/sandbox/sandbox_builder.rs index 80fd822b..b31766f4 100644 --- a/src/hyperlight-js/src/sandbox/sandbox_builder.rs +++ b/src/hyperlight-js/src/sandbox/sandbox_builder.rs @@ -55,10 +55,6 @@ pub struct SandboxBuilder { #[cfg(gdb)] guest_debug_info: Option, host_print_fn: Option, - /// Requested legacy input capacity in bytes, also used for host replies. - legacy_input_capacity: usize, - /// Requested legacy output capacity in bytes, used for host requests. - legacy_output_capacity: usize, /// Explicit input budget before minimum-size normalization, if set. requested_input_pool_pages: Option, /// Explicit output budget before minimum-size normalization, if set. @@ -79,15 +75,12 @@ pub struct SandboxBuilder { /// Increase it for allocation-heavy handlers or larger transport pools. const MIN_SCRATCH_SIZE: usize = 5 * 1024 * 1024; -/// The previous 16 KiB message capacity for each direction. -const DEFAULT_LEGACY_BUFFER_SIZE: usize = 16 * 1024; +/// Message capacity reserved in each direction when no pool budget is supplied. +const DEFAULT_TRANSPORT_MESSAGE_CAPACITY: usize = 16 * 1024; /// Default capacity of each full-size transport buffer. const DEFAULT_TRANSPORT_BUFFER_SIZE: usize = 16 * 1024; -/// The previous 8 KiB minimum for byte-based buffer configuration. -const MIN_LEGACY_BUFFER_SIZE: usize = 8 * 1024; - impl SandboxBuilder { fn with_source(source: S) -> Self { let mut config = SandboxConfiguration::default(); @@ -101,8 +94,6 @@ impl SandboxBuilder { #[cfg(gdb)] guest_debug_info: None, host_print_fn: None, - legacy_input_capacity: DEFAULT_LEGACY_BUFFER_SIZE, - legacy_output_capacity: DEFAULT_LEGACY_BUFFER_SIZE, input_transport_buffer_size: DEFAULT_TRANSPORT_BUFFER_SIZE, output_transport_buffer_size: DEFAULT_TRANSPORT_BUFFER_SIZE, requested_input_pool_pages: None, @@ -174,26 +165,6 @@ impl SandboxBuilder { self } - /// Set the guest-to-host message capacity in bytes. - #[deprecated(note = "Use with_output_transport_pool_pages for an explicit pool budget")] - pub fn with_guest_output_buffer_size(mut self, guest_output_buffer_size: usize) -> Self { - self.legacy_output_capacity = guest_output_buffer_size; - self.requested_output_pool_pages = None; - - self - } - - /// Set the host-to-guest message capacity in bytes. - /// Also reserves output-pool space for host callback replies. - #[deprecated(note = "Use with_input_transport_pool_pages for explicit pool budgets")] - pub fn with_guest_input_buffer_size(mut self, guest_input_buffer_size: usize) -> Self { - self.legacy_input_capacity = guest_input_buffer_size; - self.requested_input_pool_pages = None; - self.requested_output_pool_pages = None; - - self - } - /// Set the total guest-to-host buffer pool size in 4 KiB pages. /// /// One page is split into small buffers. The rest must fit at least two @@ -224,7 +195,7 @@ impl SandboxBuilder { /// than one buffer, including framing, are split across buffers. /// /// Pool and descriptor sizing is deferred to configuration resolution, - /// preserving explicit page budgets or legacy message capacities. + /// preserving explicit page budgets or the default message capacity. pub fn with_output_transport_buffer_size(mut self, size: usize) -> Self { self.output_transport_buffer_size = size; @@ -237,7 +208,7 @@ impl SandboxBuilder { /// Messages larger than one buffer, including framing, are split across buffers. /// /// Pool and descriptor sizing is deferred to configuration resolution, - /// preserving explicit page budgets or legacy message capacities. + /// preserving explicit page budgets or the default message capacity. pub fn with_input_transport_buffer_size(mut self, size: usize) -> Self { self.input_transport_buffer_size = size; @@ -303,8 +274,8 @@ impl SandboxBuilder { self } - /// Normalizes buffer sizes, applies explicit pool budgets or legacy - /// capacities, and sizes descriptor queues from the complete buffer counts. + /// Normalizes buffer sizes and pool budgets, and sizes descriptor queues + /// from the complete buffer counts. /// Reserves a control spare and room for simultaneous callback requests/replies. /// /// Saturating arithmetic leaves unrepresentable pool sizes for Hyperlight's @@ -316,26 +287,20 @@ impl SandboxBuilder { let inbufsz = config.get_h2g_buffer_size(); let outbufsz = config.get_g2h_buffer_size(); - let input_cap = Self::legacy_capacity(self.legacy_input_capacity); - let output_cap = Self::legacy_capacity(self.legacy_output_capacity); - let input_pages = match self.requested_input_pool_pages { Some(pages) => pages.max(Self::pages_for_buffers(2, inbufsz)), - None => { - let data_buffers = input_cap.div_ceil(inbufsz); - - // Keep one buffer free for control calls that release retained external payloads. - Self::pages_for_buffers(data_buffers + 1, inbufsz) - } + None => Self::pages_for_buffers( + DEFAULT_TRANSPORT_MESSAGE_CAPACITY.div_ceil(inbufsz) + 1, + inbufsz, + ), }; - let output_pages = match self.requested_output_pool_pages { Some(pages) => pages.max(1 + Self::pages_for_buffers(2, outbufsz)), None => { - let req_bufs = output_cap.div_ceil(outbufsz); - let reply_bufs = input_cap.div_ceil(outbufsz); - // The output pool needs one extra page for its fixed 256-byte small-buffer tier. - 1 + Self::pages_for_buffers(req_bufs + reply_bufs, outbufsz) + 1 + Self::pages_for_buffers( + 2 * DEFAULT_TRANSPORT_MESSAGE_CAPACITY.div_ceil(outbufsz), + outbufsz, + ) } }; @@ -353,15 +318,6 @@ impl SandboxBuilder { config.set_g2h_queue_size(output_buffers.max(SandboxConfiguration::DEFAULT_G2H_QUEUE_SIZE)); } - /// Applies the legacy 8 KiB minimum and rounds byte capacity up to whole pages. - /// Saturates if the rounded capacity cannot be represented. - fn legacy_capacity(bytes: usize) -> usize { - bytes - .max(MIN_LEGACY_BUFFER_SIZE) - .div_ceil(PAGE_SIZE) - .saturating_mul(PAGE_SIZE) - } - /// Rounds the combined buffer storage up to pages, saturating on overflow. fn pages_for_buffers(count: usize, buffer_size: usize) -> usize { count.saturating_mul(buffer_size).div_ceil(PAGE_SIZE) diff --git a/src/hyperlight-js/tests/host_functions.rs b/src/hyperlight-js/tests/host_functions.rs index a821c336..e8627678 100644 --- a/src/hyperlight-js/tests/host_functions.rs +++ b/src/hyperlight-js/tests/host_functions.rs @@ -16,8 +16,6 @@ limitations under the License. //! Test for host modules / functions. #![allow(clippy::disallowed_macros)] -// Most tests here cover the deprecated ProtoJSSandbox registration API. -#![allow(deprecated)] use std::cell::RefCell; use std::sync::Once; @@ -47,20 +45,20 @@ fn can_call_host_functions() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox - .register("host", "print", |msg: String| { - assert_eq!(msg, "Hello, World!!"); - 42 - }) - .unwrap(); - proto_js_sandbox - .register("utils", "add", |a: i32, b: i32| { - assert_eq!(a, 42); - assert_eq!(b, 24); - 66 - }) + let mut host = HostFunctionModule::new("host"); + host.register("print", |msg: String| { + assert_eq!(msg, "Hello, World!!"); + 42 + }); + let mut utils = HostFunctionModule::new("utils"); + utils.register("add", |a: i32, b: i32| { + assert_eq!(a, 42); + assert_eq!(b, 24); + 66 + }); + let proto_js_sandbox = SandboxBuilder::new() + .with_host_function_modules([host, utils]) + .build() .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); @@ -90,20 +88,20 @@ fn should_fail_for_invalid_host_function() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox - .register("host", "print", |msg: String| { - assert_eq!(msg, "Hello, World!!"); - 42 - }) - .unwrap(); - proto_js_sandbox - .register("utils", "add", |a: i32, b: i32| { - assert_eq!(a, 42); - assert_eq!(b, 24); - 66 - }) + let mut host = HostFunctionModule::new("host"); + host.register("print", |msg: String| { + assert_eq!(msg, "Hello, World!!"); + 42 + }); + let mut utils = HostFunctionModule::new("utils"); + utils.register("add", |a: i32, b: i32| { + assert_eq!(a, 42); + assert_eq!(b, 24); + 66 + }); + let proto_js_sandbox = SandboxBuilder::new() + .with_host_function_modules([host, utils]) + .build() .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); @@ -132,17 +130,14 @@ fn host_modules_should_contain_all_host_functions() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.register("host", "life", || 42).unwrap(); - proto_js_sandbox - .register("host", "add", |a: i32, b: i32| a + b) - .unwrap(); - proto_js_sandbox - .register("host", "hello", || String::from("Hello, World!")) - .unwrap(); - proto_js_sandbox - .register("host", "no-op", || String::from("Hello, World!")) + let mut host = HostFunctionModule::new("host"); + host.register("life", || 42); + host.register("add", |a: i32, b: i32| a + b); + host.register("hello", || String::from("Hello, World!")); + host.register("no-op", || String::from("Hello, World!")); + let proto_js_sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); @@ -174,10 +169,11 @@ fn host_fn_call_should_fail_if_wrong_arg_types() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox - .register("host", "add", |a: i32, b: i32| a + b) + let mut host = HostFunctionModule::new("host"); + host.register("add", |a: i32, b: i32| a + b); + let proto_js_sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); @@ -206,10 +202,11 @@ fn host_fn_with_unusual_names() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox - .register("host", "scoped/add/😊", |a: i32, b: i32| a + b) + let mut host = HostFunctionModule::new("host"); + host.register("scoped/add/😊", |a: i32, b: i32| a + b); + let proto_js_sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); @@ -246,10 +243,9 @@ fn minimum_pool_pages_support_host_callbacks() { assert_eq!(config.get_h2g_pool_pages(), input_pages); assert_eq!(config.get_g2h_pool_pages(), output_pages); - let mut proto = builder.build().unwrap(); - proto - .register("host", "echo", |value: String| value) - .unwrap(); + let mut host = HostFunctionModule::new("host"); + host.register("echo", |value: String| value); + let proto = builder.with_host_function_modules([host]).build().unwrap(); let mut sandbox = proto.load_runtime().unwrap(); sandbox @@ -300,33 +296,32 @@ fn register_js_chunked_sidecar_round_trip() { "#, ); - let mut proto = SandboxBuilder::new() + let mut host = HostFunctionModule::new("host"); + host.register_js("echo", |args, mut blobs| { + assert_eq!( + args, + serde_json::json!([ + { "payload": { "__bin__": 0 }, "empty": { "__bin__": 1 } }, + { "__bin__": 2 }, + ]) + ); + assert_eq!(blobs.len(), 3); + assert!(blobs[1].is_empty()); + assert_eq!(blobs[2], [9, 8, 7]); + + for (index, byte) in blobs[0].iter().enumerate() { + assert_eq!(*byte as usize, (index + 1) % 251); + } + + Ok(hyperlight_js::FnReturn::Binary(blobs.remove(0))) + }); + + let proto = SandboxBuilder::new() .with_input_transport_pool_pages(64) .with_output_transport_pool_pages(128) + .with_host_function_modules([host]) .build() .unwrap(); - - proto - .host_module("host") - .register_js("echo", |args, mut blobs| { - assert_eq!( - args, - serde_json::json!([ - { "payload": { "__bin__": 0 }, "empty": { "__bin__": 1 } }, - { "__bin__": 2 }, - ]) - ); - assert_eq!(blobs.len(), 3); - assert!(blobs[1].is_empty()); - assert_eq!(blobs[2], [9, 8, 7]); - - for (index, byte) in blobs[0].iter().enumerate() { - assert_eq!(*byte as usize, (index + 1) % 251); - } - - Ok(hyperlight_js::FnReturn::Binary(blobs.remove(0))) - }); - let mut sandbox = proto.load_runtime().unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -371,9 +366,8 @@ fn register_js_binary_arg_round_trip() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "byte_length", |_args: serde_json::Value, blobs: Vec>| { // The first arg should be a placeholder {"__bin__": 0} @@ -390,7 +384,12 @@ fn register_js_binary_arg_round_trip() { }, ); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -416,16 +415,20 @@ fn register_js_binary_return() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "get_bytes", |_args: serde_json::Value, _blobs: Vec>| { Ok(hyperlight_js::FnReturn::Binary(vec![10, 20, 30, 40, 50])) }, ); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -451,9 +454,8 @@ fn register_js_mixed_args() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "describe", |args: serde_json::Value, blobs: Vec>| { // args is [{"__bin__": 0}, "pfx", 42] or ["pfx", {"__bin__": 0}, 42] @@ -478,7 +480,12 @@ fn register_js_mixed_args() { }, ); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -508,12 +515,14 @@ fn register_typed_rejects_binary_args_e2e() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - proto_js_sandbox - .register("host", "add", |a: i32, b: i32| a + b) + let mut host = HostFunctionModule::new("host"); + host.register("add", |a: i32, b: i32| a + b); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() .unwrap(); - - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -540,9 +549,8 @@ fn register_js_empty_uint8array() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "byte_length", |_args: serde_json::Value, blobs: Vec>| { let len = blobs.first().map(|b| b.len()).unwrap_or(0); @@ -552,7 +560,12 @@ fn register_js_empty_uint8array() { }, ); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -579,9 +592,8 @@ fn register_js_multiple_binary_args() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "total_length", |_args: serde_json::Value, blobs: Vec>| { let total: usize = blobs.iter().map(|b| b.len()).sum(); @@ -591,7 +603,12 @@ fn register_js_multiple_binary_args() { }, ); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -621,25 +638,26 @@ fn register_js_binary_in_nested_object() { let event = r#"{}"#; - let mut proto_js_sandbox = SandboxBuilder::new().build().unwrap(); - - proto_js_sandbox.host_module("host").register_js( - "process", - |args: serde_json::Value, blobs: Vec>| { - // The object should have {"name": "test", "data": {"__bin__": 0}, "count": 3} - // with blobs containing [10, 20, 30] - let arr = args.as_array().unwrap(); - let obj = arr[0].as_object().unwrap(); - let name = obj.get("name").unwrap().as_str().unwrap(); - let blob_len = blobs.first().map(|b| b.len()).unwrap_or(0); - let result = format!("{name}-{blob_len}"); - let json = serde_json::to_string(&result) - .map_err(|e| hyperlight_js::HyperlightError::Error(format!("{e}")))?; - Ok(hyperlight_js::FnReturn::Json(json)) - }, - ); + let mut host = HostFunctionModule::new("host"); + host.register_js("process", |args: serde_json::Value, blobs: Vec>| { + // The object should have {"name": "test", "data": {"__bin__": 0}, "count": 3} + // with blobs containing [10, 20, 30] + let arr = args.as_array().unwrap(); + let obj = arr[0].as_object().unwrap(); + let name = obj.get("name").unwrap().as_str().unwrap(); + let blob_len = blobs.first().map(|b| b.len()).unwrap_or(0); + let result = format!("{name}-{blob_len}"); + let json = serde_json::to_string(&result) + .map_err(|e| hyperlight_js::HyperlightError::Error(format!("{e}")))?; + Ok(hyperlight_js::FnReturn::Json(json)) + }); - let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded_sandbox = sandbox.get_loaded_sandbox().unwrap(); @@ -669,10 +687,14 @@ fn host_fn_with_i32_arg_from_event_data() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("math", "double", |x: i32| x * 2).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut math = HostFunctionModule::new("math"); + math.register("double", |x: i32| x * 2); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -693,10 +715,14 @@ fn host_fn_with_i64_arg_from_event_data() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("math", "negate", |x: i64| -x).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut math = HostFunctionModule::new("math"); + math.register("negate", |x: i64| -x); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -718,10 +744,14 @@ fn host_fn_with_f64_arg_preserves_fractional() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("math", "half", |x: f64| x / 2.0).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut math = HostFunctionModule::new("math"); + math.register("half", |x: f64| x / 2.0); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -748,10 +778,14 @@ fn host_fn_with_bool_arg() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("logic", "flip", |b: bool| !b).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut logic = HostFunctionModule::new("logic"); + logic.register("flip", |flag: bool| !flag); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([logic]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -773,14 +807,16 @@ fn host_fn_with_mixed_numeric_types() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto - .register("math", "weighted_add", |a: i32, b: i32, w: f64| { - (a as f64 * w + b as f64 * (1.0 - w)) as i32 - }) + let mut math = HostFunctionModule::new("math"); + math.register("weighted_add", |a: i32, b: i32, w: f64| { + (a as f64 * w + b as f64 * (1.0 - w)) as i32 + }); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() .unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -805,10 +841,14 @@ fn host_fn_with_negative_integer() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("math", "abs", |x: i32| x.abs()).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut math = HostFunctionModule::new("math"); + math.register("abs", |x: i32| x.abs()); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -829,10 +869,14 @@ fn host_fn_with_zero() { "#, ); - let mut proto = SandboxBuilder::new().build().unwrap(); - proto.register("math", "inc", |x: i32| x + 1).unwrap(); - - let mut sandbox = proto.load_runtime().unwrap(); + let mut math = HostFunctionModule::new("math"); + math.register("inc", |x: i32| x + 1); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([math]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -849,21 +893,23 @@ fn host_fn_with_zero() { /// Borrowed return decoding still produces independently owned, mutable arrays. #[test] fn register_js_repeated_binary_returns_are_independent() { - let mut proto = SandboxBuilder::new().build().unwrap(); - - proto - .host_module("host") - .register_js("get_payload", |_, _| { - let sidecar = hyperlight_js_common::encode_binaries(&[b"ABC".as_slice(), b""]) - .map_err(|error| hyperlight_js::HyperlightError::Error(error.to_string()))?; - - Ok(hyperlight_js::FnReturn::JsonWithBinaries( - r#"{"first":{"__bin__":0},"again":{"__bin__":0},"empty":{"__bin__":1}}"#.into(), - sidecar, - )) - }); + let mut host = HostFunctionModule::new("host"); + host.register_js("get_payload", |_, _| { + let sidecar = hyperlight_js_common::encode_binaries(&[b"ABC".as_slice(), b""]) + .map_err(|error| hyperlight_js::HyperlightError::Error(error.to_string()))?; + + Ok(hyperlight_js::FnReturn::JsonWithBinaries( + r#"{"first":{"__bin__":0},"again":{"__bin__":0},"empty":{"__bin__":1}}"#.into(), + sidecar, + )) + }); - let mut sandbox = proto.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox .add_handler( "handler", @@ -921,9 +967,8 @@ fn register_js_nested_binary_return_in_object() { let event = r#"{}"#; - let mut proto = SandboxBuilder::new().build().unwrap(); - - proto.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "get_payload", |_args: serde_json::Value, _blobs: Vec>| { // Return JSON + sidecar: {"name": "test", "data": {"__bin__": 0}} @@ -939,7 +984,12 @@ fn register_js_nested_binary_return_in_object() { }, ); - let mut sandbox = proto.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -970,9 +1020,8 @@ fn register_js_nested_binary_return_in_array() { let event = r#"{}"#; - let mut proto = SandboxBuilder::new().build().unwrap(); - - proto.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "get_items", |_args: serde_json::Value, _blobs: Vec>| { // Return an array of two binary blobs @@ -985,7 +1034,12 @@ fn register_js_nested_binary_return_in_array() { }, ); - let mut sandbox = proto.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -1018,9 +1072,8 @@ fn register_js_deeply_nested_binary_return() { let event = r#"{}"#; - let mut proto = SandboxBuilder::new().build().unwrap(); - - proto.host_module("host").register_js( + let mut host = HostFunctionModule::new("host"); + host.register_js( "get_nested", |_args: serde_json::Value, _blobs: Vec>| { let sidecar = hyperlight_js_common::encode_binaries(&[&[0xABu8, 0xCD][..]]) @@ -1039,7 +1092,12 @@ fn register_js_deeply_nested_binary_return() { }, ); - let mut sandbox = proto.load_runtime().unwrap(); + let mut sandbox = SandboxBuilder::new() + .with_host_function_modules([host]) + .build() + .unwrap() + .load_runtime() + .unwrap(); sandbox.add_handler("handler", handler).unwrap(); let mut loaded = sandbox.get_loaded_sandbox().unwrap(); @@ -1052,9 +1110,9 @@ fn register_js_deeply_nested_binary_return() { #[test] fn js_restore_rejects_missing_host_function_before_mutation() { - let mut source_proto = SandboxBuilder::new().build().unwrap(); - source_proto - .register("required", "value", |_: i32| 1) + let source_proto = SandboxBuilder::new() + .with_host_function_modules([required_host_function_module()]) + .build() .unwrap(); let mut source = source_proto.load_runtime().unwrap(); source @@ -1094,9 +1152,9 @@ fn js_restore_rejects_missing_host_function_before_mutation() { #[test] fn loaded_restore_rejects_missing_host_function_before_mutation() { - let mut source_proto = SandboxBuilder::new().build().unwrap(); - source_proto - .register("required", "value", |_: i32| 1) + let source_proto = SandboxBuilder::new() + .with_host_function_modules([required_host_function_module()]) + .build() .unwrap(); let mut source = source_proto.load_runtime().unwrap(); source diff --git a/src/hyperlight-js/tests/module_loader.rs b/src/hyperlight-js/tests/module_loader.rs index a3d44cc4..1c3d3325 100644 --- a/src/hyperlight-js/tests/module_loader.rs +++ b/src/hyperlight-js/tests/module_loader.rs @@ -138,12 +138,9 @@ fn test_handler_import_restrictions() { } "#; - // Compatibility coverage for callers that still configure a fresh ProtoJSSandbox. - #[allow(deprecated)] let proto_js_sandbox = SandboxBuilder::new() + .with_module_loader(fs) .build() - .unwrap() - .set_module_loader(fs) .unwrap(); let mut sandbox = proto_js_sandbox.load_runtime().unwrap(); diff --git a/src/js-host-api/README.md b/src/js-host-api/README.md index 2e0aa944..70fab479 100644 --- a/src/js-host-api/README.md +++ b/src/js-host-api/README.md @@ -56,8 +56,6 @@ Creates and configures a new sandbox. - `setOutputTransportPoolPages(pages: number)` → `this` — Set the guest-to-host buffer pool size in 4 KiB pages (must be > 0, chainable) - `setInputTransportBufferSize(bytes: number)` → `this` — Set the capacity of each host-to-guest transport buffer (must be > 0, chainable) - `setOutputTransportBufferSize(bytes: number)` → `this` — Set the capacity of each large guest-to-host transport buffer (must be > 0, chainable) -- `setInputBufferSize(bytes: number)` → `this` — **Deprecated:** set legacy input/host-reply capacity in bytes; use `setInputTransportPoolPages` and `setOutputTransportPoolPages` for explicit pool budgets -- `setOutputBufferSize(bytes: number)` → `this` — **Deprecated:** set legacy output/host-request capacity in bytes; use `setOutputTransportPoolPages` - `setHostFunctionModules(modules: HostFunctionModule[])` → `this` — Supply host callbacks for one sandbox. Each module is consumed - `build()` → `Promise` — Builds a proto sandbox ready to load the JavaScript runtime @@ -81,7 +79,6 @@ Configure host functions on `SandboxBuilder` before calling `build()`. **Methods:** - `loadRuntime()` → `Promise` — Loads the JavaScript runtime into the sandbox. -- `hostModule()` / `register()` — **Deprecated:** use `SandboxBuilder.setHostFunctionModules()`, which also works when restoring snapshots. ```javascript function hostFunctionModules() { @@ -160,7 +157,6 @@ A sandbox with handlers loaded, ready to process events. **Properties:** - `interruptHandle` → `InterruptHandle` — Gets a handle to interrupt/kill handler execution (getter, not a method) - `status` → `SandboxStatus` — Lifecycle status: `ready`, `poisoned`, or `unrecoverable` -- `poisoned` → `boolean` — Deprecated compatibility alias for `status === 'poisoned'` - `lastCallStats` → `CallStats | null` — Execution statistics from the most recent `callHandler()` call (see [CallStats](#callstats-) below) ```javascript diff --git a/src/js-host-api/examples/cpu-timeout.js b/src/js-host-api/examples/cpu-timeout.js index ef3a440f..1638a5b3 100644 --- a/src/js-host-api/examples/cpu-timeout.js +++ b/src/js-host-api/examples/cpu-timeout.js @@ -48,7 +48,7 @@ async function main() { console.log(` ✅ SUCCESS: Handler completed!`); console.log(` 📊 Counter: ${result.counter.toLocaleString()}`); printCallStats(loaded); - console.log(` 🔒 Poisoned: ${loaded.poisoned}\n`); + console.log(` 🔒 Status: ${loaded.status}\n`); } catch (err) { console.log(` ❌ Unexpected timeout: ${err.message}\n`); } @@ -101,13 +101,13 @@ async function main() { console.log(` ⚡ CPU time limit: 500ms (fired first for compute-bound work)`); console.log(` ⏱️ Wall-clock limit: 5000ms (backstop, not reached)`); printCallStats(loaded); - console.log(` 🔒 Poisoned: ${loaded.poisoned} (sandbox is in inconsistent state)`); + console.log(` 🔒 Status: ${loaded.status} (sandbox is in inconsistent state)`); console.log(` ✅ SUCCESS: Timeout enforced correctly!\n`); // Demonstrate recovery from poisoned state console.log('📸 Restoring sandbox from snapshot...'); await loaded.restore(snapshot); - console.log(` 🔒 Poisoned after restore: ${loaded.poisoned}`); + console.log(` 🔒 Status after restore: ${loaded.status}`); console.log(' ✅ Sandbox recovered and ready for use!\n'); } else { console.log(` ❌ Unexpected error: ${err.message}\n`); diff --git a/src/js-host-api/examples/interrupt.js b/src/js-host-api/examples/interrupt.js index 854a855b..c2fb0a8d 100644 --- a/src/js-host-api/examples/interrupt.js +++ b/src/js-host-api/examples/interrupt.js @@ -49,7 +49,7 @@ async function main() { console.log(` ✅ SUCCESS: Handler completed in ${elapsed}ms`); console.log(` 📊 Counter: ${result.counter.toLocaleString()}`); console.log(` 🎯 Timeout: 1000ms (not reached)`); - console.log(` 🔒 Poisoned: ${loaded.poisoned}\n`); + console.log(` 🔒 Status: ${loaded.status}\n`); } catch (err) { console.log(` ❌ Unexpected timeout: ${err.message}\n`); } @@ -94,13 +94,13 @@ async function main() { if (err.code === 'ERR_CANCELLED') { console.log(` 💀 Handler killed after ~${elapsed}ms`); console.log(` ⏱️ Expected: ~1000ms`); - console.log(` 🔒 Poisoned: ${loaded.poisoned} (sandbox is in inconsistent state)`); + console.log(` 🔒 Status: ${loaded.status} (sandbox is in inconsistent state)`); console.log(` ✅ SUCCESS: Handler was properly interrupted!\n`); // Demonstrate recovery from poisoned state console.log('📸 Restoring sandbox from snapshot...'); await loaded.restore(snapshot); - console.log(` 🔒 Poisoned after restore: ${loaded.poisoned}`); + console.log(` 🔒 Status after restore: ${loaded.status}`); console.log(' ✅ Sandbox recovered and ready for use!\n'); } else { console.log(` ❌ Unexpected error: ${err.message}\n`); diff --git a/src/js-host-api/lib.js b/src/js-host-api/lib.js index 6d99fd4e..6805994f 100644 --- a/src/js-host-api/lib.js +++ b/src/js-host-api/lib.js @@ -117,15 +117,8 @@ function wrapSync(fn) { // cached by require(), so prototypes are patched once per process, after // this module has been required at least once. -const { - LoadedJSSandbox, - JSSandbox, - ProtoJSSandbox, - SandboxBuilder, - Snapshot, - HostFunctionModule, - HostModule, -} = native; +const { LoadedJSSandbox, JSSandbox, ProtoJSSandbox, SandboxBuilder, Snapshot, HostFunctionModule } = + native; /** * Wrap a getter so that thrown errors have enriched codes. @@ -157,7 +150,7 @@ for (const method of ['callHandler', 'unload', 'snapshot', 'restore', 'dispose'] if (!orig) throw new Error(`Cannot wrap missing method: LoadedJSSandbox.${method}`); LoadedJSSandbox.prototype[method] = wrapAsync(orig); } -wrapGetter(LoadedJSSandbox, 'poisoned'); +wrapGetter(LoadedJSSandbox, 'status'); wrapGetter(LoadedJSSandbox, 'interruptHandle'); wrapGetter(LoadedJSSandbox, 'lastCallStats'); @@ -182,7 +175,6 @@ for (const method of [ JSSandbox.prototype[method] = wrapSync(orig); } wrapGetter(JSSandbox, 'status'); -wrapGetter(JSSandbox, 'poisoned'); // ProtoJSSandbox — fresh runtime construction for (const method of ['loadRuntime']) { @@ -191,21 +183,6 @@ for (const method of ['loadRuntime']) { ProtoJSSandbox.prototype[method] = wrapAsync(orig); } -// hostModule() is sync — just wrap for error enrichment -ProtoJSSandbox.prototype.hostModule = wrapSync(ProtoJSSandbox.prototype.hostModule); - -// ProtoJSSandbox — register() handle errors and wraps callback to return Promise -{ - const origRegister = ProtoJSSandbox.prototype.register; - ProtoJSSandbox.prototype.register = wrapSync(function (moduleName, functionName, callback) { - // the rust code expects the host function to return a Promise, so we wrap the callback result in Promise.resolve().then(..) to allow sync functions as well - // note that Promise.resolve(callback(...args)) would not work because if callback throws that would not return a rejected promise, it would just throw before returning the promise. - return origRegister.call(this, moduleName, functionName, (...args) => - Promise.resolve().then(() => callback(...args)) - ); - }); -} - // Host-function modules — register() with Buffer support function wrapHostFunctionModule(cls) { const origRegister = cls.prototype.register; @@ -238,7 +215,6 @@ function wrapHostFunctionModule(cls) { }); } wrapHostFunctionModule(HostFunctionModule); -wrapHostFunctionModule(HostModule); const HostFunctionModuleExport = new Proxy(HostFunctionModule, { construct(target, args, newTarget) { @@ -292,8 +268,6 @@ for (const method of [ 'setOutputTransportPoolPages', 'setInputTransportBufferSize', 'setOutputTransportBufferSize', - 'setInputBufferSize', - 'setOutputBufferSize', 'setHostFunctionModules', ]) { const orig = SandboxBuilder.prototype[method]; diff --git a/src/js-host-api/lib.mjs b/src/js-host-api/lib.mjs index 291f7f4c..352efc0b 100644 --- a/src/js-host-api/lib.mjs +++ b/src/js-host-api/lib.mjs @@ -22,7 +22,6 @@ import native from './lib.js'; export const { HostFunctionModule, - HostModule, InterruptHandle, JSSandbox, LoadedJSSandbox, diff --git a/src/js-host-api/package-lock.json b/src/js-host-api/package-lock.json index 7a2f2b95..557b2a17 100644 --- a/src/js-host-api/package-lock.json +++ b/src/js-host-api/package-lock.json @@ -1047,9 +1047,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1067,9 +1064,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1087,9 +1081,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1107,9 +1098,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1127,9 +1115,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1147,9 +1132,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1167,9 +1149,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1387,9 +1366,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1407,9 +1383,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1427,9 +1400,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1447,9 +1417,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1467,9 +1434,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1487,9 +1451,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1709,9 +1670,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1729,9 +1687,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1749,9 +1704,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1769,9 +1721,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/src/js-host-api/scripts/normalize-generated-types.mjs b/src/js-host-api/scripts/normalize-generated-types.mjs index b50a591c..95d6b469 100644 --- a/src/js-host-api/scripts/normalize-generated-types.mjs +++ b/src/js-host-api/scripts/normalize-generated-types.mjs @@ -20,7 +20,6 @@ import { URL } from 'node:url'; const declarationsPath = new URL('../index.d.ts', import.meta.url); const publicTypes = [ 'HostFunctionModule', - 'HostModule', 'InterruptHandle', 'JSSandbox', 'LoadedJSSandbox', diff --git a/src/js-host-api/src/lib.rs b/src/js-host-api/src/lib.rs index 2681f13b..1de9f75e 100644 --- a/src/js-host-api/src/lib.rs +++ b/src/js-host-api/src/lib.rs @@ -120,10 +120,6 @@ impl SandboxStatus { _ => unreachable!("invalid sandbox status"), } } - - const fn is_poisoned(self) -> bool { - matches!(self, Self::Poisoned) - } } // ── Error codes ────────────────────────────────────────────────────── @@ -547,54 +543,6 @@ impl SandboxBuilderWrapper { } } - /// Set the legacy guest-to-host message capacity in bytes. - /// - /// Preserves the legacy 8 KiB minimum and rounds up to whole 4 KiB pages. - /// The output pool also reserves the last legacy input capacity for host - /// replies and one page for small buffers, so its total memory is larger. - /// - /// @param size - Buffer size in bytes (must be > 0) - /// @returns this (for chaining) - /// @throws If size is 0 - /// @deprecated Use setOutputTransportPoolPages for an explicit pool budget. - #[napi] - #[allow(deprecated)] - pub fn set_output_buffer_size(&self, size: u32) -> napi::Result<&Self> { - if size == 0 { - return Err(invalid_arg_error( - "Output buffer size must be greater than 0", - )); - } - - self.with_inner( - |state| map_builder!(state, b => b.with_guest_output_buffer_size(size as usize)), - ) - } - - /// Set the legacy host-to-guest message capacity in bytes. - /// - /// Preserves the legacy 8 KiB minimum and rounds up to whole 4 KiB pages. - /// Adds a spare input transport buffer and also sizes the output pool for - /// host callback replies. Larger capacities may need more scratch space. - /// - /// @param size - Buffer size in bytes (must be > 0) - /// @returns this (for chaining) - /// @throws If size is 0 - /// @deprecated Use setInputTransportPoolPages and setOutputTransportPoolPages for explicit pool budgets. - #[napi] - #[allow(deprecated)] - pub fn set_input_buffer_size(&self, size: u32) -> napi::Result<&Self> { - if size == 0 { - return Err(invalid_arg_error( - "Input buffer size must be greater than 0", - )); - } - - self.with_inner( - |state| map_builder!(state, b => b.with_guest_input_buffer_size(size as usize)), - ) - } - /// Set the guest scratch size in bytes. /// /// Shared writable-memory budget for the guest heap, stack, transport pools, @@ -839,17 +787,13 @@ impl SandboxBuilderWrapper { /// A sandbox with VM resources allocated, ready to load the JS runtime. /// -/// This is a transitional state — register host functions with -/// `hostModule()` / `register()`, then call `loadRuntime()` to proceed -/// to `JSSandbox` where you can register handlers. +/// Configure host functions on `SandboxBuilder` before building this state. +/// Call `loadRuntime()` to proceed to `JSSandbox` and register handlers. /// /// ```js -/// const proto = await new SandboxBuilder().build(); -/// -/// // Register host functions callable from guest JS -/// const math = proto.hostModule('math'); +/// const math = new HostFunctionModule('math'); /// math.register('add', (a, b) => a + b); -/// +/// const proto = await new SandboxBuilder().setHostFunctionModules([math]).build(); /// const sandbox = await proto.loadRuntime(); /// ``` #[napi(js_name = "ProtoJSSandbox")] @@ -859,18 +803,6 @@ pub struct ProtoJSSandboxWrapper { } impl ProtoJSSandboxWrapper { - /// Borrow the inner value mutably via Mutex, or error if consumed. - fn with_inner_mut(&self, f: F) -> napi::Result - where - F: FnOnce(&mut ProtoJSSandbox) -> napi::Result, - { - let mut guard = self.inner.lock().map_err(|_| lock_error())?; - let sandbox = guard - .as_mut() - .ok_or_else(|| consumed_error("ProtoJSSandbox"))?; - f(sandbox) - } - /// Take ownership of the inner value, returning a consumed-state error if /// this instance has already been used. fn take_inner(&self) -> napi::Result { @@ -886,9 +818,8 @@ impl ProtoJSSandboxWrapper { impl ProtoJSSandboxWrapper { /// Load the JavaScript runtime into the sandbox. /// - /// All host functions registered via `hostModule()` / `register()` - /// are applied before the runtime is loaded. The `ProtoJSSandbox` is - /// consumed and cannot be reused. + /// Host functions supplied on the builder are applied before the runtime + /// is loaded. The `ProtoJSSandbox` is consumed and cannot be reused. /// /// Returns a `Promise` — does not block the Node.js event loop. /// @@ -908,69 +839,6 @@ impl ProtoJSSandboxWrapper { busy_flag: Arc::new(AtomicBool::new(false)), }) } - - /// Get a builder for registering host functions in a named module. - /// - /// Host modules are namespaces for host functions that guest JavaScript - /// can import: - /// - /// ```js - /// // Host side (Node.js) - /// const math = proto.hostModule('math'); - /// math.register('add', (a, b) => a + b); - /// - /// // Guest side (sandboxed JS) - /// import * as math from "host:math"; - /// const result = math.add(1, 2); // calls host function - /// ``` - /// - /// The returned `HostModule` stores registrations that are - /// applied during `loadRuntime()`. - /// - /// @param name - Module name that guest JS uses in `import * as name from "host:name"` - /// @returns A `HostModule` for registering functions - /// @throws If the module name is empty - /// @deprecated Use `SandboxBuilder.setHostFunctionModules()`, which also works when restoring snapshots. - #[napi] - pub fn host_module(&self, name: String) -> napi::Result { - validate_module_name(&name)?; - Ok(HostModuleWrapper { - module_name: format!("{HOST_MODULE_PREFIX}{name}"), - sandbox: self.clone(), - }) - } - - /// Register a host function in a named module (convenience method). - /// - /// Equivalent to `proto.hostModule(module).register(name, callback)`. - /// The `host:` prefix is added automatically — guest code imports with - /// `from "host:"`. - /// - /// Arguments are automatically parsed from JSON and spread into your - /// callback. The return value is automatically JSON-stringified. - /// - /// @param moduleName - Bare module name (e.g. `'math'`); guest imports as `"host:math"` - /// @param functionName - Function name within the module - /// @param callback - `(...args) => any | Promise` — the host function implementation - /// @throws If module name or function name is empty - /// @deprecated Use `SandboxBuilder.setHostFunctionModules()`, which also works when restoring snapshots. - #[napi] - #[allow(clippy::type_complexity)] // allow the type complexity here so that index.d.ts is cleaner - pub fn register( - &self, - module_name: String, - function_name: String, - func: ThreadsafeFunction< - Rest>, - Promise>, - Rest>, - Status, - false, - true, - >, - ) -> napi::Result<()> { - self.host_module(module_name)?.register(function_name, func) - } } /// Napi takes a tuple of values as the generic for `ThreadsafeFunction`'s input arguments. @@ -1712,105 +1580,6 @@ impl HostFunctionModuleWrapper { } } -// ── HostModule compatibility API ──────────────────────────────────── - -/// A builder for registering host functions in a named module. -/// -/// Obtained from the compatibility API `ProtoJSSandbox.hostModule(name)`. -/// Host functions registered here become available to guest JavaScript code via -/// `import * as from "host:"` after `loadRuntime()` is called. -/// -/// The `host:` prefix is added automatically by the NAPI layer to prevent -/// collisions with built-in QuickJS modules (e.g. `io`, `crypto`). -/// You register with a bare name (`'math'`) and guest code imports with the -/// prefix (`from "host:math"`). -/// -/// ```js -/// // Host side (Node.js) -/// const math = proto.hostModule('math'); -/// math.register('add', (a, b) => a + b); -/// math.register('multiply', (a, b) => a * b); -/// -/// // Guest side (sandboxed JS) -/// import * as math from "host:math"; -/// math.add(1, 2); // calls host function -/// math.multiply(3, 4); // calls host function -/// ``` -/// -/// Arguments are automatically parsed from JSON and spread into your -/// callback. The return value is automatically JSON-stringified. -#[napi(js_name = "HostModule")] -pub struct HostModuleWrapper { - /// Module name this builder registers functions under. - module_name: String, - - /// Fresh sandbox that receives registrations from this compatibility handle. - sandbox: ProtoJSSandboxWrapper, -} - -#[napi] -impl HostModuleWrapper { - /// Register a host function in this module. - /// - /// Arguments are automatically parsed from JSON and spread into your - /// callback. The return value is automatically JSON-stringified. - /// Both sync and async callbacks are supported — if the callback - /// returns a `Promise`, the bridge awaits it automatically. - /// - /// **Binary data support**: `Uint8Array`/`Buffer` arguments from guest - /// code are automatically converted to Node.js `Buffer` objects before - /// being passed to your callback. If your callback returns a `Buffer`, - /// it will be converted back to a `Uint8Array` on the guest side. - /// - /// Registering a function with the same name as an existing one in - /// this module overwrites the previous registration. - /// - /// ```js - /// const math = proto.hostModule('math'); - /// - /// // Sync callback — args are spread, return value auto-stringified - /// math.register('add', (a, b) => a + b); - /// - /// // Async callback (automatically awaited) - /// math.register('fetchData', async (url) => { - /// const res = await fetch(url); - /// return res.json(); - /// }); - /// - /// // Binary data — Buffer args/returns work natively - /// math.register('compress', (data) => { - /// // data is a Buffer if guest passed Uint8Array - /// return zlib.gzipSync(data); // Return Buffer → Uint8Array on guest - /// }); - /// ``` - /// - /// @param name - Function name within the module (must be non-empty) - /// @param callback - `(...args) => any | Promise` — the host function - /// @throws If the function name is empty - #[napi] - #[allow(clippy::type_complexity)] // allow the type complexity here so that index.d.ts is cleaner - pub fn register( - &self, - name: String, - #[napi(ts_arg_type = "(...args: any[]) => unknown | Promise")] - func: JsHostFunction, - ) -> napi::Result<()> { - if name.is_empty() { - return Err(invalid_arg_error("Function name must not be empty")); - } - - let wrapper = js_host_function(func); - self.sandbox.with_inner_mut(|sandbox| { - #[allow(deprecated)] - sandbox - .host_module(&self.module_name) - .register_js(name, wrapper); - Ok(()) - })?; - Ok(()) - } -} - // ── JSSandbox ──────────────────────────────────────────────────────── /// A sandbox with the JavaScript runtime loaded, ready for handlers. @@ -2090,17 +1859,6 @@ impl JSSandboxWrapper { self.with_inner_ref(|sandbox| Ok(SandboxStatus::from_hyperlight(sandbox.status()))) } - /// Whether the sandbox is in a poisoned (inconsistent) state. - /// - /// A poisoned sandbox has had its guest execution interrupted or - /// aborted. Most operations will fail with an `ERR_POISONED` error code. - /// - /// @deprecated Use `status` instead. - #[napi(getter)] - pub fn poisoned(&self) -> napi::Result { - self.status().map(SandboxStatus::is_poisoned) - } - /// Eagerly release the underlying sandbox resources. /// /// After calling `dispose()`, the sandbox is consumed and all @@ -2514,27 +2272,6 @@ impl LoadedJSSandboxWrapper { Ok(SandboxStatus::from_u8(self.status.load(Ordering::Acquire))) } - /// Whether the sandbox is in a poisoned (inconsistent) state. - /// - /// A sandbox becomes poisoned when guest execution is interrupted - /// (e.g., by a monitor timeout), when the guest panics, or on memory - /// violations. Most operations will fail with an `ERR_POISONED` error code. - /// - /// This getter is lock-free — it reads from an atomic flag updated - /// after every sandbox operation. It never blocks the event loop, - /// even while a handler is executing on a background thread. - /// - /// Recovery options: - /// - `restore(snapshot)` — revert to a captured state - /// - `unload()` — discard handlers and start fresh - /// - /// @deprecated Use `status` instead. - /// @throws `ERR_CONSUMED` if the sandbox has been consumed via `dispose()` or `unload()` - #[napi(getter)] - pub fn poisoned(&self) -> napi::Result { - self.status().map(SandboxStatus::is_poisoned) - } - /// Execution statistics from the most recent `callHandler()` call. /// /// Returns `null` before any call has been made. After each call, diff --git a/src/js-host-api/tests/host-functions.test.js b/src/js-host-api/tests/host-functions.test.js index a716025e..99822d29 100644 --- a/src/js-host-api/tests/host-functions.test.js +++ b/src/js-host-api/tests/host-functions.test.js @@ -2,69 +2,39 @@ // // Tests the NAPI bridge for registering host-side JS callbacks that guest // sandboxed code can call via `import * as from "host:"`. -import { describe, it, expect, beforeEach } from 'vitest'; -import { SandboxBuilder } from '../lib.js'; +import { describe, it, expect } from 'vitest'; +import { HostFunctionModule, SandboxBuilder } from '../lib.js'; import { expectThrowsWithCode, trackSandbox } from './test-helpers.js'; // ── Helpers ────────────────────────────────────────────────────────── /** - * Build a full pipeline: proto → register host fns → runtime → add handler → loaded. + * Build a full pipeline with fresh host-function modules and a guest handler. * - * @param {(proto: import('../lib.js').ProtoJSSandbox) => void} registerFns - * — callback to register host functions on the proto sandbox + * @param {() => import('../lib.js').HostFunctionModule | import('../lib.js').HostFunctionModule[]} createModules + * — factory for this sandbox's host-function modules * @param {string} handlerScript * — guest JS source defining a `handler(event)` function * @returns {Promise} */ -async function buildLoadedSandbox(registerFns, handlerScript) { - const proto = await new SandboxBuilder().build(); - registerFns(proto); +async function buildLoadedSandbox(createModules, handlerScript) { + const modules = createModules(); + const proto = await new SandboxBuilder() + .setHostFunctionModules(Array.isArray(modules) ? modules : [modules]) + .build(); const sandbox = await trackSandbox(proto.loadRuntime()); sandbox.addHandler('handler', handlerScript); return trackSandbox(sandbox.getLoadedSandbox()); } -// ── HostModule ──────────────────────────────────────────────── - -describe('HostModule', () => { - let proto; - - beforeEach(async () => { - proto = await new SandboxBuilder().build(); - }); - - it('should return a HostModule from hostModule()', () => { - const builder = proto.hostModule('math'); - expect(builder).toBeDefined(); - expect(typeof builder.register).toBe('function'); - }); - - it('should throw on empty module name', () => { - expectThrowsWithCode(() => proto.hostModule(''), 'ERR_INVALID_ARG'); - }); - - it('should throw on empty function name in register()', () => { - const builder = proto.hostModule('math'); - expectThrowsWithCode(() => builder.register('', () => 42), 'ERR_INVALID_ARG'); - }); -}); - -// ── ProtoJSSandbox.register() convenience method ───────────────────── - -describe('ProtoJSSandbox.register()', () => { - let proto; - - beforeEach(async () => { - proto = await new SandboxBuilder().build(); - }); - +describe('HostFunctionModule', () => { it('should throw on empty module name', () => { - expectThrowsWithCode(() => proto.register('', 'add', () => 42), 'ERR_INVALID_ARG'); + expectThrowsWithCode(() => new HostFunctionModule(''), 'ERR_INVALID_ARG'); }); it('should throw on empty function name', () => { - expectThrowsWithCode(() => proto.register('math', '', () => 42), 'ERR_INVALID_ARG'); + const module = new HostFunctionModule('math'); + expectThrowsWithCode(() => module.register('', () => 42), 'ERR_INVALID_ARG'); }); }); @@ -94,8 +64,8 @@ describe('Host function invocation', () => { .setInputTransportBufferSize(256) .setOutputTransportBufferSize(3001), ]) { - const proto = await builder.build(); - proto.hostModule('host').register('echo', (value) => value); + const host = new HostFunctionModule('host').register('echo', (value) => value); + const proto = await builder.setHostFunctionModules([host]).build(); const sandbox = await trackSandbox(proto.loadRuntime()); sandbox.addHandler('handler', source); const loaded = await trackSandbox(sandbox.getLoadedSandbox()); @@ -109,8 +79,8 @@ describe('Host function invocation', () => { it('should call a sync host function from guest code', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('math').register('add', (a, b) => a + b); + () => { + return new HostFunctionModule('math').register('add', (a, b) => a + b); }, ` import * as math from "host:math"; @@ -126,8 +96,8 @@ describe('Host function invocation', () => { it('should call an async host function from guest code', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('utils').register('greet', async (name) => { + () => { + return new HostFunctionModule('utils').register('greet', async (name) => { // Simulate async work (e.g., a database lookup) await new Promise((resolve) => setTimeout(resolve, 10)); return `Hello, ${name}!`; @@ -147,10 +117,11 @@ describe('Host function invocation', () => { it('should support multiple functions in one module', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - const math = proto.hostModule('math'); + () => { + const math = new HostFunctionModule('math'); math.register('add', (a, b) => a + b); math.register('multiply', (a, b) => a * b); + return math; }, ` import * as math from "host:math"; @@ -168,9 +139,12 @@ describe('Host function invocation', () => { it('should support multiple modules', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('math').register('add', (a, b) => a + b); - proto.hostModule('strings').register('upper', (s) => s.toUpperCase()); + () => { + const math = new HostFunctionModule('math').register('add', (a, b) => a + b); + const strings = new HostFunctionModule('strings').register('upper', (s) => + s.toUpperCase() + ); + return [math, strings]; }, ` import * as math from "host:math"; @@ -187,27 +161,10 @@ describe('Host function invocation', () => { expect(result).toEqual({ sum: 3, upper: 'HELLO' }); }); - it('should support the convenience register() method', async () => { - const loaded = await buildLoadedSandbox( - (proto) => { - proto.register('math', 'add', (a, b) => a + b); - }, - ` - import * as math from "host:math"; - function handler(event) { - return { result: math.add(3, 4) }; - } - ` - ); - - const result = await loaded.callHandler('handler', {}); - expect(result).toEqual({ result: 7 }); - }); - it('should propagate errors from host function callbacks', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('explode', () => { + () => { + return new HostFunctionModule('host').register('explode', () => { throw new Error('💥 kaboom from host'); }); }, @@ -225,8 +182,8 @@ describe('Host function invocation', () => { it('should handle host function returning complex objects', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('db').register('query', (table) => ({ + () => { + return new HostFunctionModule('db').register('query', (table) => ({ rows: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, @@ -249,9 +206,9 @@ describe('Host function invocation', () => { it('should work with snapshot/restore cycle', async () => { const loaded = await buildLoadedSandbox( - (proto) => { + () => { let counter = 0; - proto.hostModule('state').register('increment', () => { + return new HostFunctionModule('state').register('increment', () => { counter++; return counter; }); @@ -276,70 +233,10 @@ describe('Host function invocation', () => { expect(r2.count).toBe(2); }); - // ── register() — host function registration ───────────────── - - it('should support register() on HostModule', async () => { - const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('math').register('add', (a, b) => { - return a + b; - }); - }, - ` - import * as math from "host:math"; - function handler(event) { - return { result: math.add(event.a, event.b) }; - } - ` - ); - - const result = await loaded.callHandler('handler', { a: 10, b: 32 }); - expect(result).toEqual({ result: 42 }); - }); - - it('should support register() convenience method', async () => { - const loaded = await buildLoadedSandbox( - (proto) => { - proto.register('math', 'add', (a, b) => { - return a + b; - }); - }, - ` - import * as math from "host:math"; - function handler(event) { - return { result: math.add(3, 4) }; - } - ` - ); - - const result = await loaded.callHandler('handler', {}); - expect(result).toEqual({ result: 7 }); - }); - - it('should support async register() callbacks', async () => { - const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('utils').register('greet', async (name) => { - await new Promise((resolve) => setTimeout(resolve, 10)); - return `Hello, ${name}!`; - }); - }, - ` - import * as utils from "host:utils"; - function handler(event) { - return { greeting: utils.greet(event.name) }; - } - ` - ); - - const result = await loaded.callHandler('handler', { name: 'World' }); - expect(result).toEqual({ greeting: 'Hello, World!' }); - }); - it('should propagate errors from register() callbacks', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('explode', () => { + () => { + return new HostFunctionModule('host').register('explode', () => { throw new Error('💥 async kaboom from host'); }); }, @@ -365,8 +262,8 @@ describe('Host function invocation', () => { it('should propagate errors from register() async callbacks', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('explode', async () => { + () => { + return new HostFunctionModule('host').register('explode', async () => { await new Promise((resolve) => setTimeout(resolve, 10)); throw new Error('💥 async kaboom from host'); }); @@ -404,11 +301,7 @@ describe('Multi-sandbox isolation', () => { * Returns { loaded, tag } so callers can identify which sandbox responded. */ async function buildTaggedSandbox(tag, hostFnImpl, handlerScript) { - const proto = await new SandboxBuilder().build(); - hostFnImpl(proto); - const sandbox = await trackSandbox(proto.loadRuntime()); - sandbox.addHandler('handler', handlerScript); - const loaded = await trackSandbox(sandbox.getLoadedSandbox()); + const loaded = await buildLoadedSandbox(hostFnImpl, handlerScript); return { loaded, tag }; } @@ -416,7 +309,7 @@ describe('Multi-sandbox isolation', () => { // Sandbox A: math.compute returns a + b const { loaded: loadedA } = await buildTaggedSandbox( 'A', - (proto) => proto.hostModule('math').register('compute', (a, b) => a + b), + () => new HostFunctionModule('math').register('compute', (a, b) => a + b), ` import * as math from "host:math"; function handler(event) { @@ -428,7 +321,7 @@ describe('Multi-sandbox isolation', () => { // Sandbox B: math.compute returns a * b (same module, same fn name!) const { loaded: loadedB } = await buildTaggedSandbox( 'B', - (proto) => proto.hostModule('math').register('compute', (a, b) => a * b), + () => new HostFunctionModule('math').register('compute', (a, b) => a * b), ` import * as math from "host:math"; function handler(event) { @@ -452,8 +345,8 @@ describe('Multi-sandbox isolation', () => { const { loaded: loadedA } = await buildTaggedSandbox( 'A', - (proto) => - proto.hostModule('stats').register('hit', () => { + () => + new HostFunctionModule('stats').register('hit', () => { counterA++; return counterA; }), @@ -465,8 +358,8 @@ describe('Multi-sandbox isolation', () => { const { loaded: loadedB } = await buildTaggedSandbox( 'B', - (proto) => - proto.hostModule('stats').register('hit', () => { + () => + new HostFunctionModule('stats').register('hit', () => { counterB++; return counterB; }), @@ -498,8 +391,8 @@ describe('Multi-sandbox isolation', () => { it('should isolate async host functions across sandboxes with interleaved calls', async () => { const { loaded: loadedA } = await buildTaggedSandbox( 'A', - (proto) => - proto.hostModule('net').register('fetch', async (url) => { + () => + new HostFunctionModule('net').register('fetch', async (url) => { await new Promise((resolve) => setTimeout(resolve, 20)); return `A:${url}`; }), @@ -511,8 +404,8 @@ describe('Multi-sandbox isolation', () => { const { loaded: loadedB } = await buildTaggedSandbox( 'B', - (proto) => - proto.hostModule('net').register('fetch', async (url) => { + () => + new HostFunctionModule('net').register('fetch', async (url) => { await new Promise((resolve) => setTimeout(resolve, 20)); return `B:${url}`; }), @@ -541,10 +434,11 @@ describe('Multi-sandbox isolation', () => { // sharing the same resolver map, across two independent maps. const { loaded: loadedA } = await buildTaggedSandbox( 'A', - (proto) => { - const math = proto.hostModule('math'); + () => { + const math = new HostFunctionModule('math'); math.register('add', (a, b) => a + b); math.register('multiply', (a, b) => a * b); + return math; }, ` import * as math from "host:math"; @@ -556,11 +450,12 @@ describe('Multi-sandbox isolation', () => { const { loaded: loadedB } = await buildTaggedSandbox( 'B', - (proto) => { - const math = proto.hostModule('math'); + () => { + const math = new HostFunctionModule('math'); // Reversed! add does multiply, multiply does add math.register('add', (a, b) => a * b); math.register('multiply', (a, b) => a + b); + return math; }, ` import * as math from "host:math"; @@ -586,19 +481,22 @@ describe('Binary data support', () => { it('should retain owned buffers across async callbacks and sandbox disposal', async () => { let retained; const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('retain', async (data, nested, label) => { - expect(Buffer.isBuffer(data)).toBe(true); - expect(Buffer.isBuffer(nested.data)).toBe(true); - expect(Buffer.isBuffer(nested.empty)).toBe(true); - expect(label).toBe('tail'); - - retained = data; - await new Promise((resolve) => setTimeout(resolve, 10)); - data[0] = 99; - nested.data[0] = 88; - return { data, nested }; - }); + () => { + return new HostFunctionModule('host').register( + 'retain', + async (data, nested, label) => { + expect(Buffer.isBuffer(data)).toBe(true); + expect(Buffer.isBuffer(nested.data)).toBe(true); + expect(Buffer.isBuffer(nested.empty)).toBe(true); + expect(label).toBe('tail'); + + retained = data; + await new Promise((resolve) => setTimeout(resolve, 10)); + data[0] = 99; + nested.data[0] = 88; + return { data, nested }; + } + ); }, ` import * as host from "host:host"; @@ -633,8 +531,8 @@ describe('Binary data support', () => { it('should keep repeated binary placeholders independently mutable', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('check', (first, rest) => { + () => { + return new HostFunctionModule('host').register('check', (first, rest) => { expect(Buffer.isBuffer(first)).toBe(true); expect(Buffer.isBuffer(rest.data)).toBe(true); expect(Buffer.isBuffer(rest.last)).toBe(true); @@ -665,8 +563,8 @@ describe('Binary data support', () => { it('should pass Buffer args from guest Uint8Array to host', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('byte_length', (data) => { + () => { + return new HostFunctionModule('host').register('byte_length', (data) => { expect(Buffer.isBuffer(data)).toBe(true); return data.length; }); @@ -685,8 +583,8 @@ describe('Binary data support', () => { it('should return Buffer from host as Uint8Array on guest', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_bytes', () => { + () => { + return new HostFunctionModule('host').register('get_bytes', () => { return Buffer.from([1, 2, 3, 4, 5]); }); }, @@ -704,8 +602,8 @@ describe('Binary data support', () => { it('should handle mixed Buffer and JSON args', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('describe', (prefix, data, num) => { + () => { + return new HostFunctionModule('host').register('describe', (prefix, data, num) => { expect(typeof prefix).toBe('string'); expect(Buffer.isBuffer(data)).toBe(true); expect(typeof num).toBe('number'); @@ -726,8 +624,8 @@ describe('Binary data support', () => { it('should handle empty Uint8Array', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('check_empty', (data) => { + () => { + return new HostFunctionModule('host').register('check_empty', (data) => { expect(Buffer.isBuffer(data)).toBe(true); return data.length; }); @@ -748,8 +646,8 @@ describe('Binary data support', () => { // empty buffers. JsReturn::from_napi_value must not panic on the // null pointer — it should return an empty Vec instead. const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('empty_response', () => { + () => { + return new HostFunctionModule('host').register('empty_response', () => { return Buffer.alloc(0); }); }, @@ -767,8 +665,8 @@ describe('Binary data support', () => { it('should round-trip binary data (send and receive)', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('echo_bytes', (data) => { + () => { + return new HostFunctionModule('host').register('echo_bytes', (data) => { // Return the same Buffer back return data; }); @@ -797,8 +695,8 @@ describe('Binary data support', () => { it('should handle nested Buffer in returned object', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_payload', () => { + () => { + return new HostFunctionModule('host').register('get_payload', () => { return { name: 'test', data: Buffer.from([10, 20, 30]), @@ -829,8 +727,8 @@ describe('Binary data support', () => { it('should handle nested Buffer in returned array', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_items', () => { + () => { + return new HostFunctionModule('host').register('get_items', () => { return [Buffer.from([1, 2, 3]), Buffer.from([4, 5])]; }); }, @@ -858,8 +756,8 @@ describe('Binary data support', () => { it('should handle deeply nested Buffer in returned object', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_nested', () => { + () => { + return new HostFunctionModule('host').register('get_nested', () => { return { outer: { inner: { @@ -892,8 +790,8 @@ describe('Binary data support', () => { it('should handle mixed Buffers and JSON in returned object', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_mixed', () => { + () => { + return new HostFunctionModule('host').register('get_mixed', () => { return { header: Buffer.from([1, 2]), status: 'ok', @@ -930,8 +828,8 @@ describe('Binary data support', () => { it('should handle nested Uint8Array (not just Buffer)', async () => { const loaded = await buildLoadedSandbox( - (proto) => { - proto.hostModule('host').register('get_uint8', () => { + () => { + return new HostFunctionModule('host').register('get_uint8', () => { return { data: new Uint8Array([7, 8, 9]) }; }); }, diff --git a/src/js-host-api/tests/sandbox.test.js b/src/js-host-api/tests/sandbox.test.js index 78207594..682c6929 100644 --- a/src/js-host-api/tests/sandbox.test.js +++ b/src/js-host-api/tests/sandbox.test.js @@ -22,8 +22,6 @@ describe('SandboxBuilder', () => { const builder = new SandboxBuilder(); const result = builder .setScratchSize(8 * 1024 * 1024) - .setInputBufferSize(4096) - .setOutputBufferSize(4096) .setInputTransportPoolPages(4) .setOutputTransportPoolPages(4) .setInputTransportBufferSize(3001) @@ -62,14 +60,12 @@ describe('SandboxBuilder', () => { it('should reject zero input buffer size', () => { const builder = new SandboxBuilder(); - expectThrowsWithCode(() => builder.setInputBufferSize(0), 'ERR_INVALID_ARG'); expectThrowsWithCode(() => builder.setInputTransportPoolPages(0), 'ERR_INVALID_ARG'); expectThrowsWithCode(() => builder.setInputTransportBufferSize(0), 'ERR_INVALID_ARG'); }); it('should reject zero output buffer size', () => { const builder = new SandboxBuilder(); - expectThrowsWithCode(() => builder.setOutputBufferSize(0), 'ERR_INVALID_ARG'); expectThrowsWithCode(() => builder.setOutputTransportPoolPages(0), 'ERR_INVALID_ARG'); expectThrowsWithCode(() => builder.setOutputTransportBufferSize(0), 'ERR_INVALID_ARG'); }); @@ -138,7 +134,6 @@ describe('JSSandbox', () => { it('should report ready status', () => { expect(sandbox.status).toBe('ready'); - expect(sandbox.poisoned).toBe(false); }); it('should throw CONSUMED on double getLoadedSandbox()', async () => { @@ -190,7 +185,7 @@ describe('LoadedJSSandbox', () => { expect(result.message).toBe('Hello, Default!'); expect(result.name).toBe('Default'); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should handle events with explicit gc: true', async () => { @@ -198,12 +193,11 @@ describe('LoadedJSSandbox', () => { expect(result.message).toBe('Hello, GC!'); expect(result.name).toBe('GC'); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should not be poisoned initially', () => { expect(loaded.status).toBe('ready'); - expect(loaded.poisoned).toBe(false); }); it('should take and restore snapshots', async () => { @@ -213,7 +207,7 @@ describe('LoadedJSSandbox', () => { expect(snapshot).toBeDefined(); await loaded.restore(snapshot); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should unload back to JSSandbox', async () => { @@ -268,7 +262,7 @@ describe('Scratch allocation budget', () => { loaded.callHandler('handler', { bytes: 8 * mib }), 'ERR_GUEST_ABORT' ); - expect(loaded.poisoned).toBe(true); + expect(loaded.status).toBe('poisoned'); await expectRejectsWithCode( loaded.callHandler('handler', { bytes: 1 }), 'ERR_POISONED' @@ -277,7 +271,7 @@ describe('Scratch allocation budget', () => { expect(await loaded.callHandler('handler', { bytes: 8 * mib })).toBe(7); } await loaded.restore(snapshot); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); expect(await loaded.callHandler('handler', { bytes: 1 })).toBe(7); }); }); @@ -378,14 +372,14 @@ describe('JSSandbox.dispose()', () => { sandbox.dispose(); // should not throw }); - it('should make poisoned getter throw ERR_CONSUMED', async () => { + it('should make status getter throw ERR_CONSUMED', async () => { const builder = new SandboxBuilder(); const proto = await builder.build(); const sandbox = await trackSandbox(proto.loadRuntime()); sandbox.dispose(); - expectThrowsWithCode(() => sandbox.poisoned, 'ERR_CONSUMED'); + expectThrowsWithCode(() => sandbox.status, 'ERR_CONSUMED'); }); }); @@ -413,7 +407,7 @@ describe('LoadedJSSandbox.dispose()', () => { await loaded.dispose(); // should not throw }); - it('should make poisoned getter throw ERR_CONSUMED', async () => { + it('should make status getter throw ERR_CONSUMED', async () => { const builder = new SandboxBuilder(); const proto = await builder.build(); const sandbox = await trackSandbox(proto.loadRuntime()); @@ -422,7 +416,7 @@ describe('LoadedJSSandbox.dispose()', () => { await loaded.dispose(); - expectThrowsWithCode(() => loaded.poisoned, 'ERR_CONSUMED'); + expectThrowsWithCode(() => loaded.status, 'ERR_CONSUMED'); }); it('should make interruptHandle getter throw ERR_CONSUMED', async () => { @@ -453,7 +447,7 @@ describe('LoadedJSSandbox.dispose()', () => { // ── unload() consumption ───────────────────────────────────────────── describe('LoadedJSSandbox.unload()', () => { - it('should make poisoned getter throw ERR_CONSUMED after unload', async () => { + it('should make status getter throw ERR_CONSUMED after unload', async () => { const builder = new SandboxBuilder(); const proto = await builder.build(); const sandbox = await trackSandbox(proto.loadRuntime()); @@ -462,7 +456,7 @@ describe('LoadedJSSandbox.unload()', () => { await trackSandbox(loaded.unload()); - expectThrowsWithCode(() => loaded.poisoned, 'ERR_CONSUMED'); + expectThrowsWithCode(() => loaded.status, 'ERR_CONSUMED'); }); it('should make interruptHandle getter throw ERR_CONSUMED after unload', async () => { diff --git a/src/js-host-api/tests/timeout.test.js b/src/js-host-api/tests/timeout.test.js index 67c838ef..f32d4f67 100644 --- a/src/js-host-api/tests/timeout.test.js +++ b/src/js-host-api/tests/timeout.test.js @@ -46,7 +46,7 @@ describe('Wall Clock Timeout', () => { expect(typeof result).toBe('object'); expect(result.counter).toBeGreaterThan(0); expect(result.actualRuntime).toBeLessThan(500); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should kill slow handler after timeout', async () => { @@ -71,7 +71,6 @@ describe('Wall Clock Timeout', () => { expect(elapsed).toBeLessThan(2000); expect(elapsed).toBeGreaterThan(300); expect(loaded.status).toBe('poisoned'); - expect(loaded.poisoned).toBe(true); }); it('should recover from poisoned state with restore', async () => { @@ -88,13 +87,11 @@ describe('Wall Clock Timeout', () => { ); expect(loaded.status).toBe('poisoned'); - expect(loaded.poisoned).toBe(true); // Restore from snapshot await loaded.restore(snapshot); expect(loaded.status).toBe('ready'); - expect(loaded.poisoned).toBe(false); // Should be able to use the sandbox again const result = await loaded.callHandler( @@ -147,7 +144,7 @@ describe('CPU Time Timeout', () => { // Result is now a JS object, not a string expect(typeof result).toBe('object'); expect(result.counter).toBeGreaterThan(0); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should kill CPU-intensive handler after CPU timeout', async () => { @@ -169,7 +166,7 @@ describe('CPU Time Timeout', () => { // On a loaded host, CPU time accrues several times slower than wall time. expect(elapsed).toBeLessThan(30000); - expect(loaded.poisoned).toBe(true); + expect(loaded.status).toBe('poisoned'); }, 90000); }); @@ -213,7 +210,7 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { ); expect(result.counter).toBeGreaterThan(0); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should kill CPU-intensive handler (CPU fires first)', async () => { @@ -236,7 +233,7 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { // On a loaded host, CPU time accrues several times slower than wall time. expect(elapsed).toBeLessThan(30000); - expect(loaded.poisoned).toBe(true); + expect(loaded.status).toBe('poisoned'); }, 90000); it('should recover after combined monitor kill', async () => { @@ -252,11 +249,11 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { 'ERR_CANCELLED' ); - expect(loaded.poisoned).toBe(true); + expect(loaded.status).toBe('poisoned'); // Restore from snapshot await loaded.restore(snapshot); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); // Should work again const result = await loaded.callHandler( @@ -275,21 +272,21 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { const result = await loaded.callHandler('handler', { runtime: 50 }, {}); expect(typeof result).toBe('object'); expect(result.counter).toBeGreaterThan(0); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should call handler with gc: false and no monitors', async () => { const result = await loaded.callHandler('handler', { runtime: 50 }, { gc: false }); expect(typeof result).toBe('object'); expect(result.counter).toBeGreaterThan(0); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should call handler with gc: true and no monitors', async () => { const result = await loaded.callHandler('handler', { runtime: 50 }, { gc: true }); expect(typeof result).toBe('object'); expect(result.counter).toBeGreaterThan(0); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should throw INVALID_ARG for timeout exceeding maximum', async () => { @@ -343,7 +340,7 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { } ); expect(typeof result).toBe('object'); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); it('should default gc to true when not specified', async () => { @@ -356,7 +353,7 @@ describe('Combined Monitors (CPU + Wall Clock)', () => { } ); expect(typeof result).toBe('object'); - expect(loaded.poisoned).toBe(false); + expect(loaded.status).toBe('ready'); }); }); @@ -398,7 +395,7 @@ describe('Interrupt Handle', () => { await expectRejectsWithCode(promise, 'ERR_CANCELLED'); clearTimeout(timer); - expect(loaded.poisoned).toBe(true); + expect(loaded.status).toBe('poisoned'); }); it('should reject empty handler name on callHandler', async () => { diff --git a/src/js-host-api/tests/user-modules.test.js b/src/js-host-api/tests/user-modules.test.js index 77622d29..ae16c975 100644 --- a/src/js-host-api/tests/user-modules.test.js +++ b/src/js-host-api/tests/user-modules.test.js @@ -5,7 +5,7 @@ // using the `:` convention. import { describe, it, expect, beforeEach } from 'vitest'; -import { SandboxBuilder } from '../lib.js'; +import { HostFunctionModule, SandboxBuilder } from '../lib.js'; import { expectThrowsWithCode, expectRejectsWithCode, trackSandbox } from './test-helpers.js'; // ── Helpers ────────────────────────────────────────────────────────── @@ -217,8 +217,9 @@ describe('Inter-module imports', () => { describe('User module importing host functions', () => { it('should allow a user module to call a host function', async () => { - const proto = await new SandboxBuilder().build(); - proto.hostModule('db').register('lookup', (id) => ({ id, name: `User ${id}` })); + const db = new HostFunctionModule('db'); + db.register('lookup', (id) => ({ id, name: `User ${id}` })); + const proto = await new SandboxBuilder().setHostFunctionModules([db]).build(); const sandbox = await trackSandbox(proto.loadRuntime());