camel-component-wasm 0.19.0

WASM plugin component for rust-camel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde_json::Value;
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::WasiCtxBuilder;

use camel_core::Registry;

use crate::bindings::Plugin;
use crate::bindings::camel::plugin::types::WasmExchange;
use crate::error::WasmError;

pub struct WasmHostState {
    pub table: ResourceTable,
    pub wasi: wasmtime_wasi::WasiCtx,
    pub properties: HashMap<String, Value>,
    pub registry: Arc<std::sync::Mutex<Registry>>,
    pub call_depth: u32,
    pub limits: wasmtime::StoreLimits,
    pub state_store: crate::state_store::StateStore,
    pub tokio_handle: tokio::runtime::Handle,
}

impl wasmtime_wasi::WasiView for WasmHostState {
    fn ctx(&mut self) -> wasmtime_wasi::WasiCtxView<'_> {
        wasmtime_wasi::WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

pub struct WasmRuntime {
    engine: Engine,
    linker: Linker<WasmHostState>,
    component: Component,
    module_path: PathBuf,
    config: crate::config::WasmConfig,
    #[allow(dead_code)]
    epoch_ticker: crate::epoch::EpochTicker,
}

impl WasmRuntime {
    pub async fn new(
        module_path: impl AsRef<Path>,
        wasm_config: crate::config::WasmConfig,
    ) -> Result<Self, WasmError> {
        let module_path = module_path.as_ref().to_path_buf();

        let mut config = Config::new();
        config.wasm_component_model(true);
        #[cfg(feature = "epoch-interruption")]
        config.epoch_interruption(true);

        let engine =
            Engine::new(&config).map_err(|e| WasmError::CompilationFailed(e.to_string()))?;

        let component = Component::from_file(&engine, &module_path).map_err(|e| {
            WasmError::ModuleNotFound(format!(
                "Failed to load WASM module {}: {}",
                module_path.display(),
                e
            ))
        })?;

        let mut linker: Linker<WasmHostState> = Linker::new(&engine);

        wasmtime_wasi::p2::add_to_linker_async(&mut linker)
            .map_err(|e| WasmError::CompilationFailed(e.to_string()))?;

        crate::host_functions::add_to_linker(&mut linker)
            .map_err(|e| WasmError::CompilationFailed(e.to_string()))?;

        let epoch_ticker =
            crate::epoch::EpochTicker::start(engine.clone(), wasm_config.epoch_interval());

        Ok(Self {
            engine,
            linker,
            component,
            module_path,
            config: wasm_config,
            epoch_ticker,
        })
    }

    /// Construct a fresh `WasmHostState` for one guest invocation.
    ///
    /// `max_memory_bytes` is enforced via `wasmtime::StoreLimitsBuilder::memory_size`.
    /// Pass `0` to fall back to `StoreLimits::default()` (4 GiB wasmtime ceiling);
    /// any positive value is applied as the cap.
    pub fn create_host_state(
        registry: Arc<std::sync::Mutex<Registry>>,
        properties: HashMap<String, Value>,
        state_store: crate::state_store::StateStore,
        tokio_handle: tokio::runtime::Handle,
        max_memory_bytes: u64,
    ) -> WasmHostState {
        let limits = if max_memory_bytes == 0 {
            wasmtime::StoreLimits::default()
        } else {
            wasmtime::StoreLimitsBuilder::new()
                .memory_size(max_memory_bytes as usize)
                .build()
        };
        WasmHostState {
            table: ResourceTable::new(),
            wasi: WasiCtxBuilder::new().inherit_stderr().build(),
            properties,
            registry,
            call_depth: 0,
            limits,
            state_store,
            tokio_handle,
        }
    }

    /// Classify a wasmtime error into a structured WasmError.
    ///
    /// Downcasts to `wasmtime::Trap` first — if successful, routes to
    /// Timeout/OutOfMemory/Trap variants. Otherwise falls back to GuestPanic.
    fn classify_error(&self, e: wasmtime::Error) -> WasmError {
        self.config.classify_error(&self.module_path, e)
    }

    pub async fn call_init_once(
        &self,
        registry: Arc<std::sync::Mutex<Registry>>,
        properties: HashMap<String, Value>,
        state_store: crate::state_store::StateStore,
        tokio_handle: tokio::runtime::Handle,
    ) -> Result<(), WasmError> {
        let host_state = Self::create_host_state(
            registry,
            properties,
            state_store,
            tokio_handle,
            self.config.max_memory_bytes,
        );
        let mut store = Store::new(&self.engine, host_state);
        store.limiter(|state| &mut state.limits);
        store.set_epoch_deadline(self.config.epoch_deadline());

        let plugin = Plugin::instantiate_async(&mut store, &self.component, &self.linker)
            .await
            .map_err(|e| WasmError::InstantiationFailed(e.to_string()))?;

        let result: Result<(), String> = plugin
            .call_init(&mut store)
            .await
            .map_err(|e| self.classify_error(e))?;

        if let Err(e) = result {
            tracing::debug!(
                "WASM init() returned error (optional hook): {} — {}",
                self.module_path.display(),
                e
            );
        }
        Ok(())
    }

    pub async fn call_process(
        &self,
        registry: Arc<std::sync::Mutex<Registry>>,
        properties: HashMap<String, Value>,
        state_store: crate::state_store::StateStore,
        tokio_handle: tokio::runtime::Handle,
        exchange: WasmExchange,
    ) -> Result<WasmExchange, WasmError> {
        let host_state = Self::create_host_state(
            registry,
            properties,
            state_store,
            tokio_handle,
            self.config.max_memory_bytes,
        );
        let mut store = Store::new(&self.engine, host_state);
        store.limiter(|state| &mut state.limits);
        store.set_epoch_deadline(self.config.epoch_deadline());

        let plugin = Plugin::instantiate_async(&mut store, &self.component, &self.linker)
            .await
            .map_err(|e| WasmError::InstantiationFailed(e.to_string()))?;

        let result: Result<WasmExchange, crate::bindings::camel::plugin::types::WasmError> = plugin
            .call_process(&mut store, &exchange)
            .await
            .map_err(|e| self.classify_error(e))?;

        result.map_err(|wasm_err| match wasm_err {
            crate::bindings::camel::plugin::types::WasmError::ProcessorError(s) => {
                WasmError::GuestPanic(s)
            }
            crate::bindings::camel::plugin::types::WasmError::TypeConversion(s) => {
                WasmError::TypeConversion(s)
            }
            crate::bindings::camel::plugin::types::WasmError::Io(s) => WasmError::Io(s),
            crate::bindings::camel::plugin::types::WasmError::Timeout => {
                WasmError::GuestPanic("guest timeout".to_string())
            }
        })
    }

    pub fn module_path(&self) -> &Path {
        &self.module_path
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::OnceLock;

    fn test_tokio_handle() -> tokio::runtime::Handle {
        static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
        RT.get_or_init(|| tokio::runtime::Runtime::new().expect("test runtime"))
            .handle()
            .clone()
    }

    #[test]
    fn test_wasm_host_state_creation() {
        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let props = HashMap::new();
        let state = WasmHostState {
            table: ResourceTable::new(),
            wasi: WasiCtxBuilder::new().inherit_stderr().build(),
            properties: props,
            registry,
            call_depth: 0,
            limits: wasmtime::StoreLimits::default(),
            state_store: crate::state_store::StateStore::new(),
            tokio_handle: test_tokio_handle(),
        };
        assert!(state.properties.is_empty());
        assert_eq!(state.call_depth, 0);
    }

    #[test]
    fn create_host_state_with_zero_memory_falls_back_to_default() {
        // Defensive: passing 0 must not produce a StoreLimits that blocks all
        // memory growth — it should fall back to wasmtime's default.
        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            0,
        );
        let _ = host_state; // smoke test: constructor tolerates 0
    }

    // Per-plugin-type coverage: this test runs at the shared `create_host_state`
    // layer, so its enforcement guarantee applies to every plugin type (Processor,
    // Bean, AuthorizationPolicy, SecurityPolicy) — they all call this function.
    #[tokio::test]
    async fn memory_growth_rejected_past_configured_cap() {
        // Behavioral test for acceptance criterion #4: max_memory_bytes is
        // *actually enforced*. Builds a tiny core-wasm module that exports a
        // `grow` function calling `memory.grow(64)` (requesting ~4 MiB) against
        // a host state with a 64 KiB cap. The grow call must return -1.
        //
        // We use a core (non-component) module here because the limiter is
        // applied at the wasmtime::Store level — the same store that components
        // use — so core wasm exercises the same enforcement path without the
        // boilerplate of synthesizing a full component.
        let wat = r#"
        (module
          (memory $mem (export "memory") 1)
          (func (export "grow") (param i32) (result i32)
            local.get 0
            memory.grow $mem)
        )
    "#;

        let config = wasmtime::Config::new();
        let engine = Engine::new(&config).unwrap();
        let module = wasmtime::Module::new(&engine, wat).expect("compile wat");

        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            64 * 1024, // 64 KiB cap
        );
        let mut store = Store::new(&engine, host_state);
        store.limiter(|state| &mut state.limits);

        let instance = wasmtime::Instance::new_async(&mut store, &module, &[])
            .await
            .expect("instantiate");
        let grow = instance
            .get_typed_func::<i32, i32>(&mut store, "grow")
            .expect("get grow export");

        // memory.grow(64) requests 64 pages = 4 MiB, far above the 64 KiB cap.
        // The limiter must refuse it; memory.grow returns -1 on rejection.
        let result = grow.call_async(&mut store, 64).await.expect("grow call");
        assert_eq!(
            result, -1,
            "memory.grow must return -1 when the cap (64 KiB) would be exceeded"
        );
    }

    #[tokio::test]
    async fn memory_growth_allowed_under_cap() {
        // Companion to the above: a growth request that stays under the cap
        // must succeed. Guards against the limiter being accidentally
        // over-restrictive.
        let wat = r#"
        (module
          (memory $mem (export "memory") 1)
          (func (export "grow") (param i32) (result i32)
            local.get 0
            memory.grow $mem)
        )
    "#;

        let config = wasmtime::Config::new();
        let engine = Engine::new(&config).unwrap();
        let module = wasmtime::Module::new(&engine, wat).expect("compile wat");

        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        // Cap = 1 page initial + 1 page growable = 2 pages = 128 KiB.
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            128 * 1024,
        );
        let mut store = Store::new(&engine, host_state);
        store.limiter(|state| &mut state.limits);

        let instance = wasmtime::Instance::new_async(&mut store, &module, &[])
            .await
            .expect("instantiate");
        let grow = instance
            .get_typed_func::<i32, i32>(&mut store, "grow")
            .expect("get grow export");

        // memory.grow(1) requests 1 page = 64 KiB. With a 128 KiB cap and
        // 1 page initial, the growable budget is 64 KiB (one page). Must succeed
        // and return the previous page count (1, since initial is 1 page).
        let result = grow.call_async(&mut store, 1).await.expect("grow call");
        assert_eq!(result, 1, "memory.grow of 1 page under cap must succeed");
    }

    #[test]
    fn test_host_state_has_limits_field() {
        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            0,
        );
        let _limits: &wasmtime::StoreLimits = &state.limits;
    }

    #[test]
    fn test_epoch_deadline_set_on_store() {
        let mut config = wasmtime::Config::new();
        config.epoch_interruption(true);
        config.wasm_component_model(true);
        let engine = Engine::new(&config).unwrap();
        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            0,
        );
        let mut store = Store::new(&engine, host_state);
        store.set_epoch_deadline(500);
        // NOTE: wasmtime v31 does not expose `get_epoch_deadline()` on Store,
        // so we cannot assert the value was set. This test verifies the API
        // compiles and does not panic at runtime. The actual deadline enforcement
        // is validated indirectly by the epoch_interruption integration tests.
    }

    #[test]
    fn test_store_limiter_uses_host_state_limits() {
        let mut config = wasmtime::Config::new();
        config.epoch_interruption(true);
        config.wasm_component_model(true);
        let engine = Engine::new(&config).unwrap();
        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            1024, // 1 KiB cap; threaded through create_host_state
        );
        let mut store = Store::new(&engine, host_state);
        store.limiter(|state| &mut state.limits);
        // Verifies store.limiter accepts WasmHostState::limits after the new
        // create_host_state wires the memory cap through StoreLimitsBuilder.
    }

    #[tokio::test]
    async fn timeout_kills_infinite_loop_guest() {
        // Behavioral test for the timeout half of the safety net:
        // a guest that loops forever must be killed by epoch interruption
        // within a bounded time of the configured deadline.
        //
        // This test is the runtime-level proof of acceptance criterion #5
        // ("timeout_secs honoured end-to-end"). All plugin types (Processor,
        // Bean, AuthorizationPolicy, SecurityPolicy) share the same
        // `create_host_state` + `set_epoch_deadline` mechanism, so proving
        // it once at the runtime level covers every plugin type.
        //
        // Per-plugin-type coverage: this test runs at the shared
        // `create_host_state` + `set_epoch_deadline` layer, so its enforcement
        // guarantee applies to every plugin type (Processor, Bean,
        // AuthorizationPolicy, SecurityPolicy) — they all call `create_host_state`
        // and `store.set_epoch_deadline(...)`.
        let wat = r#"
        (module
          (func (export "loop_forever")
            loop
              br 0
            end
          )
        )
        "#;

        let mut config = wasmtime::Config::new();
        config.epoch_interruption(true);
        let engine = Engine::new(&config).unwrap();
        let module = wasmtime::Module::new(&engine, wat).expect("compile wat");

        let registry = Arc::new(std::sync::Mutex::new(Registry::new()));
        let host_state = WasmRuntime::create_host_state(
            registry,
            HashMap::new(),
            crate::state_store::StateStore::new(),
            test_tokio_handle(),
            0, // no memory cap — this test is about timeout, not memory
        );
        let mut store = Store::new(&engine, host_state);
        // Very short deadline: 1 epoch tick. With a 10ms tick interval, this
        // means the call must be interrupted within ~20ms (one tick + deadline).
        store.set_epoch_deadline(1);

        // Spawn the epoch ticker on a dedicated OS thread. This mirrors the
        // production EpochTicker::start wiring (also a dedicated OS thread,
        // see epoch.rs) — a tokio::spawn ticker would be queued behind
        // call_async on a single-worker runtime and never get polled, so the
        // epoch deadline would never fire. A std::thread is scheduled by the
        // kernel and increments the epoch regardless of tokio's cooperation.
        // The shutdown flag lets us stop the thread as soon as the assertion
        // succeeds, instead of letting it run for the full ~2s budget.
        use std::sync::atomic::{AtomicBool, Ordering};
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown_clone = shutdown.clone();
        let engine_clone = engine.clone();
        let ticker = std::thread::spawn(move || {
            while !shutdown_clone.load(Ordering::SeqCst) {
                std::thread::sleep(std::time::Duration::from_millis(10));
                engine_clone.increment_epoch();
            }
        });

        let instance = wasmtime::Instance::new_async(&mut store, &module, &[])
            .await
            .expect("instantiate");
        let func = instance
            .get_typed_func::<(), ()>(&mut store, "loop_forever")
            .expect("get loop_forever export");

        let start = std::time::Instant::now();
        let result = func.call_async(&mut store, ()).await;
        let elapsed = start.elapsed();

        // Stop the ticker thread before asserting — keeps the test tidy and
        // prevents the thread from outliving the test by ~2 seconds.
        shutdown.store(true, Ordering::SeqCst);
        ticker.join().expect("ticker thread to exit cleanly");

        assert!(
            result.is_err(),
            "infinite loop must be killed by epoch interruption"
        );
        // Loose upper bound: must interrupt within 2 seconds even on slow CI.
        // A typical run is ~20ms.
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "timeout must trigger quickly, took {:?}",
            elapsed
        );
    }
}