Skip to content

Commit 5d6a90a

Browse files
committed
Set timeout limits to flow scripts
Signed-off-by: Didier Wenzek <didier.wenzek@free.fr>
1 parent ff8359b commit 5d6a90a

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

crates/extensions/tedge_gen_mapper/src/js_runtime.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rquickjs::Ctx;
88
use rquickjs::Module;
99
use std::collections::HashMap;
1010
use std::path::Path;
11+
use std::sync::atomic::AtomicUsize;
1112
use std::time::Duration;
1213
use tokio::sync::mpsc;
1314
use tokio::sync::oneshot;
@@ -19,11 +20,19 @@ pub struct JsRuntime {
1920
execution_timeout: Duration,
2021
}
2122

23+
static TIME_CREDITS: AtomicUsize = AtomicUsize::new(1000);
24+
2225
impl JsRuntime {
2326
pub async fn try_new() -> Result<Self, LoadError> {
2427
let runtime = rquickjs::AsyncRuntime::new()?;
2528
runtime.set_memory_limit(16 * 1024 * 1024).await;
2629
runtime.set_max_stack_size(256 * 1024).await;
30+
runtime
31+
.set_interrupt_handler(Some(Box::new(|| {
32+
let credits = TIME_CREDITS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
33+
credits == 0
34+
})))
35+
.await;
2736
let context = rquickjs::AsyncContext::full(&runtime).await?;
2837
let worker = JsWorker::spawn(context).await;
2938
let execution_timeout = Duration::from_secs(5);
@@ -65,6 +74,7 @@ impl JsRuntime {
6574
let (sender, receiver) = oneshot::channel();
6675
let source = source.into();
6776
let imports = vec!["onMessage", "onConfigUpdate", "onInterval"];
77+
TIME_CREDITS.store(100000, std::sync::atomic::Ordering::Relaxed);
6878
self.send(
6979
receiver,
7080
JsRequest::LoadModule {
@@ -84,6 +94,7 @@ impl JsRuntime {
8494
args: Vec<JsonValue>,
8595
) -> Result<JsonValue, LoadError> {
8696
let (sender, receiver) = oneshot::channel();
97+
TIME_CREDITS.store(1000, std::sync::atomic::Ordering::Relaxed);
8798
self.send(
8899
receiver,
89100
JsRequest::CallFunction {

crates/extensions/tedge_gen_mapper/src/js_script.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,6 @@ export function onMessage(message) {
471471
}
472472

473473
#[tokio::test]
474-
#[ignore = "FIXME: scripts must be cancelled if running too long"]
475474
async fn while_loop() {
476475
let js = r#"export function onMessage(msg) { while(true); };"#;
477476
let (runtime, script) = runtime_with(js).await;
@@ -482,9 +481,7 @@ export function onMessage(message) {
482481
.await
483482
.unwrap_err();
484483
eprintln!("{:?}", error);
485-
assert!(error
486-
.to_string()
487-
.contains("Maximum processing time exceeded"));
484+
assert!(error.to_string().contains("interrupted"));
488485
}
489486

490487
#[tokio::test]

0 commit comments

Comments
 (0)