The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! `__native.net`: fetch, WebSocket, clipboard and audio for `runtime/net.ts`.
//!
//! Network I/O runs on worker threads (one per request, one per socket) and never touches
//! JavaScript; results are posted to the main thread and delivered through one page-installed
//! handler, `handler(kind, id, ...)`, unless the page went away meanwhile. Bodies and binary
//! messages cross as ArrayBuffers that adopt the Rust allocation (no copy, no per-byte JS work).
mod audio;
mod clipboard;
mod conn;
mod decode;
mod http;
mod netwatch;
mod proxy;
mod ws;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::{Arc, Mutex};
use jsc::{Ctx, Persistent, TypedArrayType, Value};
pub use http::get as http_get;
// Kinds of native → page events (see `runtime/net.ts`).
const FETCH_HEAD: f64 = 1.0;
const FETCH_BODY: f64 = 2.0;
const FETCH_ERROR: f64 = 3.0;
const WS_OPEN: f64 = 10.0;
const WS_TEXT: f64 = 11.0;
const WS_BINARY: f64 = 12.0;
const WS_CLOSE: f64 = 13.0;
const AUDIO_ENDED: f64 = 20.0;
thread_local! {
static HANDLER: RefCell<Option<Persistent>> = const { RefCell::new(None) };
static FETCHES: RefCell<HashMap<u32, Arc<conn::Cancel>>> = RefCell::new(HashMap::new());
static SOCKETS: RefCell<HashMap<u32, Arc<ws::Shared>>> = RefCell::new(HashMap::new());
}
static USER_AGENT: Mutex<String> = Mutex::new(String::new());
/// The page's `navigator.userAgent` (also used for proxy tunnels and `http_get`).
pub fn user_agent() -> String {
let ua = USER_AGENT.lock().unwrap();
if ua.is_empty() {
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) ThreeRT/0.1 Safari/605.1.15".into()
} else {
ua.clone()
}
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn http_clear_pool() {
http::clear_pool();
}
/// Ask every open socket to check that its peer is still there (network change, wake).
pub(crate) fn probe_sockets(why: &str) {
let n = SOCKETS.with(|s| {
let s = s.borrow();
for sh in s.values() {
sh.push(ws::Cmd::Probe);
}
s.len()
});
if n > 0 {
eprintln!("[net] {why}: probing {n} WebSocket(s)");
}
}
fn dispatch(c: Ctx, args: &[Value]) {
let Some(h) = HANDLER.with(|h| h.borrow().as_ref().map(|p| p.get())) else { return };
if let Err(e) = c.call(h, None, args) {
rt::report("net event", &e);
}
}
/// Run `f` on the main thread with the page context, unless the page changed since `generation`.
fn post_page(generation: u64, f: impl FnOnce(Ctx) + Send + 'static) {
rt::post(move || {
if rt::page_gen() == generation {
if let Some(c) = rt::ctx() {
f(c);
}
}
});
}
unsafe extern "C" fn free_bytes(bytes: *mut c_void, len: *mut c_void) {
unsafe { drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(bytes.cast::<u8>(), len as usize))) }
}
/// An ArrayBuffer that adopts `data` (freed by JavaScriptCore's GC).
fn array_buffer(c: Ctx, data: Vec<u8>) -> Value {
if data.is_empty() {
return c.typed_array(TypedArrayType::Uint8, 0, &[]).get(c, "buffer");
}
let b = data.into_boxed_slice();
let len = b.len();
let p = Box::into_raw(b).cast::<u8>();
let o = unsafe { jsc::JSObjectMakeArrayBufferWithBytesNoCopy(c.0, p.cast(), len, Some(free_bytes), len as *mut c_void, std::ptr::null_mut()) };
if o.is_null() {
unsafe { free_bytes(p.cast(), len as *mut c_void) };
return c.undefined();
}
Value(o)
}
/// A JS string as UTF-8 (lone surrogates become U+FFFD, like a USVString).
fn utf8(c: Ctx, v: Value) -> String {
String::from_utf16_lossy(v.to_js_string(c).utf16())
}
/// Body bytes from a string (UTF-8) or a buffer source.
fn body_bytes(c: Ctx, v: Value) -> Option<Vec<u8>> {
if v.is_nullish(c) {
return None;
}
if let Some(b) = v.bytes(c) {
return Some(b.to_vec());
}
Some(utf8(c, v).into_bytes())
}
fn arg(a: &[Value], i: usize, c: Ctx) -> Value {
a.get(i).copied().unwrap_or_else(|| c.undefined())
}
fn string_list(c: Ctx, v: Value) -> Vec<String> {
if !v.is_array(c) {
return Vec::new();
}
(0..v.len(c)).map(|i| v.at(c, i).to_string(c)).collect()
}
// ---------------------------------------------------------------- fetch
fn start_fetch(c: Ctx, a: &[Value]) -> jsc::NativeResult {
let id = arg(a, 0, c).to_u32(c);
let method = arg(a, 1, c).to_string(c);
let url = arg(a, 2, c).to_string(c);
let flat = string_list(c, arg(a, 3, c));
let headers: Vec<(String, String)> = flat.chunks(2).filter(|p| p.len() == 2).map(|p| (p[0].clone(), p[1].clone())).collect();
let body = body_bytes(c, arg(a, 4, c));
let redirect = match arg(a, 5, c).to_u32(c) {
1 => http::RedirectMode::Error,
2 => http::RedirectMode::Manual,
_ => http::RedirectMode::Follow,
};
let req = http::Request { method, url, headers, body, redirect };
let generation = rt::page_gen();
let cancel = Arc::new(conn::Cancel::default());
FETCHES.with(|f| f.borrow_mut().insert(id, cancel.clone()));
let spawned = std::thread::Builder::new().name("net-fetch".into()).stack_size(512 * 1024).spawn(move || {
let result = http::fetch(req, &cancel, |head| {
post_page(generation, move |c| {
if !FETCHES.with(|f| f.borrow().contains_key(&id)) {
return;
}
let mut hv = Vec::with_capacity(head.headers.len() * 2);
for (k, v) in &head.headers {
hv.push(c.str(k));
hv.push(c.str(v));
}
let args = [
c.num(FETCH_HEAD),
c.num(id as f64),
c.num(head.status as f64),
c.str(&head.status_text),
c.array(&hv),
c.str(&head.url),
c.bool(head.redirected),
c.bool(head.opaque_redirect),
];
dispatch(c, &args);
});
});
post_page(generation, move |c| {
if FETCHES.with(|f| f.borrow_mut().remove(&id)).is_none() {
return;
}
match result {
Ok(body) => {
let buf = array_buffer(c, body);
dispatch(c, &[c.num(FETCH_BODY), c.num(id as f64), buf]);
}
Err(e) => dispatch(c, &[c.num(FETCH_ERROR), c.num(id as f64), c.str(&e.to_string())]),
}
});
});
if spawned.is_err() {
FETCHES.with(|f| f.borrow_mut().remove(&id));
return Err("could not start a network thread".into());
}
Ok(c.undefined())
}
// ---------------------------------------------------------------- WebSocket
fn deliver_ws(id: u32, generation: u64) {
if rt::page_gen() != generation {
return;
}
let Some(c) = rt::ctx() else { return };
let Some(sh) = SOCKETS.with(|s| s.borrow().get(&id).cloned()) else { return };
for ev in sh.take_events() {
let idv = c.num(id as f64);
match ev {
ws::Event::Open { protocol, extensions } => dispatch(c, &[c.num(WS_OPEN), idv, c.str(&protocol), c.str(&extensions)]),
ws::Event::Text(s) => dispatch(c, &[c.num(WS_TEXT), idv, c.str(&s)]),
ws::Event::Binary(b) => {
let buf = array_buffer(c, b);
dispatch(c, &[c.num(WS_BINARY), idv, buf]);
}
ws::Event::Close { code, reason, clean, error } => {
SOCKETS.with(|s| s.borrow_mut().remove(&id));
dispatch(c, &[c.num(WS_CLOSE), idv, c.num(code as f64), c.str(&reason), c.bool(clean), c.bool(error)]);
return;
}
}
}
}
fn ws_open(c: Ctx, a: &[Value]) -> jsc::NativeResult {
let id = arg(a, 0, c).to_u32(c);
let params = ws::Params {
url: arg(a, 1, c).to_string(c),
protocols: string_list(c, arg(a, 2, c)),
origin: arg(a, 3, c).to_string(c),
user_agent: user_agent(),
accept_language: arg(a, 4, c).to_string(c),
};
netwatch::install();
let generation = rt::page_gen();
let shared = ws::open(params, move || rt::post(move || deliver_ws(id, generation))).map_err(|e| e.to_string())?;
SOCKETS.with(|s| s.borrow_mut().insert(id, shared));
Ok(c.undefined())
}
fn socket(id: u32) -> Option<Arc<ws::Shared>> {
SOCKETS.with(|s| s.borrow().get(&id).cloned())
}
// ---------------------------------------------------------------- audio
fn audio_events(c: Ctx, v: Value) -> Vec<audio::Ev> {
let Some(b) = (if v.typed_kind(c) == TypedArrayType::Float64 { v.bytes(c) } else { None }) else { return Vec::new() };
let nums: Vec<f64> = b.chunks_exact(8).map(|x| f64::from_ne_bytes(x.try_into().unwrap())).collect();
nums.chunks_exact(5).filter_map(audio::Ev::from_flat).collect()
}
fn deliver_ended() {
let ids = audio::take_ended();
let Some(c) = rt::ctx() else { return };
for id in ids {
dispatch(c, &[c.num(AUDIO_ENDED), c.num(id as f64)]);
}
}
// ---------------------------------------------------------------- install
fn reset() {
HANDLER.with(|h| h.borrow_mut().take());
for (_, cancel) in FETCHES.with(|f| std::mem::take(&mut *f.borrow_mut())) {
cancel.cancel();
}
for (_, s) in SOCKETS.with(|s| std::mem::take(&mut *s.borrow_mut())) {
s.teardown();
}
audio::reset();
}
/// Define this module's native functions on `__native.net`.
pub fn install(c: Ctx, native: Value) {
rt::on_reset(reset);
audio::set_ended_notify(|| rt::post(deliver_ended));
let net = c.object();
native.set(c, "net", net);
let def = |name: &str, f: Value| net.set(c, name, f);
def("setHandler", c.function(|c, _, a| {
let f = arg(a, 0, c);
if !f.is_function(c) {
return Err("setHandler: not a function".into());
}
HANDLER.with(|h| *h.borrow_mut() = Some(Persistent::new(c, f)));
let ua = arg(a, 1, c);
if !ua.is_nullish(c) {
*USER_AGENT.lock().unwrap() = ua.to_string(c);
}
Ok(c.undefined())
}));
// fetch(id, method, url, [name, value, …], body, redirect: 0 follow | 1 error | 2 manual)
def("fetch", c.function(|c, _, a| start_fetch(c, a)));
def("fetchAbort", c.function(|c, _, a| {
let id = arg(a, 0, c).to_u32(c);
if let Some(cancel) = FETCHES.with(|f| f.borrow_mut().remove(&id)) {
cancel.cancel();
}
Ok(c.undefined())
}));
// wsOpen(id, url, protocols[], origin, acceptLanguage)
def("wsOpen", c.function(|c, _, a| ws_open(c, a)));
def("wsSend", c.function(|c, _, a| {
let id = arg(a, 0, c).to_u32(c);
let data = arg(a, 1, c);
let cmd = match data.bytes(c) {
Some(b) => ws::Cmd::Binary(b.to_vec()),
None => ws::Cmd::Text(utf8(c, data)),
};
if let Some(s) = socket(id) {
s.push(cmd);
}
Ok(c.undefined())
}));
def("wsClose", c.function(|c, _, a| {
let id = arg(a, 0, c).to_u32(c);
let code = arg(a, 1, c).to_i32(c);
let frame = (code > 0).then(|| (code as u16, arg(a, 2, c).to_string(c)));
if let Some(s) = socket(id) {
s.push(ws::Cmd::Close(frame));
}
Ok(c.undefined())
}));
// Check every open socket's peer now (network change and wake do this natively; the app or a
// test may ask too). A peer that does not answer within 5 s is closed with 1006.
def("probeSockets", c.function(|c, _, _| {
probe_sockets("page request");
Ok(c.undefined())
}));
def("wsBuffered", c.function(|c, _, a| {
let id = arg(a, 0, c).to_u32(c);
let n = socket(id).map_or(0, |s| s.buffered.load(std::sync::atomic::Ordering::Relaxed));
Ok(c.num(n as f64))
}));
// Text <-> UTF-8 without per-byte JavaScript.
def("utf8Decode", c.function(|c, _, a| {
let Some(b) = arg(a, 0, c).bytes(c) else { return Ok(c.str("")) };
let b = b.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(b);
let s = String::from_utf8_lossy(b).into_owned();
Ok(c.str(&s))
}));
def("utf8Encode", c.function(|c, _, a| {
let s = utf8(c, arg(a, 0, c));
Ok(c.typed_array(TypedArrayType::Uint8, s.len(), s.as_bytes()))
}));
def("clipboardWrite", c.function(|c, _, a| {
let s = utf8(c, arg(a, 0, c));
Ok(c.bool(clipboard::write(&s)))
}));
def("clipboardRead", c.function(|c, _, _| Ok(c.str(&clipboard::read()))));
// audio
def("audioRate", c.function(|c, _, _| Ok(c.num(audio::sample_rate()))));
def("audioCreate", c.function(|c, _, _| Ok(c.num(audio::create_context() as f64))));
def("audioTime", c.function(|c, _, a| Ok(c.num(audio::context_time(arg(a, 0, c).to_u32(c))))));
def("audioSuspend", c.function(|c, _, a| {
audio::suspend(arg(a, 0, c).to_u32(c));
Ok(c.undefined())
}));
def("audioResume", c.function(|c, _, a| {
audio::resume(arg(a, 0, c).to_u32(c));
Ok(c.undefined())
}));
def("audioClose", c.function(|c, _, a| {
audio::close_context(arg(a, 0, c).to_u32(c));
Ok(c.undefined())
}));
// audioNode(ctx, kind: 1 gain | 2 oscillator) -> id
def("audioNode", c.function(|c, _, a| {
let kind = arg(a, 1, c).to_u32(c).clamp(1, 2) as u8;
Ok(c.num(audio::create_node(arg(a, 0, c).to_u32(c), kind) as f64))
}));
// audioConnect(from, to, paramIndex | -1)
def("audioConnect", c.function(|c, _, a| {
audio::connect(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c), arg(a, 2, c).to_i32(c));
Ok(c.undefined())
}));
// audioDisconnect(from, to | 0 for all, paramIndex | -1)
def("audioDisconnect", c.function(|c, _, a| {
audio::disconnect(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c), arg(a, 2, c).to_i32(c));
Ok(c.undefined())
}));
// audioParam(node, index, intrinsic, Float64Array [type, time, value, tau, scheduledAt]*)
def("audioParam", c.function(|c, _, a| {
let evs = audio_events(c, arg(a, 3, c));
audio::set_param(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c) as usize, arg(a, 2, c).to_num(c) as f32, evs);
Ok(c.undefined())
}));
def("audioParamValue", c.function(|c, _, a| {
let evs = audio_events(c, arg(a, 0, c));
Ok(c.num(audio::param_value(&evs, arg(a, 1, c).to_num(c) as f32, arg(a, 2, c).to_num(c)) as f64))
}));
def("audioWave", c.function(|c, _, a| {
let w = match arg(a, 1, c).to_u32(c) {
1 => audio::Wave::Square,
2 => audio::Wave::Sawtooth,
3 => audio::Wave::Triangle,
_ => audio::Wave::Sine,
};
audio::set_wave(arg(a, 0, c).to_u32(c), w);
Ok(c.undefined())
}));
def("audioStart", c.function(|c, _, a| {
audio::start(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_num(c));
Ok(c.undefined())
}));
def("audioStop", c.function(|c, _, a| {
audio::stop(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_num(c));
Ok(c.undefined())
}));
def("audioWantEnded", c.function(|c, _, a| {
audio::want_ended(arg(a, 0, c).to_u32(c));
Ok(c.undefined())
}));
def("audioRelease", c.function(|c, _, a| {
audio::release(arg(a, 0, c).to_u32(c));
Ok(c.undefined())
}));
}