| 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 | |
| 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. |
| 15 | pub 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. |
| 26 | pub 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. |
| 45 | pub 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. |
| 54 | pub(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. |
| 58 | const WS_PULL_TAG_TEXT: u8 = 0; |
| 59 | const WS_PULL_TAG_BINARY: u8 = 1; |
| 60 | const WS_PULL_TAG_OPEN: u8 = 2; |
| 61 | const WS_PULL_TAG_CLOSE: u8 = 3; |
| 62 | |
| 63 | impl 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 | |
| 87 | struct 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))] |
| 96 | impl 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 | |
| 103 | struct 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 | |
| 112 | struct WsPullSendState { |
| 113 | tx: tokio::sync::mpsc::UnboundedSender<QueuedWsPull>, |
| 114 | terminal_sent: bool, |
| 115 | } |
| 116 | |
| 117 | #[derive(Clone)] |
| 118 | pub 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 | |
| 125 | pub 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 | |
| 131 | pub 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 | |
| 154 | impl 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 | |
| 165 | impl 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 | |
| 249 | impl 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))] |
| 270 | mod 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. |
| 276 | type WsPullQueue = Arc<tokio::sync::Mutex<WsPullReceiver>>; |
| 277 | type WsPullRegistry = std::sync::Mutex<HashMap<u64, WsPullQueue>>; |
| 278 | |
| 279 | /// Inbound queues for isolate-polled sockets, keyed by wsId. |
| 280 | fn ws_pull() -> Arc<WsPullRegistry> { |
| 281 | asyncrt::services().websockets().pull.clone() |
| 282 | } |
| 283 | |
| 284 | pub 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 | |
| 291 | pub 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. |
| 300 | pub struct WorkerWebSocket { |
| 301 | id: u64, |
| 302 | inbound: WsPullSender, |
| 303 | } |
| 304 | |
| 305 | impl 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 | |
| 315 | impl Drop for WorkerWebSocket { |
| 316 | fn drop(&mut self) { |
| 317 | ws_pull_unregister(self.id); |
| 318 | ws_unregister(self.id); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | fn 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 | |
| 332 | pub(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. |
| 351 | pub(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 | ¤t_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)] |
| 381 | pub 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. |
| 386 | fn ws_track_request_socket(id: u64) { |
| 387 | current_context().sockets.lock().unwrap().push(id); |
| 388 | } |
| 389 | pub enum WsIn { |
| 390 | Text(String), |
| 391 | Binary(Vec<u8>), |
| 392 | } |
| 393 | |
| 394 | impl 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)] |
| 404 | pub 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)] |
| 419 | pub struct WsRegistry { |
| 420 | outputs: HashMap<u64, tokio::sync::mpsc::UnboundedSender<WsOut>>, |
| 421 | pub metadata: HashMap<u64, WsMeta>, |
| 422 | worker_handoffs: HashMap<u64, WsPullSender>, |
| 423 | } |
| 424 | impl 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 — the private build runs one per test runtime, and a |
| 462 | /// per-isolate or per-generation instance in production would inherit the |
| 463 | /// collision. |
| 464 | pub(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 | |
| 473 | impl 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 | |
| 486 | fn ws_registry() -> Arc<std::sync::Mutex<WsRegistry>> { |
| 487 | asyncrt::services().websockets().registry.clone() |
| 488 | } |
| 489 | |
| 490 | fn regular_ws_counts() -> Arc<std::sync::Mutex<HashMap<String, usize>>> { |
| 491 | asyncrt::services().websockets().regular_counts.clone() |
| 492 | } |
| 493 | fn increment_regular_ws(scope: &str) { |
| 494 | *regular_ws_counts() |
| 495 | .lock() |
| 496 | .unwrap() |
| 497 | .entry(scope.to_string()) |
| 498 | .or_default() += 1; |
| 499 | } |
| 500 | fn 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 | } |
| 511 | pub 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. |
| 522 | fn 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. |
| 531 | pub 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 | |
| 551 | fn unix_ms() -> f64 { |
| 552 | asyncrt::wall_ms() as f64 |
| 553 | } |
| 554 | |
| 555 | pub 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 | } |
| 563 | pub fn ws_next_id() -> u64 { |
| 564 | asyncrt::services() |
| 565 | .websockets() |
| 566 | .next_id |
| 567 | .fetch_add(1, Ordering::Relaxed) |
| 568 | } |
| 569 | pub 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)] |
| 575 | pub(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 | } |
| 595 | pub 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 | } |
| 617 | pub 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 | |
| 624 | pub(super) fn ws_capture_begin() { |
| 625 | current_context() |
| 626 | .ws_capture |
| 627 | .lock() |
| 628 | .unwrap() |
| 629 | .push(Vec::new()); |
| 630 | } |
| 631 | |
| 632 | pub(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. |
| 654 | fn 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)] |
| 676 | struct 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 | |
| 698 | impl 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. |
| 816 | fn 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)] |
| 825 | pub 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)] |
| 832 | pub 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(®istry, 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)] |
| 843 | pub 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)] |
| 856 | pub fn ws_release_flush(held: WsHeldFlush) { |
| 857 | let registry = ws_registry(); |
| 858 | held.0.state.release(®istry, 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. |
| 871 | struct WsFlushGuard { |
| 872 | state: Arc<WsFlushState>, |
| 873 | id: u64, |
| 874 | } |
| 875 | |
| 876 | impl 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. |
| 900 | pub 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)] |
| 912 | pub 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. |
| 920 | fn 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(®istry, 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(®istry, 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. |
| 972 | fn 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. |
| 989 | pub 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, ®istry, 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. |
| 1000 | pub 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). |
| 1010 | pub 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 | |
| 1027 | pub(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 | } |
| 1040 | pub(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 | } |
| 1053 | pub(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 | } |
| 1067 | pub(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 | |
| 1075 | pub(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. |
| 1090 | pub(super) fn op_ws_upgrade( |
| 1091 | scope: &mut v8::PinScope, |
| 1092 | args: v8::FunctionCallbackArguments, |
| 1093 | mut rv: v8::ReturnValue<v8::Value>, |
| 1094 | ) { |
| 1095 | if actor_runtime_state(scope).egress == EgressPolicy::Deny { |
| 1096 | return loader_throw( |
| 1097 | scope, |
| 1098 | "This worker is not permitted to access the internet via global functions.", |
| 1099 | ); |
| 1100 | } |
| 1101 | let id = args |
| 1102 | .get(0) |
| 1103 | .to_integer(scope) |
| 1104 | .map(|n| n.value() as u64) |
| 1105 | .unwrap_or(0); |
| 1106 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 1107 | let url = args.get(2).to_rust_string_lossy(scope); |
| 1108 | // The subprotocol list is read back out of these headers, so a silent |
| 1109 | // default opened the socket with no headers and no subprotocol at all. |
| 1110 | let headers: Vec<(String, String)> = |
| 1111 | match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { |
| 1112 | Ok(headers) => headers, |
| 1113 | Err(error) => { |
| 1114 | return loader_throw( |
| 1115 | scope, |
| 1116 | &format!("websocket: the upgrade headers are not a name/value list: {error}"), |
| 1117 | ) |
| 1118 | } |
| 1119 | }; |
| 1120 | let protocols: Vec<String> = headers |
| 1121 | .iter() |
| 1122 | .find(|(name, _)| name.eq_ignore_ascii_case("sec-websocket-protocol")) |
| 1123 | .map(|(_, value)| value.split(',').map(|p| p.trim().to_string()).collect()) |
| 1124 | .unwrap_or_default(); |
| 1125 | let pull = cell.is_empty().then(|| { |
| 1126 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 1127 | ws_pull_register(id, pull_rx); |
| 1128 | ws_track_request_socket(id); |
| 1129 | pull_tx |
| 1130 | }); |
| 1131 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1132 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 1133 | sender |
| 1134 | .send(OutboundWsReq { |
| 1135 | scope: cell, |
| 1136 | id, |
| 1137 | url, |
| 1138 | protocols, |
| 1139 | pull, |
| 1140 | headers, |
| 1141 | want_response: true, |
| 1142 | target: None, |
| 1143 | reply: tx, |
| 1144 | }) |
| 1145 | .is_ok() |
| 1146 | }); |
| 1147 | let async_id = asyncrt::enqueue(async move { |
| 1148 | if !sent { |
| 1149 | return Err("no outbound WebSocket channel".into()); |
| 1150 | } |
| 1151 | let open = match rx.await { |
| 1152 | Ok(Ok(open)) => open, |
| 1153 | Ok(Err(error)) => return Err(format!("WebSocket upgrade failed: {error}")), |
| 1154 | Err(error) => return Err(format!("WebSocket connector dropped: {error}")), |
| 1155 | }; |
| 1156 | Ok(match open.declined { |
| 1157 | Some(declined) => serde_json::json!({ |
| 1158 | "upgraded": false, |
| 1159 | "status": declined.status, |
| 1160 | "headers": declined.headers, |
| 1161 | "body": declined.body, |
| 1162 | }) |
| 1163 | .to_string(), |
| 1164 | None => serde_json::json!({ |
| 1165 | "upgraded": true, |
| 1166 | "protocol": open.protocol.unwrap_or_default(), |
| 1167 | }) |
| 1168 | .to_string(), |
| 1169 | }) |
| 1170 | }); |
| 1171 | rv.set(promise_for(scope, async_id)); |
| 1172 | } |
| 1173 | |
| 1174 | /// Await the next inbound event on an isolate-polled socket. Resolves with a |
| 1175 | /// tagged buffer; a closed queue resolves as a 1006 close so the JS pump always |
| 1176 | /// terminates rather than hanging on a dropped sender. |
| 1177 | pub(super) fn op_ws_next( |
| 1178 | scope: &mut v8::PinScope, |
| 1179 | args: v8::FunctionCallbackArguments, |
| 1180 | mut rv: v8::ReturnValue<v8::Value>, |
| 1181 | ) { |
| 1182 | let id = args |
| 1183 | .get(0) |
| 1184 | .to_integer(scope) |
| 1185 | .map(|n| n.value() as u64) |
| 1186 | .unwrap_or(0); |
| 1187 | let queue = ws_pull().lock().unwrap().get(&id).cloned(); |
| 1188 | let async_id = asyncrt::enqueue_io_context(async move { |
| 1189 | let Some(queue) = queue else { |
| 1190 | return Ok(WsPull::Close(1006, "socket is not registered".into(), false).encode()); |
| 1191 | }; |
| 1192 | let mut queue = queue.lock().await; |
| 1193 | Ok(queue |
| 1194 | .recv() |
| 1195 | .await |
| 1196 | .unwrap_or_else(|| WsPull::Close(1006, String::new(), false)) |
| 1197 | .encode()) |
| 1198 | }); |
| 1199 | rv.set(promise_for(scope, async_id)); |
| 1200 | } |
| 1201 | |
| 1202 | pub(super) fn op_ws_connect( |
| 1203 | scope: &mut v8::PinScope, |
| 1204 | args: v8::FunctionCallbackArguments, |
| 1205 | mut rv: v8::ReturnValue<v8::Value>, |
| 1206 | ) { |
| 1207 | if actor_runtime_state(scope).egress == EgressPolicy::Deny { |
| 1208 | return loader_throw( |
| 1209 | scope, |
| 1210 | "This worker is not permitted to access the internet via global functions.", |
| 1211 | ); |
| 1212 | } |
| 1213 | let id = args |
| 1214 | .get(0) |
| 1215 | .to_integer(scope) |
| 1216 | .map(|n| n.value() as u64) |
| 1217 | .unwrap_or(0); |
| 1218 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 1219 | let url = args.get(2).to_rust_string_lossy(scope); |
| 1220 | let protocols: Vec<String> = |
| 1221 | match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { |
| 1222 | Ok(protocols) => protocols, |
| 1223 | Err(error) => { |
| 1224 | return loader_throw( |
| 1225 | scope, |
| 1226 | &format!("websocket: the subprotocol list is not a JSON array: {error}"), |
| 1227 | ) |
| 1228 | } |
| 1229 | }; |
| 1230 | // No cell means a Worker socket: the isolate polls it, so register the |
| 1231 | // queue here on the JS thread and track it against the running request. |
| 1232 | let pull = cell.is_empty().then(|| { |
| 1233 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 1234 | ws_pull_register(id, pull_rx); |
| 1235 | ws_track_request_socket(id); |
| 1236 | pull_tx |
| 1237 | }); |
| 1238 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1239 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 1240 | sender |
| 1241 | .send(OutboundWsReq { |
| 1242 | scope: cell, |
| 1243 | id, |
| 1244 | url, |
| 1245 | protocols, |
| 1246 | pull, |
| 1247 | headers: Vec::new(), |
| 1248 | want_response: false, |
| 1249 | target: None, |
| 1250 | reply: tx, |
| 1251 | }) |
| 1252 | .is_ok() |
| 1253 | }); |
| 1254 | let async_id = asyncrt::enqueue(async move { |
| 1255 | if !sent { |
| 1256 | return Err("no outbound WebSocket channel".into()); |
| 1257 | } |
| 1258 | match rx.await { |
| 1259 | Ok(Ok(open)) => Ok(open.protocol.unwrap_or_default()), |
| 1260 | Ok(Err(error)) => Err(format!("WebSocket connection failed: {error}")), |
| 1261 | Err(error) => Err(format!("WebSocket connector dropped: {error}")), |
| 1262 | } |
| 1263 | }); |
| 1264 | rv.set(promise_for(scope, async_id)); |
| 1265 | } |
| 1266 | |
| 1267 | /// Join this isolate's client socket to a Durable Object socket that a |
| 1268 | /// subrequest already upgraded. The cell end lives in another isolate, so |
| 1269 | /// the host carries each direction: it is the same route an external client |
| 1270 | /// takes, with a pull queue in place of a TCP connection. |
| 1271 | /// |
| 1272 | /// Called from `accept()`, never from the upgrade itself. A Worker that |
| 1273 | /// passes the response straight back out never accepts the socket, and the |
| 1274 | /// host binds that 101 to the real client instead — binding here as well |
| 1275 | /// would give one cell socket two readers. |
| 1276 | pub(super) fn op_ws_bind_target( |
| 1277 | scope: &mut v8::PinScope, |
| 1278 | args: v8::FunctionCallbackArguments, |
| 1279 | _rv: v8::ReturnValue<v8::Value>, |
| 1280 | ) { |
| 1281 | let id = args |
| 1282 | .get(0) |
| 1283 | .to_integer(scope) |
| 1284 | .map(|n| n.value() as u64) |
| 1285 | .unwrap_or(0); |
| 1286 | let Ok(target) = serde_json::from_str::<WsTarget>(&args.get(1).to_rust_string_lossy(scope)) |
| 1287 | else { |
| 1288 | return loader_throw(scope, "WebSocket target is not valid"); |
| 1289 | }; |
| 1290 | // The caller's scope, which is empty for a Worker — the socket is |
| 1291 | // accounted against the isolate holding it, exactly as `op_ws_connect` |
| 1292 | // accounts an outbound one. |
| 1293 | let cell = args.get(2).to_rust_string_lossy(scope); |
| 1294 | let (pull_tx, pull_rx) = ws_pull_channel(); |
| 1295 | ws_pull_register(id, pull_rx); |
| 1296 | if cell.is_empty() { |
| 1297 | ws_track_request_socket(id); |
| 1298 | } |
| 1299 | // Registered here, on the JS thread, so a frame sent between this op and |
| 1300 | // the pipe task buffers as a pending frame instead of being dropped for |
| 1301 | // a socket the registry has never heard of. `accept()` opens the socket |
| 1302 | // synchronously, so that window is reachable by an ordinary `send()`. |
| 1303 | ws_register_outbound(id, &cell); |
| 1304 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1305 | let sent = outbound_ws_tx().is_some_and(|sender| { |
| 1306 | sender |
| 1307 | .send(OutboundWsReq { |
| 1308 | scope: target.scope.clone(), |
| 1309 | id, |
| 1310 | url: String::new(), |
| 1311 | protocols: Vec::new(), |
| 1312 | pull: Some(pull_tx), |
| 1313 | headers: Vec::new(), |
| 1314 | want_response: false, |
| 1315 | target: Some(target), |
| 1316 | reply: tx, |
| 1317 | }) |
| 1318 | .is_ok() |
| 1319 | }); |
| 1320 | // Nothing observes the outcome: the socket is already open, so there is |
| 1321 | // no handshake for JS to await. The task keeps the reply receiver alive |
| 1322 | // until the connector answers. A bind failure drops the pull sender, so |
| 1323 | // `op_ws_next` reports the caller socket as abnormally closed. |
| 1324 | asyncrt::enqueue(async move { |
| 1325 | if !sent { |
| 1326 | return Err::<String, String>("no outbound WebSocket channel".into()); |
| 1327 | } |
| 1328 | match rx.await { |
| 1329 | Ok(Ok(_)) => Ok(String::new()), |
| 1330 | Ok(Err(error)) => Err(format!("WebSocket bind failed: {error}")), |
| 1331 | Err(error) => Err(format!("WebSocket connector dropped: {error}")), |
| 1332 | } |
| 1333 | }); |
| 1334 | } |
| 1335 | pub(super) fn op_ws_accept( |
| 1336 | scope: &mut v8::PinScope, |
| 1337 | args: v8::FunctionCallbackArguments, |
| 1338 | _rv: v8::ReturnValue<v8::Value>, |
| 1339 | ) { |
| 1340 | let id = args |
| 1341 | .get(0) |
| 1342 | .to_integer(scope) |
| 1343 | .map(|n| n.value() as u64) |
| 1344 | .unwrap_or(0); |
| 1345 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 1346 | // Tags are how `state.getWebSockets(tag)` finds this socket again after a |
| 1347 | // hibernation, so a silent default accepted the socket untagged and the |
| 1348 | // Worker could not address it by tag; only a bare `getWebSockets()` still |
| 1349 | // returned it. |
| 1350 | let tags: Vec<String> = match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) { |
| 1351 | Ok(tags) => tags, |
| 1352 | Err(error) => { |
| 1353 | return loader_throw( |
| 1354 | scope, |
| 1355 | &format!("websocket: the tag list is not a JSON array: {error}"), |
| 1356 | ) |
| 1357 | } |
| 1358 | }; |
| 1359 | let replaced_regular_scope = { |
| 1360 | let registry = ws_registry(); |
| 1361 | let mut registry = registry.lock().unwrap(); |
| 1362 | let sockets = &mut registry.metadata; |
| 1363 | let replaced_regular_scope = sockets |
| 1364 | .get(&id) |
| 1365 | .filter(|meta| !meta.hibernatable) |
| 1366 | .map(|meta| meta.scope.clone()); |
| 1367 | sockets |
| 1368 | .entry(id) |
| 1369 | .and_modify(|meta| { |
| 1370 | meta.scope = cell.clone(); |
| 1371 | meta.hibernatable = true; |
| 1372 | meta.tags = tags.clone(); |
| 1373 | }) |
| 1374 | .or_insert(WsMeta { |
| 1375 | scope: cell.clone(), |
| 1376 | hibernatable: true, |
| 1377 | tags, |
| 1378 | attachment: None, |
| 1379 | pending: Vec::new(), |
| 1380 | auto_response_at: None, |
| 1381 | }); |
| 1382 | replaced_regular_scope |
| 1383 | }; |
| 1384 | if let Some(scope) = replaced_regular_scope { |
| 1385 | decrement_regular_ws(&scope); |
| 1386 | } |
| 1387 | tracing::info!(ws_id = id, scope = %cell, "accepted hibernatable WebSocket"); |
| 1388 | } |
| 1389 | pub(super) fn op_ws_accept_regular( |
| 1390 | scope: &mut v8::PinScope, |
| 1391 | args: v8::FunctionCallbackArguments, |
| 1392 | _rv: v8::ReturnValue<v8::Value>, |
| 1393 | ) { |
| 1394 | let id = args |
| 1395 | .get(0) |
| 1396 | .to_integer(scope) |
| 1397 | .map(|n| n.value() as u64) |
| 1398 | .unwrap_or(0); |
| 1399 | let cell = args.get(1).to_rust_string_lossy(scope); |
| 1400 | let inserted = { |
| 1401 | let registry = ws_registry(); |
| 1402 | let mut registry = registry.lock().unwrap(); |
| 1403 | let sockets = &mut registry.metadata; |
| 1404 | if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) { |
| 1405 | entry.insert(WsMeta { |
| 1406 | scope: cell.clone(), |
| 1407 | hibernatable: false, |
| 1408 | tags: Vec::new(), |
| 1409 | attachment: None, |
| 1410 | pending: Vec::new(), |
| 1411 | auto_response_at: None, |
| 1412 | }); |
| 1413 | true |
| 1414 | } else { |
| 1415 | false |
| 1416 | } |
| 1417 | }; |
| 1418 | if inserted { |
| 1419 | increment_regular_ws(&cell); |
| 1420 | } |
| 1421 | tracing::info!(ws_id = id, scope = %cell, "accepted regular WebSocket"); |
| 1422 | } |
| 1423 | pub(super) fn op_ws_list( |
| 1424 | scope: &mut v8::PinScope, |
| 1425 | args: v8::FunctionCallbackArguments, |
| 1426 | mut rv: v8::ReturnValue<v8::Value>, |
| 1427 | ) { |
| 1428 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 1429 | let tag = args.get(1); |
| 1430 | let tag = if tag.is_undefined() || tag.is_null() { |
| 1431 | None |
| 1432 | } else { |
| 1433 | Some(tag.to_rust_string_lossy(scope)) |
| 1434 | }; |
| 1435 | let rows = ws_registry() |
| 1436 | .lock() |
| 1437 | .unwrap() |
| 1438 | .metadata |
| 1439 | .iter() |
| 1440 | .filter(|(_, meta)| { |
| 1441 | meta.hibernatable |
| 1442 | && meta.scope == cell |
| 1443 | && tag.as_ref().is_none_or(|tag| meta.tags.contains(tag)) |
| 1444 | }) |
| 1445 | .map(|(id, meta)| { |
| 1446 | serde_json::json!({ |
| 1447 | "id": id, |
| 1448 | "tags": meta.tags, |
| 1449 | "attachment": meta.attachment, |
| 1450 | }) |
| 1451 | }) |
| 1452 | .collect::<Vec<_>>(); |
| 1453 | let json = serde_json::to_string(&rows).unwrap(); |
| 1454 | rv.set(v8::String::new(scope, &json).unwrap().into()); |
| 1455 | } |
| 1456 | pub(super) fn op_ws_attachment_set( |
| 1457 | scope: &mut v8::PinScope, |
| 1458 | args: v8::FunctionCallbackArguments, |
| 1459 | _rv: v8::ReturnValue<v8::Value>, |
| 1460 | ) { |
| 1461 | let id = args |
| 1462 | .get(0) |
| 1463 | .to_integer(scope) |
| 1464 | .map(|n| n.value() as u64) |
| 1465 | .unwrap_or(0); |
| 1466 | let Some(attachment) = view_bytes(args.get(1)) else { |
| 1467 | let message = v8::String::new(scope, "__ws_attachment_set expects bytes").unwrap(); |
| 1468 | let exception = v8::Exception::type_error(scope, message); |
| 1469 | scope.throw_exception(exception); |
| 1470 | return; |
| 1471 | }; |
| 1472 | if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) { |
| 1473 | meta.attachment = Some(attachment.to_vec()); |
| 1474 | } |
| 1475 | } |
| 1476 | |
| 1477 | pub(super) fn op_ws_auto_response_set( |
| 1478 | scope: &mut v8::PinScope, |
| 1479 | args: v8::FunctionCallbackArguments, |
| 1480 | _rv: v8::ReturnValue<v8::Value>, |
| 1481 | ) { |
| 1482 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 1483 | let request = args.get(1); |
| 1484 | if request.is_null() || request.is_undefined() { |
| 1485 | ws_auto_responses().lock().unwrap().remove(&cell); |
| 1486 | return; |
| 1487 | } |
| 1488 | let request = request.to_rust_string_lossy(scope); |
| 1489 | let response = args.get(2).to_rust_string_lossy(scope); |
| 1490 | ws_auto_responses() |
| 1491 | .lock() |
| 1492 | .unwrap() |
| 1493 | .insert(cell, (request, response)); |
| 1494 | } |
| 1495 | pub(super) fn op_ws_auto_response_get( |
| 1496 | scope: &mut v8::PinScope, |
| 1497 | args: v8::FunctionCallbackArguments, |
| 1498 | mut rv: v8::ReturnValue<v8::Value>, |
| 1499 | ) { |
| 1500 | let cell = args.get(0).to_rust_string_lossy(scope); |
| 1501 | let pair = ws_auto_responses().lock().unwrap().get(&cell).cloned(); |
| 1502 | let json = match pair { |
| 1503 | Some((request, response)) => serde_json::to_string(&[request, response]).unwrap(), |
| 1504 | None => "null".to_string(), |
| 1505 | }; |
| 1506 | rv.set(v8::String::new(scope, &json).unwrap().into()); |
| 1507 | } |
| 1508 | pub(super) fn op_ws_auto_response_ts( |
| 1509 | scope: &mut v8::PinScope, |
| 1510 | args: v8::FunctionCallbackArguments, |
| 1511 | mut rv: v8::ReturnValue<v8::Value>, |
| 1512 | ) { |
| 1513 | let id = args |
| 1514 | .get(0) |
| 1515 | .to_integer(scope) |
| 1516 | .map(|n| n.value() as u64) |
| 1517 | .unwrap_or(0); |
| 1518 | let stamped = ws_registry() |
| 1519 | .lock() |
| 1520 | .unwrap() |
| 1521 | .metadata |
| 1522 | .get(&id) |
| 1523 | .and_then(|meta| meta.auto_response_at); |
| 1524 | match stamped { |
| 1525 | Some(ms) => rv.set(v8::Number::new(scope, ms).into()), |
| 1526 | None => rv.set(v8::null(scope).into()), |
| 1527 | } |
| 1528 | } |