| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! WebSockets inside the isolate: the registry, the ops JS calls, and the |
| 4 | //! frames waiting to leave. |
| 5 | //! |
| 6 | //! A socket outlives the event that created it, so the registry is what |
| 7 | //! connects the two — JS holds an id, and this module knows what that id |
| 8 | //! is attached to. Frames emitted inside an output-gate region are held |
| 9 | //! until the gate opens, which is why emitting is not simply a send. |
| 10 | use super::*; |
| 11 | pub use crate::ws_registry::*; |
| 12 | |
| 13 | #[derive(Default)] |
| 14 | pub(super) struct WsCapture { |
| 15 | frames: WsBatch, |
| 16 | /// The handler whose outcome authorizes an incremental flush. This is |
| 17 | /// installed after the synchronous dispatch returns its promise; until |
| 18 | /// then no turn-end flush can run. |
| 19 | promise: Option<v8::Global<v8::Promise>>, |
| 20 | } |
| 21 | |
| 22 | fn prepare_worker_websocket_handoff(id: u64) { |
| 23 | let (inbound, receiver) = ws_pull_channel(); |
| 24 | ws_pull_register(id, receiver); |
| 25 | ws_register_outbound(id, "", None); |
| 26 | ws_track_request_socket(id); |
| 27 | let registry = ws_registry(); |
| 28 | let replaced = registry.lock().unwrap().worker_handoffs.insert(id, inbound); |
| 29 | drop(replaced); |
| 30 | } |
| 31 | |
| 32 | pub(super) fn transfer_worker_websocket_handoff(id: u64) -> Option<WorkerWebSocket> { |
| 33 | let inbound = ws_registry().lock().unwrap().worker_handoffs.remove(&id)?; |
| 34 | // The response now owns cleanup. Transfer the frame channel and request |
| 35 | // ownership together so request retirement cannot close a returned socket. |
| 36 | current_context() |
| 37 | .sockets |
| 38 | .lock() |
| 39 | .unwrap() |
| 40 | .retain(|opened| *opened != id); |
| 41 | Some(WorkerWebSocket { id, inbound }) |
| 42 | } |
| 43 | |
| 44 | /// Close every isolate-polled socket a finished request opened. |
| 45 | /// |
| 46 | /// The close frame is what actually ends the connection: the connector task |
| 47 | /// writes it to the wire and stops pumping, and only then does it drop the |
| 48 | /// `WsPull` sender that this socket's `__ws_next` is waiting on. Unregistering |
| 49 | /// first would strand the task instead — it detects a dead isolate by the |
| 50 | /// send failing, and nothing else tells it to go. |
| 51 | pub(super) fn ws_close_request_sockets(opened: Vec<u64>) { |
| 52 | for id in opened { |
| 53 | let registry = ws_registry(); |
| 54 | let handoff = registry.lock().unwrap().worker_handoffs.remove(&id); |
| 55 | drop(handoff); |
| 56 | // A socket whose remote already hung up has no output sender left, |
| 57 | // and that is the ordinary case rather than an error. `ws_emit` logs |
| 58 | // a dropped frame for an unknown id, so ask before sending. |
| 59 | let open = ws_registry().lock().unwrap().outputs.contains_key(&id); |
| 60 | if open { |
| 61 | // The event's own end, run by its turn: the owner is the context. |
| 62 | ws_emit( |
| 63 | ¤t_context(), |
| 64 | id, |
| 65 | WsOut::Close(1001, "request ended".into()), |
| 66 | ); |
| 67 | } |
| 68 | ws_pull_unregister(id); |
| 69 | ws_unregister(id); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Account a Worker socket to the request that opened it. |
| 74 | fn ws_track_request_socket(id: u64) { |
| 75 | current_context().sockets.lock().unwrap().push(id); |
| 76 | } |
| 77 | |
| 78 | pub(super) fn ws_capture_begin() { |
| 79 | current_context() |
| 80 | .ws_capture |
| 81 | .lock() |
| 82 | .unwrap() |
| 83 | .push(WsCapture::default()); |
| 84 | } |
| 85 | |
| 86 | pub(super) fn ws_capture_set_promise(context: &IoContext, promise: v8::Global<v8::Promise>) { |
| 87 | context |
| 88 | .ws_capture |
| 89 | .lock() |
| 90 | .unwrap() |
| 91 | .last_mut() |
| 92 | .expect("a WebSocket handler has an active capture") |
| 93 | .promise = Some(promise); |
| 94 | } |
| 95 | |
| 96 | pub(super) fn ws_capture_take() -> WsBatch { |
| 97 | current_context() |
| 98 | .ws_capture |
| 99 | .lock() |
| 100 | .unwrap() |
| 101 | .pop() |
| 102 | .unwrap_or_default() |
| 103 | .frames |
| 104 | } |
| 105 | |
| 106 | pub(super) fn ws_capture_discard(context: &IoContext) { |
| 107 | if let Some(capture) = context.ws_capture.lock().unwrap().pop() { |
| 108 | capture.frames.discard(); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Release what a running `webSocketMessage` handler has sent so far. |
| 113 | /// |
| 114 | /// Called at the end of every turn, so a handler that suspends delivers the |
| 115 | /// frames it has already sent instead of holding them until it returns. An |
| 116 | /// AI chat agent streams its answer through this path: it sends a chunk, it |
| 117 | /// awaits the next one, and a client that receives the whole answer in one |
| 118 | /// burst at the end has lost the streaming the application was written for |
| 119 | /// (denoland/celld#229). |
| 120 | /// |
| 121 | /// One ticket covers the turn rather than one for each frame, because a |
| 122 | /// broadcast sends the same chunk to every client in one turn and a ticket |
| 123 | /// for each of them would cost a core round trip for each of them. |
| 124 | /// |
| 125 | /// The capture stays in place, so the frames of a later turn are held and |
| 126 | /// released the same way. A handler that never suspends captures its frames |
| 127 | /// in one turn and answers in it, so `ws_capture_take` finds them first and |
| 128 | /// this releases nothing: that handler still leaves through the cell's |
| 129 | /// barrier queue, exactly as before. |
| 130 | fn ws_capture_flush(tc: &mut v8::PinScope, context: &IoContext) { |
| 131 | let frames = { |
| 132 | let mut capture = context.ws_capture.lock().unwrap(); |
| 133 | let Some(pending) = capture.last() else { |
| 134 | return; |
| 135 | }; |
| 136 | let Some(promise) = pending.promise.as_ref() else { |
| 137 | return; |
| 138 | }; |
| 139 | match v8::Local::new(tc, promise).state() { |
| 140 | v8::PromiseState::Pending => {} |
| 141 | // The event's own settlement takes a fulfilled capture with its |
| 142 | // dispatch. Flushing it here would split the established batch. |
| 143 | v8::PromiseState::Fulfilled => return, |
| 144 | // A foreign handler can reject wholly inside this turn's |
| 145 | // checkpoint, before its own driver gets a turn in which to run |
| 146 | // `settle`. Drop its frames now instead of publishing output |
| 147 | // from a failed dispatch. |
| 148 | v8::PromiseState::Rejected => { |
| 149 | std::mem::take(&mut capture.last_mut().unwrap().frames).discard(); |
| 150 | return; |
| 151 | } |
| 152 | } |
| 153 | let pending = capture.last_mut().unwrap(); |
| 154 | if pending.frames.is_empty() { |
| 155 | return; |
| 156 | } |
| 157 | std::mem::take(&mut pending.frames) |
| 158 | }; |
| 159 | // Every captured frame belongs to a hibernatable socket, because that is |
| 160 | // what `ws_emit` captures, so one channel names the whole batch. |
| 161 | let gate = egress_gate_request(context, celld_logic::Channel::WsHibernatable); |
| 162 | // On the HOST runtime, for the reason `ws_emit` spawns there: this flush |
| 163 | // must outlive the turn that produced the frames, and the ticket it waits |
| 164 | // for resolves with no isolate involvement. |
| 165 | asyncrt::op_handle().spawn(async move { |
| 166 | let held = await_egress_gate(gate).await; |
| 167 | frames.release(held); |
| 168 | }); |
| 169 | } |
| 170 | |
| 171 | /// Flush every capture that received a frame during this isolate turn. |
| 172 | /// |
| 173 | /// Weak references make this list bookkeeping rather than event ownership. |
| 174 | /// A context that retires before the turn ends therefore disappears instead |
| 175 | /// of being kept alive only to flush output that its dispatch cannot return. |
| 176 | pub(super) fn ws_capture_flush_touched(tc: &mut v8::PinScope, runtime_state: &ActorRuntimeState) { |
| 177 | let touched = std::mem::take(&mut *runtime_state.ws_capture_touched.lock().unwrap()); |
| 178 | for context in touched.into_iter().filter_map(|context| context.upgrade()) { |
| 179 | ws_capture_flush(tc, &context); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// Send or hold one frame. `context` is the event the sending JavaScript |
| 184 | /// belongs to: the continuation's own for a V8 entry point, so a reaction of |
| 185 | /// cell A that runs inside another event's checkpoint is captured by and |
| 186 | /// gated against A, not the checkpoint's owner. |
| 187 | fn ws_emit(context: &Arc<IoContext>, id: u64, out: WsOut) { |
| 188 | let mut capture = context.ws_capture.lock().unwrap(); |
| 189 | if !capture.is_empty() && ws_channel(id) == celld_logic::Channel::WsHibernatable { |
| 190 | capture.last_mut().unwrap().frames.capture(id, out); |
| 191 | let runtime_state = context |
| 192 | .continuation |
| 193 | .as_ref() |
| 194 | .and_then(|(_, runtime_state)| runtime_state.upgrade()) |
| 195 | .expect("a WebSocket capture belongs to a live tracked context"); |
| 196 | let mut touched = runtime_state.ws_capture_touched.lock().unwrap(); |
| 197 | if !touched.iter().any(|candidate| { |
| 198 | candidate |
| 199 | .upgrade() |
| 200 | .is_some_and(|candidate| Arc::ptr_eq(&candidate, context)) |
| 201 | }) { |
| 202 | touched.push(Arc::downgrade(context)); |
| 203 | } |
| 204 | return; |
| 205 | } |
| 206 | drop(capture); |
| 207 | // A socket the isolate opened itself, which the capture above deliberately |
| 208 | // will not hold: releasing captured frames waits for the handler to |
| 209 | // return, and this handler may be awaiting a reply to the very frame being |
| 210 | // held. Waiting on the DURABILITY ticket instead has no such cycle -- it |
| 211 | // is resolved by the replicator, which does not need this event loop -- so |
| 212 | // the frame can be held without deadlocking the script that sent it. |
| 213 | let gate = egress_gate_request(context, ws_channel(id)); |
| 214 | // Resolved here, on the thread the frame was sent from; the registry is |
| 215 | // moved into the flush below. The flush runs on a runtime that has no |
| 216 | // services of its own, so a lookup inside it would answer with whichever |
| 217 | // instance that runtime reaches — the socket's frames and the socket's |
| 218 | // registry could then come from two different instances. |
| 219 | let flush = ws_flush_state(); |
| 220 | let registry = ws_registry(); |
| 221 | // Gated for a read-only frame as well, and deliberately: the frame reveals |
| 222 | // what the cell holds, so it has to ask the core whether a barrier is open |
| 223 | // rather than assume its own event opened one. A cell with nothing |
| 224 | // outstanding answers at once and the queue flushes on the same tick. |
| 225 | let Some(flushing) = |
| 226 | flush.emit_or_defer(®istry, std::iter::once((id, out)), gate.is_gated()) |
| 227 | else { |
| 228 | return; |
| 229 | }; |
| 230 | // Detached onto the HOST runtime (`op_handle`) deliberately: this flush |
| 231 | // exists precisely to outlive the dispatch that produced the frames — a |
| 232 | // writing connect handler's ready frame, an alarm broadcast — and it |
| 233 | // awaits a durability ticket that resolves with no isolate involvement. |
| 234 | // Both region-owned homes silently kill it: `asyncrt::enqueue`'s future is |
| 235 | // aborted when the dispatch region closes, and the isolate thread's local |
| 236 | // request driver stops polling its operation future the moment the |
| 237 | // dispatch returns. Either way the frames never left the process. |
| 238 | asyncrt::op_handle().spawn(async move { |
| 239 | let held = await_egress_gate(gate).await; |
| 240 | flushing.release(®istry, held); |
| 241 | }); |
| 242 | } |
| 243 | |
| 244 | pub(super) fn op_ws_send( |
| 245 | scope: &mut v8::PinScope, |
| 246 | args: v8::FunctionCallbackArguments, |
| 247 | _rv: v8::ReturnValue<v8::Value>, |
| 248 | ) { |
| 249 | let id = args |
| 250 | .get(0) |
| 251 | .to_integer(scope) |
| 252 | .map(|n| n.value() as u64) |
| 253 | .unwrap_or(0); |
| 254 | let data = args.get(1).to_rust_string_lossy(scope); |
| 255 | ws_emit(&event_context(scope), id, WsOut::Text(data)); |
| 256 | } |
| 257 | pub(super) fn op_ws_send_binary( |
| 258 | scope: &mut v8::PinScope, |
| 259 | args: v8::FunctionCallbackArguments, |
| 260 | _rv: v8::ReturnValue<v8::Value>, |
| 261 | ) { |
| 262 | let id = args |
| 263 | .get(0) |
| 264 | .to_integer(scope) |
| 265 | .map(|n| n.value() as u64) |
| 266 | .unwrap_or(0); |
| 267 | let data = view_bytes(args.get(1)).unwrap_or_default(); |
| 268 | ws_emit(&event_context(scope), id, WsOut::Binary(data)); |
| 269 | } |
| 270 | pub(super) fn op_ws_close( |
| 271 | scope: &mut v8::PinScope, |
| 272 | args: v8::FunctionCallbackArguments, |
| 273 | _rv: v8::ReturnValue<v8::Value>, |
| 274 | ) { |
| 275 | let id = args |
| 276 | .get(0) |
| 277 | .to_integer(scope) |
| 278 | .map(|n| n.value() as u64) |
| 279 | .unwrap_or(0); |
| 280 | let code = args.get(1).uint32_value(scope).unwrap_or(1000) as u16; |
| 281 | let reason = args.get(2).to_rust_string_lossy(scope); |
| 282 | ws_emit(&event_context(scope), id, WsOut::Close(code, reason)); |
| 283 | } |
| 284 | pub(super) fn op_ws_alloc( |
| 285 | scope: &mut v8::PinScope, |
| 286 | _args: v8::FunctionCallbackArguments, |
| 287 | mut rv: v8::ReturnValue<v8::Value>, |
| 288 | ) { |
| 289 | rv.set(v8::Number::new(scope, ws_next_id() as f64).into()); |
| 290 | } |
| 291 | |
| 292 | pub(super) fn op_ws_prepare_worker_handoff( |
| 293 | scope: &mut v8::PinScope, |
| 294 | args: v8::FunctionCallbackArguments, |
| 295 | _rv: v8::ReturnValue<v8::Value>, |
| 296 | ) { |
| 297 | let id = args |
| 298 | .get(0) |
| 299 | .to_integer(scope) |
| 300 | .map(|n| n.value() as u64) |
| 301 | .unwrap_or(0); |
| 302 | prepare_worker_websocket_handoff(id); |
| 303 | } |
| 304 | /// The facet record of an outbound socket that `cell` opens, when the running |
| 305 | /// event belongs to a Durable Object facet. |
| 306 | /// |
| 307 | /// A facet is not a cell. A socket that names the facet's scope as its cell |
| 308 | /// starts an activation of a class that no Worker exports, so the upgrade |
| 309 | /// fails with `RuntimeFailed`. The socket must route, register, and gate |
| 310 | /// through the facet's root instead. The record comes from the frame that |
| 311 | /// the host installed when the event started, not from `cell`, because the |
| 312 | /// scope crosses application JavaScript. |
| 313 | fn dialing_facet(scope: &mut v8::PinScope, cell: &str) -> Result<Option<FacetSocket>, String> { |
| 314 | if cell.is_empty() { |
| 315 | return Ok(None); |
| 316 | } |
| 317 | let Some(EgressFrame { |
| 318 | storage, |
| 319 | root: Some(root), |
| 320 | .. |
| 321 | }) = current_cell_event(&event_context(scope)) |
| 322 | else { |
| 323 | return Ok(None); |
| 324 | }; |
| 325 | if storage != cell { |
| 326 | return Err(format!( |
| 327 | "websocket: the socket names {cell}, but the running Durable Object facet is {storage}" |
| 328 | )); |
| 329 | } |
| 330 | let opening = storage::facet_opening(&storage).ok_or( |
| 331 | "websocket: the Durable Object facet that opened this socket is no longer running", |
| 332 | )?; |
| 333 | Ok(Some(FacetSocket { |
| 334 | root: root.cell, |
| 335 | stream: root.stream, |
| 336 | epoch: root.epoch, |
| 337 | opening, |
| 338 | })) |
| 339 | } |
| 340 | |
| 341 | /// `fetch(url, { headers: { Upgrade: "websocket" } })`. Returns a JSON |
| 342 | /// envelope: either an upgraded socket, or the ordinary response a server sent |
| 343 | /// instead, which the caller returns unchanged. |
| 344 | pub(super) fn op_ws_upgrade( |
| 345 | scope: &mut v8::PinScope, |
| 346 | args: v8::FunctionCallbackArguments, |
| 347 | mut rv: v8::ReturnValue<v8::Value>, |
| 348 | ) { |
| 349 | match &actor_runtime_state(scope).egress { |
| 350 | EgressPolicy::Allow => {} |
| 351 | EgressPolicy::Deny => { |
| 352 | return loader_throw( |
| 353 | scope, |
| 354 | "This worker is not permitted to access the internet via global functions.", |
| 355 | ); |
| 356 | } |
| 357 | EgressPolicy::Broker(_) => { |
| 358 | return loader_throw( |
| 359 | scope, |
| 360 | "A globalOutbound Fetcher cannot broker WebSockets in celld.", |
| 361 | ); |
| 362 | } |
| 363 | } |
| 364 | let id = args |
| 365 | .get(0) |
| 366 | .to_integer(scope) |
| 367 | .map(|n| n.value() as u64) |
| 368 | .unwrap_or(0); |
| 369 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 370 | let facet = match dialing_facet(scope, &cell) { |
| 371 | Ok(facet) => facet, |
| 372 | Err(error) => return loader_throw(scope, &error), |
| 373 | }; |
| 374 | let url = args.get(2).to_rust_string_lossy(scope); |
| 375 | // The subprotocol list is read back out of these headers, so a silent |
| 376 | // default opened the socket with no headers and no subprotocol at all. |
| 377 | let headers: Vec<(String, String)> = |
| 378 | match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { |
| 379 | Ok(headers) => headers, |
| 380 | Err(error) => { |
| 381 | return loader_throw( |
| 382 | scope, |
| 383 | &format!("websocket: the upgrade headers are not a name/value list: {error}"), |
| 384 | ) |
| 385 | } |
| 386 | }; |
| 387 | let protocols: Vec<String> = headers |
| 388 | .iter() |
| 389 | .find(|(name, _)| name.eq_ignore_ascii_case("sec-websocket-protocol")) |
| 390 | .map(|(_, value)| value.split(',').map(|p| p.trim().to_string()).collect()) |
| 391 | .unwrap_or_default(); |
| 392 | let pull = cell.is_empty().then(|| { |
| 393 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 394 | ws_pull_register(id, pull_rx); |
| 395 | ws_track_request_socket(id); |
| 396 | pull_tx |
| 397 | }); |
| 398 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 399 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 400 | sender |
| 401 | .send(OutboundWsReq { |
| 402 | scope: cell, |
| 403 | id, |
| 404 | url, |
| 405 | protocols, |
| 406 | pull, |
| 407 | headers, |
| 408 | want_response: true, |
| 409 | target: None, |
| 410 | facet, |
| 411 | reply: tx, |
| 412 | }) |
| 413 | .is_ok() |
| 414 | }); |
| 415 | let async_id = asyncrt::enqueue(async move { |
| 416 | if !sent { |
| 417 | return Err("no outbound WebSocket channel".into()); |
| 418 | } |
| 419 | let open = match rx.await { |
| 420 | Ok(Ok(open)) => open, |
| 421 | Ok(Err(error)) => return Err(format!("WebSocket upgrade failed: {error}")), |
| 422 | Err(error) => return Err(format!("WebSocket connector dropped: {error}")), |
| 423 | }; |
| 424 | Ok(match open.declined { |
| 425 | Some(declined) => serde_json::json!({ |
| 426 | "upgraded": false, |
| 427 | "status": declined.status, |
| 428 | "headers": declined.headers, |
| 429 | "body": declined.body, |
| 430 | }) |
| 431 | .to_string(), |
| 432 | None => serde_json::json!({ |
| 433 | "upgraded": true, |
| 434 | "protocol": open.protocol.unwrap_or_default(), |
| 435 | }) |
| 436 | .to_string(), |
| 437 | }) |
| 438 | }); |
| 439 | rv.set(promise_for(scope, async_id)); |
| 440 | } |
| 441 | |
| 442 | /// Await the next inbound event on an isolate-polled socket. Resolves with a |
| 443 | /// tagged buffer; a closed queue resolves as a 1006 close so the JS pump always |
| 444 | /// terminates rather than hanging on a dropped sender. |
| 445 | pub(super) fn op_ws_next( |
| 446 | scope: &mut v8::PinScope, |
| 447 | args: v8::FunctionCallbackArguments, |
| 448 | mut rv: v8::ReturnValue<v8::Value>, |
| 449 | ) { |
| 450 | let id = args |
| 451 | .get(0) |
| 452 | .to_integer(scope) |
| 453 | .map(|n| n.value() as u64) |
| 454 | .unwrap_or(0); |
| 455 | let queue = ws_pull().lock().unwrap().get(&id).cloned(); |
| 456 | let async_id = asyncrt::enqueue_io_context(async move { |
| 457 | let Some(queue) = queue else { |
| 458 | return Ok(WsPull::Close(1006, "socket is not registered".into(), false).encode()); |
| 459 | }; |
| 460 | let mut queue = queue.lock().await; |
| 461 | Ok(queue |
| 462 | .recv() |
| 463 | .await |
| 464 | .unwrap_or_else(|| WsPull::Close(1006, String::new(), false)) |
| 465 | .encode()) |
| 466 | }); |
| 467 | rv.set(promise_for(scope, async_id)); |
| 468 | } |
| 469 | |
| 470 | pub(super) fn op_ws_connect( |
| 471 | scope: &mut v8::PinScope, |
| 472 | args: v8::FunctionCallbackArguments, |
| 473 | mut rv: v8::ReturnValue<v8::Value>, |
| 474 | ) { |
| 475 | match &actor_runtime_state(scope).egress { |
| 476 | EgressPolicy::Allow => {} |
| 477 | EgressPolicy::Deny => { |
| 478 | return loader_throw( |
| 479 | scope, |
| 480 | "This worker is not permitted to access the internet via global functions.", |
| 481 | ); |
| 482 | } |
| 483 | EgressPolicy::Broker(_) => { |
| 484 | return loader_throw( |
| 485 | scope, |
| 486 | "A globalOutbound Fetcher cannot broker WebSockets in celld.", |
| 487 | ); |
| 488 | } |
| 489 | } |
| 490 | let id = args |
| 491 | .get(0) |
| 492 | .to_integer(scope) |
| 493 | .map(|n| n.value() as u64) |
| 494 | .unwrap_or(0); |
| 495 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 496 | let facet = match dialing_facet(scope, &cell) { |
| 497 | Ok(facet) => facet, |
| 498 | Err(error) => return loader_throw(scope, &error), |
| 499 | }; |
| 500 | let url = args.get(2).to_rust_string_lossy(scope); |
| 501 | let protocols: Vec<String> = |
| 502 | match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { |
| 503 | Ok(protocols) => protocols, |
| 504 | Err(error) => { |
| 505 | return loader_throw( |
| 506 | scope, |
| 507 | &format!("websocket: the subprotocol list is not a JSON array: {error}"), |
| 508 | ) |
| 509 | } |
| 510 | }; |
| 511 | // No cell means a Worker socket: the isolate polls it, so register the |
| 512 | // queue here on the JS thread and track it against the running request. |
| 513 | let pull = cell.is_empty().then(|| { |
| 514 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 515 | ws_pull_register(id, pull_rx); |
| 516 | ws_track_request_socket(id); |
| 517 | pull_tx |
| 518 | }); |
| 519 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 520 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 521 | sender |
| 522 | .send(OutboundWsReq { |
| 523 | scope: cell, |
| 524 | id, |
| 525 | url, |
| 526 | protocols, |
| 527 | pull, |
| 528 | headers: Vec::new(), |
| 529 | want_response: false, |
| 530 | target: None, |
| 531 | facet, |
| 532 | reply: tx, |
| 533 | }) |
| 534 | .is_ok() |
| 535 | }); |
| 536 | let async_id = asyncrt::enqueue(async move { |
| 537 | if !sent { |
| 538 | return Err("no outbound WebSocket channel".into()); |
| 539 | } |
| 540 | match rx.await { |
| 541 | Ok(Ok(open)) => Ok(open.protocol.unwrap_or_default()), |
| 542 | Ok(Err(error)) => Err(format!("WebSocket connection failed: {error}")), |
| 543 | Err(error) => Err(format!("WebSocket connector dropped: {error}")), |
| 544 | } |
| 545 | }); |
| 546 | rv.set(promise_for(scope, async_id)); |
| 547 | } |
| 548 | |
| 549 | /// Join this isolate's client socket to a Durable Object socket that a |
| 550 | /// subrequest already upgraded. The cell end lives in another isolate, so |
| 551 | /// the host carries each direction: it is the same route an external client |
| 552 | /// takes, with a pull queue in place of a TCP connection. |
| 553 | /// |
| 554 | /// Called from `accept()`, never from the upgrade itself. A Worker that |
| 555 | /// passes the response straight back out never accepts the socket, and the |
| 556 | /// host binds that 101 to the real client instead — binding here as well |
| 557 | /// would give one cell socket two readers. |
| 558 | pub(super) fn op_ws_bind_target( |
| 559 | scope: &mut v8::PinScope, |
| 560 | args: v8::FunctionCallbackArguments, |
| 561 | _rv: v8::ReturnValue<v8::Value>, |
| 562 | ) { |
| 563 | let id = args |
| 564 | .get(0) |
| 565 | .to_integer(scope) |
| 566 | .map(|n| n.value() as u64) |
| 567 | .unwrap_or(0); |
| 568 | let Ok(target) = serde_json::from_str::<WsTarget>(&args.get(1).to_rust_string_lossy(scope)) |
| 569 | else { |
| 570 | return loader_throw(scope, "WebSocket target is not valid"); |
| 571 | }; |
| 572 | // The caller's scope, which is empty for a Worker — the socket is |
| 573 | // accounted against the isolate holding it, exactly as `op_ws_connect` |
| 574 | // accounts an outbound one. |
| 575 | let cell = args.get(2).to_rust_string_lossy(scope); |
| 576 | // The caller end's frames reach this isolate through its pull queue, so |
| 577 | // they never route by `cell`. The record still matters: a facet that |
| 578 | // stops closes its sockets by it, and this end would otherwise keep the |
| 579 | // other Durable Object's socket open after the facet is gone. |
| 580 | let facet = match dialing_facet(scope, &cell) { |
| 581 | Ok(facet) => facet, |
| 582 | Err(error) => return loader_throw(scope, &error), |
| 583 | }; |
| 584 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 585 | ws_pull_register(id, pull_rx); |
| 586 | if cell.is_empty() { |
| 587 | ws_track_request_socket(id); |
| 588 | } |
| 589 | // Registered here, on the JS thread, so a frame sent between this op and |
| 590 | // the pipe task buffers as a pending frame instead of being dropped for |
| 591 | // a socket the registry has never heard of. `accept()` opens the socket |
| 592 | // synchronously, so that window is reachable by an ordinary `send()`. |
| 593 | ws_register_outbound(id, &cell, facet); |
| 594 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 595 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 596 | sender |
| 597 | .send(OutboundWsReq { |
| 598 | scope: target.scope.clone(), |
| 599 | id, |
| 600 | url: String::new(), |
| 601 | protocols: Vec::new(), |
| 602 | pull: Some(pull_tx), |
| 603 | headers: Vec::new(), |
| 604 | want_response: false, |
| 605 | target: Some(target), |
| 606 | // `scope` names the target, which keeps its own route. |
| 607 | facet: None, |
| 608 | reply: tx, |
| 609 | }) |
| 610 | .is_ok() |
| 611 | }); |
| 612 | // Nothing observes the outcome: the socket is already open, so there is |
| 613 | // no handshake for JS to await. The task keeps the reply receiver alive |
| 614 | // until the connector answers. A bind failure drops the pull sender, so |
| 615 | // `op_ws_next` reports the caller socket as abnormally closed. |
| 616 | asyncrt::enqueue(async move { |
| 617 | if !sent { |
| 618 | return Err::<String, String>("no outbound WebSocket channel".into()); |
| 619 | } |
| 620 | match rx.await { |
| 621 | Ok(Ok(_)) => Ok(String::new()), |
| 622 | Ok(Err(error)) => Err(format!("WebSocket bind failed: {error}")), |
| 623 | Err(error) => Err(format!("WebSocket connector dropped: {error}")), |
| 624 | } |
| 625 | }); |
| 626 | } |
| 627 | pub(super) fn op_ws_accept( |
| 628 | scope: &mut v8::PinScope, |
| 629 | args: v8::FunctionCallbackArguments, |
| 630 | _rv: v8::ReturnValue<v8::Value>, |
| 631 | ) { |
| 632 | let id = args |
| 633 | .get(0) |
| 634 | .to_integer(scope) |
| 635 | .map(|n| n.value() as u64) |
| 636 | .unwrap_or(0); |
| 637 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 638 | // Tags are how `state.getWebSockets(tag)` finds this socket again after a |
| 639 | // hibernation, so a silent default accepted the socket untagged and the |
| 640 | // Worker could not address it by tag; only a bare `getWebSockets()` still |
| 641 | // returned it. |
| 642 | let tags: Vec<String> = match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) { |
| 643 | Ok(tags) => tags, |
| 644 | Err(error) => { |
| 645 | return loader_throw( |
| 646 | scope, |
| 647 | &format!("websocket: the tag list is not a JSON array: {error}"), |
| 648 | ) |
| 649 | } |
| 650 | }; |
| 651 | let replaced_regular_scope = { |
| 652 | let registry = ws_registry(); |
| 653 | let mut registry = registry.lock().unwrap(); |
| 654 | let sockets = &mut registry.metadata; |
| 655 | let replaced_regular_scope = sockets |
| 656 | .get(&id) |
| 657 | .filter(|meta| !meta.hibernatable) |
| 658 | .map(|meta| meta.scope.clone()); |
| 659 | sockets |
| 660 | .entry(id) |
| 661 | .and_modify(|meta| { |
| 662 | meta.scope = cell.clone(); |
| 663 | meta.hibernatable = true; |
| 664 | meta.tags = tags.clone(); |
| 665 | }) |
| 666 | .or_insert(WsMeta { |
| 667 | scope: cell.clone(), |
| 668 | hibernatable: true, |
| 669 | tags, |
| 670 | attachment: None, |
| 671 | pending: Vec::new(), |
| 672 | auto_response_at: None, |
| 673 | facet: None, |
| 674 | }); |
| 675 | replaced_regular_scope |
| 676 | }; |
| 677 | if let Some(scope) = replaced_regular_scope { |
| 678 | decrement_regular_ws(&scope); |
| 679 | } |
| 680 | tracing::info!(ws_id = id, scope = %cell, "accepted hibernatable WebSocket"); |
| 681 | } |
| 682 | pub(super) fn op_ws_accept_regular( |
| 683 | scope: &mut v8::PinScope, |
| 684 | args: v8::FunctionCallbackArguments, |
| 685 | _rv: v8::ReturnValue<v8::Value>, |
| 686 | ) { |
| 687 | let id = args |
| 688 | .get(0) |
| 689 | .to_integer(scope) |
| 690 | .map(|n| n.value() as u64) |
| 691 | .unwrap_or(0); |
| 692 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 693 | let inserted = { |
| 694 | let registry = ws_registry(); |
| 695 | let mut registry = registry.lock().unwrap(); |
| 696 | let sockets = &mut registry.metadata; |
| 697 | if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) { |
| 698 | entry.insert(WsMeta { |
| 699 | scope: cell.clone(), |
| 700 | hibernatable: false, |
| 701 | tags: Vec::new(), |
| 702 | attachment: None, |
| 703 | pending: Vec::new(), |
| 704 | auto_response_at: None, |
| 705 | facet: None, |
| 706 | }); |
| 707 | true |
| 708 | } else { |
| 709 | false |
| 710 | } |
| 711 | }; |
| 712 | if inserted { |
| 713 | increment_regular_ws(&cell); |
| 714 | } |
| 715 | tracing::info!(ws_id = id, scope = %cell, "accepted regular WebSocket"); |
| 716 | } |
| 717 | pub(super) fn op_ws_list( |
| 718 | scope: &mut v8::PinScope, |
| 719 | args: v8::FunctionCallbackArguments, |
| 720 | mut rv: v8::ReturnValue<v8::Value>, |
| 721 | ) { |
| 722 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 723 | let tag = args.get(1); |
| 724 | let tag = if tag.is_undefined() || tag.is_null() { |
| 725 | None |
| 726 | } else { |
| 727 | Some(tag.to_rust_string_lossy(scope)) |
| 728 | }; |
| 729 | let rows = ws_registry() |
| 730 | .lock() |
| 731 | .unwrap() |
| 732 | .metadata |
| 733 | .iter() |
| 734 | .filter(|(_, meta)| { |
| 735 | meta.hibernatable |
| 736 | && meta.scope == cell |
| 737 | && tag.as_ref().is_none_or(|tag| meta.tags.contains(tag)) |
| 738 | }) |
| 739 | .map(|(id, meta)| { |
| 740 | serde_json::json!({ |
| 741 | "id": id, |
| 742 | "tags": meta.tags, |
| 743 | "attachment": meta.attachment, |
| 744 | }) |
| 745 | }) |
| 746 | .collect::<Vec<_>>(); |
| 747 | let json = serde_json::to_string(&rows).unwrap(); |
| 748 | rv.set(v8::String::new(scope, &json).unwrap().into()); |
| 749 | } |
| 750 | pub(super) fn op_ws_attachment_set( |
| 751 | scope: &mut v8::PinScope, |
| 752 | args: v8::FunctionCallbackArguments, |
| 753 | _rv: v8::ReturnValue<v8::Value>, |
| 754 | ) { |
| 755 | let id = args |
| 756 | .get(0) |
| 757 | .to_integer(scope) |
| 758 | .map(|n| n.value() as u64) |
| 759 | .unwrap_or(0); |
| 760 | let Some(attachment) = view_bytes(args.get(1)) else { |
| 761 | let message = v8::String::new(scope, "__ws_attachment_set expects bytes").unwrap(); |
| 762 | let exception = v8::Exception::type_error(scope, message); |
| 763 | scope.throw_exception(exception); |
| 764 | return; |
| 765 | }; |
| 766 | if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) { |
| 767 | meta.attachment = Some(attachment.to_vec()); |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | pub(super) fn op_ws_auto_response_set( |
| 772 | scope: &mut v8::PinScope, |
| 773 | args: v8::FunctionCallbackArguments, |
| 774 | _rv: v8::ReturnValue<v8::Value>, |
| 775 | ) { |
| 776 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 777 | let request = args.get(1); |
| 778 | if request.is_null() || request.is_undefined() { |
| 779 | ws_auto_responses().lock().unwrap().remove(&cell); |
| 780 | return; |
| 781 | } |
| 782 | let request = request.to_rust_string_lossy(scope); |
| 783 | let response = args.get(2).to_rust_string_lossy(scope); |
| 784 | ws_auto_responses() |
| 785 | .lock() |
| 786 | .unwrap() |
| 787 | .insert(cell, (request, response)); |
| 788 | } |
| 789 | pub(super) fn op_ws_auto_response_get( |
| 790 | scope: &mut v8::PinScope, |
| 791 | args: v8::FunctionCallbackArguments, |
| 792 | mut rv: v8::ReturnValue<v8::Value>, |
| 793 | ) { |
| 794 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 795 | let pair = ws_auto_responses().lock().unwrap().get(&cell).cloned(); |
| 796 | let json = match pair { |
| 797 | Some((request, response)) => serde_json::to_string(&[request, response]).unwrap(), |
| 798 | None => "null".to_string(), |
| 799 | }; |
| 800 | rv.set(v8::String::new(scope, &json).unwrap().into()); |
| 801 | } |
| 802 | pub(super) fn op_ws_auto_response_ts( |
| 803 | scope: &mut v8::PinScope, |
| 804 | args: v8::FunctionCallbackArguments, |
| 805 | mut rv: v8::ReturnValue<v8::Value>, |
| 806 | ) { |
| 807 | let id = args |
| 808 | .get(0) |
| 809 | .to_integer(scope) |
| 810 | .map(|n| n.value() as u64) |
| 811 | .unwrap_or(0); |
| 812 | let stamped = ws_registry() |
| 813 | .lock() |
| 814 | .unwrap() |
| 815 | .metadata |
| 816 | .get(&id) |
| 817 | .and_then(|meta| meta.auto_response_at); |
| 818 | match stamped { |
| 819 | Some(ms) => rv.set(v8::Number::new(scope, ms).into()), |
| 820 | None => rv.set(v8::null(scope).into()), |
| 821 | } |
| 822 | } |