Adding a max runtime timeout to Deno JS execution

As the title states, I would like to be able to add a timeout to any JS code that I am executing in my deno_core JsRuntime in rust. I haven't been able to find any way to get this to work as all solutions seem to require that Deno yields the async runtime which it doesn't ever seem to do until it finishes. Any advice you could give or places you could point to would be extremely helpful, thanks!
Deno AI Helper
Deno AI Helper17d ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on your message, it seems like you're trying to implement a timeout for JavaScript code execution within the deno_core JsRuntime in Rust. While I can't provide a solution based on the official documentation, I can suggest a general approach that might be applicable to your situation. In Rust, you could potentially use the tokio::time::timeout function to achieve a maximum runtime for an asynchronous task. Here's a very basic example of how you might use it:
use tokio::time::{timeout, Duration};

async fn run_js_code(js_runtime: &mut JsRuntime) {
// Your code to run JS here
}

#[tokio::main]
async fn main() {
let mut js_runtime = JsRuntime::new(RuntimeOptions::default());

let duration = Duration::from_secs(5); // Set your timeout duration here
let result = timeout(duration, run_js_code(&mut js_runtime)).await;

match result {
Ok(_) => println!("JS code executed within the time limit"),
Err(_) => println!("JS code execution timed out"),
}
}
use tokio::time::{timeout, Duration};

async fn run_js_code(js_runtime: &mut JsRuntime) {
// Your code to run JS here
}

#[tokio::main]
async fn main() {
let mut js_runtime = JsRuntime::new(RuntimeOptions::default());

let duration = Duration::from_secs(5); // Set your timeout duration here
let result = timeout(duration, run_js_code(&mut js_runtime)).await;

match result {
Ok(_) => println!("JS code executed within the time limit"),
Err(_) => println!("JS code execution timed out"),
}
}
Please note that this advice is not based on the Deno documentation, and you should double-check the accuracy of this advice. The actual implementation details would depend on how you've set up your JsRuntime and the specifics of your application. If you're not already using tokio or another async runtime, you would need to integrate one to use this approach. For a more tailored solution, you might want to explore the deno_core source code or reach out to the community for patterns they've used in similar situations.