Skip to content
Open
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
10 changes: 2 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -532,3 +532,6 @@ opt-level = 3
opt-level = 3
[profile.release.package.deno_npm_cache]
opt-level = 3

[patch.crates-io]
deno_core = { path = "../deno_core/core" }
79 changes: 3 additions & 76 deletions ext/fetch/26_fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
op_fetch,
op_fetch_promise_is_settled,
op_fetch_send,
op_wasm_streaming_feed,
op_wasm_streaming_set_url,
} from "ext:core/ops";
const {
ArrayPrototypePush,
Expand All @@ -32,8 +30,8 @@
SafePromisePrototypeFinally,
String,
StringPrototypeEndsWith,
StringPrototypeStartsWith,

Check failure on line 33 in ext/fetch/26_fetch.js

View workflow job for this annotation

GitHub Actions / lint debug linux-x86_64

`StringPrototypeStartsWith` is never used
StringPrototypeToLowerCase,

Check failure on line 34 in ext/fetch/26_fetch.js

View workflow job for this annotation

GitHub Actions / lint debug linux-x86_64

`StringPrototypeToLowerCase` is never used
TypeError,
TypedArrayPrototypeGetSymbolToStringTag,
} = primordials;
Expand Down Expand Up @@ -100,6 +98,8 @@
*/
function createResponseBodyStream(responseBodyRid, terminator) {
const readable = readableStreamForRid(responseBodyRid);
// internal, used by wasm streaming
readable.rid = responseBodyRid;
Copy link
Member

Choose a reason for hiding this comment

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

this already exists under Symbol(_resourceBacking)


function onAbort() {
errorReadableStream(readable, terminator.reason);
Expand Down Expand Up @@ -532,77 +532,4 @@
);
}

/**
* Handle the Response argument to the WebAssembly streaming APIs, after
* resolving if it was passed as a promise. This function should be registered
* through `Deno.core.setWasmStreamingCallback`.
*
* @param {any} source The source parameter that the WebAssembly streaming API
* was called with. If it was called with a Promise, `source` is the resolved
* value of that promise.
* @param {number} rid An rid that represents the wasm streaming resource.
*/
function handleWasmStreaming(source, rid) {
// This implements part of
// https://webassembly.github.io/spec/web-api/#compile-a-potential-webassembly-response
try {
const res = webidl.converters["Response"](
source,
"Failed to execute 'WebAssembly.compileStreaming'",
"Argument 1",
);

// 2.3.
// The spec is ambiguous here, see
// https://github.com/WebAssembly/spec/issues/1138. The WPT tests expect
// the raw value of the Content-Type attribute lowercased. We ignore this
// for file:// because file fetches don't have a Content-Type.
if (!StringPrototypeStartsWith(res.url, "file://")) {
const contentType = res.headers.get("Content-Type");
if (
typeof contentType !== "string" ||
StringPrototypeToLowerCase(contentType) !== "application/wasm"
) {
throw new TypeError("Invalid WebAssembly content type");
}
}

// 2.5.
if (!res.ok) {
throw new TypeError(
`Failed to receive WebAssembly content: HTTP status code ${res.status}`,
);
}

// Pass the resolved URL to v8.
op_wasm_streaming_set_url(rid, res.url);

if (res.body !== null) {
// 2.6.
// Rather than consuming the body as an ArrayBuffer, this passes each
// chunk to the feed as soon as it's available.
PromisePrototypeThen(
(async () => {
const reader = res.body.getReader();
while (true) {
const { value: chunk, done } = await reader.read();
if (done) break;
op_wasm_streaming_feed(rid, chunk);
}
})(),
// 2.7
() => core.close(rid),
// 2.8
(err) => core.abortWasmStreaming(rid, err),
);
} else {
// 2.7
core.close(rid);
}
} catch (err) {
// 2.8
core.abortWasmStreaming(rid, err);
}
}

export { fetch, handleWasmStreaming, mainFetch };
export { fetch, mainFetch };
3 changes: 0 additions & 3 deletions ext/fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ import * as response from "ext:deno_fetch/23_response.js";
import * as fetch from "ext:deno_fetch/26_fetch.js";
import * as eventSource from "ext:deno_fetch/27_eventsource.js";

// Set up the callback for Wasm streaming ops
Deno.core.setWasmStreamingCallback(fetch.handleWasmStreaming);

Object.defineProperty(globalThis, "fetch", {
value: fetch.fetch,
enumerable: true,
Expand Down
2 changes: 2 additions & 0 deletions ext/fetch/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod fs_fetch_handler;
mod proxy;
#[cfg(test)]
mod tests;
mod wasm_streaming;

use std::borrow::Cow;
use std::cell::RefCell;
Expand Down Expand Up @@ -94,6 +95,7 @@ use tower::Service;
use tower::ServiceExt;
use tower::retry;
use tower_http::decompression::Decompression;
pub use wasm_streaming::handle_wasm_streaming;

#[derive(Clone)]
pub struct Options {
Expand Down
189 changes: 189 additions & 0 deletions ext/fetch/wasm_streaming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

use std::cell::RefCell;
use std::rc::Rc;

use deno_core::OpState;
use deno_core::ResourceId;
use deno_core::v8;
use deno_error::JsErrorBox;

/// The Wasm streaming compilation pipeline.
pub fn handle_wasm_streaming<'a>(
state: Rc<RefCell<OpState>>,
scope: &mut v8::PinScope<'a, '_>,
value: v8::Local<'a, v8::Value>,
mut wasm_streaming: v8::WasmStreaming,
) {
let (url, rid) = match compile_response(scope, value) {
Ok(Some((url, rid))) => (url, rid),
Ok(None) => {
// 2.7
wasm_streaming.finish();
return;
}
Err(e) => {
// 2.8
let err = v8::String::new(scope, &e.to_string()).unwrap();
wasm_streaming.abort(Some(err.into()));
return;
}
};

wasm_streaming.set_url(&url);

deno_core::unsync::spawn(async move {
loop {
let resource = state.borrow().resource_table.get_any(rid);
let resource = match resource {
Ok(r) => r,
Err(_) => {
state.borrow().borrow::<deno_core::V8TaskSpawner>().spawn(
move |scope| {
wasm_streaming.abort(Some(
v8::String::new(scope, "Failed to get resource.")
.unwrap()
.into(),
))
},
);
return;
}
};

let view = deno_core::BufMutView::new(65536);
let (bytes, view) = match resource.read_byob(view).await {
Ok(bytes) => bytes,
Err(e) => {
state.borrow().borrow::<deno_core::V8TaskSpawner>().spawn(
move |scope| {
wasm_streaming.abort(Some(
v8::String::new(
scope,
&format!("Error reading wasm resource: {}", e),
)
.unwrap()
.into(),
))
},
);

return;
}
};
/* EOF */
if bytes == 0 {
break;
}

wasm_streaming.on_bytes_received(&view[..bytes]);
}

/* Spawn a task on JS loop to finish the streaming compilation */
state
.borrow()
.borrow::<deno_core::V8TaskSpawner>()
.spawn(move |_| wasm_streaming.finish());
});
}

// Partially implements https://webassembly.github.io/spec/web-api/#compile-a-potential-webassembly-response
pub fn compile_response<'a>(
scope: &mut v8::PinScope<'a, '_>,
value: v8::Local<'a, v8::Value>,
) -> Result<Option<(String, ResourceId)>, JsErrorBox> {
let object = value
.to_object(scope)
.ok_or_else(|| JsErrorBox::type_error("Response is not an object."))?;
let url = get_string(scope, object, "url")?;

// 2.3.
// The spec is ambiguous here, see
// https://github.com/WebAssembly/spec/issues/1138. The WPT tests expect
// the raw value of the Content-Type attribute lowercased. We ignore this
// for file:// because file fetches don't have a Content-Type.
if !url.starts_with("file://") {
let headers = get_value(scope, object, "headers")?;
let content_type = call_method(scope, headers, "get", "Content-Type")?;

if content_type.to_lowercase() != "application/wasm" {
return Err(JsErrorBox::type_error("Response is not a wasm file."));
}
}

// 2.5
let ok = get_value(scope, object, "ok")?;
if !ok.is_true() {
return Err(JsErrorBox::type_error("Response is not ok."));
}

let body = get_value(scope, object, "body")?;

if body.is_null() {
return Ok(None);
}
let body = body
.to_object(scope)
.ok_or_else(|| JsErrorBox::type_error("Failed to get body object."))?;
let rid = get_value(scope, body, "rid")?
.to_uint32(scope)
.ok_or_else(|| JsErrorBox::type_error("Failed to get rid."))?
.value() as ResourceId;

Ok(Some((url, rid)))
}

fn get_value<'a, 'b>(
scope: &'b mut v8::PinScope<'a, '_>,
obj: v8::Local<'a, v8::Object>,
key: &'static str,
) -> Result<v8::Local<'a, v8::Value>, JsErrorBox> {
let key = v8::String::new(scope, key)
.ok_or_else(|| JsErrorBox::type_error("Failed to create key."))?;
Ok(
obj
.get(scope, key.into())
.ok_or_else(|| JsErrorBox::type_error("Failed to get value."))?,
)
}

fn get_string(
scope: &mut v8::PinScope,
obj: v8::Local<v8::Object>,
key: &'static str,
) -> Result<String, JsErrorBox> {
let key = v8::String::new(scope, key)
.ok_or_else(|| JsErrorBox::type_error("Failed to create key."))?;
let value = obj
.get(scope, key.into())
.ok_or_else(|| JsErrorBox::type_error("Failed to get value."))?;

Ok(value.to_rust_string_lossy(scope))
}

fn call_method<'a>(
scope: &mut v8::PinScope<'a, '_>,
obj: v8::Local<'a, v8::Value>,
method: &'static str,
arg: &'static str,
) -> Result<String, JsErrorBox> {
let key = v8::String::new(scope, method)
.ok_or_else(|| JsErrorBox::type_error("Failed to create key."))?;
let function = obj
.to_object(scope)
.ok_or_else(|| JsErrorBox::type_error("Failed to create object."))?;
let function = function
.get(scope, key.into())
.ok_or_else(|| JsErrorBox::type_error("Failed to get value."))?;
let function: v8::Local<v8::Function> = function
.try_into()
.map_err(|_| JsErrorBox::type_error("Failed to get function."))?;
let arg = v8::String::new(scope, arg)
.ok_or_else(|| JsErrorBox::type_error("Failed to create arg."))?;
Ok(
function
.call(scope, obj, &[arg.into()])
.ok_or_else(|| JsErrorBox::type_error("Failed to call."))?
.to_rust_string_lossy(scope),
)
}
1 change: 1 addition & 0 deletions runtime/fmt_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ impl deno_core::error::ErrorFormat for AnsiColors {
}
LineNumber | ColumnNumber => colors::yellow(s).to_string().into(),
FunctionName | PromiseAll => colors::italic_bold(s).to_string().into(),
WorkingDirPath => colors::gray(s).to_string().into(),
}
}
}
Expand Down
1 change: 0 additions & 1 deletion runtime/js/99_main.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
} from "ext:deno_web/01_console.js";
import * as performance from "ext:deno_web/15_performance.js";
import * as url from "ext:deno_web/00_url.js";
import * as fetch from "ext:deno_fetch/26_fetch.js";

Check failure on line 70 in runtime/js/99_main.js

View workflow job for this annotation

GitHub Actions / lint debug linux-x86_64

`fetch` is never used
import * as messagePort from "ext:deno_web/13_message_port.js";
import {
denoNs,
Expand Down Expand Up @@ -397,7 +397,6 @@
tsVersion,
target,
) {
core.setWasmStreamingCallback(fetch.handleWasmStreaming);
core.setReportExceptionCallback(event.reportException);
op_set_format_exception_callback(formatException);
version.setVersions(
Expand Down
4 changes: 4 additions & 0 deletions runtime/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,10 @@ impl MainWorker {
let bootstrap_fn = v8::Local::new(scope, bootstrap_fn);
let undefined = v8::undefined(scope);
bootstrap_fn.call(scope, undefined.into(), &[args]);
deno_core::set_wasm_streaming_callback(
scope,
deno_fetch::handle_wasm_streaming,
);
if let Some(exception) = scope.exception() {
let error = JsError::from_v8_exception(scope, exception);
panic!("Bootstrap exception: {error}");
Expand Down
Loading