Diffinery

homeflare/celldpublic

celld/crates/celld/js/websocket.rs
1546 lines · 55.8 KBRaw History
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.
10use super::*;
11
12/// Outbound WebSocket traffic from a DO's `ws.send`/`ws.close`. The host holds
13/// the socket in a task decoupled from the isolate (so the cell can hibernate
14/// while the socket lives); `ws.send` routes here by wsId.
15pub enum WsOut {
16 Text(String),
17 Binary(Vec<u8>),
18 Close(u16, String),
19}
20
21/// The result of delivering one `webSocketMessage`. `frames` are the outbound
22/// frames the handler produced, captured by the output gate; `write_position`
23/// is the cell's committed-write count after the handler when it advanced past
24/// where it stood before — i.e. the handler wrote, and its frames must be held
25/// until that position is durable. `None` means no write: flush the frames.
26pub struct WsDispatch {
27 pub frames: Vec<(u64, WsOut)>,
28 pub write_position: Option<u64>,
29 /// As on `HttpResponse`: what a handler that wrote nothing observed above
30 /// the cell's published baseline, for the gate to hold its frames behind
31 /// the proof of another handler's commit.
32 pub observed_position: Option<u64>,
33}
34
35/// One inbound event on a socket the ISOLATE polls, rather than one the host
36/// pushes into a cell.
37///
38/// A Durable Object socket must survive between events and wake a hibernated
39/// cell, so its frames arrive as `CellJob`s. A Worker socket cannot work that
40/// way: the stateless pool has no addressable isolate to push into. That is
41/// not a limitation to route around — it is exactly the lifetime Cloudflare
42/// gives a Worker socket, which lives and dies with its `IoContext`, and
43/// `IoContext::close_sockets` is what enforces it here. So the isolate pulls,
44/// the same way it already pulls a streamed response body.
45pub enum WsPull {
46 Open(String),
47 Text(String),
48 Binary(Vec<u8>),
49 Close(u16, String, bool),
50}
51
52/// Maximum charged bytes for non-terminal frames in one isolate-polled
53/// WebSocket input queue.
54pub(crate) const WS_PULL_QUEUE_MAX_BYTES: usize = 1024 * 1024;
55
56/// Tags for the byte frame `__ws_next` resolves with. A tagged buffer keeps a
57/// binary message on its fast path instead of base64 through a JSON envelope.
58const WS_PULL_TAG_TEXT: u8 = 0;
59const WS_PULL_TAG_BINARY: u8 = 1;
60const WS_PULL_TAG_OPEN: u8 = 2;
61const WS_PULL_TAG_CLOSE: u8 = 3;
62
63impl WsPull {
64 fn encode(self) -> Vec<u8> {
65 let (tag, mut body) = match self {
66 WsPull::Text(text) => (WS_PULL_TAG_TEXT, text.into_bytes()),
67 WsPull::Binary(bytes) => (WS_PULL_TAG_BINARY, bytes),
68 WsPull::Open(protocol) => (WS_PULL_TAG_OPEN, protocol.into_bytes()),
69 WsPull::Close(code, reason, was_clean) => (
70 WS_PULL_TAG_CLOSE,
71 serde_json::json!({
72 "code": code,
73 "reason": reason,
74 "wasClean": was_clean,
75 })
76 .to_string()
77 .into_bytes(),
78 ),
79 };
80 let mut framed = Vec::with_capacity(body.len() + 1);
81 framed.push(tag);
82 framed.append(&mut body);
83 framed
84 }
85}
86
87struct WsPullCharge {
88 #[cfg(all(test, celld_internal_tests))]
89 bytes: usize,
90 #[cfg(all(test, celld_internal_tests))]
91 queued_bytes: Arc<std::sync::atomic::AtomicUsize>,
92 _permit: Option<tokio::sync::OwnedSemaphorePermit>,
93}
94
95#[cfg(all(test, celld_internal_tests))]
96impl Drop for WsPullCharge {
97 fn drop(&mut self) {
98 self.queued_bytes
99 .fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed);
100 }
101}
102
103struct QueuedWsPull {
104 frame: WsPull,
105 // Capacity and each non-terminal frame move through the channel together.
106 // Every path that consumes or drops that frame therefore returns its queue
107 // budget. One terminal frame has no permit because it must release a full
108 // queue, but the private observer still measures its retained bytes.
109 _charge: WsPullCharge,
110}
111
112struct WsPullSendState {
113 tx: tokio::sync::mpsc::UnboundedSender<QueuedWsPull>,
114 terminal_sent: bool,
115}
116
117#[derive(Clone)]
118pub struct WsPullSender {
119 state: Arc<std::sync::Mutex<WsPullSendState>>,
120 #[cfg(all(test, celld_internal_tests))]
121 queued_bytes: Arc<std::sync::atomic::AtomicUsize>,
122 capacity: Arc<tokio::sync::Semaphore>,
123}
124
125pub struct WsPullReceiver {
126 rx: tokio::sync::mpsc::UnboundedReceiver<QueuedWsPull>,
127 #[cfg(all(test, celld_internal_tests))]
128 queued_bytes: Arc<std::sync::atomic::AtomicUsize>,
129}
130
131pub fn ws_pull_channel() -> (WsPullSender, WsPullReceiver) {
132 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
133 #[cfg(all(test, celld_internal_tests))]
134 let queued_bytes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
135 let capacity = Arc::new(tokio::sync::Semaphore::new(WS_PULL_QUEUE_MAX_BYTES));
136 (
137 WsPullSender {
138 state: Arc::new(std::sync::Mutex::new(WsPullSendState {
139 tx,
140 terminal_sent: false,
141 })),
142 #[cfg(all(test, celld_internal_tests))]
143 queued_bytes: queued_bytes.clone(),
144 capacity,
145 },
146 WsPullReceiver {
147 rx,
148 #[cfg(all(test, celld_internal_tests))]
149 queued_bytes,
150 },
151 )
152}
153
154impl WsPull {
155 fn queue_bytes(&self) -> usize {
156 let payload = match self {
157 Self::Open(protocol) | Self::Text(protocol) => protocol.len(),
158 Self::Binary(bytes) => bytes.len(),
159 Self::Close(_, reason, _) => reason.len(),
160 };
161 std::mem::size_of::<Self>().saturating_add(payload)
162 }
163}
164
165impl WsPullSender {
166 pub fn is_closed(&self) -> bool {
167 let state = self.state.lock().unwrap();
168 state.terminal_sent || state.tx.is_closed()
169 }
170
171 pub async fn send(&self, frame: WsPull) -> Result<(), WsPull> {
172 let frame = match frame {
173 WsPull::Close(code, reason, was_clean) => {
174 return self.send_close(code, reason, was_clean);
175 }
176 frame => frame,
177 };
178 let bytes = frame.queue_bytes();
179 // One message can exceed this queue limit until the separate incoming
180 // message limit rejects it. Reserving the complete budget admits that
181 // message only into an empty queue and prevents a second message from
182 // increasing its retained peak.
183 let permit_bytes = bytes.min(WS_PULL_QUEUE_MAX_BYTES) as u32;
184 let permit = match self.capacity.clone().acquire_many_owned(permit_bytes).await {
185 Ok(permit) => permit,
186 Err(_) => return Err(frame),
187 };
188 // The terminal sender closes the semaphore before it queues the close.
189 // A data sender can already own a permit at that point, so this lock
190 // either orders that data before the close or rejects it after the
191 // close. Without the shared order, a data frame could enter behind the
192 // only terminal frame and keep the receiver open.
193 let state = self.state.lock().unwrap();
194 if state.terminal_sent {
195 return Err(frame);
196 }
197 #[cfg(all(test, celld_internal_tests))]
198 self.queued_bytes
199 .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
200 state
201 .tx
202 .send(QueuedWsPull {
203 frame,
204 _charge: WsPullCharge {
205 #[cfg(all(test, celld_internal_tests))]
206 bytes,
207 #[cfg(all(test, celld_internal_tests))]
208 queued_bytes: self.queued_bytes.clone(),
209 _permit: Some(permit),
210 },
211 })
212 .map_err(|error| error.0.frame)
213 }
214
215 /// Queue the one terminal event without waiting for data capacity.
216 ///
217 /// The shared state orders the close against a data sender that already
218 /// owns capacity. Closing the semaphore wakes every sender that still waits
219 /// for capacity, so a stopped isolate cannot keep a host socket task alive.
220 pub fn send_close(&self, code: u16, reason: String, was_clean: bool) -> Result<(), WsPull> {
221 let frame = WsPull::Close(code, reason, was_clean);
222 #[cfg(all(test, celld_internal_tests))]
223 let bytes = frame.queue_bytes();
224 let mut state = self.state.lock().unwrap();
225 if state.terminal_sent {
226 return Err(frame);
227 }
228 state.terminal_sent = true;
229 self.capacity.close();
230 #[cfg(all(test, celld_internal_tests))]
231 self.queued_bytes
232 .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
233 state
234 .tx
235 .send(QueuedWsPull {
236 frame,
237 _charge: WsPullCharge {
238 #[cfg(all(test, celld_internal_tests))]
239 bytes,
240 #[cfg(all(test, celld_internal_tests))]
241 queued_bytes: self.queued_bytes.clone(),
242 _permit: None,
243 },
244 })
245 .map_err(|error| error.0.frame)
246 }
247}
248
249impl WsPullReceiver {
250 async fn recv(&mut self) -> Option<WsPull> {
251 let queued = self.rx.recv().await?;
252 let QueuedWsPull { frame, _charge } = queued;
253 if matches!(&frame, WsPull::Close(..)) {
254 // The sender state prevents a frame from entering behind this one.
255 // Close the receiver as part of consuming the terminal event, so a
256 // later pull observes the end instead of waiting for sender drops.
257 self.rx.close();
258 }
259 drop(_charge);
260 Some(frame)
261 }
262
263 #[cfg(all(test, celld_internal_tests))]
264 fn queued_bytes(&self) -> usize {
265 self.queued_bytes.load(std::sync::atomic::Ordering::Relaxed)
266 }
267}
268
269#[cfg(all(test, celld_internal_tests))]
270mod input_queue_private {
271 include!(env!("CELLD_INTERNAL_WEBSOCKET_TESTS"));
272}
273
274/// One socket's inbound queue. Shared so an op can await it without holding
275/// the registry lock; one isolate polls a given socket serially.
276type WsPullQueue = Arc<tokio::sync::Mutex<WsPullReceiver>>;
277type WsPullRegistry = std::sync::Mutex<HashMap<u64, WsPullQueue>>;
278
279/// Inbound queues for isolate-polled sockets, keyed by wsId.
280fn ws_pull() -> Arc<WsPullRegistry> {
281 asyncrt::services().websockets().pull.clone()
282}
283
284pub fn ws_pull_register(id: u64, rx: WsPullReceiver) {
285 ws_pull()
286 .lock()
287 .unwrap()
288 .insert(id, Arc::new(tokio::sync::Mutex::new(rx)));
289}
290
291pub fn ws_pull_unregister(id: u64) {
292 ws_pull().lock().unwrap().remove(&id);
293}
294
295/// The frame channel that a top-level Worker transfers with its 101 response.
296///
297/// The channel and the socket id move together. Dropping the response before
298/// the HTTP upgrade, or ending the upgrade task, therefore removes every host
299/// registration instead of leaving a socket that no isolate can reach.
300pub struct WorkerWebSocket {
301 id: u64,
302 inbound: WsPullSender,
303}
304
305impl WorkerWebSocket {
306 pub fn id(&self) -> u64 {
307 self.id
308 }
309
310 pub fn inbound(&self) -> WsPullSender {
311 self.inbound.clone()
312 }
313}
314
315impl Drop for WorkerWebSocket {
316 fn drop(&mut self) {
317 ws_pull_unregister(self.id);
318 ws_unregister(self.id);
319 }
320}
321
322fn prepare_worker_websocket_handoff(id: u64) {
323 let (inbound, receiver) = ws_pull_channel();
324 ws_pull_register(id, receiver);
325 ws_register_outbound(id, "");
326 ws_track_request_socket(id);
327 let registry = ws_registry();
328 let replaced = registry.lock().unwrap().worker_handoffs.insert(id, inbound);
329 drop(replaced);
330}
331
332pub(super) fn transfer_worker_websocket_handoff(id: u64) -> Option<WorkerWebSocket> {
333 let inbound = ws_registry().lock().unwrap().worker_handoffs.remove(&id)?;
334 // The response now owns cleanup. Transfer the frame channel and request
335 // ownership together so request retirement cannot close a returned socket.
336 current_context()
337 .sockets
338 .lock()
339 .unwrap()
340 .retain(|opened| *opened != id);
341 Some(WorkerWebSocket { id, inbound })
342}
343
344/// Close every isolate-polled socket a finished request opened.
345///
346/// The close frame is what actually ends the connection: the connector task
347/// writes it to the wire and stops pumping, and only then does it drop the
348/// `WsPull` sender that this socket's `__ws_next` is waiting on. Unregistering
349/// first would strand the task instead — it detects a dead isolate by the
350/// send failing, and nothing else tells it to go.
351pub(super) fn ws_close_request_sockets(opened: Vec<u64>) {
352 for id in opened {
353 let registry = ws_registry();
354 let handoff = registry.lock().unwrap().worker_handoffs.remove(&id);
355 drop(handoff);
356 // A socket whose remote already hung up has no output sender left,
357 // and that is the ordinary case rather than an error. `ws_emit` logs
358 // a dropped frame for an unknown id, so ask before sending.
359 let open = ws_registry().lock().unwrap().outputs.contains_key(&id);
360 if open {
361 // The event's own end, run by its turn: the owner is the context.
362 ws_emit(
363 &current_context(),
364 id,
365 WsOut::Close(1001, "request ended".into()),
366 );
367 }
368 ws_pull_unregister(id);
369 ws_unregister(id);
370 }
371}
372
373/// Whether the host still holds an inbound queue for `id`.
374///
375/// A leak here is invisible from outside the process: the queue holds the
376/// receiver whose survival keeps a connector task — and its TCP connection —
377/// alive, and a request that dies before its socket is ever registered for
378/// output leaves nothing else to observe.
379#[cfg(celld_internal_tests)]
380#[doc(hidden)]
381pub fn ws_pull_registered(id: u64) -> bool {
382 ws_pull().lock().unwrap().contains_key(&id)
383}
384
385/// Account a Worker socket to the request that opened it.
386fn ws_track_request_socket(id: u64) {
387 current_context().sockets.lock().unwrap().push(id);
388}
389pub enum WsIn {
390 Text(String),
391 Binary(Vec<u8>),
392}
393
394impl From<WsIn> for WsPull {
395 fn from(frame: WsIn) -> Self {
396 match frame {
397 WsIn::Text(text) => Self::Text(text),
398 WsIn::Binary(bytes) => Self::Binary(bytes),
399 }
400 }
401}
402
403#[doc(hidden)]
404pub struct WsMeta {
405 pub scope: String,
406 pub hibernatable: bool,
407 pub tags: Vec<String>,
408 /// Structured-clone bytes, not JSON: `serializeAttachment` accepts
409 /// anything cloneable, so Date, Map and Set must survive a round trip.
410 pub attachment: Option<Vec<u8>>,
411 pub pending: Vec<WsOut>,
412 /// When the shell last answered this socket with the cell's auto-response,
413 /// unix ms. Lives here rather than in the isolate because the reply is
414 /// sent while the cell may not be resident at all.
415 pub auto_response_at: Option<f64>,
416}
417#[derive(Default)]
418#[doc(hidden)]
419pub struct WsRegistry {
420 outputs: HashMap<u64, tokio::sync::mpsc::UnboundedSender<WsOut>>,
421 pub metadata: HashMap<u64, WsMeta>,
422 worker_handoffs: HashMap<u64, WsPullSender>,
423}
424impl WsRegistry {
425 #[doc(hidden)]
426 pub fn register(&mut self, id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
427 if let Some(meta) = self.metadata.get_mut(&id) {
428 for pending in meta.pending.drain(..) {
429 let _ = tx.send(pending);
430 }
431 }
432 self.outputs.insert(id, tx);
433 }
434
435 fn unregister(&mut self, id: u64) -> Option<WsMeta> {
436 self.outputs.remove(&id);
437 self.metadata.remove(&id)
438 }
439
440 #[doc(hidden)]
441 pub fn emit(&mut self, id: u64, out: WsOut) {
442 if let Some(tx) = self.outputs.get(&id) {
443 tracing::debug!(ws_id = id, "queued outbound WebSocket frame");
444 let _ = tx.send(out);
445 } else if let Some(meta) = self.metadata.get_mut(&id) {
446 tracing::debug!(ws_id = id, "buffered pre-upgrade WebSocket frame");
447 meta.pending.push(out);
448 } else {
449 // The socket is gone and the frame has nowhere to go. Silence here
450 // is what made a held frame indistinguishable from a sent one.
451 tracing::warn!(ws_id = id, "dropped a frame for a closed WebSocket");
452 }
453 }
454}
455/// Every piece of one instance's WebSocket state.
456///
457/// A socket's id is allocated by `next_id` here, so an id identifies a socket
458/// only within one instance. Each map a socket reaches must therefore belong
459/// to the same instance: a map that stayed process-wide would be shared by
460/// the sockets that two instances both numbered, and a second instance is not
461/// hypothetical: a test can run multiple instances, and a per-isolate or
462/// per-generation instance in production would inherit the
463/// collision.
464pub(crate) struct WebSocketService {
465 registry: Arc<std::sync::Mutex<WsRegistry>>,
466 regular_counts: Arc<std::sync::Mutex<HashMap<String, usize>>>,
467 next_id: AtomicU64,
468 auto_responses: Arc<std::sync::Mutex<HashMap<String, (String, String)>>>,
469 pull: Arc<WsPullRegistry>,
470 flush: Arc<WsFlushState>,
471}
472
473impl Default for WebSocketService {
474 fn default() -> Self {
475 Self {
476 registry: Arc::new(std::sync::Mutex::new(WsRegistry::default())),
477 regular_counts: Arc::new(std::sync::Mutex::new(HashMap::new())),
478 next_id: AtomicU64::new(1),
479 auto_responses: Arc::new(std::sync::Mutex::new(HashMap::new())),
480 pull: Arc::new(std::sync::Mutex::new(HashMap::new())),
481 flush: Arc::new(WsFlushState::default()),
482 }
483 }
484}
485
486fn ws_registry() -> Arc<std::sync::Mutex<WsRegistry>> {
487 asyncrt::services().websockets().registry.clone()
488}
489
490fn regular_ws_counts() -> Arc<std::sync::Mutex<HashMap<String, usize>>> {
491 asyncrt::services().websockets().regular_counts.clone()
492}
493fn increment_regular_ws(scope: &str) {
494 *regular_ws_counts()
495 .lock()
496 .unwrap()
497 .entry(scope.to_string())
498 .or_default() += 1;
499}
500fn decrement_regular_ws(scope: &str) {
501 let counts = regular_ws_counts();
502 let mut counts = counts.lock().unwrap();
503 let Some(count) = counts.get_mut(scope) else {
504 return;
505 };
506 *count = count.saturating_sub(1);
507 if *count == 0 {
508 counts.remove(scope);
509 }
510}
511pub fn has_regular_websocket(scope: &str) -> bool {
512 regular_ws_counts()
513 .lock()
514 .unwrap()
515 .get(scope)
516 .is_some_and(|count| *count > 0)
517}
518/// The auto-response pair per cell scope, set by
519/// `state.setWebSocketAutoResponse`. Shell state, like the socket registry:
520/// the whole point of the feature is answering a matched message while the
521/// cell is not resident, so the isolate cannot hold it.
522fn ws_auto_responses() -> Arc<std::sync::Mutex<HashMap<String, (String, String)>>> {
523 asyncrt::services().websockets().auto_responses.clone()
524}
525
526/// The shell's read path asks here before dispatching a text frame. A match
527/// returns the response to send on the same socket and stamps the socket's
528/// timestamp; the frame then never reaches the cell — no dispatch, no wake.
529/// Only hibernatable sockets participate, as in workerd, where matching
530/// lives in the hibernation manager's read loop.
531pub fn ws_auto_response(scope: &str, id: u64, text: &str) -> Option<String> {
532 let response = {
533 let pairs = ws_auto_responses();
534 let pairs = pairs.lock().unwrap();
535 let (request, response) = pairs.get(scope)?;
536 if request != text {
537 return None;
538 }
539 response.clone()
540 };
541 let registry = ws_registry();
542 let mut registry = registry.lock().unwrap();
543 let meta = registry.metadata.get_mut(&id)?;
544 if !meta.hibernatable {
545 return None;
546 }
547 meta.auto_response_at = Some(unix_ms());
548 Some(response)
549}
550
551fn unix_ms() -> f64 {
552 asyncrt::wall_ms() as f64
553}
554
555pub fn ws_hibernatable(id: u64) -> Option<bool> {
556 ws_registry()
557 .lock()
558 .unwrap()
559 .metadata
560 .get(&id)
561 .map(|meta| meta.hibernatable)
562}
563pub fn ws_next_id() -> u64 {
564 asyncrt::services()
565 .websockets()
566 .next_id
567 .fetch_add(1, Ordering::Relaxed)
568}
569pub fn ws_register(id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
570 ws_registry().lock().unwrap().register(id, tx);
571}
572
573/// Install one hibernatable socket through a cfg-gated execution backend.
574#[cfg(celld_internal_tests)]
575pub(crate) fn ws_register_hibernatable_for_test(
576 id: u64,
577 scope: &str,
578 tx: tokio::sync::mpsc::UnboundedSender<WsOut>,
579) {
580 let registry = ws_registry();
581 let mut registry = registry.lock().unwrap();
582 registry.register(id, tx);
583 registry.metadata.insert(
584 id,
585 WsMeta {
586 scope: scope.to_string(),
587 hibernatable: true,
588 tags: Vec::new(),
589 attachment: None,
590 pending: Vec::new(),
591 auto_response_at: None,
592 },
593 );
594}
595pub fn ws_register_outbound(id: u64, scope: &str) {
596 let inserted = {
597 let registry = ws_registry();
598 let mut registry = registry.lock().unwrap();
599 if let std::collections::hash_map::Entry::Vacant(entry) = registry.metadata.entry(id) {
600 entry.insert(WsMeta {
601 scope: scope.to_string(),
602 hibernatable: false,
603 tags: Vec::new(),
604 attachment: None,
605 pending: Vec::new(),
606 auto_response_at: None,
607 });
608 true
609 } else {
610 false
611 }
612 };
613 if inserted {
614 increment_regular_ws(scope);
615 }
616}
617pub fn ws_unregister(id: u64) {
618 let meta = ws_registry().lock().unwrap().unregister(id);
619 if let Some(meta) = meta.filter(|meta| !meta.hibernatable) {
620 decrement_regular_ws(&meta.scope);
621 }
622}
623
624pub(super) fn ws_capture_begin() {
625 current_context()
626 .ws_capture
627 .lock()
628 .unwrap()
629 .push(Vec::new());
630}
631
632pub(super) fn ws_capture_take() -> Vec<(u64, WsOut)> {
633 current_context()
634 .ws_capture
635 .lock()
636 .unwrap()
637 .pop()
638 .unwrap_or_default()
639}
640
641/// Which channel a frame on this socket leaves by.
642///
643/// A hibernatable transport is `WsHibernatable`: the host pushes its messages
644/// into the cell, captures what the handler emits, and releases the batch from
645/// the cell's barrier queue.
646///
647/// A socket the isolate opened and polls itself is `WsSelf`, and the two are
648/// separate channels in the model for a concrete reason. That handler runs
649/// inside the isolate's event loop, and that loop is what a captured frame
650/// would be waiting on: the reply to a frame the gate is withholding never
651/// arrives, so the loop never finishes, so the frame is never released. It
652/// takes a durability ticket on the host runtime instead, which is a different
653/// way of being held rather than not being held at all.
654fn ws_channel(id: u64) -> celld_logic::Channel {
655 let registry = ws_registry();
656 let registry = registry.lock().unwrap();
657 if registry
658 .metadata
659 .get(&id)
660 .is_some_and(|meta| meta.hibernatable)
661 {
662 celld_logic::Channel::WsHibernatable
663 } else {
664 celld_logic::Channel::WsSelf
665 }
666}
667
668/// The frames one instance holds behind its output gates, and the flushes
669/// that own them.
670///
671/// The three fields are one invariant, so they are one value: a socket has a
672/// queue exactly while a flush counted in `flushes` will drain it, and a
673/// count that falls must notify `done`. Held together, no caller can take the
674/// queue of one instance of the services and the count of another.
675#[derive(Default)]
676struct WsFlushState {
677 /// Frames held back because the handler that produced them has written
678 /// something not yet durable, one queue per socket.
679 ///
680 /// A socket with a queue has a flush already scheduled, and every later
681 /// frame for that socket joins the queue rather than overtaking it: a
682 /// socket's frames must arrive in the order the script sent them.
683 /// Ordering is a property of one socket, which is what the key says.
684 ///
685 /// Owned by the services, not by a thread. It is filled inside the
686 /// isolate and drained by an op, and an op runs on the host runtime — so
687 /// a thread-local queue was filled on one thread and taken, empty, on
688 /// another. The frames never left the process, and because the queue
689 /// stayed non-empty every later frame joined them.
690 deferred: std::sync::Mutex<HashMap<u64, Vec<WsOut>>>,
691 /// How many flushes still hold frames for a socket. A count, not a flag:
692 /// one flush can finish and drain its queue while a later frame starts
693 /// another.
694 flushes: std::sync::Mutex<HashMap<u64, usize>>,
695 done: tokio::sync::Notify,
696}
697
698impl WsFlushState {
699 /// Send `out` on `id`, or hold it behind the socket's gate.
700 ///
701 /// `gated` is the core's answer for this frame's event. A socket that
702 /// already holds frames joins them whatever that answer is, so a later
703 /// frame cannot overtake an earlier one.
704 ///
705 /// Returns the guard for the flush this frame started, and only then, so
706 /// the caller cannot spawn a second flush for a queue that already has
707 /// one and cannot spawn none for a queue that has none. The count is
708 /// taken while the queue lock is held: a teardown that reads the count
709 /// must not observe a queued frame with no flush behind it.
710 fn emit_or_defer(
711 self: &Arc<Self>,
712 registry: &std::sync::Mutex<WsRegistry>,
713 id: u64,
714 out: WsOut,
715 gated: bool,
716 ) -> Option<WsFlushGuard> {
717 // Held until this frame is either queued or sent. A flush runs on
718 // another thread, so releasing between the check and the send would
719 // let it drain its queue in between, putting a later frame ahead of
720 // an earlier one.
721 let mut deferred = self.deferred.lock().unwrap();
722 let already_deferring = deferred.contains_key(&id);
723 if !gated && !already_deferring {
724 ws_emit_ordered(&mut deferred, registry, std::iter::once((id, out)));
725 return None;
726 }
727 deferred.entry(id).or_default().push(out);
728 (!already_deferring).then(|| {
729 *self.flushes.lock().unwrap().entry(id).or_default() += 1;
730 WsFlushGuard {
731 state: self.clone(),
732 id,
733 }
734 })
735 }
736
737 /// Release the frames one flush held, or replace them with a close.
738 ///
739 /// `held` is what the gate answered. `Err` means the frames describe a
740 /// write the fleet may never have, so they must not be delivered.
741 /// Dropping them and leaving the socket open is not an option -- a
742 /// WebSocket is an ordered stream, and a peer cannot see a hole in one.
743 /// It would read the frames on either side of the gap as consecutive.
744 ///
745 /// Close instead. A truncated stream is something the peer can detect and
746 /// resynchronise from; a silently incomplete one is not. The cell is
747 /// reset underneath this as well, but that is a separate path and this
748 /// must not depend on its timing.
749 fn release(&self, registry: &std::sync::Mutex<WsRegistry>, id: u64, held: Result<(), String>) {
750 // Keep the lock from removal through the registry send. Once the
751 // entry is absent, another release would otherwise look direct and
752 // overtake these frames.
753 let mut deferred = self.deferred.lock().unwrap();
754 let frames = deferred.remove(&id).unwrap_or_default();
755 match held {
756 Err(_) => ws_emit_ordered(
757 &mut deferred,
758 registry,
759 std::iter::once((
760 id,
761 WsOut::Close(
762 1011,
763 "celld could not prove the write behind this message durable".to_string(),
764 ),
765 )),
766 ),
767 Ok(()) => ws_emit_ordered(
768 &mut deferred,
769 registry,
770 frames.into_iter().map(|out| (id, out)),
771 ),
772 }
773 }
774
775 /// Wait until no flush holds frames for `id` any more.
776 async fn await_flushes(&self, id: u64) {
777 loop {
778 // Registered before the count is read. A flush that finishes in
779 // between must find a waiter to wake, or this parks forever on a
780 // notification that already happened.
781 let notified = self.done.notified();
782 tokio::pin!(notified);
783 notified.as_mut().enable();
784 if !self.flushes.lock().unwrap().contains_key(&id) {
785 return;
786 }
787 notified.await;
788 }
789 }
790
791 /// Wait until no flush of this instance still owns deferred frames.
792 async fn await_all_flushes(&self) {
793 loop {
794 // Register before observing the map, exactly as the per-socket
795 // wait does. The final guard can otherwise notify between the
796 // empty check and waiter registration, leaving shutdown parked
797 // forever.
798 let notified = self.done.notified();
799 tokio::pin!(notified);
800 notified.as_mut().enable();
801 if self.flushes.lock().unwrap().is_empty() {
802 return;
803 }
804 notified.await;
805 }
806 }
807}
808
809/// The flush state of the services the caller runs under.
810///
811/// A flush task outlives the dispatch that spawned it and runs on a runtime
812/// with no services of its own, so every caller that hands work to one
813/// resolves the state here first and moves it in. Resolving inside the task
814/// would answer from whichever instance that runtime reaches, which is the
815/// process-wide sharing this state exists to end.
816fn ws_flush_state() -> Arc<WsFlushState> {
817 asyncrt::services().websockets().flush.clone()
818}
819
820/// One held queue and the flush that owns it, for a test that stands in for
821/// the durability ticket. Holding the guard is what keeps the socket's
822/// teardown wait honest while the queue exists.
823#[cfg(celld_internal_tests)]
824#[doc(hidden)]
825pub struct WsHeldFlush(WsFlushGuard);
826
827/// Hold `out` behind `id`'s gate exactly as a gated frame does, and return
828/// the flush the frame started. `None` when the socket already holds frames,
829/// because then an earlier flush owns the queue.
830#[cfg(celld_internal_tests)]
831#[doc(hidden)]
832pub fn ws_defer_frame(id: u64, out: WsOut) -> Option<WsHeldFlush> {
833 let flush = ws_flush_state();
834 let registry = ws_registry();
835 flush
836 .emit_or_defer(&registry, id, out, true)
837 .map(WsHeldFlush)
838}
839
840/// How many frames this instance holds for `id`.
841#[cfg(celld_internal_tests)]
842#[doc(hidden)]
843pub fn ws_deferred_count(id: u64) -> usize {
844 ws_flush_state()
845 .deferred
846 .lock()
847 .unwrap()
848 .get(&id)
849 .map_or(0, Vec::len)
850}
851
852/// Release a held flush as a settled durability ticket does, then count it
853/// out. Consuming the guard is what makes the two happen together.
854#[cfg(celld_internal_tests)]
855#[doc(hidden)]
856pub fn ws_release_flush(held: WsHeldFlush) {
857 let registry = ws_registry();
858 held.0.state.release(&registry, held.0.id, Ok(()));
859}
860
861/// Counts one flush out on every exit path, including the ones that run no
862/// code: a flush spawned onto a runtime that is already shutting down is
863/// dropped unpolled, and a panic unwinds through it. A count left behind by
864/// either would park the socket's teardown. Held by the flush, so the count
865/// falls whether it finished, failed, or never ran. It cannot help a flush
866/// that is merely parked -- nothing drops, so nothing runs -- which is what
867/// the teardown wait is bounded for.
868///
869/// It carries the state rather than resolving it on drop, because the drop
870/// can run on a runtime that answers with another instance, or with none.
871struct WsFlushGuard {
872 state: Arc<WsFlushState>,
873 id: u64,
874}
875
876impl Drop for WsFlushGuard {
877 fn drop(&mut self) {
878 {
879 let mut flushes = self.state.flushes.lock().unwrap();
880 if let Some(count) = flushes.get_mut(&self.id) {
881 *count -= 1;
882 if *count == 0 {
883 flushes.remove(&self.id);
884 }
885 }
886 }
887 self.state.done.notify_waiters();
888 }
889}
890
891/// Wait until no flush holds frames for `id` any more.
892///
893/// The socket's own teardown calls this. Closing reads the handler's output
894/// with a non-blocking drain and, finding none, answers the peer with the
895/// protocol echo of the close the peer itself sent -- so a close frame still
896/// behind the gate is not merely late, it is replaced. The wait is bounded by
897/// the gate: a cell with no barrier answers at once, a barrier settles when
898/// its proof does, and an unprovable one still resolves the flush through its
899/// fail-closed arm.
900pub async fn ws_await_flushes(id: u64) {
901 ws_flush_state().await_flushes(id).await;
902}
903
904/// Wait until no WebSocket flush of these services still owns deferred
905/// frames.
906///
907/// Shutdown calls this after the cell handoff has settled every output gate
908/// and before connection tasks can unregister their sockets. Waiting per
909/// socket cannot enforce that ordering because socket teardown deliberately
910/// skips its gate wait once the node is draining.
911#[doc(hidden)]
912pub async fn ws_await_all_flushes() {
913 ws_flush_state().await_all_flushes().await;
914}
915
916/// Send or hold one frame. `context` is the event the sending JavaScript
917/// belongs to: the continuation's own for a V8 entry point, so a reaction of
918/// cell A that runs inside another event's checkpoint is captured by and
919/// gated against A, not the checkpoint's owner.
920fn ws_emit(context: &IoContext, id: u64, out: WsOut) {
921 let mut capture = context.ws_capture.lock().unwrap();
922 if !capture.is_empty() && ws_channel(id) == celld_logic::Channel::WsHibernatable {
923 capture.last_mut().unwrap().push((id, out));
924 return;
925 }
926 drop(capture);
927 // A socket the isolate opened itself, which the capture above deliberately
928 // will not hold: releasing captured frames waits for the handler to
929 // return, and this handler may be awaiting a reply to the very frame being
930 // held. Waiting on the DURABILITY ticket instead has no such cycle -- it
931 // is resolved by the replicator, which does not need this event loop -- so
932 // the frame can be held without deadlocking the script that sent it.
933 let gate = egress_gate_request(context, ws_channel(id));
934 // Resolved here, on the thread the frame was sent from, and moved into the
935 // flush below. The flush runs on a runtime that has no services of its
936 // own, so a lookup inside it would answer with whichever instance that
937 // runtime reaches — the socket's frames and the socket's registry could
938 // then come from two different instances.
939 let flush = ws_flush_state();
940 let registry = ws_registry();
941 // Gated for a read-only frame as well, and deliberately: the frame reveals
942 // what the cell holds, so it has to ask the core whether a barrier is open
943 // rather than assume its own event opened one. A cell with nothing
944 // outstanding answers at once and the queue flushes on the same tick.
945 let Some(counted) = flush.emit_or_defer(&registry, id, out, gate.is_gated()) else {
946 return;
947 };
948 // Detached onto the HOST runtime (`op_handle`) deliberately: this flush
949 // exists precisely to outlive the dispatch that produced the frames — a
950 // writing connect handler's ready frame, an alarm broadcast — and it
951 // awaits a durability ticket that resolves with no isolate involvement.
952 // Both region-owned homes silently kill it: `asyncrt::enqueue`'s future is
953 // aborted when the dispatch region closes, and the isolate thread's local
954 // request driver stops polling its operation future the moment the
955 // dispatch returns. Either way the frames never left the process.
956 asyncrt::op_handle().spawn(async move {
957 let _counted = counted;
958 let held = await_egress_gate(gate).await;
959 flush.release(&registry, id, held);
960 });
961}
962
963/// Emit released frames without crossing a queue that already orders a socket.
964///
965/// The held queue map is a parameter rather than a lookup, so a caller holds
966/// it from the queue check through the registry send. Otherwise a flush can
967/// remove an earlier queue between those two steps, or a later release can
968/// reach the registry before that removed queue does. A batch can span
969/// sockets, so each frame makes the decision independently. The registry is a
970/// parameter for the same reason the queue is: both must come from the
971/// instance that owns the socket, and a flush cannot look either up.
972fn ws_emit_ordered(
973 deferred: &mut HashMap<u64, Vec<WsOut>>,
974 registry: &std::sync::Mutex<WsRegistry>,
975 frames: impl IntoIterator<Item = (u64, WsOut)>,
976) {
977 let mut registry = registry.lock().unwrap();
978 for (id, out) in frames {
979 match deferred.get_mut(&id) {
980 Some(queue) => queue.push(out),
981 None => registry.emit(id, out),
982 }
983 }
984}
985
986/// Release a batch into each socket's ordered stream. A socket whose
987/// durability-ticket queue is still present joins that queue, so an Actor
988/// barrier release cannot overtake an earlier frame on the same socket.
989pub fn ws_emit_batch(frames: Vec<(u64, WsOut)>) {
990 let flush = ws_flush_state();
991 let registry = ws_registry();
992 let mut deferred = flush.deferred.lock().unwrap();
993 ws_emit_ordered(&mut deferred, &registry, frames);
994}
995
996/// Close one socket. A forced generation swap closes the regular and
997/// outbound sockets that pin a cell to its old isolate and nothing else: the
998/// cell stays on this node, so its hibernatable sockets and auto-response
999/// pair survive, which `ws_close_scope` would take with it.
1000pub fn ws_close(id: u64, code: u16, reason: &str) {
1001 ws_registry()
1002 .lock()
1003 .unwrap()
1004 .emit(id, WsOut::Close(code, reason.to_string()));
1005}
1006
1007/// Break a cell's sockets: the output gate could not prove a write durable, so
1008/// close every socket the cell owns rather than let a client keep a connection
1009/// whose acknowledged effects may not have persisted (a reset DO).
1010pub fn ws_close_scope(scope: &str, code: u16, reason: &str) {
1011 // A reset cell is a new actor; workerd's hibernation manager dies with
1012 // the old one and takes the auto-response pair with it.
1013 ws_auto_responses().lock().unwrap().remove(scope);
1014 let registry = ws_registry();
1015 let mut registry = registry.lock().unwrap();
1016 let ids: Vec<u64> = registry
1017 .metadata
1018 .iter()
1019 .filter(|(_, meta)| meta.scope == scope)
1020 .map(|(id, _)| *id)
1021 .collect();
1022 for id in ids {
1023 registry.emit(id, WsOut::Close(code, reason.to_string()));
1024 }
1025}
1026
1027pub(super) fn op_ws_send(
1028 scope: &mut v8::PinScope,
1029 args: v8::FunctionCallbackArguments,
1030 _rv: v8::ReturnValue<v8::Value>,
1031) {
1032 let id = args
1033 .get(0)
1034 .to_integer(scope)
1035 .map(|n| n.value() as u64)
1036 .unwrap_or(0);
1037 let data = args.get(1).to_rust_string_lossy(scope);
1038 ws_emit(&event_context(scope), id, WsOut::Text(data));
1039}
1040pub(super) fn op_ws_send_binary(
1041 scope: &mut v8::PinScope,
1042 args: v8::FunctionCallbackArguments,
1043 _rv: v8::ReturnValue<v8::Value>,
1044) {
1045 let id = args
1046 .get(0)
1047 .to_integer(scope)
1048 .map(|n| n.value() as u64)
1049 .unwrap_or(0);
1050 let data = view_bytes(args.get(1)).unwrap_or_default();
1051 ws_emit(&event_context(scope), id, WsOut::Binary(data));
1052}
1053pub(super) fn op_ws_close(
1054 scope: &mut v8::PinScope,
1055 args: v8::FunctionCallbackArguments,
1056 _rv: v8::ReturnValue<v8::Value>,
1057) {
1058 let id = args
1059 .get(0)
1060 .to_integer(scope)
1061 .map(|n| n.value() as u64)
1062 .unwrap_or(0);
1063 let code = args.get(1).uint32_value(scope).unwrap_or(1000) as u16;
1064 let reason = args.get(2).to_rust_string_lossy(scope);
1065 ws_emit(&event_context(scope), id, WsOut::Close(code, reason));
1066}
1067pub(super) fn op_ws_alloc(
1068 scope: &mut v8::PinScope,
1069 _args: v8::FunctionCallbackArguments,
1070 mut rv: v8::ReturnValue<v8::Value>,
1071) {
1072 rv.set(v8::Number::new(scope, ws_next_id() as f64).into());
1073}
1074
1075pub(super) fn op_ws_prepare_worker_handoff(
1076 scope: &mut v8::PinScope,
1077 args: v8::FunctionCallbackArguments,
1078 _rv: v8::ReturnValue<v8::Value>,
1079) {
1080 let id = args
1081 .get(0)
1082 .to_integer(scope)
1083 .map(|n| n.value() as u64)
1084 .unwrap_or(0);
1085 prepare_worker_websocket_handoff(id);
1086}
1087/// `fetch(url, { headers: { Upgrade: "websocket" } })`. Returns a JSON
1088/// envelope: either an upgraded socket, or the ordinary response a server sent
1089/// instead, which the caller returns unchanged.
1090pub(super) fn op_ws_upgrade(
1091 scope: &mut v8::PinScope,
1092 args: v8::FunctionCallbackArguments,
1093 mut rv: v8::ReturnValue<v8::Value>,
1094) {
1095 match &actor_runtime_state(scope).egress {
1096 EgressPolicy::Allow => {}
1097 EgressPolicy::Deny => {
1098 return loader_throw(
1099 scope,
1100 "This worker is not permitted to access the internet via global functions.",
1101 );
1102 }
1103 EgressPolicy::Broker(_) => {
1104 return loader_throw(
1105 scope,
1106 "A globalOutbound Fetcher cannot broker WebSockets in celld.",
1107 );
1108 }
1109 }
1110 let id = args
1111 .get(0)
1112 .to_integer(scope)
1113 .map(|n| n.value() as u64)
1114 .unwrap_or(0);
1115 let cell = args.get(1).to_rust_string_lossy(scope);
1116 let url = args.get(2).to_rust_string_lossy(scope);
1117 // The subprotocol list is read back out of these headers, so a silent
1118 // default opened the socket with no headers and no subprotocol at all.
1119 let headers: Vec<(String, String)> =
1120 match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) {
1121 Ok(headers) => headers,
1122 Err(error) => {
1123 return loader_throw(
1124 scope,
1125 &format!("websocket: the upgrade headers are not a name/value list: {error}"),
1126 )
1127 }
1128 };
1129 let protocols: Vec<String> = headers
1130 .iter()
1131 .find(|(name, _)| name.eq_ignore_ascii_case("sec-websocket-protocol"))
1132 .map(|(_, value)| value.split(',').map(|p| p.trim().to_string()).collect())
1133 .unwrap_or_default();
1134 let pull = cell.is_empty().then(|| {
1135 let (pull_tx, pull_rx) = ws_pull_channel();
1136 ws_pull_register(id, pull_rx);
1137 ws_track_request_socket(id);
1138 pull_tx
1139 });
1140 let (tx, rx) = tokio::sync::oneshot::channel();
1141 let sent = outbound_ws_tx().is_some_and(|sender| {
1142 sender
1143 .send(OutboundWsReq {
1144 scope: cell,
1145 id,
1146 url,
1147 protocols,
1148 pull,
1149 headers,
1150 want_response: true,
1151 target: None,
1152 reply: tx,
1153 })
1154 .is_ok()
1155 });
1156 let async_id = asyncrt::enqueue(async move {
1157 if !sent {
1158 return Err("no outbound WebSocket channel".into());
1159 }
1160 let open = match rx.await {
1161 Ok(Ok(open)) => open,
1162 Ok(Err(error)) => return Err(format!("WebSocket upgrade failed: {error}")),
1163 Err(error) => return Err(format!("WebSocket connector dropped: {error}")),
1164 };
1165 Ok(match open.declined {
1166 Some(declined) => serde_json::json!({
1167 "upgraded": false,
1168 "status": declined.status,
1169 "headers": declined.headers,
1170 "body": declined.body,
1171 })
1172 .to_string(),
1173 None => serde_json::json!({
1174 "upgraded": true,
1175 "protocol": open.protocol.unwrap_or_default(),
1176 })
1177 .to_string(),
1178 })
1179 });
1180 rv.set(promise_for(scope, async_id));
1181}
1182
1183/// Await the next inbound event on an isolate-polled socket. Resolves with a
1184/// tagged buffer; a closed queue resolves as a 1006 close so the JS pump always
1185/// terminates rather than hanging on a dropped sender.
1186pub(super) fn op_ws_next(
1187 scope: &mut v8::PinScope,
1188 args: v8::FunctionCallbackArguments,
1189 mut rv: v8::ReturnValue<v8::Value>,
1190) {
1191 let id = args
1192 .get(0)
1193 .to_integer(scope)
1194 .map(|n| n.value() as u64)
1195 .unwrap_or(0);
1196 let queue = ws_pull().lock().unwrap().get(&id).cloned();
1197 let async_id = asyncrt::enqueue_io_context(async move {
1198 let Some(queue) = queue else {
1199 return Ok(WsPull::Close(1006, "socket is not registered".into(), false).encode());
1200 };
1201 let mut queue = queue.lock().await;
1202 Ok(queue
1203 .recv()
1204 .await
1205 .unwrap_or_else(|| WsPull::Close(1006, String::new(), false))
1206 .encode())
1207 });
1208 rv.set(promise_for(scope, async_id));
1209}
1210
1211pub(super) fn op_ws_connect(
1212 scope: &mut v8::PinScope,
1213 args: v8::FunctionCallbackArguments,
1214 mut rv: v8::ReturnValue<v8::Value>,
1215) {
1216 match &actor_runtime_state(scope).egress {
1217 EgressPolicy::Allow => {}
1218 EgressPolicy::Deny => {
1219 return loader_throw(
1220 scope,
1221 "This worker is not permitted to access the internet via global functions.",
1222 );
1223 }
1224 EgressPolicy::Broker(_) => {
1225 return loader_throw(
1226 scope,
1227 "A globalOutbound Fetcher cannot broker WebSockets in celld.",
1228 );
1229 }
1230 }
1231 let id = args
1232 .get(0)
1233 .to_integer(scope)
1234 .map(|n| n.value() as u64)
1235 .unwrap_or(0);
1236 let cell = args.get(1).to_rust_string_lossy(scope);
1237 let url = args.get(2).to_rust_string_lossy(scope);
1238 let protocols: Vec<String> =
1239 match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) {
1240 Ok(protocols) => protocols,
1241 Err(error) => {
1242 return loader_throw(
1243 scope,
1244 &format!("websocket: the subprotocol list is not a JSON array: {error}"),
1245 )
1246 }
1247 };
1248 // No cell means a Worker socket: the isolate polls it, so register the
1249 // queue here on the JS thread and track it against the running request.
1250 let pull = cell.is_empty().then(|| {
1251 let (pull_tx, pull_rx) = ws_pull_channel();
1252 ws_pull_register(id, pull_rx);
1253 ws_track_request_socket(id);
1254 pull_tx
1255 });
1256 let (tx, rx) = tokio::sync::oneshot::channel();
1257 let sent = outbound_ws_tx().is_some_and(|sender| {
1258 sender
1259 .send(OutboundWsReq {
1260 scope: cell,
1261 id,
1262 url,
1263 protocols,
1264 pull,
1265 headers: Vec::new(),
1266 want_response: false,
1267 target: None,
1268 reply: tx,
1269 })
1270 .is_ok()
1271 });
1272 let async_id = asyncrt::enqueue(async move {
1273 if !sent {
1274 return Err("no outbound WebSocket channel".into());
1275 }
1276 match rx.await {
1277 Ok(Ok(open)) => Ok(open.protocol.unwrap_or_default()),
1278 Ok(Err(error)) => Err(format!("WebSocket connection failed: {error}")),
1279 Err(error) => Err(format!("WebSocket connector dropped: {error}")),
1280 }
1281 });
1282 rv.set(promise_for(scope, async_id));
1283}
1284
1285/// Join this isolate's client socket to a Durable Object socket that a
1286/// subrequest already upgraded. The cell end lives in another isolate, so
1287/// the host carries each direction: it is the same route an external client
1288/// takes, with a pull queue in place of a TCP connection.
1289///
1290/// Called from `accept()`, never from the upgrade itself. A Worker that
1291/// passes the response straight back out never accepts the socket, and the
1292/// host binds that 101 to the real client instead — binding here as well
1293/// would give one cell socket two readers.
1294pub(super) fn op_ws_bind_target(
1295 scope: &mut v8::PinScope,
1296 args: v8::FunctionCallbackArguments,
1297 _rv: v8::ReturnValue<v8::Value>,
1298) {
1299 let id = args
1300 .get(0)
1301 .to_integer(scope)
1302 .map(|n| n.value() as u64)
1303 .unwrap_or(0);
1304 let Ok(target) = serde_json::from_str::<WsTarget>(&args.get(1).to_rust_string_lossy(scope))
1305 else {
1306 return loader_throw(scope, "WebSocket target is not valid");
1307 };
1308 // The caller's scope, which is empty for a Worker — the socket is
1309 // accounted against the isolate holding it, exactly as `op_ws_connect`
1310 // accounts an outbound one.
1311 let cell = args.get(2).to_rust_string_lossy(scope);
1312 let (pull_tx, pull_rx) = ws_pull_channel();
1313 ws_pull_register(id, pull_rx);
1314 if cell.is_empty() {
1315 ws_track_request_socket(id);
1316 }
1317 // Registered here, on the JS thread, so a frame sent between this op and
1318 // the pipe task buffers as a pending frame instead of being dropped for
1319 // a socket the registry has never heard of. `accept()` opens the socket
1320 // synchronously, so that window is reachable by an ordinary `send()`.
1321 ws_register_outbound(id, &cell);
1322 let (tx, rx) = tokio::sync::oneshot::channel();
1323 let sent = outbound_ws_tx().is_some_and(|sender| {
1324 sender
1325 .send(OutboundWsReq {
1326 scope: target.scope.clone(),
1327 id,
1328 url: String::new(),
1329 protocols: Vec::new(),
1330 pull: Some(pull_tx),
1331 headers: Vec::new(),
1332 want_response: false,
1333 target: Some(target),
1334 reply: tx,
1335 })
1336 .is_ok()
1337 });
1338 // Nothing observes the outcome: the socket is already open, so there is
1339 // no handshake for JS to await. The task keeps the reply receiver alive
1340 // until the connector answers. A bind failure drops the pull sender, so
1341 // `op_ws_next` reports the caller socket as abnormally closed.
1342 asyncrt::enqueue(async move {
1343 if !sent {
1344 return Err::<String, String>("no outbound WebSocket channel".into());
1345 }
1346 match rx.await {
1347 Ok(Ok(_)) => Ok(String::new()),
1348 Ok(Err(error)) => Err(format!("WebSocket bind failed: {error}")),
1349 Err(error) => Err(format!("WebSocket connector dropped: {error}")),
1350 }
1351 });
1352}
1353pub(super) fn op_ws_accept(
1354 scope: &mut v8::PinScope,
1355 args: v8::FunctionCallbackArguments,
1356 _rv: v8::ReturnValue<v8::Value>,
1357) {
1358 let id = args
1359 .get(0)
1360 .to_integer(scope)
1361 .map(|n| n.value() as u64)
1362 .unwrap_or(0);
1363 let cell = args.get(1).to_rust_string_lossy(scope);
1364 // Tags are how `state.getWebSockets(tag)` finds this socket again after a
1365 // hibernation, so a silent default accepted the socket untagged and the
1366 // Worker could not address it by tag; only a bare `getWebSockets()` still
1367 // returned it.
1368 let tags: Vec<String> = match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) {
1369 Ok(tags) => tags,
1370 Err(error) => {
1371 return loader_throw(
1372 scope,
1373 &format!("websocket: the tag list is not a JSON array: {error}"),
1374 )
1375 }
1376 };
1377 let replaced_regular_scope = {
1378 let registry = ws_registry();
1379 let mut registry = registry.lock().unwrap();
1380 let sockets = &mut registry.metadata;
1381 let replaced_regular_scope = sockets
1382 .get(&id)
1383 .filter(|meta| !meta.hibernatable)
1384 .map(|meta| meta.scope.clone());
1385 sockets
1386 .entry(id)
1387 .and_modify(|meta| {
1388 meta.scope = cell.clone();
1389 meta.hibernatable = true;
1390 meta.tags = tags.clone();
1391 })
1392 .or_insert(WsMeta {
1393 scope: cell.clone(),
1394 hibernatable: true,
1395 tags,
1396 attachment: None,
1397 pending: Vec::new(),
1398 auto_response_at: None,
1399 });
1400 replaced_regular_scope
1401 };
1402 if let Some(scope) = replaced_regular_scope {
1403 decrement_regular_ws(&scope);
1404 }
1405 tracing::info!(ws_id = id, scope = %cell, "accepted hibernatable WebSocket");
1406}
1407pub(super) fn op_ws_accept_regular(
1408 scope: &mut v8::PinScope,
1409 args: v8::FunctionCallbackArguments,
1410 _rv: v8::ReturnValue<v8::Value>,
1411) {
1412 let id = args
1413 .get(0)
1414 .to_integer(scope)
1415 .map(|n| n.value() as u64)
1416 .unwrap_or(0);
1417 let cell = args.get(1).to_rust_string_lossy(scope);
1418 let inserted = {
1419 let registry = ws_registry();
1420 let mut registry = registry.lock().unwrap();
1421 let sockets = &mut registry.metadata;
1422 if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) {
1423 entry.insert(WsMeta {
1424 scope: cell.clone(),
1425 hibernatable: false,
1426 tags: Vec::new(),
1427 attachment: None,
1428 pending: Vec::new(),
1429 auto_response_at: None,
1430 });
1431 true
1432 } else {
1433 false
1434 }
1435 };
1436 if inserted {
1437 increment_regular_ws(&cell);
1438 }
1439 tracing::info!(ws_id = id, scope = %cell, "accepted regular WebSocket");
1440}
1441pub(super) fn op_ws_list(
1442 scope: &mut v8::PinScope,
1443 args: v8::FunctionCallbackArguments,
1444 mut rv: v8::ReturnValue<v8::Value>,
1445) {
1446 let cell = args.get(0).to_rust_string_lossy(scope);
1447 let tag = args.get(1);
1448 let tag = if tag.is_undefined() || tag.is_null() {
1449 None
1450 } else {
1451 Some(tag.to_rust_string_lossy(scope))
1452 };
1453 let rows = ws_registry()
1454 .lock()
1455 .unwrap()
1456 .metadata
1457 .iter()
1458 .filter(|(_, meta)| {
1459 meta.hibernatable
1460 && meta.scope == cell
1461 && tag.as_ref().is_none_or(|tag| meta.tags.contains(tag))
1462 })
1463 .map(|(id, meta)| {
1464 serde_json::json!({
1465 "id": id,
1466 "tags": meta.tags,
1467 "attachment": meta.attachment,
1468 })
1469 })
1470 .collect::<Vec<_>>();
1471 let json = serde_json::to_string(&rows).unwrap();
1472 rv.set(v8::String::new(scope, &json).unwrap().into());
1473}
1474pub(super) fn op_ws_attachment_set(
1475 scope: &mut v8::PinScope,
1476 args: v8::FunctionCallbackArguments,
1477 _rv: v8::ReturnValue<v8::Value>,
1478) {
1479 let id = args
1480 .get(0)
1481 .to_integer(scope)
1482 .map(|n| n.value() as u64)
1483 .unwrap_or(0);
1484 let Some(attachment) = view_bytes(args.get(1)) else {
1485 let message = v8::String::new(scope, "__ws_attachment_set expects bytes").unwrap();
1486 let exception = v8::Exception::type_error(scope, message);
1487 scope.throw_exception(exception);
1488 return;
1489 };
1490 if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) {
1491 meta.attachment = Some(attachment.to_vec());
1492 }
1493}
1494
1495pub(super) fn op_ws_auto_response_set(
1496 scope: &mut v8::PinScope,
1497 args: v8::FunctionCallbackArguments,
1498 _rv: v8::ReturnValue<v8::Value>,
1499) {
1500 let cell = args.get(0).to_rust_string_lossy(scope);
1501 let request = args.get(1);
1502 if request.is_null() || request.is_undefined() {
1503 ws_auto_responses().lock().unwrap().remove(&cell);
1504 return;
1505 }
1506 let request = request.to_rust_string_lossy(scope);
1507 let response = args.get(2).to_rust_string_lossy(scope);
1508 ws_auto_responses()
1509 .lock()
1510 .unwrap()
1511 .insert(cell, (request, response));
1512}
1513pub(super) fn op_ws_auto_response_get(
1514 scope: &mut v8::PinScope,
1515 args: v8::FunctionCallbackArguments,
1516 mut rv: v8::ReturnValue<v8::Value>,
1517) {
1518 let cell = args.get(0).to_rust_string_lossy(scope);
1519 let pair = ws_auto_responses().lock().unwrap().get(&cell).cloned();
1520 let json = match pair {
1521 Some((request, response)) => serde_json::to_string(&[request, response]).unwrap(),
1522 None => "null".to_string(),
1523 };
1524 rv.set(v8::String::new(scope, &json).unwrap().into());
1525}
1526pub(super) fn op_ws_auto_response_ts(
1527 scope: &mut v8::PinScope,
1528 args: v8::FunctionCallbackArguments,
1529 mut rv: v8::ReturnValue<v8::Value>,
1530) {
1531 let id = args
1532 .get(0)
1533 .to_integer(scope)
1534 .map(|n| n.value() as u64)
1535 .unwrap_or(0);
1536 let stamped = ws_registry()
1537 .lock()
1538 .unwrap()
1539 .metadata
1540 .get(&id)
1541 .and_then(|meta| meta.auto_response_at);
1542 match stamped {
1543 Some(ms) => rv.set(v8::Number::new(scope, ms).into()),
1544 None => rv.set(v8::null(scope).into()),
1545 }
1546}