| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The WebSocket registry: the sockets an instance holds, the frames waiting |
| 4 | //! to leave, and the isolate-polled input queues. Engine-neutral; the V8 ops |
| 5 | //! stay in `crate::js::websocket`, which re-exports every item at its old |
| 6 | //! path. |
| 7 | use crate::asyncrt; |
| 8 | use crate::engine_api::WsTarget; |
| 9 | use anyhow::Result; |
| 10 | use std::collections::HashMap; |
| 11 | use std::sync::atomic::AtomicU64; |
| 12 | use std::sync::atomic::Ordering; |
| 13 | use std::sync::Arc; |
| 14 | |
| 15 | pub struct OutboundWsReq { |
| 16 | pub scope: String, |
| 17 | pub id: u64, |
| 18 | pub url: String, |
| 19 | pub protocols: Vec<String>, |
| 20 | /// Present for an isolate-polled (Worker) socket. Created and registered |
| 21 | /// on the JS thread before the request is sent, so `__ws_next` can never |
| 22 | /// run ahead of its own queue. |
| 23 | pub pull: Option<WsPullSender>, |
| 24 | /// Extra request headers, for the `fetch()` upgrade form. |
| 25 | pub headers: Vec<(String, String)>, |
| 26 | /// A `fetch()` upgrade wants the whole handshake outcome, including the |
| 27 | /// ordinary response a server that declines to upgrade sent instead. |
| 28 | pub want_response: bool, |
| 29 | /// A socket already upgraded in this process, which this request joins |
| 30 | /// instead of dialing `url`. It is the cell end of a Durable Object |
| 31 | /// subrequest whose caller kept the client end, so there is no handshake |
| 32 | /// to run and no connection to open: the host only has to carry frames |
| 33 | /// between two isolates. |
| 34 | pub target: Option<WsTarget>, |
| 35 | /// The facet that dialed, when `scope` names a Durable Object facet. The |
| 36 | /// op derives it from the running event, so the socket routes through |
| 37 | /// the facet's root and never names the facet as a cell. |
| 38 | pub facet: Option<FacetSocket>, |
| 39 | pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>, |
| 40 | } |
| 41 | |
| 42 | /// The ordinary HTTP response a server sent instead of upgrading. `fetch()` |
| 43 | /// returns it verbatim rather than turning it into a connection error. |
| 44 | pub struct DeclinedUpgrade { |
| 45 | pub status: u16, |
| 46 | pub headers: Vec<(String, String)>, |
| 47 | pub body: Vec<u8>, |
| 48 | } |
| 49 | |
| 50 | /// What an outbound handshake produced. |
| 51 | pub struct OutboundWsOpen { |
| 52 | pub protocol: Option<String>, |
| 53 | pub declined: Option<DeclinedUpgrade>, |
| 54 | } |
| 55 | |
| 56 | /// Outbound WebSocket traffic from a DO's `ws.send`/`ws.close`. The host holds |
| 57 | /// the socket in a task decoupled from the isolate (so the cell can hibernate |
| 58 | /// while the socket lives); `ws.send` routes here by wsId. |
| 59 | pub enum WsOut { |
| 60 | Text(String), |
| 61 | Binary(Vec<u8>), |
| 62 | Close(u16, String), |
| 63 | } |
| 64 | |
| 65 | /// Outbound frames together with any positions already reserved in their sockets. |
| 66 | /// Captured sends reserve positions inside the isolate, before a later RPC can |
| 67 | /// send. The reservation travels through the handler and Actor gate with the |
| 68 | /// batch; reconstructing a plain vector at either handoff loses send order. |
| 69 | pub struct WsBatch(WsBatchState); |
| 70 | |
| 71 | enum WsBatchState { |
| 72 | Frames(Vec<(u64, WsOut)>), |
| 73 | Captured(CapturedWsBatch), |
| 74 | } |
| 75 | |
| 76 | struct CapturedWsBatch { |
| 77 | registry: Arc<std::sync::Mutex<WsRegistry>>, |
| 78 | state: Arc<WsFlushState>, |
| 79 | /// The one flush that owns every segment this batch reserved. `None` |
| 80 | /// only until the first frame, since a guard must name a segment. |
| 81 | flush: Option<WsFlushGuard>, |
| 82 | /// The newest segment `flush` holds on each socket, by token. A map, so a |
| 83 | /// broadcast to many sockets does not scan every earlier segment per frame. |
| 84 | tails: HashMap<u64, u64>, |
| 85 | frames: usize, |
| 86 | } |
| 87 | |
| 88 | impl Default for WsBatch { |
| 89 | fn default() -> Self { |
| 90 | Self(WsBatchState::Frames(Vec::new())) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl WsBatch { |
| 95 | pub fn len(&self) -> usize { |
| 96 | match &self.0 { |
| 97 | WsBatchState::Frames(frames) => frames.len(), |
| 98 | WsBatchState::Captured(batch) => batch.frames, |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub fn is_empty(&self) -> bool { |
| 103 | self.len() == 0 |
| 104 | } |
| 105 | |
| 106 | pub(crate) fn capture(&mut self, id: u64, out: WsOut) { |
| 107 | if let WsBatchState::Frames(frames) = &self.0 { |
| 108 | assert!(frames.is_empty(), "capture starts with an empty batch"); |
| 109 | self.0 = WsBatchState::Captured(CapturedWsBatch { |
| 110 | registry: ws_registry(), |
| 111 | state: ws_flush_state(), |
| 112 | flush: None, |
| 113 | tails: HashMap::new(), |
| 114 | frames: 0, |
| 115 | }); |
| 116 | } |
| 117 | let WsBatchState::Captured(batch) = &mut self.0 else { |
| 118 | unreachable!("capture installs its ordered batch"); |
| 119 | }; |
| 120 | batch |
| 121 | .state |
| 122 | .capture(&mut batch.flush, &mut batch.tails, id, out); |
| 123 | batch.frames += 1; |
| 124 | } |
| 125 | |
| 126 | pub(crate) fn release(self, verdict: Result<(), String>) { |
| 127 | match self.0 { |
| 128 | WsBatchState::Captured(mut batch) => { |
| 129 | if let Some(flush) = batch.flush.take() { |
| 130 | flush.release(&batch.registry, verdict); |
| 131 | } |
| 132 | } |
| 133 | WsBatchState::Frames(frames) if verdict.is_ok() && !frames.is_empty() => { |
| 134 | let flushing = ws_flush_state().emit_or_defer(&ws_registry(), frames, false); |
| 135 | debug_assert!(flushing.is_none(), "a released batch opens no flush"); |
| 136 | } |
| 137 | WsBatchState::Frames(_) => {} |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// A rejected handler never published these frames. Remove its reservations |
| 142 | /// without cancelling independent events queued behind them. |
| 143 | pub(crate) fn discard(self) { |
| 144 | if let WsBatchState::Captured(mut batch) = self.0 { |
| 145 | if let Some(flush) = batch.flush.take() { |
| 146 | flush.discard(&batch.registry); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl From<Vec<(u64, WsOut)>> for WsBatch { |
| 153 | fn from(frames: Vec<(u64, WsOut)>) -> Self { |
| 154 | Self(WsBatchState::Frames(frames)) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl Drop for CapturedWsBatch { |
| 159 | fn drop(&mut self) { |
| 160 | // A lost dispatch or cancelled flush has no successful gate verdict. |
| 161 | // Refuse its reservations so successors cannot hang or cross the gap. |
| 162 | if let Some(flush) = self.flush.take() { |
| 163 | flush.release(&self.registry, Err("WebSocket batch abandoned".into())); |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// The result of delivering one `webSocketMessage`. `frames` are the outbound |
| 169 | /// frames of the turn the handler answered in, captured by the output gate; a |
| 170 | /// turn the handler suspended in released its own frames as it ended, so those |
| 171 | /// are already gone. `write_position` is the cell's committed-write count |
| 172 | /// after the handler when it advanced past where it stood before — i.e. the |
| 173 | /// handler wrote, and its frames must be held until that position is durable. |
| 174 | /// `None` means no write: flush the frames. |
| 175 | pub struct WsDispatch { |
| 176 | pub frames: WsBatch, |
| 177 | pub write_position: Option<u64>, |
| 178 | /// As on `HttpResponse`: what a handler that wrote nothing observed above |
| 179 | /// the cell's published baseline, for the gate to hold its frames behind |
| 180 | /// the proof of another handler's commit. |
| 181 | pub observed_position: Option<u64>, |
| 182 | } |
| 183 | |
| 184 | /// One inbound event on a socket the ISOLATE polls, rather than one the host |
| 185 | /// pushes into a cell. |
| 186 | /// |
| 187 | /// A Durable Object socket must survive between events and wake a hibernated |
| 188 | /// cell, so its frames arrive as `CellJob`s. A Worker socket cannot work that |
| 189 | /// way: the stateless pool has no addressable isolate to push into. That is |
| 190 | /// not a limitation to route around — it is exactly the lifetime Cloudflare |
| 191 | /// gives a Worker socket, which lives and dies with its `IoContext`, and |
| 192 | /// `IoContext::close_sockets` is what enforces it here. So the isolate pulls, |
| 193 | /// the same way it already pulls a streamed response body. |
| 194 | pub enum WsPull { |
| 195 | Open(String), |
| 196 | Text(String), |
| 197 | Binary(Vec<u8>), |
| 198 | Close(u16, String, bool), |
| 199 | } |
| 200 | |
| 201 | /// Maximum charged bytes for non-terminal frames in one isolate-polled |
| 202 | /// WebSocket input queue. |
| 203 | pub(crate) const WS_PULL_QUEUE_MAX_BYTES: usize = 1024 * 1024; |
| 204 | |
| 205 | /// Tags for the byte frame `__ws_next` resolves with. A tagged buffer keeps a |
| 206 | /// binary message on its fast path instead of base64 through a JSON envelope. |
| 207 | const WS_PULL_TAG_TEXT: u8 = 0; |
| 208 | const WS_PULL_TAG_BINARY: u8 = 1; |
| 209 | const WS_PULL_TAG_OPEN: u8 = 2; |
| 210 | const WS_PULL_TAG_CLOSE: u8 = 3; |
| 211 | |
| 212 | impl WsPull { |
| 213 | pub(crate) fn encode(self) -> Vec<u8> { |
| 214 | let (tag, mut body) = match self { |
| 215 | WsPull::Text(text) => (WS_PULL_TAG_TEXT, text.into_bytes()), |
| 216 | WsPull::Binary(bytes) => (WS_PULL_TAG_BINARY, bytes), |
| 217 | WsPull::Open(protocol) => (WS_PULL_TAG_OPEN, protocol.into_bytes()), |
| 218 | WsPull::Close(code, reason, was_clean) => ( |
| 219 | WS_PULL_TAG_CLOSE, |
| 220 | serde_json::json!({ |
| 221 | "code": code, |
| 222 | "reason": reason, |
| 223 | "wasClean": was_clean, |
| 224 | }) |
| 225 | .to_string() |
| 226 | .into_bytes(), |
| 227 | ), |
| 228 | }; |
| 229 | let mut framed = Vec::with_capacity(body.len() + 1); |
| 230 | framed.push(tag); |
| 231 | framed.append(&mut body); |
| 232 | framed |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | struct WsPullCharge { |
| 237 | #[cfg(all(test, celld_internal_tests))] |
| 238 | bytes: usize, |
| 239 | #[cfg(all(test, celld_internal_tests))] |
| 240 | queued_bytes: Arc<std::sync::atomic::AtomicUsize>, |
| 241 | _permit: Option<tokio::sync::OwnedSemaphorePermit>, |
| 242 | } |
| 243 | |
| 244 | #[cfg(all(test, celld_internal_tests))] |
| 245 | impl Drop for WsPullCharge { |
| 246 | fn drop(&mut self) { |
| 247 | self.queued_bytes |
| 248 | .fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | struct QueuedWsPull { |
| 253 | frame: WsPull, |
| 254 | // Capacity and each non-terminal frame move through the channel together. |
| 255 | // Every path that consumes or drops that frame therefore returns its queue |
| 256 | // budget. One terminal frame has no permit because it must release a full |
| 257 | // queue, but the test observer still measures its retained bytes. |
| 258 | _charge: WsPullCharge, |
| 259 | } |
| 260 | |
| 261 | struct WsPullSendState { |
| 262 | tx: tokio::sync::mpsc::UnboundedSender<QueuedWsPull>, |
| 263 | terminal_sent: bool, |
| 264 | } |
| 265 | |
| 266 | #[derive(Clone)] |
| 267 | pub struct WsPullSender { |
| 268 | state: Arc<std::sync::Mutex<WsPullSendState>>, |
| 269 | #[cfg(all(test, celld_internal_tests))] |
| 270 | queued_bytes: Arc<std::sync::atomic::AtomicUsize>, |
| 271 | capacity: Arc<tokio::sync::Semaphore>, |
| 272 | } |
| 273 | |
| 274 | pub struct WsPullReceiver { |
| 275 | rx: tokio::sync::mpsc::UnboundedReceiver<QueuedWsPull>, |
| 276 | #[cfg(all(test, celld_internal_tests))] |
| 277 | queued_bytes: Arc<std::sync::atomic::AtomicUsize>, |
| 278 | } |
| 279 | |
| 280 | pub fn ws_pull_channel() -> (WsPullSender, WsPullReceiver) { |
| 281 | let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); |
| 282 | #[cfg(all(test, celld_internal_tests))] |
| 283 | let queued_bytes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); |
| 284 | let capacity = Arc::new(tokio::sync::Semaphore::new(WS_PULL_QUEUE_MAX_BYTES)); |
| 285 | ( |
| 286 | WsPullSender { |
| 287 | state: Arc::new(std::sync::Mutex::new(WsPullSendState { |
| 288 | tx, |
| 289 | terminal_sent: false, |
| 290 | })), |
| 291 | #[cfg(all(test, celld_internal_tests))] |
| 292 | queued_bytes: queued_bytes.clone(), |
| 293 | capacity, |
| 294 | }, |
| 295 | WsPullReceiver { |
| 296 | rx, |
| 297 | #[cfg(all(test, celld_internal_tests))] |
| 298 | queued_bytes, |
| 299 | }, |
| 300 | ) |
| 301 | } |
| 302 | |
| 303 | impl WsPull { |
| 304 | fn queue_bytes(&self) -> usize { |
| 305 | let payload = match self { |
| 306 | Self::Open(protocol) | Self::Text(protocol) => protocol.len(), |
| 307 | Self::Binary(bytes) => bytes.len(), |
| 308 | Self::Close(_, reason, _) => reason.len(), |
| 309 | }; |
| 310 | std::mem::size_of::<Self>().saturating_add(payload) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | impl WsPullSender { |
| 315 | pub fn is_closed(&self) -> bool { |
| 316 | let state = self.state.lock().unwrap(); |
| 317 | state.terminal_sent || state.tx.is_closed() |
| 318 | } |
| 319 | |
| 320 | pub async fn send(&self, frame: WsPull) -> Result<(), WsPull> { |
| 321 | let frame = match frame { |
| 322 | WsPull::Close(code, reason, was_clean) => { |
| 323 | return self.send_close(code, reason, was_clean); |
| 324 | } |
| 325 | frame => frame, |
| 326 | }; |
| 327 | let bytes = frame.queue_bytes(); |
| 328 | // One message can exceed this queue limit until the separate incoming |
| 329 | // message limit rejects it. Reserving the complete budget admits that |
| 330 | // message only into an empty queue and prevents a second message from |
| 331 | // increasing its retained peak. |
| 332 | let permit_bytes = bytes.min(WS_PULL_QUEUE_MAX_BYTES) as u32; |
| 333 | let permit = match self.capacity.clone().acquire_many_owned(permit_bytes).await { |
| 334 | Ok(permit) => permit, |
| 335 | Err(_) => return Err(frame), |
| 336 | }; |
| 337 | // The terminal sender closes the semaphore before it queues the close. |
| 338 | // A data sender can already own a permit at that point, so this lock |
| 339 | // either orders that data before the close or rejects it after the |
| 340 | // close. Without the shared order, a data frame could enter behind the |
| 341 | // only terminal frame and keep the receiver open. |
| 342 | let state = self.state.lock().unwrap(); |
| 343 | if state.terminal_sent { |
| 344 | return Err(frame); |
| 345 | } |
| 346 | #[cfg(all(test, celld_internal_tests))] |
| 347 | self.queued_bytes |
| 348 | .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed); |
| 349 | state |
| 350 | .tx |
| 351 | .send(QueuedWsPull { |
| 352 | frame, |
| 353 | _charge: WsPullCharge { |
| 354 | #[cfg(all(test, celld_internal_tests))] |
| 355 | bytes, |
| 356 | #[cfg(all(test, celld_internal_tests))] |
| 357 | queued_bytes: self.queued_bytes.clone(), |
| 358 | _permit: Some(permit), |
| 359 | }, |
| 360 | }) |
| 361 | .map_err(|error| error.0.frame) |
| 362 | } |
| 363 | |
| 364 | /// Queue the one terminal event without waiting for data capacity. |
| 365 | /// |
| 366 | /// The shared state orders the close against a data sender that already |
| 367 | /// owns capacity. Closing the semaphore wakes every sender that still waits |
| 368 | /// for capacity, so a stopped isolate cannot keep a host socket task alive. |
| 369 | pub fn send_close(&self, code: u16, reason: String, was_clean: bool) -> Result<(), WsPull> { |
| 370 | let frame = WsPull::Close(code, reason, was_clean); |
| 371 | #[cfg(all(test, celld_internal_tests))] |
| 372 | let bytes = frame.queue_bytes(); |
| 373 | let mut state = self.state.lock().unwrap(); |
| 374 | if state.terminal_sent { |
| 375 | return Err(frame); |
| 376 | } |
| 377 | state.terminal_sent = true; |
| 378 | self.capacity.close(); |
| 379 | #[cfg(all(test, celld_internal_tests))] |
| 380 | self.queued_bytes |
| 381 | .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed); |
| 382 | state |
| 383 | .tx |
| 384 | .send(QueuedWsPull { |
| 385 | frame, |
| 386 | _charge: WsPullCharge { |
| 387 | #[cfg(all(test, celld_internal_tests))] |
| 388 | bytes, |
| 389 | #[cfg(all(test, celld_internal_tests))] |
| 390 | queued_bytes: self.queued_bytes.clone(), |
| 391 | _permit: None, |
| 392 | }, |
| 393 | }) |
| 394 | .map_err(|error| error.0.frame) |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | impl WsPullReceiver { |
| 399 | pub(crate) async fn recv(&mut self) -> Option<WsPull> { |
| 400 | let queued = self.rx.recv().await?; |
| 401 | let QueuedWsPull { frame, _charge } = queued; |
| 402 | if matches!(&frame, WsPull::Close(..)) { |
| 403 | // The sender state prevents a frame from entering behind this one. |
| 404 | // Close the receiver as part of consuming the terminal event, so a |
| 405 | // later pull observes the end instead of waiting for sender drops. |
| 406 | self.rx.close(); |
| 407 | } |
| 408 | drop(_charge); |
| 409 | Some(frame) |
| 410 | } |
| 411 | |
| 412 | #[cfg(all(test, celld_internal_tests))] |
| 413 | fn queued_bytes(&self) -> usize { |
| 414 | self.queued_bytes.load(std::sync::atomic::Ordering::Relaxed) |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | #[cfg(all(test, celld_internal_tests))] |
| 419 | mod input_queue_private { |
| 420 | include!(env!("CELLD_INTERNAL_WEBSOCKET_TESTS")); |
| 421 | } |
| 422 | |
| 423 | /// One socket's inbound queue. Shared so an op can await it without holding |
| 424 | /// the registry lock; one isolate polls a given socket serially. |
| 425 | type WsPullQueue = Arc<tokio::sync::Mutex<WsPullReceiver>>; |
| 426 | type WsPullRegistry = std::sync::Mutex<HashMap<u64, WsPullQueue>>; |
| 427 | |
| 428 | /// Inbound queues for isolate-polled sockets, keyed by wsId. |
| 429 | pub(crate) fn ws_pull() -> Arc<WsPullRegistry> { |
| 430 | asyncrt::services().websockets().pull.clone() |
| 431 | } |
| 432 | |
| 433 | pub fn ws_pull_register(id: u64, rx: WsPullReceiver) { |
| 434 | ws_pull() |
| 435 | .lock() |
| 436 | .unwrap() |
| 437 | .insert(id, Arc::new(tokio::sync::Mutex::new(rx))); |
| 438 | } |
| 439 | |
| 440 | pub fn ws_pull_unregister(id: u64) { |
| 441 | ws_pull().lock().unwrap().remove(&id); |
| 442 | } |
| 443 | |
| 444 | /// The frame channel that a top-level Worker transfers with its 101 response. |
| 445 | /// |
| 446 | /// The channel and the socket id move together. Dropping the response before |
| 447 | /// the HTTP upgrade, or ending the upgrade task, therefore removes every host |
| 448 | /// registration instead of leaving a socket that no isolate can reach. |
| 449 | pub struct WorkerWebSocket { |
| 450 | pub(crate) id: u64, |
| 451 | pub(crate) inbound: WsPullSender, |
| 452 | } |
| 453 | |
| 454 | impl WorkerWebSocket { |
| 455 | pub fn id(&self) -> u64 { |
| 456 | self.id |
| 457 | } |
| 458 | |
| 459 | pub fn inbound(&self) -> WsPullSender { |
| 460 | self.inbound.clone() |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | impl Drop for WorkerWebSocket { |
| 465 | fn drop(&mut self) { |
| 466 | ws_pull_unregister(self.id); |
| 467 | ws_unregister(self.id); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /// Whether the host still holds an inbound queue for `id`. |
| 472 | /// |
| 473 | /// A leak here is invisible from outside the process: the queue holds the |
| 474 | /// receiver whose survival keeps a connector task — and its TCP connection — |
| 475 | /// alive, and a request that dies before its socket is ever registered for |
| 476 | /// output leaves nothing else to observe. |
| 477 | #[cfg(celld_internal_tests)] |
| 478 | #[doc(hidden)] |
| 479 | pub fn ws_pull_registered(id: u64) -> bool { |
| 480 | ws_pull().lock().unwrap().contains_key(&id) |
| 481 | } |
| 482 | |
| 483 | pub enum WsIn { |
| 484 | Text(String), |
| 485 | Binary(Vec<u8>), |
| 486 | } |
| 487 | |
| 488 | impl From<WsIn> for WsPull { |
| 489 | fn from(frame: WsIn) -> Self { |
| 490 | match frame { |
| 491 | WsIn::Text(text) => Self::Text(text), |
| 492 | WsIn::Binary(bytes) => Self::Binary(bytes), |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | #[doc(hidden)] |
| 498 | pub struct WsMeta { |
| 499 | pub scope: String, |
| 500 | pub hibernatable: bool, |
| 501 | pub tags: Vec<String>, |
| 502 | /// Structured-clone bytes, not JSON: `serializeAttachment` accepts |
| 503 | /// anything cloneable, so Date, Map and Set must survive a round trip. |
| 504 | pub attachment: Option<Vec<u8>>, |
| 505 | pub pending: Vec<WsOut>, |
| 506 | /// When the shell last answered this socket with the cell's auto-response, |
| 507 | /// unix ms. Lives here rather than in the isolate because the reply is |
| 508 | /// sent while the cell may not be resident at all. |
| 509 | pub auto_response_at: Option<f64>, |
| 510 | /// The root cell and facet stream behind a socket that a Durable Object |
| 511 | /// facet accepted, dialed, or bound. `None` for a socket of an ordinary |
| 512 | /// cell. `scope` then names the facet. |
| 513 | pub facet: Option<FacetSocket>, |
| 514 | } |
| 515 | |
| 516 | /// Where the events of a facet's socket go, and what proves their output. |
| 517 | /// |
| 518 | /// A facet is not a cell: no Worker exports its class under the facet's |
| 519 | /// scope, so routing an event by that scope activated a cell that cannot |
| 520 | /// start (denoland/celld#252). The root cell owns the facet, its residency, |
| 521 | /// and its gate, so the socket routes and registers under `root`. The facet's |
| 522 | /// own writes are proved on `stream` at `epoch`. |
| 523 | /// |
| 524 | /// Recorded by the host, never read from a `WsTarget`. A target crosses |
| 525 | /// application JavaScript, which could otherwise name another root. |
| 526 | #[derive(Clone, Debug)] |
| 527 | pub struct FacetSocket { |
| 528 | pub root: String, |
| 529 | pub stream: String, |
| 530 | pub epoch: u64, |
| 531 | /// The opening of the facet that holds the socket. An event reaches |
| 532 | /// that opening only, never a later one at the same scope. |
| 533 | pub opening: u64, |
| 534 | } |
| 535 | #[derive(Default)] |
| 536 | #[doc(hidden)] |
| 537 | pub struct WsRegistry { |
| 538 | pub(crate) outputs: HashMap<u64, tokio::sync::mpsc::UnboundedSender<WsOut>>, |
| 539 | pub metadata: HashMap<u64, WsMeta>, |
| 540 | pub(crate) worker_handoffs: HashMap<u64, WsPullSender>, |
| 541 | } |
| 542 | impl WsRegistry { |
| 543 | #[doc(hidden)] |
| 544 | pub fn register(&mut self, id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) { |
| 545 | if let Some(meta) = self.metadata.get_mut(&id) { |
| 546 | for pending in meta.pending.drain(..) { |
| 547 | let _ = tx.send(pending); |
| 548 | } |
| 549 | } |
| 550 | self.outputs.insert(id, tx); |
| 551 | } |
| 552 | |
| 553 | fn unregister(&mut self, id: u64) -> Option<WsMeta> { |
| 554 | self.outputs.remove(&id); |
| 555 | self.metadata.remove(&id) |
| 556 | } |
| 557 | |
| 558 | #[doc(hidden)] |
| 559 | pub fn emit(&mut self, id: u64, out: WsOut) { |
| 560 | if let Some(tx) = self.outputs.get(&id) { |
| 561 | tracing::debug!(ws_id = id, "queued outbound WebSocket frame"); |
| 562 | let _ = tx.send(out); |
| 563 | } else if let Some(meta) = self.metadata.get_mut(&id) { |
| 564 | tracing::debug!(ws_id = id, "buffered pre-upgrade WebSocket frame"); |
| 565 | meta.pending.push(out); |
| 566 | } else { |
| 567 | // The socket is gone and the frame has nowhere to go. Silence here |
| 568 | // is what made a held frame indistinguishable from a sent one. |
| 569 | tracing::warn!(ws_id = id, "dropped a frame for a closed WebSocket"); |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | /// Every piece of one instance's WebSocket state. |
| 574 | /// |
| 575 | /// A socket's id is allocated by `next_id` here, so an id identifies a socket |
| 576 | /// only within one instance. Each map a socket reaches must therefore belong |
| 577 | /// to the same instance: a map that stayed process-wide would be shared by |
| 578 | /// the sockets that two instances both numbered, and a second instance is not |
| 579 | /// hypothetical: a test can run multiple instances, and a per-isolate or |
| 580 | /// per-generation instance in production would inherit the |
| 581 | /// collision. |
| 582 | pub(crate) struct WebSocketService { |
| 583 | registry: Arc<std::sync::Mutex<WsRegistry>>, |
| 584 | regular_counts: Arc<std::sync::Mutex<HashMap<String, usize>>>, |
| 585 | next_id: AtomicU64, |
| 586 | auto_responses: Arc<std::sync::Mutex<HashMap<String, (String, String)>>>, |
| 587 | pull: Arc<WsPullRegistry>, |
| 588 | flush: Arc<WsFlushState>, |
| 589 | } |
| 590 | |
| 591 | impl Default for WebSocketService { |
| 592 | fn default() -> Self { |
| 593 | Self { |
| 594 | registry: Arc::new(std::sync::Mutex::new(WsRegistry::default())), |
| 595 | regular_counts: Arc::new(std::sync::Mutex::new(HashMap::new())), |
| 596 | next_id: AtomicU64::new(1), |
| 597 | auto_responses: Arc::new(std::sync::Mutex::new(HashMap::new())), |
| 598 | pull: Arc::new(std::sync::Mutex::new(HashMap::new())), |
| 599 | flush: Arc::new(WsFlushState::default()), |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | pub(crate) fn ws_registry() -> Arc<std::sync::Mutex<WsRegistry>> { |
| 605 | asyncrt::services().websockets().registry.clone() |
| 606 | } |
| 607 | |
| 608 | fn regular_ws_counts() -> Arc<std::sync::Mutex<HashMap<String, usize>>> { |
| 609 | asyncrt::services().websockets().regular_counts.clone() |
| 610 | } |
| 611 | pub(crate) fn increment_regular_ws(scope: &str) { |
| 612 | *regular_ws_counts() |
| 613 | .lock() |
| 614 | .unwrap() |
| 615 | .entry(scope.to_string()) |
| 616 | .or_default() += 1; |
| 617 | } |
| 618 | pub(crate) fn decrement_regular_ws(scope: &str) { |
| 619 | let counts = regular_ws_counts(); |
| 620 | let mut counts = counts.lock().unwrap(); |
| 621 | let Some(count) = counts.get_mut(scope) else { |
| 622 | return; |
| 623 | }; |
| 624 | *count = count.saturating_sub(1); |
| 625 | if *count == 0 { |
| 626 | counts.remove(scope); |
| 627 | } |
| 628 | } |
| 629 | pub fn has_regular_websocket(scope: &str) -> bool { |
| 630 | regular_ws_counts() |
| 631 | .lock() |
| 632 | .unwrap() |
| 633 | .get(scope) |
| 634 | .is_some_and(|count| *count > 0) |
| 635 | } |
| 636 | /// The auto-response pair per cell scope, set by |
| 637 | /// `state.setWebSocketAutoResponse`. Shell state, like the socket registry: |
| 638 | /// the whole point of the feature is answering a matched message while the |
| 639 | /// cell is not resident, so the isolate cannot hold it. |
| 640 | pub(crate) fn ws_auto_responses() -> Arc<std::sync::Mutex<HashMap<String, (String, String)>>> { |
| 641 | asyncrt::services().websockets().auto_responses.clone() |
| 642 | } |
| 643 | |
| 644 | /// The shell's read path asks here before dispatching a text frame. A match |
| 645 | /// returns the response to send on the same socket and stamps the socket's |
| 646 | /// timestamp; the frame then never reaches the cell — no dispatch, no wake. |
| 647 | /// Only hibernatable sockets participate, as in workerd, where matching |
| 648 | /// lives in the hibernation manager's read loop. |
| 649 | pub fn ws_auto_response(scope: &str, id: u64, text: &str) -> Option<String> { |
| 650 | let response = { |
| 651 | let pairs = ws_auto_responses(); |
| 652 | let pairs = pairs.lock().unwrap(); |
| 653 | let (request, response) = pairs.get(scope)?; |
| 654 | if request != text { |
| 655 | return None; |
| 656 | } |
| 657 | response.clone() |
| 658 | }; |
| 659 | let registry = ws_registry(); |
| 660 | let mut registry = registry.lock().unwrap(); |
| 661 | let meta = registry.metadata.get_mut(&id)?; |
| 662 | if !meta.hibernatable { |
| 663 | return None; |
| 664 | } |
| 665 | meta.auto_response_at = Some(unix_ms()); |
| 666 | Some(response) |
| 667 | } |
| 668 | |
| 669 | fn unix_ms() -> f64 { |
| 670 | asyncrt::wall_ms() as f64 |
| 671 | } |
| 672 | |
| 673 | /// Mark a socket as accepted by the facet `scope`, so its events reach the |
| 674 | /// facet through `facet.root`. A socket that `scope` did not accept keeps its |
| 675 | /// own route: a facet can return a socket that another cell accepted. |
| 676 | pub(crate) fn ws_attach_facet(id: u64, scope: &str, facet: FacetSocket) { |
| 677 | if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) { |
| 678 | if meta.scope == scope { |
| 679 | meta.facet = Some(facet); |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// The facet route of a socket, when a facet accepted it. |
| 685 | pub fn ws_facet(id: u64) -> Option<FacetSocket> { |
| 686 | ws_registry() |
| 687 | .lock() |
| 688 | .unwrap() |
| 689 | .metadata |
| 690 | .get(&id) |
| 691 | .and_then(|meta| meta.facet.clone()) |
| 692 | } |
| 693 | |
| 694 | /// The cell the core holds `target` under, and whether that registration can |
| 695 | /// hibernate. |
| 696 | /// |
| 697 | /// A facet's socket registers under its root, as a socket that cannot |
| 698 | /// hibernate. A root that hibernated would close its facets, and nothing can |
| 699 | /// restart a facet without the root's code: the class came from the root's |
| 700 | /// startup callback. The socket therefore keeps the root resident, as a |
| 701 | /// regular socket does. |
| 702 | pub fn ws_core_registration(target: &WsTarget) -> (String, bool) { |
| 703 | let registry = ws_registry(); |
| 704 | let registry = registry.lock().unwrap(); |
| 705 | match registry.metadata.get(&target.id) { |
| 706 | Some(WsMeta { |
| 707 | facet: Some(facet), .. |
| 708 | }) => (facet.root.clone(), false), |
| 709 | meta => ( |
| 710 | target.scope.clone(), |
| 711 | meta.is_some_and(|meta| meta.hibernatable), |
| 712 | ), |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | /// Remove the registration of a socket that the facet `scope` accepted for a |
| 717 | /// response that never left. No socket task exists for it, so nothing else |
| 718 | /// would remove it. |
| 719 | pub(crate) fn ws_release_unanswered(id: u64, scope: &str) { |
| 720 | let accepted = ws_registry() |
| 721 | .lock() |
| 722 | .unwrap() |
| 723 | .metadata |
| 724 | .get(&id) |
| 725 | .is_some_and(|meta| meta.scope == scope); |
| 726 | if accepted { |
| 727 | ws_unregister(id); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | /// Register a socket that a facet accepted, through a cfg-gated execution |
| 732 | /// backend that has no facet call to record it. |
| 733 | #[cfg(celld_internal_tests)] |
| 734 | #[doc(hidden)] |
| 735 | pub fn ws_register_facet_for_test( |
| 736 | id: u64, |
| 737 | scope: &str, |
| 738 | facet: FacetSocket, |
| 739 | tx: tokio::sync::mpsc::UnboundedSender<WsOut>, |
| 740 | ) { |
| 741 | ws_register_hibernatable_for_test(id, scope, tx); |
| 742 | ws_attach_facet(id, scope, facet); |
| 743 | } |
| 744 | |
| 745 | pub fn ws_next_id() -> u64 { |
| 746 | asyncrt::services() |
| 747 | .websockets() |
| 748 | .next_id |
| 749 | .fetch_add(1, Ordering::Relaxed) |
| 750 | } |
| 751 | pub fn ws_register(id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) { |
| 752 | ws_registry().lock().unwrap().register(id, tx); |
| 753 | } |
| 754 | |
| 755 | /// Install one hibernatable socket through a cfg-gated execution backend. |
| 756 | #[cfg(celld_internal_tests)] |
| 757 | pub(crate) fn ws_register_hibernatable_for_test( |
| 758 | id: u64, |
| 759 | scope: &str, |
| 760 | tx: tokio::sync::mpsc::UnboundedSender<WsOut>, |
| 761 | ) { |
| 762 | let registry = ws_registry(); |
| 763 | let mut registry = registry.lock().unwrap(); |
| 764 | registry.register(id, tx); |
| 765 | registry.metadata.insert( |
| 766 | id, |
| 767 | WsMeta { |
| 768 | scope: scope.to_string(), |
| 769 | hibernatable: true, |
| 770 | tags: Vec::new(), |
| 771 | attachment: None, |
| 772 | pending: Vec::new(), |
| 773 | auto_response_at: None, |
| 774 | facet: None, |
| 775 | }, |
| 776 | ); |
| 777 | } |
| 778 | /// Register an outbound socket of `scope`. A socket that a facet opened |
| 779 | /// takes its facet record in the same insertion, so no event, close, or |
| 780 | /// `ws_close_facet` can find the entry without it. |
| 781 | pub fn ws_register_outbound(id: u64, scope: &str, facet: Option<FacetSocket>) { |
| 782 | let inserted = { |
| 783 | let registry = ws_registry(); |
| 784 | let mut registry = registry.lock().unwrap(); |
| 785 | if let std::collections::hash_map::Entry::Vacant(entry) = registry.metadata.entry(id) { |
| 786 | entry.insert(WsMeta { |
| 787 | scope: scope.to_string(), |
| 788 | hibernatable: false, |
| 789 | tags: Vec::new(), |
| 790 | attachment: None, |
| 791 | pending: Vec::new(), |
| 792 | auto_response_at: None, |
| 793 | facet, |
| 794 | }); |
| 795 | true |
| 796 | } else { |
| 797 | false |
| 798 | } |
| 799 | }; |
| 800 | if inserted { |
| 801 | increment_regular_ws(scope); |
| 802 | } |
| 803 | } |
| 804 | pub fn ws_unregister(id: u64) { |
| 805 | let meta = ws_registry().lock().unwrap().unregister(id); |
| 806 | if let Some(meta) = meta.filter(|meta| !meta.hibernatable) { |
| 807 | decrement_regular_ws(&meta.scope); |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | /// Which channel a frame on this socket leaves by. |
| 812 | /// |
| 813 | /// A hibernatable transport is `WsHibernatable`: the host pushes its messages |
| 814 | /// into the cell and captures what the handler emits. A turn the handler |
| 815 | /// suspends in releases its own batch on a ticket of its own, and the turn the |
| 816 | /// handler answers in releases its batch from the cell's barrier queue. |
| 817 | /// |
| 818 | /// A socket the isolate opened and polls itself is `WsSelf`, and the two are |
| 819 | /// separate channels in the model for a concrete reason. That handler runs |
| 820 | /// inside the isolate's event loop, and that loop is what a captured frame |
| 821 | /// would be waiting on: the reply to a frame the gate is withholding never |
| 822 | /// arrives, so the loop never finishes, so the frame is never released. It |
| 823 | /// takes a durability ticket on the host runtime instead, which is a different |
| 824 | /// way of being held rather than not being held at all. |
| 825 | pub(crate) fn ws_channel(id: u64) -> celld_logic::Channel { |
| 826 | let registry = ws_registry(); |
| 827 | let registry = registry.lock().unwrap(); |
| 828 | if registry |
| 829 | .metadata |
| 830 | .get(&id) |
| 831 | .is_some_and(|meta| meta.hibernatable) |
| 832 | { |
| 833 | celld_logic::Channel::WsHibernatable |
| 834 | } else { |
| 835 | celld_logic::Channel::WsSelf |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | /// The frames of one flush inside a socket's ordered queue. |
| 840 | /// |
| 841 | /// A segment rather than a flat list of frames, because every flush holds a |
| 842 | /// gate ticket of its own. A later flush's frames can trail a write that an |
| 843 | /// earlier flush's ticket does not cover, so releasing a socket's whole queue |
| 844 | /// on the earlier verdict would send them before their own proof arrived. The |
| 845 | /// queue therefore drains its settled prefix and stops. |
| 846 | struct WsSegment { |
| 847 | /// Names this segment to the flush that owns it. The position in the |
| 848 | /// queue cannot: an earlier segment can drain first and move it. |
| 849 | token: u64, |
| 850 | frames: Vec<WsOut>, |
| 851 | /// What the gate answered for this segment, once its flush has an answer. |
| 852 | /// A segment with no owning flush carries `Ok` from the start: the frames |
| 853 | /// are already released and only wait for the order in front of them. |
| 854 | settled: Option<Result<(), String>>, |
| 855 | } |
| 856 | |
| 857 | /// The frames one instance holds behind its output gates, and the flushes |
| 858 | /// that own them. |
| 859 | /// |
| 860 | /// The fields are one invariant, so they are one value: a socket has a queue |
| 861 | /// exactly while the flushes counted in `flushes` will drain it, and a count |
| 862 | /// that falls must notify `done`. Held together, no caller can take the queue |
| 863 | /// of one instance of the services and the count of another. |
| 864 | #[derive(Default)] |
| 865 | pub(crate) struct WsFlushState { |
| 866 | /// Frames held back because the handler that produced them has written |
| 867 | /// something not yet durable, one queue of segments per socket. |
| 868 | /// |
| 869 | /// Every later frame for a socket that already holds frames joins the |
| 870 | /// queue rather than overtaking it: a socket's frames must arrive in the |
| 871 | /// order the script sent them. Ordering is a property of one socket, |
| 872 | /// which is what the key says. |
| 873 | /// |
| 874 | /// Owned by the services, not by a thread. It is filled inside the |
| 875 | /// isolate and drained by an op, and an op runs on the host runtime — so |
| 876 | /// a thread-local queue was filled on one thread and taken, empty, on |
| 877 | /// another. The frames never left the process, and because the queue |
| 878 | /// stayed non-empty every later frame joined them. |
| 879 | deferred: std::sync::Mutex<HashMap<u64, std::collections::VecDeque<WsSegment>>>, |
| 880 | /// How many flushes still hold frames for a socket. A count, not a flag: |
| 881 | /// one flush can finish and drain its segment while a later frame starts |
| 882 | /// another. |
| 883 | flushes: std::sync::Mutex<HashMap<u64, usize>>, |
| 884 | /// Names the next segment. Monotonic within one instance's services, so |
| 885 | /// a token identifies a segment for as long as any flush can name it. |
| 886 | next_token: AtomicU64, |
| 887 | done: tokio::sync::Notify, |
| 888 | } |
| 889 | |
| 890 | impl WsFlushState { |
| 891 | /// Send `frames` on their sockets, or hold each behind its socket's gate. |
| 892 | /// |
| 893 | /// One call is one flush: every socket the batch touches takes at most |
| 894 | /// one segment, so a broadcast that one gate ticket covers costs one |
| 895 | /// ticket rather than one for each client. |
| 896 | /// |
| 897 | /// `gated` is the core's answer for this batch's event. A socket that |
| 898 | /// already holds frames joins them whatever that answer is, so a later |
| 899 | /// frame cannot overtake an earlier one. An ungated batch therefore joins |
| 900 | /// as a segment that is settled from the start, and a gated one joins as |
| 901 | /// a segment this flush must release. |
| 902 | /// |
| 903 | /// Returns the guard for the flush this batch started, and only then, so |
| 904 | /// the caller cannot leave a held segment with no flush behind it and |
| 905 | /// cannot await a gate that holds nothing. The counts are taken while the |
| 906 | /// queue lock is held: a teardown that reads them must not observe a |
| 907 | /// queued frame with no flush behind it. |
| 908 | pub(crate) fn emit_or_defer( |
| 909 | self: &Arc<Self>, |
| 910 | registry: &std::sync::Mutex<WsRegistry>, |
| 911 | frames: impl IntoIterator<Item = (u64, WsOut)>, |
| 912 | gated: bool, |
| 913 | ) -> Option<WsFlushGuard> { |
| 914 | // Held until every frame is either queued or sent. A flush runs on |
| 915 | // another thread, so releasing between the check and the send would |
| 916 | // let it drain its queue in between, putting a later frame ahead of |
| 917 | // an earlier one. |
| 918 | let mut deferred = self.deferred.lock().unwrap(); |
| 919 | let mut direct = Vec::new(); |
| 920 | let mut mine = std::collections::HashSet::new(); |
| 921 | let mut segments = Vec::new(); |
| 922 | for (id, out) in frames { |
| 923 | if mine.contains(&id) { |
| 924 | deferred |
| 925 | .get_mut(&id) |
| 926 | .and_then(std::collections::VecDeque::back_mut) |
| 927 | .expect("a socket this batch queued still holds its segment") |
| 928 | .frames |
| 929 | .push(out); |
| 930 | continue; |
| 931 | } |
| 932 | let token = self.next_token.fetch_add(1, Ordering::Relaxed); |
| 933 | match deferred.entry(id) { |
| 934 | std::collections::hash_map::Entry::Vacant(_) if !gated => direct.push((id, out)), |
| 935 | entry => { |
| 936 | entry.or_default().push_back(WsSegment { |
| 937 | token, |
| 938 | frames: vec![out], |
| 939 | settled: (!gated).then_some(Ok(())), |
| 940 | }); |
| 941 | mine.insert(id); |
| 942 | if gated { |
| 943 | segments.push((id, token)); |
| 944 | } |
| 945 | } |
| 946 | } |
| 947 | } |
| 948 | let flushing = (!segments.is_empty()).then(|| { |
| 949 | let mut flushes = self.flushes.lock().unwrap(); |
| 950 | for (id, _) in &segments { |
| 951 | *flushes.entry(*id).or_default() += 1; |
| 952 | } |
| 953 | drop(flushes); |
| 954 | WsFlushGuard { |
| 955 | state: self.clone(), |
| 956 | segments, |
| 957 | } |
| 958 | }); |
| 959 | // Still under the queue lock: a frame this batch sends directly has |
| 960 | // no queue on its socket, and a flush that acquired the lock first |
| 961 | // cannot install one between the check above and this send. |
| 962 | emit_frames(registry, direct); |
| 963 | flushing |
| 964 | } |
| 965 | |
| 966 | /// Reserve one captured frame's place in its socket's queue, inside the |
| 967 | /// batch's single flush. |
| 968 | /// |
| 969 | /// The frame joins the flush's own segment while that segment is still |
| 970 | /// the socket's tail, so a handler that sends many frames, or broadcasts |
| 971 | /// one frame to many sockets, holds one segment per socket, as a batch |
| 972 | /// through `emit_or_defer` does. A segment for each frame would cost a |
| 973 | /// queue lock, a count, and a waiter wake-up for each frame at release. |
| 974 | /// A frame that another event queued in between ends that segment, and |
| 975 | /// this frame opens a new one behind it, so send order still holds. |
| 976 | fn capture( |
| 977 | self: &Arc<Self>, |
| 978 | flush: &mut Option<WsFlushGuard>, |
| 979 | tails: &mut HashMap<u64, u64>, |
| 980 | id: u64, |
| 981 | out: WsOut, |
| 982 | ) { |
| 983 | // One queue lock covers the tail check and the count, as in |
| 984 | // `emit_or_defer`: a teardown must not observe a queued frame with no |
| 985 | // flush behind it. |
| 986 | let mut deferred = self.deferred.lock().unwrap(); |
| 987 | let queue = deferred.entry(id).or_default(); |
| 988 | let own_tail = tails |
| 989 | .get(&id) |
| 990 | .and_then(|token| queue.back_mut().filter(|segment| segment.token == *token)); |
| 991 | if let Some(segment) = own_tail { |
| 992 | segment.frames.push(out); |
| 993 | return; |
| 994 | } |
| 995 | let token = self.next_token.fetch_add(1, Ordering::Relaxed); |
| 996 | queue.push_back(WsSegment { |
| 997 | token, |
| 998 | frames: vec![out], |
| 999 | settled: None, |
| 1000 | }); |
| 1001 | *self.flushes.lock().unwrap().entry(id).or_default() += 1; |
| 1002 | tails.insert(id, token); |
| 1003 | flush |
| 1004 | .get_or_insert_with(|| WsFlushGuard { |
| 1005 | state: self.clone(), |
| 1006 | segments: Vec::new(), |
| 1007 | }) |
| 1008 | .segments |
| 1009 | .push((id, token)); |
| 1010 | } |
| 1011 | |
| 1012 | /// Wait until no flush holds frames for `id` any more. |
| 1013 | async fn await_flushes(&self, id: u64) { |
| 1014 | loop { |
| 1015 | // Registered before the count is read. A flush that finishes in |
| 1016 | // between must find a waiter to wake, or this parks forever on a |
| 1017 | // notification that already happened. |
| 1018 | let notified = self.done.notified(); |
| 1019 | tokio::pin!(notified); |
| 1020 | notified.as_mut().enable(); |
| 1021 | if !self.flushes.lock().unwrap().contains_key(&id) { |
| 1022 | return; |
| 1023 | } |
| 1024 | notified.await; |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | /// Wait until no flush of this instance still owns deferred frames. |
| 1029 | async fn await_all_flushes(&self) { |
| 1030 | loop { |
| 1031 | // Register before observing the map, exactly as the per-socket |
| 1032 | // wait does. The final guard can otherwise notify between the |
| 1033 | // empty check and waiter registration, leaving shutdown parked |
| 1034 | // forever. |
| 1035 | let notified = self.done.notified(); |
| 1036 | tokio::pin!(notified); |
| 1037 | notified.as_mut().enable(); |
| 1038 | if self.flushes.lock().unwrap().is_empty() { |
| 1039 | return; |
| 1040 | } |
| 1041 | notified.await; |
| 1042 | } |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | /// The flush state of the services the caller runs under. |
| 1047 | /// |
| 1048 | /// A flush task outlives the dispatch that spawned it and runs on a runtime |
| 1049 | /// with no services of its own, so every caller that hands work to one |
| 1050 | /// resolves the state here first and moves it in. Resolving inside the task |
| 1051 | /// would answer from whichever instance that runtime reaches, which is the |
| 1052 | /// process-wide sharing this state exists to end. |
| 1053 | pub(crate) fn ws_flush_state() -> Arc<WsFlushState> { |
| 1054 | asyncrt::services().websockets().flush.clone() |
| 1055 | } |
| 1056 | |
| 1057 | /// One held segment and the flush that owns it, for a test that stands in for |
| 1058 | /// the durability ticket. Holding the guard is what keeps the socket's |
| 1059 | /// teardown wait honest while the queue exists. |
| 1060 | #[cfg(celld_internal_tests)] |
| 1061 | #[doc(hidden)] |
| 1062 | pub struct WsHeldFlush(WsFlushGuard); |
| 1063 | |
| 1064 | /// Hold `out` behind `id`'s gate exactly as a gated frame does, and return |
| 1065 | /// the flush that holds it. |
| 1066 | #[cfg(celld_internal_tests)] |
| 1067 | #[doc(hidden)] |
| 1068 | pub fn ws_defer_frame(id: u64, out: WsOut) -> WsHeldFlush { |
| 1069 | let flush = ws_flush_state(); |
| 1070 | let registry = ws_registry(); |
| 1071 | WsHeldFlush( |
| 1072 | flush |
| 1073 | .emit_or_defer(®istry, std::iter::once((id, out)), true) |
| 1074 | .expect("a gated frame always opens a segment of its own"), |
| 1075 | ) |
| 1076 | } |
| 1077 | |
| 1078 | /// How many frames this instance holds for `id`. |
| 1079 | #[cfg(celld_internal_tests)] |
| 1080 | #[doc(hidden)] |
| 1081 | pub fn ws_deferred_count(id: u64) -> usize { |
| 1082 | ws_flush_state() |
| 1083 | .deferred |
| 1084 | .lock() |
| 1085 | .unwrap() |
| 1086 | .get(&id) |
| 1087 | .map_or(0, |queue| { |
| 1088 | queue.iter().map(|segment| segment.frames.len()).sum() |
| 1089 | }) |
| 1090 | } |
| 1091 | |
| 1092 | /// Release a held flush as a settled durability ticket does, then count it |
| 1093 | /// out. Consuming the guard is what makes the two happen together. |
| 1094 | #[cfg(celld_internal_tests)] |
| 1095 | #[doc(hidden)] |
| 1096 | pub fn ws_release_flush(held: WsHeldFlush) { |
| 1097 | let registry = ws_registry(); |
| 1098 | held.0.release(®istry, Ok(())); |
| 1099 | } |
| 1100 | |
| 1101 | /// Answer a held flush as a refused durability ticket does. |
| 1102 | #[cfg(celld_internal_tests)] |
| 1103 | #[doc(hidden)] |
| 1104 | pub fn ws_refuse_flush(held: WsHeldFlush) { |
| 1105 | let registry = ws_registry(); |
| 1106 | held.0 |
| 1107 | .release(®istry, Err("refused for a test".to_string())); |
| 1108 | } |
| 1109 | |
| 1110 | /// The segments one flush holds, and the counts that name it to a teardown. |
| 1111 | /// |
| 1112 | /// The two travel together because either alone is wrong: a segment with no |
| 1113 | /// count lets a socket tear down over frames that have not left, and a count |
| 1114 | /// with no segment parks that teardown forever. |
| 1115 | /// |
| 1116 | /// The guard counts itself out on every exit path, including the ones that |
| 1117 | /// run no code: a flush spawned onto a runtime that is already shutting down |
| 1118 | /// is dropped unpolled, and a panic unwinds through it. It cannot help a |
| 1119 | /// flush that is merely parked -- nothing drops, so nothing runs -- which is |
| 1120 | /// what the teardown wait is bounded for. |
| 1121 | /// |
| 1122 | /// It carries the state rather than resolving it on drop, because the drop |
| 1123 | /// can run on a runtime that answers with another instance, or with none. |
| 1124 | pub(crate) struct WsFlushGuard { |
| 1125 | state: Arc<WsFlushState>, |
| 1126 | /// The segment this flush owns on each socket the batch reached, as |
| 1127 | /// (socket, token). |
| 1128 | segments: Vec<(u64, u64)>, |
| 1129 | } |
| 1130 | |
| 1131 | impl WsFlushGuard { |
| 1132 | fn discard(self, registry: &std::sync::Mutex<WsRegistry>) { |
| 1133 | { |
| 1134 | let mut deferred = self.state.deferred.lock().unwrap(); |
| 1135 | for (id, token) in &self.segments { |
| 1136 | if let Some(segment) = deferred |
| 1137 | .get_mut(id) |
| 1138 | .and_then(|queue| queue.iter_mut().find(|segment| segment.token == *token)) |
| 1139 | { |
| 1140 | segment.frames.clear(); |
| 1141 | } |
| 1142 | } |
| 1143 | } |
| 1144 | self.release(registry, Ok(())); |
| 1145 | } |
| 1146 | |
| 1147 | /// Give the gate's verdict to every segment this flush holds, then |
| 1148 | /// deliver what each socket can now release. |
| 1149 | /// |
| 1150 | /// `held` is what the gate answered. `Err` means the frames describe a |
| 1151 | /// write the fleet may never have, so they must not be delivered. |
| 1152 | /// Dropping them and leaving the socket open is not an option -- a |
| 1153 | /// WebSocket is an ordered stream, and a peer cannot see a hole in one. |
| 1154 | /// It would read the frames on either side of the gap as consecutive. |
| 1155 | /// |
| 1156 | /// Close instead. A truncated stream is something the peer can detect and |
| 1157 | /// resynchronise from; a silently incomplete one is not. The cell is |
| 1158 | /// reset underneath this as well, but that is a separate path and this |
| 1159 | /// must not depend on its timing. |
| 1160 | /// |
| 1161 | /// Takes the guard by value, so the count this flush holds falls once its |
| 1162 | /// frames have left and never before. |
| 1163 | pub(crate) fn release(self, registry: &std::sync::Mutex<WsRegistry>, held: Result<(), String>) { |
| 1164 | // Keep the lock from the verdict through the registry send. Once a |
| 1165 | // queue is drained away, another release would otherwise look direct |
| 1166 | // and overtake these frames. |
| 1167 | let mut deferred = self.state.deferred.lock().unwrap(); |
| 1168 | let mut sending = Vec::new(); |
| 1169 | for (id, token) in &self.segments { |
| 1170 | if let Some(segment) = deferred |
| 1171 | .get_mut(id) |
| 1172 | .and_then(|queue| queue.iter_mut().find(|segment| segment.token == *token)) |
| 1173 | { |
| 1174 | segment.settled = Some(held.clone()); |
| 1175 | } |
| 1176 | drain_settled(&mut deferred, *id, &mut sending); |
| 1177 | } |
| 1178 | emit_frames(registry, sending); |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | /// Take the frames a socket's queue can release: every segment up to the |
| 1183 | /// first one whose gate has not answered. |
| 1184 | /// |
| 1185 | /// A segment the gate refused ends the socket instead. Everything queued |
| 1186 | /// behind it trails the same unproven write, so it is dropped with the |
| 1187 | /// segment rather than sent as though the gap were not there. |
| 1188 | fn drain_settled( |
| 1189 | deferred: &mut HashMap<u64, std::collections::VecDeque<WsSegment>>, |
| 1190 | id: u64, |
| 1191 | sending: &mut Vec<(u64, WsOut)>, |
| 1192 | ) { |
| 1193 | let Some(queue) = deferred.get_mut(&id) else { |
| 1194 | return; |
| 1195 | }; |
| 1196 | let mut refused = false; |
| 1197 | while let Some(segment) = queue.front() { |
| 1198 | match &segment.settled { |
| 1199 | None => break, |
| 1200 | Some(Err(_)) => { |
| 1201 | refused = true; |
| 1202 | break; |
| 1203 | } |
| 1204 | Some(Ok(())) => { |
| 1205 | let segment = queue.pop_front().expect("the front segment is present"); |
| 1206 | sending.extend(segment.frames.into_iter().map(|frame| (id, frame))); |
| 1207 | } |
| 1208 | } |
| 1209 | } |
| 1210 | if refused { |
| 1211 | deferred.remove(&id); |
| 1212 | sending.push(( |
| 1213 | id, |
| 1214 | WsOut::Close( |
| 1215 | 1011, |
| 1216 | "celld could not prove the write behind this message durable".to_string(), |
| 1217 | ), |
| 1218 | )); |
| 1219 | } else if queue.is_empty() { |
| 1220 | deferred.remove(&id); |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | impl Drop for WsFlushGuard { |
| 1225 | fn drop(&mut self) { |
| 1226 | { |
| 1227 | let mut flushes = self.state.flushes.lock().unwrap(); |
| 1228 | for (id, _) in &self.segments { |
| 1229 | let Some(count) = flushes.get_mut(id) else { |
| 1230 | continue; |
| 1231 | }; |
| 1232 | *count -= 1; |
| 1233 | if *count == 0 { |
| 1234 | flushes.remove(id); |
| 1235 | } |
| 1236 | } |
| 1237 | } |
| 1238 | self.state.done.notify_waiters(); |
| 1239 | } |
| 1240 | } |
| 1241 | |
| 1242 | /// Wait until no flush holds frames for `id` any more. |
| 1243 | /// |
| 1244 | /// The socket's own teardown calls this. Closing reads the handler's output |
| 1245 | /// with a non-blocking drain and, finding none, answers the peer with the |
| 1246 | /// protocol echo of the close the peer itself sent -- so a close frame still |
| 1247 | /// behind the gate is not merely late, it is replaced. The wait is bounded by |
| 1248 | /// the gate: a cell with no barrier answers at once, a barrier settles when |
| 1249 | /// its proof does, and an unprovable one still resolves the flush through its |
| 1250 | /// fail-closed arm. |
| 1251 | pub async fn ws_await_flushes(id: u64) { |
| 1252 | ws_flush_state().await_flushes(id).await; |
| 1253 | } |
| 1254 | |
| 1255 | /// Wait until no WebSocket flush of these services still owns deferred |
| 1256 | /// frames. |
| 1257 | /// |
| 1258 | /// Shutdown calls this after the cell handoff has settled every output gate |
| 1259 | /// and before connection tasks can unregister their sockets. Waiting per |
| 1260 | /// socket cannot enforce that ordering because socket teardown deliberately |
| 1261 | /// skips its gate wait once the node is draining. |
| 1262 | #[doc(hidden)] |
| 1263 | pub async fn ws_await_all_flushes() { |
| 1264 | ws_flush_state().await_all_flushes().await; |
| 1265 | } |
| 1266 | |
| 1267 | /// Hand frames that cross no queue to the registry, under one lock. |
| 1268 | /// |
| 1269 | /// The registry is a parameter rather than a lookup: a flush runs on a |
| 1270 | /// runtime with no services of its own, so it must send to the instance that |
| 1271 | /// owns the socket instead of to whichever instance that runtime reaches. |
| 1272 | fn emit_frames( |
| 1273 | registry: &std::sync::Mutex<WsRegistry>, |
| 1274 | frames: impl IntoIterator<Item = (u64, WsOut)>, |
| 1275 | ) { |
| 1276 | let mut frames = frames.into_iter().peekable(); |
| 1277 | if frames.peek().is_none() { |
| 1278 | return; |
| 1279 | } |
| 1280 | let mut registry = registry.lock().unwrap(); |
| 1281 | for (id, out) in frames { |
| 1282 | registry.emit(id, out); |
| 1283 | } |
| 1284 | } |
| 1285 | |
| 1286 | /// Release a batch into each socket's ordered stream. A socket whose |
| 1287 | /// durability-ticket queue is still present joins that queue, so an Actor |
| 1288 | /// barrier release cannot overtake an earlier frame on the same socket. |
| 1289 | pub fn ws_emit_batch(frames: impl Into<WsBatch>) { |
| 1290 | frames.into().release(Ok(())); |
| 1291 | } |
| 1292 | |
| 1293 | /// Close one socket. A forced generation swap closes the regular and |
| 1294 | /// outbound sockets that pin a cell to its old isolate and nothing else: the |
| 1295 | /// cell stays on this node, so its hibernatable sockets and auto-response |
| 1296 | /// pair survive, which `ws_close_scope` would take with it. |
| 1297 | pub fn ws_close(id: u64, code: u16, reason: &str) { |
| 1298 | ws_registry() |
| 1299 | .lock() |
| 1300 | .unwrap() |
| 1301 | .emit(id, WsOut::Close(code, reason.to_string())); |
| 1302 | } |
| 1303 | |
| 1304 | /// Break a cell's sockets: the output gate could not prove a write durable, so |
| 1305 | /// close every socket the cell owns rather than let a client keep a connection |
| 1306 | /// whose acknowledged effects may not have persisted (a reset DO). |
| 1307 | /// |
| 1308 | /// The sockets of the cell's facets close too. A facet's writes trail the |
| 1309 | /// root cell's gate, and the facet does not outlive its root. |
| 1310 | pub fn ws_close_scope(scope: &str, code: u16, reason: &str) { |
| 1311 | let mut scopes = vec![scope.to_string()]; |
| 1312 | { |
| 1313 | let registry = ws_registry(); |
| 1314 | let mut registry = registry.lock().unwrap(); |
| 1315 | let ids: Vec<u64> = registry |
| 1316 | .metadata |
| 1317 | .iter() |
| 1318 | .filter(|(_, meta)| { |
| 1319 | let facet_of_scope = meta.facet.as_ref().is_some_and(|facet| facet.root == scope); |
| 1320 | if facet_of_scope && !scopes.contains(&meta.scope) { |
| 1321 | scopes.push(meta.scope.clone()); |
| 1322 | } |
| 1323 | meta.scope == scope || facet_of_scope |
| 1324 | }) |
| 1325 | .map(|(id, _)| *id) |
| 1326 | .collect(); |
| 1327 | for id in ids { |
| 1328 | registry.emit(id, WsOut::Close(code, reason.to_string())); |
| 1329 | } |
| 1330 | } |
| 1331 | // A reset cell is a new actor; workerd's hibernation manager dies with |
| 1332 | // the old one and takes the auto-response pair with it. |
| 1333 | let pairs = ws_auto_responses(); |
| 1334 | let mut pairs = pairs.lock().unwrap(); |
| 1335 | for scope in &scopes { |
| 1336 | pairs.remove(scope); |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | /// Close the sockets of a facet that stopped: an abort, a delete, or its |
| 1341 | /// root's give-back. |
| 1342 | /// |
| 1343 | /// No later event can reach the facet, and a facet restarted under the same |
| 1344 | /// name is a new actor that never accepted these sockets. Leaving them open |
| 1345 | /// would accept frames that no handler can receive. 1001 is the code for an |
| 1346 | /// endpoint that is going away. |
| 1347 | pub(crate) fn ws_close_facet(scope: &str, reason: &str) { |
| 1348 | ws_auto_responses().lock().unwrap().remove(scope); |
| 1349 | let registry = ws_registry(); |
| 1350 | let mut registry = registry.lock().unwrap(); |
| 1351 | let ids: Vec<u64> = registry |
| 1352 | .metadata |
| 1353 | .iter() |
| 1354 | .filter(|(_, meta)| meta.scope == scope && meta.facet.is_some()) |
| 1355 | .map(|(id, _)| *id) |
| 1356 | .collect(); |
| 1357 | for id in ids { |
| 1358 | registry.emit(id, WsOut::Close(1001, reason.to_string())); |
| 1359 | } |
| 1360 | } |