Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions crates/volt-runner/src/js_runtime/tests/native_modules/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,92 @@ fn plugins_module_prefetch_for_is_available() {

assert_eq!(result, "ok");
}

#[test]
fn plugins_module_exposes_state_and_error_queries() {
let (manager, _) = build_plugin_manager();
manager.fail_plugin(
"acme.search",
"PLUGIN_BROKEN",
"boom".to_string(),
None,
None,
);
let runtime = runtime_with_plugin_manager(
unique_temp_dir("plugins-observability"),
&["fs"],
Some(manager),
);

let result = runtime
.client()
.eval_promise_string(
"(async () => {
const plugins = globalThis.__volt.plugins;
const state = await plugins.getPluginState('acme.search');
const errors = await plugins.getPluginErrors('acme.search');
return `${state.currentState}:${errors.length}:${errors[0].code}`;
})()",
)
.expect("plugin state");

assert_eq!(result, "failed:1:PLUGIN_BROKEN");
}

#[test]
fn plugins_module_receives_lifecycle_events_via_native_bridge() {
let (manager, _) = build_plugin_manager();
let runtime = runtime_with_plugin_manager(
unique_temp_dir("plugins-lifecycle-events"),
&["fs"],
Some(manager.clone()),
);
let runtime_client = runtime.client();
let _subscription = manager.on_lifecycle(Box::new(move |event| {
let payload = serde_json::to_value(event).expect("serialize event");
runtime_client
.dispatch_native_event("plugin:lifecycle", payload)
.expect("dispatch lifecycle event");
}));

runtime
.client()
.eval_unit(
"(async () => {
const plugins = globalThis.__volt.plugins;
globalThis.__pluginLifecycleEvents = [];
const handler = (event) => globalThis.__pluginLifecycleEvents.push(event.newState);
globalThis.__pluginLifecycleHandler = handler;
plugins.on('plugin:lifecycle', handler);
})()",
)
.expect("bind lifecycle handler");

manager.fail_plugin(
"acme.search",
"PLUGIN_BROKEN",
"boom".to_string(),
None,
None,
);

let seen = runtime
.client()
.eval_string("globalThis.__pluginLifecycleEvents.join(',')")
.expect("captured events");
assert_eq!(seen, "failed");

runtime
.client()
.eval_unit(
"globalThis.__volt.plugins.off('plugin:lifecycle', globalThis.__pluginLifecycleHandler)",
)
.expect("unbind lifecycle handler");
let _ = manager.retry_plugin("acme.search");

let after_off = runtime
.client()
.eval_string("globalThis.__pluginLifecycleEvents.join(',')")
.expect("events after off");
assert_eq!(after_off, "failed");
}
29 changes: 29 additions & 0 deletions crates/volt-runner/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ fn run() -> Result<(), RunnerError> {
.load_backend_bundle(&backend_bundle_source)
.map_err(|err| RunnerError::App(format!("failed to load backend bundle: {err}")))?;
let runtime_client = js_runtime.client();
let lifecycle_runtime = runtime_client.clone();
let _lifecycle_subscription = plugin_manager.on_lifecycle(Box::new(move |event| {
dispatch_plugin_lifecycle_event(&lifecycle_runtime, "plugin:lifecycle", event);
}));
let failed_runtime = runtime_client.clone();
let _failed_subscription = plugin_manager.on_plugin_failed(Box::new(move |event| {
dispatch_plugin_lifecycle_event(&failed_runtime, "plugin:failed", event);
}));
let activated_runtime = runtime_client.clone();
let _activated_subscription = plugin_manager.on_plugin_activated(Box::new(move |event| {
dispatch_plugin_lifecycle_event(&activated_runtime, "plugin:activated", event);
}));
let ipc_bridge = ipc_bridge::IpcBridge::new_with_plugin_manager(
runtime_client.clone(),
Some(plugin_manager.clone()),
Expand Down Expand Up @@ -127,3 +139,20 @@ fn run() -> Result<(), RunnerError> {

Ok(())
}

fn dispatch_plugin_lifecycle_event(
runtime_client: &js_runtime_pool::JsRuntimePoolClient,
event_type: &str,
event: &plugin_manager::PluginLifecycleEvent,
) {
let payload = match serde_json::to_value(event) {
Ok(payload) => payload,
Err(error) => {
tracing::error!(error = %error, event_type = %event_type, "failed to serialize plugin lifecycle event");
return;
}
};
if let Err(error) = runtime_client.dispatch_native_event(event_type, payload) {
tracing::error!(error = %error, event_type = %event_type, "failed to dispatch plugin lifecycle event");
}
}
148 changes: 146 additions & 2 deletions crates/volt-runner/src/modules/volt_plugins.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
use boa_engine::{Context, IntoJsFunctionCopied, JsValue, Module};
use boa_engine::object::builtins::JsFunction;
use boa_engine::{Context, IntoJsFunctionCopied, JsResult, JsValue, Module};
use serde_json::Value;

use super::{native_function_module, plugin_manager, promise_from_result};
use super::{
bind_native_event_handler, js_error, native_function_module, plugin_manager,
promise_from_json_result, promise_from_result,
};

const NATIVE_EVENT_ON_GLOBAL: &str = "__volt_native_event_on__";
const NATIVE_EVENT_OFF_GLOBAL: &str = "__volt_native_event_off__";

fn delegate_grant(plugin_id: String, grant_id: String, context: &mut Context) -> JsValue {
promise_from_result(context, delegate_grant_result(plugin_id, grant_id)).into()
Expand All @@ -14,6 +22,42 @@ fn prefetch_for(surface: String, context: &mut Context) -> JsValue {
promise_from_result(context, prefetch_for_result(surface)).into()
}

fn get_states(context: &mut Context) -> JsValue {
promise_from_json_result(context, get_states_result()).into()
}

fn get_plugin_state(plugin_id: String, context: &mut Context) -> JsValue {
promise_from_json_result(context, get_plugin_state_result(plugin_id)).into()
}

fn get_errors(context: &mut Context) -> JsValue {
promise_from_json_result(context, get_errors_result()).into()
}

fn get_plugin_errors(plugin_id: String, context: &mut Context) -> JsValue {
promise_from_json_result(context, get_plugin_errors_result(plugin_id)).into()
}

fn get_discovery_issues(context: &mut Context) -> JsValue {
promise_from_json_result(context, get_discovery_issues_result()).into()
}

fn retry_plugin(plugin_id: String, context: &mut Context) -> JsValue {
promise_from_result(context, retry_plugin_result(plugin_id)).into()
}

fn enable_plugin(plugin_id: String, context: &mut Context) -> JsValue {
promise_from_result(context, enable_plugin_result(plugin_id)).into()
}

fn on(event_name: String, handler: JsFunction, context: &mut Context) -> JsResult<()> {
bind_native_plugin_event(context, "on", NATIVE_EVENT_ON_GLOBAL, event_name, handler)
}

fn off(event_name: String, handler: JsFunction, context: &mut Context) -> JsResult<()> {
bind_native_plugin_event(context, "off", NATIVE_EVENT_OFF_GLOBAL, event_name, handler)
}

fn delegate_grant_result(plugin_id: String, grant_id: String) -> Result<(), String> {
let plugin_id = required_name(plugin_id, "plugin id")?;
let grant_id = required_name(grant_id, "grant id")?;
Expand All @@ -35,6 +79,72 @@ fn prefetch_for_result(surface: String) -> Result<(), String> {
Ok(())
}

fn get_states_result() -> Result<Value, String> {
serde_json::to_value(plugin_manager()?.get_states()).map_err(|error| error.to_string())
}

fn get_plugin_state_result(plugin_id: String) -> Result<Value, String> {
let plugin_id = required_name(plugin_id, "plugin id")?;
serde_json::to_value(plugin_manager()?.get_plugin_state(&plugin_id))
.map_err(|error| error.to_string())
}

fn get_errors_result() -> Result<Value, String> {
serde_json::to_value(plugin_manager()?.get_errors()).map_err(|error| error.to_string())
}

fn get_plugin_errors_result(plugin_id: String) -> Result<Value, String> {
let plugin_id = required_name(plugin_id, "plugin id")?;
serde_json::to_value(plugin_manager()?.get_plugin_errors(&plugin_id))
.map_err(|error| error.to_string())
}

fn get_discovery_issues_result() -> Result<Value, String> {
serde_json::to_value(plugin_manager()?.discovery_issues()).map_err(|error| error.to_string())
}

fn retry_plugin_result(plugin_id: String) -> Result<(), String> {
let plugin_id = required_name(plugin_id, "plugin id")?;
plugin_manager()?
.retry_plugin(&plugin_id)
.map_err(|error| error.to_string())
}

fn enable_plugin_result(plugin_id: String) -> Result<(), String> {
let plugin_id = required_name(plugin_id, "plugin id")?;
plugin_manager()?
.enable_plugin(&plugin_id)
.map_err(|error| error.to_string())
}

fn bind_native_plugin_event(
context: &mut Context,
api_function: &'static str,
global_name: &'static str,
event_name: String,
handler: JsFunction,
) -> JsResult<()> {
bind_native_event_handler(
context,
"volt:plugins",
api_function,
global_name,
normalize_event_name(event_name)
.map_err(|error| js_error("volt:plugins", api_function, error))?,
handler,
)
}

fn normalize_event_name(event_name: String) -> Result<&'static str, String> {
match event_name.trim() {
"plugin:lifecycle" => Ok("plugin:lifecycle"),
"plugin:failed" => Ok("plugin:failed"),
"plugin:activated" => Ok("plugin:activated"),
"" => Err("plugin event name must not be empty".to_string()),
other => Err(format!("unsupported plugin event '{other}'")),
}
}

fn required_name(value: String, label: &str) -> Result<String, String> {
let trimmed = value.trim();
if trimmed.is_empty() {
Expand All @@ -47,13 +157,31 @@ pub fn build_module(context: &mut Context) -> Module {
let delegate_grant = delegate_grant.into_js_function_copied(context);
let revoke_grant = revoke_grant.into_js_function_copied(context);
let prefetch_for = prefetch_for.into_js_function_copied(context);
let get_states = get_states.into_js_function_copied(context);
let get_plugin_state = get_plugin_state.into_js_function_copied(context);
let get_errors = get_errors.into_js_function_copied(context);
let get_plugin_errors = get_plugin_errors.into_js_function_copied(context);
let get_discovery_issues = get_discovery_issues.into_js_function_copied(context);
let retry_plugin = retry_plugin.into_js_function_copied(context);
let enable_plugin = enable_plugin.into_js_function_copied(context);
let on = on.into_js_function_copied(context);
let off = off.into_js_function_copied(context);

native_function_module(
context,
vec![
("delegateGrant", delegate_grant),
("revokeGrant", revoke_grant),
("prefetchFor", prefetch_for),
("getStates", get_states),
("getPluginState", get_plugin_state),
("getErrors", get_errors),
("getPluginErrors", get_plugin_errors),
("getDiscoveryIssues", get_discovery_issues),
("retryPlugin", retry_plugin),
("enablePlugin", enable_plugin),
("on", on),
("off", off),
],
)
}
Expand Down Expand Up @@ -81,4 +209,20 @@ mod tests {

assert!(error.contains("plugin manager is unavailable"));
}

#[test]
fn normalize_event_name_accepts_supported_events() {
assert_eq!(
normalize_event_name("plugin:lifecycle".to_string()),
Ok("plugin:lifecycle")
);
assert_eq!(
normalize_event_name("plugin:failed".to_string()),
Ok("plugin:failed")
);
assert_eq!(
normalize_event_name("plugin:activated".to_string()),
Ok("plugin:activated")
);
}
}
Loading
Loading