use crate::extensions::flow_state::{CasOutcome, FlowStore, flow_result};
use crate::imposter::ResponseMode;
use anyhow::{Result, anyhow};
use rhai::Dynamic;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
mod bounded;
mod compiled_cache;
pub(crate) mod env;
mod rhai_engine;
pub use bounded::{
DEFAULT_SCRIPT_TIMEOUT_MS, ScriptTimeoutError, resolve_script_timeout_ms,
should_inject_bounded, should_inject_bounded_with_ctx, should_inject_bounded_with_ctx_traced,
should_inject_wasm, should_inject_wasm_traced,
};
#[cfg(feature = "wasm")]
mod wasm;
#[cfg(feature = "wasm")]
#[doc(hidden)]
pub use wasm::bench as wasm_bench;
#[derive(Debug, Clone, Copy)]
pub struct WasmScript<'a> {
pub code: &'a str,
pub export: Option<&'a str>,
pub knobs: Option<&'a serde_json::Value>,
pub limits: crate::imposter::WasmLimits,
pub clock: Option<&'a ScriptClock>,
pub instance: Option<&'a str>,
pub instances: Option<&'a WasmInstances>,
}
#[derive(Default)]
pub struct WasmInstances {
#[cfg(feature = "wasm")]
pub(crate) map: wasm::instances::InstanceMap,
}
impl std::fmt::Debug for WasmInstances {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WasmInstances").finish_non_exhaustive()
}
}
impl WasmInstances {
#[must_use]
pub fn is_empty(&self) -> bool {
#[cfg(feature = "wasm")]
{
self.map.is_empty()
}
#[cfg(not(feature = "wasm"))]
{
true
}
}
pub fn clear(&self) {
#[cfg(feature = "wasm")]
self.map.clear();
}
#[must_use]
pub fn list(&self) -> Vec<WasmInstanceInfo> {
#[cfg(feature = "wasm")]
{
self.map.list()
}
#[cfg(not(feature = "wasm"))]
{
Vec::new()
}
}
#[cfg_attr(not(feature = "wasm"), allow(unused_variables, clippy::unused_async))]
pub async fn snapshot<'s>(
&self,
id: Option<&str>,
stubs: impl Iterator<Item = &'s crate::imposter::Stub>,
flow_store: std::sync::Arc<dyn crate::extensions::flow_state::FlowStore>,
) -> Result<WasmSnapshot, WasmSnapshotError> {
#[cfg(feature = "wasm")]
{
if self.map.is_empty() {
let (mut wasm, mut keeps_one) = (false, false);
for script in stubs
.flat_map(|stub| stub.responses.iter())
.filter_map(|response| match response {
crate::imposter::StubResponse::RiftScript { rift, .. } => {
rift.script.as_ref()
}
_ => None,
})
{
wasm |= script.engine.as_deref() == Some("wasm");
keeps_one |= wasm::instances::key_of(script).is_some();
}
return Err(if wasm && !keeps_one {
WasmSnapshotError::RequestMode
} else {
WasmSnapshotError::NotInstantiated
});
}
wasm::instances::snapshot(&self.map, id, flow_store).await
}
#[cfg(not(feature = "wasm"))]
{
Err(WasmSnapshotError::Unavailable)
}
}
#[cfg_attr(not(feature = "wasm"), allow(unused_variables))]
pub(crate) fn retain_referenced<'s>(
&self,
stubs: impl Iterator<Item = &'s crate::imposter::Stub>,
) {
#[cfg(feature = "wasm")]
{
if self.map.is_empty() {
return;
}
let referenced: std::collections::HashSet<_> = stubs
.flat_map(|stub| stub.responses.iter())
.filter_map(|response| match response {
crate::imposter::StubResponse::RiftScript { rift, .. } => rift.script.as_ref(),
_ => None,
})
.filter_map(wasm::instances::key_of)
.collect();
self.map.retain(&referenced);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WasmSnapshot {
pub body: String,
pub fuel_used: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WasmSnapshotError {
#[error("more than one wasm instance is live; name one with ?instance=<id> ({})", .0.join(", "))]
Ambiguous(Vec<String>),
#[error("not instantiated")]
NotInstantiated,
#[error("no live instance (instance: \"request\")")]
RequestMode,
#[error("component does not export rift:mock/introspect")]
NoExport,
#[error("{0}")]
Guest(String),
#[error("snapshot is not JSON")]
NotJson,
#[error("{0}")]
Trap(String),
#[error("timed out waiting for the wasm instance")]
Busy,
#[error("engine \"wasm\" is not available in this build")]
Unavailable,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WasmInstanceInfo {
pub id: String,
pub sha256: String,
pub export: Option<String>,
pub knobs_hash: String,
pub instantiated_at: u64,
pub calls: u64,
pub memory_bytes: usize,
}
#[derive(Debug, Clone)]
pub enum WasmAnswer {
Decision(FaultDecision),
Response(WasmResponse),
}
#[derive(Debug, Clone)]
pub struct WasmResponse {
pub status: u16,
pub headers: hyper::HeaderMap,
pub body: bytes::Bytes,
}
impl WasmAnswer {
pub fn into_fault_decision(self, rule_id: &str) -> anyhow::Result<FaultDecision> {
match self {
Self::Decision(decision) => Ok(decision),
Self::Response(response) => {
let body = String::from_utf8(response.body.to_vec()).map_err(|_| {
anyhow::anyhow!(
"the component's response body is not UTF-8, which this caller cannot serve"
)
})?;
Ok(FaultDecision::Error {
status: response.status,
body,
rule_id: rule_id.to_owned(),
headers: joined_headers(&response.headers),
})
}
}
}
}
pub fn joined_headers(headers: &hyper::HeaderMap) -> std::collections::HashMap<String, String> {
let mut joined: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for (name, value) in headers {
let value = String::from_utf8_lossy(value.as_bytes());
joined
.entry(name.as_str().to_owned())
.and_modify(|v| {
v.push_str(", ");
v.push_str(&value);
})
.or_insert_with(|| value.into_owned());
}
joined
}
#[derive(Debug, Clone)]
pub enum ScriptClock {
Imposter(std::sync::Arc<crate::imposter::clock::ImposterClock>),
Fixed(i64),
}
impl ScriptClock {
#[must_use]
pub fn frozen_ms(&self) -> Option<i64> {
match self {
Self::Imposter(clock) => match clock.mode() {
crate::imposter::clock::ClockMode::Wall => None,
crate::imposter::clock::ClockMode::Frozen { now_ms } => Some(now_ms),
},
Self::Fixed(ms) => Some(*ms),
}
}
}
pub use rhai_engine::RhaiEngine;
pub(crate) use rhai_engine::values_map_to_rhai;
pub(crate) fn rift_rhai_engine() -> rhai::Engine {
let mut engine = rhai::Engine::new();
engine.set_module_resolver(rhai::module_resolvers::DummyModuleResolver::new());
engine
}
#[cfg(feature = "javascript")]
mod js_engine;
#[cfg(feature = "javascript")]
mod js_runtime;
#[cfg(feature = "javascript")]
pub(crate) use js_engine::bounded_js_context;
#[cfg(feature = "javascript")]
pub use js_engine::{
InjectionFailure, JsEngine, MountebankRequest, PredicateInjectionError, compile_js_to_bytecode,
execute_mountebank_decorate, execute_mountebank_decorate_bounded,
execute_mountebank_decorate_within, execute_mountebank_inject,
execute_mountebank_inject_bounded, execute_predicate_generator_inject,
execute_predicate_inject,
};
#[cfg(feature = "javascript")]
#[allow(unused_imports)]
pub use js_engine::{MountebankInjectResponse, execute_js_bytecode};
pub(crate) type ScriptStateCell =
std::sync::Arc<parking_lot::Mutex<serde_json::Map<String, serde_json::Value>>>;
#[derive(Clone)]
pub struct ScriptScope {
pub port: u16,
#[cfg_attr(not(feature = "javascript"), allow(dead_code))]
pub(crate) state: ScriptStateCell,
#[cfg_attr(not(feature = "javascript"), allow(dead_code))]
pub(crate) probe: crate::imposter::probe::ProbeHandle,
}
impl std::fmt::Debug for ScriptScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScriptScope")
.field("port", &self.port)
.field("state", &self.state)
.finish_non_exhaustive()
}
}
impl ScriptScope {
pub(crate) fn new(port: u16, state: ScriptStateCell) -> Self {
Self {
port,
state,
probe: None,
}
}
#[must_use]
pub fn with_probe(mut self, probe: std::sync::Arc<dyn crate::imposter::Probe>) -> Self {
self.probe = Some(probe);
self
}
#[must_use]
pub fn detached(port: u16) -> Self {
Self::new(port, ScriptStateCell::default())
}
pub(crate) fn standalone(port: u16) -> Self {
static STANDALONE: std::sync::LazyLock<
parking_lot::Mutex<std::collections::HashMap<u16, ScriptStateCell>>,
> = std::sync::LazyLock::new(Default::default);
let state = std::sync::Arc::clone(STANDALONE.lock().entry(port).or_default());
Self::new(port, state)
}
}
mod validator;
#[allow(unused_imports)]
pub use validator::ScriptValidationError;
pub use validator::ScriptValidator;
mod rhai_validator;
#[allow(unused_imports)]
pub use rhai_validator::RhaiValidationError;
pub use rhai_validator::RhaiValidator;
#[cfg(feature = "javascript")]
mod js_validator;
#[cfg(feature = "javascript")]
#[allow(unused_imports)]
pub use js_validator::JsValidationError;
#[cfg(feature = "javascript")]
pub use js_validator::JsValidator;
mod stub_validator;
pub use stub_validator::{validate_stub, validate_stubs};
mod entrypoint_check;
pub use entrypoint_check::{EntrypointCheckError, EntrypointMatch, check_entrypoint};
mod trace;
#[cfg(test)]
pub(crate) use trace::keep_scoped_captures_visible;
pub use trace::{ScriptTraceEntry, cap_trace_logs, capture_script_logs, render_decision};
#[derive(Debug, thiserror::Error)]
pub enum PredicateGeneratorError {
#[error("script pool failure: {0}")]
Pool(String),
#[error("script execution error: {0}")]
Script(String),
#[error("script execution error: {detail}")]
Threw {
message: Option<String>,
detail: String,
},
#[error("generator produced invalid output: {0}")]
Output(String),
#[error("generated predicate is invalid: {0}")]
Invalid(String),
#[error(transparent)]
Selector(#[from] crate::behaviors::XPathSelectorError),
}
impl PredicateGeneratorError {
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::Pool(_) => "pool-failure",
Self::Script(_) | Self::Threw { .. } => "script-error",
Self::Output(_) => "invalid-output",
Self::Invalid(_) => "invalid-predicate",
Self::Selector(_) => "selector-error",
}
}
}
#[derive(Debug, Clone)]
pub enum FaultDecision {
None,
Latency {
duration_ms: u64,
rule_id: String,
},
Error {
status: u16,
body: String,
rule_id: String,
headers: std::collections::HashMap<String, String>,
},
Reset {
rule_id: String,
},
}
#[derive(Debug, Clone, Default)]
pub struct ScriptStubContext {
pub scenario_name: Option<String>,
pub scenario_state: Option<String>,
pub stub_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ScriptCtxInput<'a> {
pub request: &'a ScriptRequest,
pub flow_id: String,
pub stub: ScriptStubContext,
pub port: u16,
}
impl<'a> ScriptCtxInput<'a> {
pub fn new(request: &'a ScriptRequest, flow_id: impl Into<String>) -> Self {
Self {
request,
flow_id: flow_id.into(),
stub: ScriptStubContext::default(),
port: 0,
}
}
#[must_use]
pub fn with_stub(mut self, stub: ScriptStubContext) -> Self {
self.stub = stub;
self
}
#[must_use]
pub fn with_port(mut self, port: u16) -> Self {
self.port = port;
self
}
}
#[derive(Debug, Clone, Default)]
pub struct ScriptCtxExtras {
pub flow_id: Option<String>,
pub stub: ScriptStubContext,
pub port: u16,
pub raw_query: Option<String>,
pub https: bool,
}
impl ScriptCtxExtras {
pub fn build_ctx_input<'a>(&self, request: &'a ScriptRequest) -> ScriptCtxInput<'a> {
let flow_id = self.flow_id.clone().unwrap_or_else(|| {
request
.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("x-flow-id"))
.and_then(|(_, v)| v.first().cloned())
.unwrap_or_default()
});
ScriptCtxInput::new(request, flow_id)
.with_stub(self.stub.clone())
.with_port(self.port)
}
}
#[derive(Debug, Clone)]
pub enum ScriptResultBody {
Json(Value),
Str(String),
}
#[derive(Debug, Clone)]
pub enum ScriptResult {
Pass,
Delay(u64),
Reset,
Http {
status: u16,
body: Option<ScriptResultBody>,
headers: Vec<(String, String)>,
},
}
impl ScriptResult {
pub fn http(status: u16, body: Option<ScriptResultBody>) -> Self {
ScriptResult::Http {
status,
body,
headers: Vec::new(),
}
}
pub fn add_header(&mut self, key: String, value: String) {
if let ScriptResult::Http { headers, .. } = self {
headers.push((key, value));
}
}
pub fn into_fault_decision(self, rule_id: &str) -> FaultDecision {
match self {
ScriptResult::Pass => FaultDecision::None,
ScriptResult::Delay(duration_ms) => FaultDecision::Latency {
duration_ms,
rule_id: rule_id.to_string(),
},
ScriptResult::Reset => FaultDecision::Reset {
rule_id: rule_id.to_string(),
},
ScriptResult::Http {
status,
body,
headers,
} => {
let mut header_map: HashMap<String, String> = HashMap::new();
let mut has_content_type = false;
for (k, v) in headers {
if k.eq_ignore_ascii_case("content-type") {
has_content_type = true;
}
header_map.insert(k, v);
}
let body_str = match body {
None => String::new(),
Some(ScriptResultBody::Str(s)) => s,
Some(ScriptResultBody::Json(v)) => {
if !has_content_type {
header_map
.insert("Content-Type".to_string(), "application/json".to_string());
}
serde_json::to_string(&v).unwrap_or_default()
}
};
FaultDecision::Error {
status,
body: body_str,
rule_id: rule_id.to_string(),
headers: header_map,
}
}
}
}
}
pub mod entrypoints {
pub const RESPOND: &str = "respond";
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptEngineKind {
Rhai,
JavaScript,
Wasm,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EngineNameError {
#[error(
"the Lua scripting engine was removed (issue #450); use engine \"rhai\" or \"javascript\""
)]
Removed,
#[error("Unknown script engine type: {0}")]
Unknown(String),
}
impl ScriptEngineKind {
pub fn parse(name: &str) -> Result<Self, EngineNameError> {
match name {
"rhai" => Ok(Self::Rhai),
"javascript" | "js" => Ok(Self::JavaScript),
"wasm" => Ok(Self::Wasm),
"lua" => Err(EngineNameError::Removed),
other => Err(EngineNameError::Unknown(other.to_owned())),
}
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Rhai => "rhai",
Self::JavaScript => "javascript",
Self::Wasm => "wasm",
}
}
#[must_use]
pub fn is_wasm(name: &str) -> bool {
matches!(Self::parse(name), Ok(Self::Wasm))
}
pub fn from_extension(ext: &str) -> Option<Result<Self, EngineNameError>> {
match ext {
"rhai" => Some(Ok(Self::Rhai)),
"js" => Some(Ok(Self::JavaScript)),
"wasm" => Some(Ok(Self::Wasm)),
"lua" => Some(Err(EngineNameError::Removed)),
_ => None,
}
}
}
#[cfg(feature = "wasm")]
pub(crate) fn wasm_admit_imports(code: &str) -> Result<Vec<String>, String> {
wasm::admit_imports(code).map_err(|e| e.to_string())
}
pub fn admit_wasm_component(code: &str, export: Option<&str>) -> Result<&'static str, String> {
#[cfg(feature = "wasm")]
{
wasm::admit_export(code, export).map_err(|e| e.to_string())
}
#[cfg(not(feature = "wasm"))]
{
let _ = (code, export);
Err(WASM_UNAVAILABLE.to_owned())
}
}
#[cfg_attr(feature = "wasm", allow(dead_code))]
pub(crate) const WASM_UNAVAILABLE: &str = "engine \"wasm\" is not available in this build";
#[derive(Clone)]
pub enum ScriptEngine {
Rhai(RhaiEngine),
#[cfg(feature = "javascript")]
JavaScript(JsEngine),
}
impl ScriptEngine {
pub fn new(engine_type: &str, script: &str, rule_id: &str) -> Result<Self> {
match ScriptEngineKind::parse(engine_type)? {
ScriptEngineKind::Rhai => Ok(ScriptEngine::Rhai(RhaiEngine::new(script, rule_id)?)),
#[cfg(feature = "javascript")]
ScriptEngineKind::JavaScript => {
Ok(ScriptEngine::JavaScript(JsEngine::new(script, rule_id)?))
}
#[cfg(not(feature = "javascript"))]
ScriptEngineKind::JavaScript => Err(anyhow!(
"JavaScript engine is not enabled. Enable the 'javascript' feature flag"
)),
#[cfg(not(feature = "wasm"))]
ScriptEngineKind::Wasm => Err(anyhow!(WASM_UNAVAILABLE)),
#[cfg(feature = "wasm")]
ScriptEngineKind::Wasm => Err(anyhow!(
"engine \"wasm\" runs only as a `_rift.script` response"
)),
}
}
pub fn should_inject_fault(
&self,
request: &ScriptRequest,
flow_store: Arc<dyn FlowStore>,
) -> Result<FaultDecision> {
self.should_inject_fault_with_ctx(request, flow_store, &ScriptCtxExtras::default())
}
pub fn should_inject_fault_with_ctx(
&self,
request: &ScriptRequest,
flow_store: Arc<dyn FlowStore>,
extra: &ScriptCtxExtras,
) -> Result<FaultDecision> {
match self {
ScriptEngine::Rhai(engine) => {
engine.should_inject_fault_with_ctx(request, flow_store, extra)
}
#[cfg(feature = "javascript")]
ScriptEngine::JavaScript(engine) => {
engine.should_inject_with_ctx(request, flow_store, extra)
}
}
}
}
#[derive(Debug, Clone)]
pub struct ScriptRequest {
pub method: String,
pub path: String,
pub headers: crate::util::MultiValueMap,
pub body: Value,
pub query: crate::util::MultiValueMap,
pub path_params: HashMap<String, String>,
pub raw_body: Option<String>,
pub mode: ResponseMode,
}
#[derive(Clone)]
pub struct ScriptFlowStore {
store: Arc<dyn FlowStore>,
}
impl ScriptFlowStore {
pub fn new(store: Arc<dyn FlowStore>) -> Self {
Self { store }
}
pub fn get(
&mut self,
flow_id: String,
key: String,
) -> std::result::Result<Dynamic, Box<rhai::EvalAltResult>> {
match flow_result("get", self.store.get(&flow_id, &key)) {
Ok(Some(val)) => Ok(rhai_engine::json_to_dynamic(val)),
Ok(None) => Ok(Dynamic::UNIT),
Err(msg) => Err(msg.into()),
}
}
pub fn set(
&mut self,
flow_id: String,
key: String,
value: Dynamic,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
let json_val = rhai_engine::dynamic_to_json(value);
match flow_result(
"set",
self.store.set(&flow_id, &key, json_val).map(|()| true),
) {
Ok(v) => Ok(v),
Err(msg) => Err(msg.into()),
}
}
pub fn exists(
&mut self,
flow_id: String,
key: String,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
match flow_result("exists", self.store.exists(&flow_id, &key)) {
Ok(v) => Ok(v),
Err(msg) => Err(msg.into()),
}
}
pub fn delete(
&mut self,
flow_id: String,
key: String,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
match flow_result("delete", self.store.delete(&flow_id, &key).map(|()| true)) {
Ok(v) => Ok(v),
Err(msg) => Err(msg.into()),
}
}
pub fn increment(
&mut self,
flow_id: String,
key: String,
) -> std::result::Result<i64, Box<rhai::EvalAltResult>> {
match flow_result("increment", self.store.increment(&flow_id, &key)) {
Ok(v) => Ok(v),
Err(msg) => Err(msg.into()),
}
}
pub fn set_ttl(
&mut self,
flow_id: String,
ttl_seconds: i64,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
match flow_result(
"setTtl",
self.store.set_ttl(&flow_id, ttl_seconds).map(|()| true),
) {
Ok(v) => Ok(v),
Err(msg) => Err(msg.into()),
}
}
pub fn last_error(&mut self) -> Dynamic {
match crate::extensions::flow_state::take_last_flow_error() {
Some(msg) => Dynamic::from(msg),
None => Dynamic::UNIT,
}
}
pub fn get_or(
&mut self,
flow_id: String,
key: String,
default: Dynamic,
) -> std::result::Result<Dynamic, Box<rhai::EvalAltResult>> {
match flow_result("getOr", self.store.get(&flow_id, &key)) {
Ok(Some(val)) => Ok(rhai_engine::json_to_dynamic(val)),
Ok(None) => Ok(default),
Err(msg) => Err(msg.into()),
}
}
pub fn increment_by(
&mut self,
flow_id: String,
key: String,
by: i64,
) -> std::result::Result<i64, Box<rhai::EvalAltResult>> {
flow_result("incrementBy", self.store.increment_by(&flow_id, &key, by)).map_err(Into::into)
}
pub fn cas(
&mut self,
flow_id: String,
key: String,
expected: Dynamic,
new: Dynamic,
) -> std::result::Result<CasOutcome, Box<rhai::EvalAltResult>> {
let expected_json = if expected.is_unit() {
None
} else {
Some(rhai_engine::dynamic_to_json(expected))
};
let new_json = rhai_engine::dynamic_to_json(new);
flow_result(
"cas",
self.store
.compare_and_set(&flow_id, &key, expected_json.as_ref(), new_json),
)
.map_err(Into::into)
}
pub fn ttl(
&mut self,
flow_id: String,
ttl_seconds: i64,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
flow_result(
"ttl",
self.store.set_ttl(&flow_id, ttl_seconds).map(|()| true),
)
.map_err(Into::into)
}
pub fn key_ttl(
&mut self,
flow_id: String,
key: String,
ttl_seconds: i64,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
flow_result(
"keyTtl",
self.store.set_key_ttl(&flow_id, &key, ttl_seconds),
)
.map_err(Into::into)
}
pub fn clear(
&mut self,
flow_id: String,
) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
flow_result("clear", self.store.clear_flow(&flow_id).map(|()| true)).map_err(Into::into)
}
}
#[cfg(test)]
mod tests {
#[test]
fn engine_names_parse_once() {
use super::{EngineNameError, ScriptEngineKind};
assert_eq!(ScriptEngineKind::parse("rhai"), Ok(ScriptEngineKind::Rhai));
assert_eq!(
ScriptEngineKind::parse("javascript"),
Ok(ScriptEngineKind::JavaScript)
);
assert_eq!(
ScriptEngineKind::parse("js"),
Ok(ScriptEngineKind::JavaScript)
);
assert_eq!(ScriptEngineKind::parse("wasm"), Ok(ScriptEngineKind::Wasm));
assert_eq!(
ScriptEngineKind::parse("lua"),
Err(EngineNameError::Removed)
);
assert_eq!(
ScriptEngineKind::parse("cobol"),
Err(EngineNameError::Unknown("cobol".to_owned()))
);
assert_eq!(ScriptEngineKind::JavaScript.as_str(), "javascript");
assert_eq!(ScriptEngineKind::Rhai.as_str(), "rhai");
assert_eq!(ScriptEngineKind::Wasm.as_str(), "wasm");
assert_eq!(
EngineNameError::Removed.to_string(),
"the Lua scripting engine was removed (issue #450); use engine \"rhai\" or \"javascript\""
);
assert_eq!(
EngineNameError::Unknown("cobol".to_owned()).to_string(),
"Unknown script engine type: cobol"
);
}
#[test]
fn engine_names_from_extensions() {
use super::{EngineNameError, ScriptEngineKind};
assert_eq!(
ScriptEngineKind::from_extension("rhai"),
Some(Ok(ScriptEngineKind::Rhai))
);
assert_eq!(
ScriptEngineKind::from_extension("js"),
Some(Ok(ScriptEngineKind::JavaScript))
);
assert_eq!(
ScriptEngineKind::from_extension("wasm"),
Some(Ok(ScriptEngineKind::Wasm))
);
assert_eq!(
ScriptEngineKind::from_extension("lua"),
Some(Err(EngineNameError::Removed))
);
assert_eq!(ScriptEngineKind::from_extension("txt"), None);
}
#[cfg(not(feature = "wasm"))]
#[test]
fn wasm_is_refused_as_unavailable() {
let err = super::ScriptEngine::new("wasm", "x", "r")
.err()
.expect("refused");
assert_eq!(
err.to_string(),
"engine \"wasm\" is not available in this build"
);
}
use super::*;
use crate::extensions::flow_state::NoOpFlowStore;
use serde_json::json;
use std::collections::HashMap;
struct FailingStore;
impl FlowStore for FailingStore {
fn get(&self, _: &str, _: &str) -> Result<Option<Value>> {
Err(anyhow!("boom"))
}
fn set(&self, _: &str, _: &str, _: Value) -> Result<()> {
Err(anyhow!("boom"))
}
fn exists(&self, _: &str, _: &str) -> Result<bool> {
Err(anyhow!("boom"))
}
fn delete(&self, _: &str, _: &str) -> Result<()> {
Err(anyhow!("boom"))
}
fn increment(&self, _: &str, _: &str) -> Result<i64> {
Err(anyhow!("boom"))
}
fn set_ttl(&self, _: &str, _: i64) -> Result<()> {
Err(anyhow!("boom"))
}
fn set_key_ttl(&self, _: &str, _: &str, _: i64) -> Result<bool> {
Err(anyhow!("boom"))
}
fn clear_flow(&self, _: &str) -> Result<()> {
Err(anyhow!("boom"))
}
}
#[test]
fn rhai_flow_store_ops_fail_loud_and_record_error() {
use crate::extensions::flow_state::take_last_flow_error;
let mut s = ScriptFlowStore::new(Arc::new(FailingStore));
let _ = take_last_flow_error();
assert!(
s.get("f".into(), "k".into()).is_err(),
"get must raise on a backend failure"
);
assert!(
take_last_flow_error().is_some_and(|e| e.contains("get")),
"get records last_error"
);
assert!(
s.set("f".into(), "k".into(), Dynamic::from(1)).is_err(),
"set must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("set")));
assert!(
s.exists("f".into(), "k".into()).is_err(),
"exists must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("exists")));
assert!(
s.delete("f".into(), "k".into()).is_err(),
"delete must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("delete")));
assert!(
s.increment("f".into(), "k".into()).is_err(),
"increment must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("increment")));
assert!(
s.set_ttl("f".into(), 60).is_err(),
"set_ttl must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("setTtl")));
assert!(
s.key_ttl("f".into(), "k".into(), 60).is_err(),
"key_ttl must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("keyTtl")));
assert!(
s.clear("f".into()).is_err(),
"clear must raise on a backend failure"
);
assert!(take_last_flow_error().is_some_and(|e| e.contains("clear")));
}
#[test]
fn rhai_flow_store_last_error_surfaces() {
use crate::extensions::flow_state::{log_flow_err, take_last_flow_error};
let _ = take_last_flow_error();
let mut s = ScriptFlowStore::new(Arc::new(NoOpFlowStore));
let _ = log_flow_err(
"increment",
0i64,
Err::<i64, _>(anyhow::anyhow!("backend down")),
);
let err = s.last_error();
assert!(
err.into_string()
.map(|x| x.contains("backend down"))
.unwrap_or(false),
"last_error() must surface the recorded backend error"
);
assert!(s.last_error().is_unit());
}
#[test]
fn test_fault_decision_none() {
let decision = FaultDecision::None;
match decision {
FaultDecision::None => {}
_ => panic!("Expected FaultDecision::None"),
}
}
#[test]
fn test_fault_decision_latency() {
let decision = FaultDecision::Latency {
duration_ms: 500,
rule_id: "test-rule".to_string(),
};
match decision {
FaultDecision::Latency {
duration_ms,
rule_id,
} => {
assert_eq!(duration_ms, 500);
assert_eq!(rule_id, "test-rule");
}
_ => panic!("Expected FaultDecision::Latency"),
}
}
#[test]
fn test_fault_decision_error() {
let mut headers = std::collections::HashMap::new();
headers.insert("X-Custom".to_string(), "value".to_string());
let decision = FaultDecision::Error {
status: 503,
body: r#"{"error": "service unavailable"}"#.to_string(),
rule_id: "error-rule".to_string(),
headers,
};
match decision {
FaultDecision::Error {
status,
body,
rule_id,
headers,
} => {
assert_eq!(status, 503);
assert!(body.contains("service unavailable"));
assert_eq!(rule_id, "error-rule");
assert_eq!(headers.get("X-Custom"), Some(&"value".to_string()));
}
_ => panic!("Expected FaultDecision::Error"),
}
}
#[test]
fn test_fault_decision_clone() {
let decision = FaultDecision::Latency {
duration_ms: 100,
rule_id: "clone-test".to_string(),
};
let cloned = decision.clone();
match cloned {
FaultDecision::Latency {
duration_ms,
rule_id,
} => {
assert_eq!(duration_ms, 100);
assert_eq!(rule_id, "clone-test");
}
_ => panic!("Expected cloned FaultDecision::Latency"),
}
}
#[test]
fn test_fault_decision_debug() {
let decision = FaultDecision::None;
let debug_str = format!("{decision:?}");
assert!(debug_str.contains("None"));
}
#[test]
fn test_fault_decision_reset() {
let decision = FaultDecision::Reset {
rule_id: "reset-rule".to_string(),
};
match decision {
FaultDecision::Reset { rule_id } => assert_eq!(rule_id, "reset-rule"),
_ => panic!("Expected FaultDecision::Reset"),
}
}
#[test]
fn test_script_result_into_fault_decision() {
assert!(matches!(
ScriptResult::Pass.into_fault_decision("r"),
FaultDecision::None
));
assert!(matches!(
ScriptResult::Delay(42).into_fault_decision("r"),
FaultDecision::Latency {
duration_ms: 42,
..
}
));
assert!(matches!(
ScriptResult::Reset.into_fault_decision("r"),
FaultDecision::Reset { .. }
));
let mut json_result =
ScriptResult::http(503, Some(ScriptResultBody::Json(json!({"e": 1}))));
json_result.add_header("Retry-After".to_string(), "1".to_string());
match json_result.into_fault_decision("r") {
FaultDecision::Error {
status,
body,
headers,
..
} => {
assert_eq!(status, 503);
assert_eq!(body, r#"{"e":1}"#);
assert_eq!(headers.get("Retry-After").map(String::as_str), Some("1"));
assert_eq!(
headers.get("Content-Type").map(String::as_str),
Some("application/json")
);
}
other => panic!("expected Error, got {other:?}"),
}
let mut custom_ct = ScriptResult::http(200, Some(ScriptResultBody::Json(json!({}))));
custom_ct.add_header("content-type".to_string(), "application/custom".to_string());
match custom_ct.into_fault_decision("r") {
FaultDecision::Error { headers, .. } => {
assert_eq!(
headers.get("content-type").map(String::as_str),
Some("application/custom")
);
assert!(!headers.contains_key("Content-Type"));
}
other => panic!("expected Error, got {other:?}"),
}
match ScriptResult::http(200, Some(ScriptResultBody::Str("hi".to_string())))
.into_fault_decision("r")
{
FaultDecision::Error { body, headers, .. } => {
assert_eq!(body, "hi");
assert!(!headers.contains_key("Content-Type"));
}
other => panic!("expected Error, got {other:?}"),
}
}
#[test]
fn test_script_request_creation() {
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "POST".to_string(),
path: "/api/users".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!({"name": "test"}),
query: Default::default(),
path_params: HashMap::new(),
};
assert_eq!(request.method, "POST");
assert_eq!(request.path, "/api/users");
}
#[test]
fn test_script_request_with_headers() {
let mut headers = crate::util::OrderedMap::default();
headers.insert(
"Content-Type".to_string(),
vec!["application/json".to_string()],
);
headers.insert(
"Authorization".to_string(),
vec!["Bearer token".to_string()],
);
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "GET".to_string(),
path: "/api/data".to_string(),
headers,
body: serde_json::json!(null),
query: Default::default(),
path_params: HashMap::new(),
};
assert_eq!(request.headers.len(), 2);
assert_eq!(
request.headers.get("Content-Type"),
Some(&vec!["application/json".to_string()])
);
}
#[test]
fn test_script_request_with_query_params() {
let mut query = crate::util::OrderedMap::default();
query.insert("page".to_string(), vec!["1".to_string()]);
query.insert("limit".to_string(), vec!["10".to_string()]);
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "GET".to_string(),
path: "/api/items".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!(null),
query,
path_params: HashMap::new(),
};
assert_eq!(request.query.get("page"), Some(&vec!["1".to_string()]));
assert_eq!(request.query.get("limit"), Some(&vec!["10".to_string()]));
}
#[test]
fn test_script_request_with_path_params() {
let mut path_params = HashMap::new();
path_params.insert("id".to_string(), "123".to_string());
path_params.insert("action".to_string(), "edit".to_string());
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "PUT".to_string(),
path: "/api/users/123/edit".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!({"name": "updated"}),
query: Default::default(),
path_params,
};
assert_eq!(request.path_params.get("id"), Some(&"123".to_string()));
}
#[test]
fn test_script_request_clone() {
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "DELETE".to_string(),
path: "/api/items/456".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!(null),
query: Default::default(),
path_params: HashMap::new(),
};
let cloned = request.clone();
assert_eq!(cloned.method, "DELETE");
assert_eq!(cloned.path, "/api/items/456");
}
#[test]
fn test_script_request_debug() {
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "GET".to_string(),
path: "/test".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!(null),
query: Default::default(),
path_params: HashMap::new(),
};
let debug_str = format!("{request:?}");
assert!(debug_str.contains("GET"));
assert!(debug_str.contains("/test"));
}
#[test]
fn test_script_flow_store_creation() {
let store = Arc::new(NoOpFlowStore);
let script_store = ScriptFlowStore::new(store);
assert!(std::mem::size_of_val(&script_store) > 0);
}
#[test]
fn test_script_flow_store_get() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.get("flow-1".to_string(), "key".to_string())
.expect("NoOp get never fails");
assert!(result.is_unit());
}
#[test]
fn test_script_flow_store_set() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.set(
"flow-1".to_string(),
"key".to_string(),
rhai::Dynamic::from(42),
)
.expect("NoOp set never fails");
assert!(result);
}
#[test]
fn test_script_flow_store_exists() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.exists("flow-1".to_string(), "key".to_string())
.expect("NoOp exists never fails");
assert!(!result); }
#[test]
fn test_script_flow_store_delete() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.delete("flow-1".to_string(), "key".to_string())
.expect("NoOp delete never fails");
assert!(result);
}
#[test]
fn test_script_flow_store_increment() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.increment("flow-1".to_string(), "counter".to_string())
.expect("NoOp increment never fails");
assert_eq!(result, 1);
}
#[test]
fn test_script_flow_store_set_ttl() {
let store = Arc::new(NoOpFlowStore);
let mut script_store = ScriptFlowStore::new(store);
let result = script_store
.set_ttl("flow-1".to_string(), 3600)
.expect("NoOp set_ttl never fails");
assert!(result);
}
#[test]
fn test_script_flow_store_clone() {
let store = Arc::new(NoOpFlowStore);
let script_store = ScriptFlowStore::new(store);
let cloned = script_store.clone();
assert!(std::mem::size_of_val(&cloned) > 0);
}
#[test]
fn test_script_engine_new_rhai() {
let script = r#"
fn respond(ctx) {
pass()
}
"#;
let engine = ScriptEngine::new("rhai", script, "test-rule");
assert!(engine.is_ok());
}
#[test]
fn test_script_engine_new_invalid_type() {
let script = "return false";
let engine = ScriptEngine::new("invalid_engine", script, "test-rule");
assert!(engine.is_err());
let err_msg = engine.err().unwrap().to_string();
assert!(err_msg.contains("Unknown script engine type"));
}
#[test]
fn test_script_engine_rhai_execution() {
let script = r#"
fn respond(ctx) {
pass()
}
"#;
let engine = ScriptEngine::new("rhai", script, "test-rule").unwrap();
let request = ScriptRequest {
mode: ResponseMode::Text,
raw_body: None,
method: "GET".to_string(),
path: "/test".to_string(),
headers: crate::util::OrderedMap::default(),
body: serde_json::json!(null),
query: Default::default(),
path_params: HashMap::new(),
};
let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> = Arc::new(NoOpFlowStore);
let result = engine.should_inject_fault(&request, flow_store);
assert!(result.is_ok());
}
#[test]
fn test_rhai_engine_creation_valid_script() {
let script = r#"
fn respond(ctx) {
pass()
}
"#;
let engine = RhaiEngine::new(script, "valid-rule");
assert!(engine.is_ok());
}
#[test]
fn test_rhai_engine_creation_syntax_error() {
let script = r#"
fn respond(ctx { // Missing closing paren
return false;
}
"#;
let engine = RhaiEngine::new(script, "invalid-rule");
assert!(engine.is_err());
}
#[test]
fn test_rhai_engine_ast_access() {
let script = r#"
fn respond(ctx) {
pass()
}
"#;
let engine = RhaiEngine::new(script, "test-rule").unwrap();
let ast = engine.ast();
assert!(std::mem::size_of_val(ast) > 0);
}
#[test]
fn test_script_engine_new_lua_removed() {
let engine = ScriptEngine::new("lua", "return false", "test-rule");
assert!(engine.is_err());
let err_msg = engine.err().unwrap().to_string();
assert!(err_msg.contains("removed"), "unexpected message: {err_msg}");
assert!(err_msg.contains("rhai"));
assert!(err_msg.contains("javascript"));
}
#[cfg(feature = "javascript")]
mod js_tests {
use super::*;
#[test]
fn test_script_engine_new_javascript() {
let script = r#"
function respond(ctx) {
return pass();
}
"#;
let engine = ScriptEngine::new("javascript", script, "js-rule");
assert!(
engine.is_ok(),
"JS engine creation failed: {:?}",
engine.err()
);
}
#[test]
fn test_script_engine_new_js_alias() {
let script = r#"
function respond(ctx) {
return pass();
}
"#;
let engine = ScriptEngine::new("js", script, "js-rule");
assert!(
engine.is_ok(),
"JS engine creation failed: {:?}",
engine.err()
);
}
#[test]
fn test_compile_js_to_bytecode() {
let script = r#"
function respond(ctx) {
return pass();
}
"#;
let bytecode = super::super::compile_js_to_bytecode(script);
assert!(bytecode.is_ok());
}
}
#[cfg(not(feature = "javascript"))]
#[test]
fn test_javascript_engine_disabled() {
let engine = ScriptEngine::new("javascript", "return false", "test");
assert!(engine.is_err());
let err_msg = engine.err().unwrap().to_string();
assert!(err_msg.contains("not enabled") || err_msg.contains("feature"));
}
}