Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error if there are pending items on the event queue #277

Merged
merged 7 commits into from
Mar 16, 2023
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
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ test-core:
test-cli: core
cargo test --package=javy --release --features=$(CLI_FEATURES) -- --nocapture

test-wpt: cli
# WPT requires a Javy build with the experimental_event_loop feature to pass
test-wpt: export CORE_FEATURES ?= experimental_event_loop
test-wpt:
# Can't use a prerequisite here b/c a prequisite will not cause a rebuild of the CLI
$(MAKE) cli
npm install --prefix wpt
npm test --prefix wpt

Expand Down
13 changes: 13 additions & 0 deletions crates/cli/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ fn test_promises() {
assert_eq!("\"foo\"\"bar\"".as_bytes(), output);
}

#[cfg(not(feature = "experimental_event_loop"))]
#[test]
fn test_promises() {
use crate::runner::RunnerError;

let mut runner = Runner::new("promise.js");
let res = runner.exec(&[]);
let err = res.err().unwrap().downcast::<RunnerError>().unwrap();
assert!(str::from_utf8(&err.stderr)
.unwrap()
.contains("Adding tasks to the event queue is not supported"));
}

#[test]
fn test_producers_section_present() {
let runner = Runner::new("readme.js");
Expand Down
36 changes: 33 additions & 3 deletions crates/cli/tests/runner/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use anyhow::Result;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::io::{self, Cursor, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{cmp, fs};
use wasi_common::pipe::{ReadPipe, WritePipe};
use wasmtime::{Config, Engine, Linker, Module, OptLevel, Store};
use wasmtime::{Config, Engine, Linker, Module, OptLevel, Store, Trap};
use wasmtime_wasi::sync::WasiCtxBuilder;
use wasmtime_wasi::WasiCtx;

Expand All @@ -14,6 +16,25 @@ pub struct Runner {
log_capacity: usize,
}

#[derive(Debug)]
pub struct RunnerError {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub trap: Trap,
}

impl Error for RunnerError {}

impl Display for RunnerError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"trap: {:?}, stdout: {:?}, stderr: {:?}",
self.trap, self.stdout, self.stderr
)
}
}

struct StoreContext {
wasi_output: WritePipe<Cursor<Vec<u8>>>,
wasi: WasiCtx,
Expand Down Expand Up @@ -98,7 +119,7 @@ impl Runner {
let instance = self.linker.instantiate(&mut store, &module)?;
let run = instance.get_typed_func::<(), (), _>(&mut store, "_start")?;

run.call(&mut store, ())?;
let res = run.call(&mut store, ());
let store_context = store.into_data();
drop(store_context.wasi);
let logs = store_context
Expand All @@ -111,7 +132,16 @@ impl Runner {
.try_into_inner()
.expect("Output stream reference still exists")
.into_inner();
Ok((output, logs))

match res {
Ok(_) => Ok((output, logs)),
Err(trap) => Err(RunnerError {
stdout: output,
stderr: logs,
trap,
}
.into()),
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion crates/core/src/execution.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use anyhow::Result;
use anyhow::{bail, Result};
use quickjs_wasm_rs::Context;

pub fn run_bytecode(context: &Context, bytecode: &[u8]) -> Result<()> {
context.eval_binary(bytecode)?;
if cfg!(feature = "experimental_event_loop") {
context.execute_pending()?;
} else if context.is_pending() {
bail!("Adding tasks to the event queue is not supported");
}
Ok(())
}
32 changes: 31 additions & 1 deletion crates/quickjs-wasm-rs/src/js_binding/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use anyhow::Result;
use once_cell::sync::Lazy;
use quickjs_wasm_sys::{
ext_js_null, ext_js_undefined, JSCFunctionData, JSClassDef, JSClassID, JSContext, JSValue,
JS_Eval, JS_ExecutePendingJob, JS_GetGlobalObject, JS_GetRuntime, JS_NewArray,
JS_Eval, JS_ExecutePendingJob, JS_GetGlobalObject, JS_GetRuntime, JS_IsJobPending, JS_NewArray,
JS_NewArrayBufferCopy, JS_NewBigInt64, JS_NewBool_Ext, JS_NewCFunctionData, JS_NewClass,
JS_NewClassID, JS_NewContext, JS_NewFloat64_Ext, JS_NewInt32_Ext, JS_NewInt64_Ext,
JS_NewObject, JS_NewObjectClass, JS_NewRuntime, JS_NewStringLen, JS_NewUint32_Ext,
Expand Down Expand Up @@ -114,6 +114,13 @@ impl Context {
self.value_from_bytecode(bytecode)?.eval_function()
}

pub fn is_pending(&self) -> bool {
unsafe {
let runtime = JS_GetRuntime(self.inner);
JS_IsJobPending(runtime) == 1
}
}

pub fn execute_pending(&self) -> Result<()> {
let runtime = unsafe { JS_GetRuntime(self.inner) };

Expand Down Expand Up @@ -641,4 +648,27 @@ mod tests {
);
Ok(())
}

#[test]
fn test_is_pending_returns_false_when_nothing_is_pending() -> Result<()> {
let ctx = Context::default();
ctx.eval_global("main", "const x = 42;")?;
assert!(!ctx.is_pending());
Ok(())
}

#[test]
fn test_is_pending_returns_true_when_pending() -> Result<()> {
let ctx = Context::default();
ctx.eval_global(
"main",
"
async function foo() {
const x = 42;
}
foo().then(() => {})",
)?;
assert!(ctx.is_pending());
Ok(())
}
}
6 changes: 3 additions & 3 deletions wpt/test_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export default [
// { // FIXME requires `encodeInto` support
// testFile: "upstream/encoding/encodeInto.any.js",
// },
{
testFile: "upstream/encoding/replacement-encodings.any.js",
},
// { // FIXME fails with `promise_test: Unhandled rejection with value: object "ReferenceError: 'XMLHttpRequest' is not defined`
// testFile: "upstream/encoding/replacement-encodings.any.js",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's unclear to me why this was needed to be commented out, could you clarify?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually doesn't need to be commented out any more since I disabled the error message with pending jobs. Technically the tests aren't completing properly but I can't figure out a way to have these tests error but have the suite setup to not cause a panic.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this does need to continue to be commented out or we get unhandled promise rejections due to Javy not implementing XMLHttpRequest when we run with the event loop enabled. I've updated the comment.

// },
{
testFile: "custom_tests/textdecoder-arguments.any.js",
},
Expand Down