| 1 | // Copyright 2026 Deno Land Inc. All rights reserved. |
| 2 | |
| 3 | //! The peer tunnel: an upgraded stream per peer, plain HTTP inside. |
| 4 | //! |
| 5 | //! Establishment is an h1 upgrade on `/peer/tunnel` — CONNECT semantics with Upgrade |
| 6 | //! mechanics, because CONNECT's authority-form target fits this use badly. |
| 7 | //! After the 101 the connection is an opaque duplex stream, and app requests |
| 8 | //! cross as literal HTTP driven by hyper on both ends: the hop never |
| 9 | //! interprets the inner bytes, so the headers the cell must receive |
| 10 | //! byte-faithful (`Host`, `Content-Length`, `Upgrade`) are data here, not |
| 11 | //! metadata. Per-call control (scope, cell name, request id, capacity |
| 12 | //! handoff) rides `x-cells-*` headers on the inner request; node A overwrites |
| 13 | //! and node B strips them, so the reserved names cannot be smuggled by an |
| 14 | //! application in either direction. |
| 15 | //! |
| 16 | //! Idle tunnels are pooled per peer and reused for sequential calls — plain |
| 17 | //! h1 keep-alive inside the tunnel, never multiplexing. Without reuse every |
| 18 | //! call is a fresh TCP connection, and a loopback-speed caller saturates the |
| 19 | //! whole ephemeral-port range into TIME_WAIT within seconds (~1k calls/s is |
| 20 | //! the hard OS ceiling), which the pooled transport this replaces never hit. |
| 21 | |
| 22 | use std::collections::HashMap; |
| 23 | use std::convert::Infallible; |
| 24 | |
| 25 | use bytes::Bytes; |
| 26 | use futures_util::StreamExt; |
| 27 | use futures_util::TryStreamExt; |
| 28 | use http_body_util::BodyExt; |
| 29 | use hyper::body::Body; |
| 30 | use hyper::body::Incoming; |
| 31 | use hyper::service::service_fn; |
| 32 | use hyper::Request; |
| 33 | use hyper::Response; |
| 34 | use hyper::StatusCode; |
| 35 | use hyper_util::rt::TokioIo; |
| 36 | |
| 37 | use super::*; |
| 38 | use celld::js::HttpChunkStream; |
| 39 | |
| 40 | pub(crate) const TUNNEL_PROTOCOL: &str = "celld-tunnel"; |
| 41 | pub(crate) const TUNNEL_VERSION: &str = "5"; |
| 42 | pub(crate) const VERSION_HEADER: &str = "x-cells-tunnel-version"; |
| 43 | pub(crate) const KIND_HEADER: &str = "x-cells-tunnel-kind"; |
| 44 | pub(crate) const SCOPE_HEADER: &str = "x-cells-scope"; |
| 45 | pub(crate) const NAME_HEADER: &str = "x-cells-do-name"; |
| 46 | pub(crate) const REQUEST_ID_HEADER: &str = "x-cells-request-id"; |
| 47 | pub(crate) const HANDOFF_HEADER: &str = "x-cells-capacity-handoff"; |
| 48 | |
| 49 | /// The inner headers node A owns. A overwrites them on the way in and B |
| 50 | /// strips them on the way out, so an application header with a reserved name |
| 51 | /// is dropped rather than obeyed. |
| 52 | const CONTROL_HEADERS: [&str; 4] = [SCOPE_HEADER, NAME_HEADER, REQUEST_ID_HEADER, HANDOFF_HEADER]; |
| 53 | |
| 54 | enum TunnelKind { |
| 55 | Do, |
| 56 | Rpc, |
| 57 | } |
| 58 | |
| 59 | /// The control fields of one tunneled call, carried as inner-request headers |
| 60 | /// so one tunnel can serve calls for any cell. |
| 61 | pub(crate) struct TunnelControl { |
| 62 | pub(crate) scope: String, |
| 63 | pub(crate) name: Option<String>, |
| 64 | pub(crate) request_id: Option<celld::js::RequestId>, |
| 65 | pub(crate) capacity_handoff: bool, |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn is_tunnel_request(request: &Request<Incoming>) -> bool { |
| 69 | request |
| 70 | .headers() |
| 71 | .get(hyper::header::UPGRADE) |
| 72 | .is_some_and(|value| value.as_bytes() == TUNNEL_PROTOCOL.as_bytes()) |
| 73 | } |
| 74 | |
| 75 | /// Node B: answer a tunnel establishment on `/peer/tunnel` with a 101 and serve the |
| 76 | /// inner connection until the peer closes it. |
| 77 | /// |
| 78 | /// The establishment carries the fleet HMAC and nothing after it does. The |
| 79 | /// signature gates who can open a tunnel — the inner calls it then carries |
| 80 | /// are cell dispatches, and a reserved-class dispatch must demand the fleet |
| 81 | /// secret on every path the way `/runtime/` does. The signature does not |
| 82 | /// authenticate the bytes after the 101 and does not encrypt anything; the |
| 83 | /// private network remains the boundary for both. |
| 84 | pub(crate) fn accept(mut request: Request<Incoming>, app: AppHandle) -> HttpReply { |
| 85 | let path_and_query = request |
| 86 | .uri() |
| 87 | .path_and_query() |
| 88 | .map_or_else(|| request.uri().path().to_string(), ToString::to_string); |
| 89 | if let Err(error) = app.peer_auth.verify( |
| 90 | request.method(), |
| 91 | &path_and_query, |
| 92 | request.headers(), |
| 93 | b"", |
| 94 | app.peer_auth.source(), |
| 95 | ) { |
| 96 | let mut denied = response(error.status(), error.message()); |
| 97 | // A wrong target means the dialer holds a stale lease for this |
| 98 | // address; the stale marker lets its redispatch invalidate the |
| 99 | // route instead of retrying the same dead name. |
| 100 | if matches!(error, peer_auth::VerifyError::WrongTarget) { |
| 101 | denied.headers_mut().insert( |
| 102 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 103 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 104 | ); |
| 105 | } |
| 106 | return peer_response(denied); |
| 107 | } |
| 108 | let headers = request.headers(); |
| 109 | if headers |
| 110 | .get(VERSION_HEADER) |
| 111 | .is_none_or(|value| value.as_bytes() != TUNNEL_VERSION.as_bytes()) |
| 112 | { |
| 113 | return peer_response(response( |
| 114 | StatusCode::UPGRADE_REQUIRED, |
| 115 | "peer tunnel version is incompatible", |
| 116 | )); |
| 117 | } |
| 118 | let kind = match headers |
| 119 | .get(KIND_HEADER) |
| 120 | .map(hyper::header::HeaderValue::as_bytes) |
| 121 | { |
| 122 | Some(b"do") => TunnelKind::Do, |
| 123 | Some(b"rpc") => TunnelKind::Rpc, |
| 124 | _ => { |
| 125 | return peer_response(response(StatusCode::BAD_REQUEST, "unknown tunnel kind")); |
| 126 | } |
| 127 | }; |
| 128 | let upgrade = hyper::upgrade::on(&mut request); |
| 129 | tokio::spawn(async move { |
| 130 | let upgraded = match upgrade.await { |
| 131 | Ok(upgraded) => upgraded, |
| 132 | Err(_) => return, |
| 133 | }; |
| 134 | match kind { |
| 135 | TunnelKind::Do => serve_do(upgraded, app).await, |
| 136 | TunnelKind::Rpc => serve_rpc(upgraded, app).await, |
| 137 | } |
| 138 | }); |
| 139 | let mut reply = response(StatusCode::SWITCHING_PROTOCOLS, ""); |
| 140 | reply.headers_mut().insert( |
| 141 | hyper::header::UPGRADE, |
| 142 | hyper::header::HeaderValue::from_static(TUNNEL_PROTOCOL), |
| 143 | ); |
| 144 | reply.headers_mut().insert( |
| 145 | hyper::header::CONNECTION, |
| 146 | hyper::header::HeaderValue::from_static("upgrade"), |
| 147 | ); |
| 148 | reply.headers_mut().insert( |
| 149 | hyper::header::HeaderName::from_static(VERSION_HEADER), |
| 150 | hyper::header::HeaderValue::from_static(TUNNEL_VERSION), |
| 151 | ); |
| 152 | peer_response(reply) |
| 153 | } |
| 154 | |
| 155 | /// One inner request, one call: parse the app request hyper already framed, |
| 156 | /// dispatch it exactly as the enveloped path did, and let the reply stream |
| 157 | /// back as an ordinary HTTP response. The connection serves calls until the |
| 158 | /// peer closes it or an inner upgrade consumes it. |
| 159 | async fn serve_do(upgraded: hyper::upgrade::Upgraded, app: AppHandle) { |
| 160 | let service = service_fn(move |mut inner: Request<Incoming>| { |
| 161 | let app = app.clone(); |
| 162 | async move { |
| 163 | let Some(scope) = inner |
| 164 | .headers() |
| 165 | .get(SCOPE_HEADER) |
| 166 | .and_then(|value| value.to_str().ok()) |
| 167 | .map(str::to_string) |
| 168 | .filter(|scope| celld_logic::cell::valid_cell_scope(scope)) |
| 169 | else { |
| 170 | return Ok::<_, Infallible>(peer_response(malformed_scope())); |
| 171 | }; |
| 172 | let control = TunnelControl { |
| 173 | scope, |
| 174 | name: inner |
| 175 | .headers() |
| 176 | .get(NAME_HEADER) |
| 177 | .and_then(|value| value.to_str().ok()) |
| 178 | .map(str::to_string), |
| 179 | request_id: inner |
| 180 | .headers() |
| 181 | .get(REQUEST_ID_HEADER) |
| 182 | .and_then(|value| value.to_str().ok()) |
| 183 | .and_then(celld::js::parse_request_id), |
| 184 | capacity_handoff: inner.headers().get(HANDOFF_HEADER).is_some(), |
| 185 | }; |
| 186 | // A tunneled upgrade is the client's own handshake, so the |
| 187 | // owner answers it directly: fastwebsockets computes the 101 |
| 188 | // for the client's key, and the inner connection becomes the |
| 189 | // socket the cell speaks — the same machinery a locally |
| 190 | // connected client gets. |
| 191 | let client_upgrade = if fastwebsockets::upgrade::is_upgrade_request(&inner) { |
| 192 | match fastwebsockets::upgrade::upgrade(&mut inner) { |
| 193 | Ok(pair) => Some(pair), |
| 194 | Err(error) => { |
| 195 | return Ok(peer_response(response( |
| 196 | StatusCode::BAD_REQUEST, |
| 197 | format!("tunneled upgrade: {error}"), |
| 198 | ))); |
| 199 | } |
| 200 | } |
| 201 | } else { |
| 202 | None |
| 203 | }; |
| 204 | let (parts, body) = inner.into_parts(); |
| 205 | let headers = parts |
| 206 | .headers |
| 207 | .iter() |
| 208 | .filter(|(name, _)| !CONTROL_HEADERS.contains(&name.as_str())) |
| 209 | .filter_map(|(name, value)| { |
| 210 | value |
| 211 | .to_str() |
| 212 | .ok() |
| 213 | .map(|value| (name.as_str().to_string(), value.to_string())) |
| 214 | }) |
| 215 | .collect(); |
| 216 | // Streaming by construction: the inner body is handed to the |
| 217 | // isolate as a stream whatever its size, bounded the way the |
| 218 | // enveloped path bounded its frame. |
| 219 | let limited = http_body_util::Limited::new(body, MAX_PEER_FORWARD_BODY_BYTES); |
| 220 | let chunks: HttpChunkStream = Box::pin( |
| 221 | http_body_util::BodyStream::new(limited) |
| 222 | .try_filter_map(|frame| async move { Ok(frame.into_data().ok()) }) |
| 223 | .map_ok(|data: Bytes| data.to_vec()) |
| 224 | .map_err(|error| error.to_string()), |
| 225 | ); |
| 226 | let stream_id = match celld::js::register_body_stream(chunks) { |
| 227 | Ok(stream_id) => stream_id, |
| 228 | Err(error) => { |
| 229 | return Ok(peer_response(response( |
| 230 | StatusCode::SERVICE_UNAVAILABLE, |
| 231 | format!("request body stream: {error}"), |
| 232 | ))); |
| 233 | } |
| 234 | }; |
| 235 | let body = celld::js::RequestBody::Stream(stream_id); |
| 236 | let fetch = ForwardedFetch { |
| 237 | name: control.name, |
| 238 | url: parts.uri.to_string(), |
| 239 | method: parts.method.to_string(), |
| 240 | headers, |
| 241 | request_id: control.request_id, |
| 242 | capacity_handoff: control.capacity_handoff, |
| 243 | }; |
| 244 | let outcome = dispatch_forwarded_fetch(app.clone(), control.scope, fetch, body).await; |
| 245 | let (target, worker_headers) = match outcome { |
| 246 | ForwardedFetchOutcome::Reply(reply) => return Ok(reply), |
| 247 | ForwardedFetchOutcome::WebSocket { target, headers } => (target, headers), |
| 248 | }; |
| 249 | let Some((accept, upgrade)) = client_upgrade else { |
| 250 | // `dispatch_forwarded_fetch` refuses a request without |
| 251 | // `Upgrade: websocket`, so this branch sees only a request |
| 252 | // that names the upgrade but is not a valid handshake. The |
| 253 | // socket is registered with the core by now, and the refusal |
| 254 | // must release it. |
| 255 | let refusal = super::websocket::refuse_websocket_without_upgrade( |
| 256 | &app, |
| 257 | HttpResponseWebSocket::Cell(target), |
| 258 | ) |
| 259 | .await; |
| 260 | return Ok(peer_response(refusal)); |
| 261 | }; |
| 262 | // The cell accepted: hand the inner stream to the same socket |
| 263 | // task a local client gets, and answer with the real 101. The |
| 264 | // Worker's application headers ride along; the sidecars and |
| 265 | // the hop framing die here. |
| 266 | tokio::spawn(async move { |
| 267 | match upgrade.await { |
| 268 | Ok(socket) => super::websocket::websocket_task(app, target, socket).await, |
| 269 | Err(error) => { |
| 270 | eprintln!("celld tunneled upgrade failed: {error}"); |
| 271 | } |
| 272 | } |
| 273 | }); |
| 274 | let (accept_parts, _) = accept.into_parts(); |
| 275 | let mut answer = Response::from_parts( |
| 276 | accept_parts, |
| 277 | BodyExt::boxed_unsync(http_body_util::Empty::new().map_err(|never| match never {})), |
| 278 | ); |
| 279 | for (name, value) in &worker_headers { |
| 280 | let lowered = name.to_ascii_lowercase(); |
| 281 | if lowered == "content-length" |
| 282 | || lowered == "upgrade" |
| 283 | || lowered == "connection" |
| 284 | || lowered == "sec-websocket-accept" |
| 285 | { |
| 286 | continue; |
| 287 | } |
| 288 | let Ok(name) = hyper::header::HeaderName::from_bytes(name.as_bytes()) else { |
| 289 | continue; |
| 290 | }; |
| 291 | let Ok(value) = hyper::header::HeaderValue::from_str(value) else { |
| 292 | continue; |
| 293 | }; |
| 294 | answer.headers_mut().append(name, value); |
| 295 | } |
| 296 | Ok(peer_response(answer)) |
| 297 | } |
| 298 | }); |
| 299 | let _ = hyper::server::conn::http1::Builder::new() |
| 300 | .serve_connection(upgraded, service) |
| 301 | .with_upgrades() |
| 302 | .await; |
| 303 | } |
| 304 | |
| 305 | type TunnelSender = hyper::client::conn::http1::SendRequest<TunnelBody>; |
| 306 | |
| 307 | /// The peer rejected the outer tunnel before an application request crossed |
| 308 | /// it. This is a definite stale route, so the caller can refresh ownership |
| 309 | /// without risking a duplicate handler invocation. |
| 310 | #[derive(Debug)] |
| 311 | pub(crate) struct StaleTunnelRoute; |
| 312 | |
| 313 | impl std::fmt::Display for StaleTunnelRoute { |
| 314 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 315 | formatter.write_str("peer rejected the stale tunnel route") |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | impl std::error::Error for StaleTunnelRoute {} |
| 320 | |
| 321 | /// Who node A dials and how it proves itself. One borrow carries the |
| 322 | /// client, the fleet key, and the routed peer's address and name through |
| 323 | /// an attempt. |
| 324 | pub(crate) struct Peer<'a> { |
| 325 | pub(crate) http: &'a reqwest::Client, |
| 326 | pub(crate) auth: &'a PeerAuth, |
| 327 | pub(crate) addr: &'a str, |
| 328 | pub(crate) node: &'a str, |
| 329 | } |
| 330 | |
| 331 | /// Idle tunnels per (peer, kind). A sender goes back only after its response |
| 332 | /// body reaches a clean end, so active replies do not consume the idle bound. |
| 333 | /// A dropped or poisoned connection reports `is_closed` and is purged on scan. |
| 334 | static TUNNELS: std::sync::OnceLock<std::sync::Mutex<HashMap<String, Vec<TunnelSender>>>> = |
| 335 | std::sync::OnceLock::new(); |
| 336 | /// Completed idle tunnels count against this bound. Active calls own their |
| 337 | /// senders outside the pool, so concurrency cannot evict a reusable tunnel. |
| 338 | const TUNNEL_POOL_CAP: usize = 64; |
| 339 | |
| 340 | fn checkout(key: &str) -> Option<TunnelSender> { |
| 341 | let mut pool = TUNNELS.get_or_init(Default::default).lock().unwrap(); |
| 342 | let senders = pool.get_mut(key)?; |
| 343 | senders.retain(|sender| !sender.is_closed()); |
| 344 | let index = senders.iter().position(TunnelSender::is_ready)?; |
| 345 | Some(senders.swap_remove(index)) |
| 346 | } |
| 347 | |
| 348 | fn park(key: &str, sender: TunnelSender) { |
| 349 | let mut pool = TUNNELS.get_or_init(Default::default).lock().unwrap(); |
| 350 | let senders = pool.entry(key.to_string()).or_default(); |
| 351 | if senders.len() < TUNNEL_POOL_CAP { |
| 352 | senders.push(sender); |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | /// Establish a fresh tunnel to `addr` and hand back its inner h1 client. |
| 357 | /// The establishment is a bodiless GET, so the fleet HMAC signs it whole — |
| 358 | /// the one signature every call on this tunnel then rides. |
| 359 | async fn establish(peer: &Peer<'_>, kind: &'static str) -> anyhow::Result<TunnelSender> { |
| 360 | let request = peer |
| 361 | .http |
| 362 | .get(format!("http://{}/peer/tunnel", peer.addr)) |
| 363 | .header(reqwest::header::UPGRADE, TUNNEL_PROTOCOL) |
| 364 | .header(reqwest::header::CONNECTION, "upgrade") |
| 365 | .header(VERSION_HEADER, TUNNEL_VERSION) |
| 366 | .header(KIND_HEADER, kind) |
| 367 | .header( |
| 368 | peer_auth::RESPONSE_VERSION_HEADER, |
| 369 | peer_auth::PROTOCOL_VERSION_TEXT, |
| 370 | ); |
| 371 | let response = peer |
| 372 | .auth |
| 373 | .sign(request, "GET", "/peer/tunnel", b"", peer.node)? |
| 374 | .send() |
| 375 | .await?; |
| 376 | peer_auth::validate_response(response.headers())?; |
| 377 | if response |
| 378 | .headers() |
| 379 | .get(STALE_ROUTE_HEADER) |
| 380 | .is_some_and(|value| value == STALE_ROUTE_VALUE) |
| 381 | { |
| 382 | return Err(StaleTunnelRoute.into()); |
| 383 | } |
| 384 | anyhow::ensure!( |
| 385 | response.status() == reqwest::StatusCode::SWITCHING_PROTOCOLS, |
| 386 | "tunnel establishment answered {}", |
| 387 | response.status() |
| 388 | ); |
| 389 | let upgraded = response.upgrade().await?; |
| 390 | let (sender, connection) = hyper::client::conn::http1::Builder::new() |
| 391 | .handshake(TokioIo::new(upgraded)) |
| 392 | .await?; |
| 393 | tokio::spawn(async move { |
| 394 | let _ = connection.with_upgrades().await; |
| 395 | }); |
| 396 | Ok(sender) |
| 397 | } |
| 398 | |
| 399 | fn inner_request( |
| 400 | control: &TunnelControl, |
| 401 | url: &str, |
| 402 | method: &str, |
| 403 | headers: &[(String, String)], |
| 404 | body: TunnelBody, |
| 405 | ) -> anyhow::Result<Request<TunnelBody>> { |
| 406 | let mut inner = Request::builder().method(method).uri(url); |
| 407 | for (name, value) in headers { |
| 408 | if CONTROL_HEADERS |
| 409 | .iter() |
| 410 | .any(|reserved| reserved.eq_ignore_ascii_case(name)) |
| 411 | { |
| 412 | continue; |
| 413 | } |
| 414 | inner = inner.header(name.as_str(), value.as_str()); |
| 415 | } |
| 416 | inner = inner.header(SCOPE_HEADER, control.scope.as_str()); |
| 417 | if let Some(name) = &control.name { |
| 418 | inner = inner.header(NAME_HEADER, name); |
| 419 | } |
| 420 | if let Some(request_id) = control.request_id { |
| 421 | inner = inner.header(REQUEST_ID_HEADER, celld::js::request_id_string(request_id)); |
| 422 | } |
| 423 | if control.capacity_handoff { |
| 424 | inner = inner.header(HANDOFF_HEADER, "1"); |
| 425 | } |
| 426 | Ok(inner.body(body)?) |
| 427 | } |
| 428 | |
| 429 | /// Send one inner request, preferring a pooled tunnel. A pooled connection |
| 430 | /// can die between checkout and use, so a replayable body retries once on a |
| 431 | /// fresh tunnel — the same stale keep-alive race every h1 pool has. A |
| 432 | /// streamed body is not replayable; its pooled failure surfaces as the |
| 433 | /// attempt failure the caller already handles. |
| 434 | async fn send_inner( |
| 435 | peer: &Peer<'_>, |
| 436 | kind: &'static str, |
| 437 | build: impl Fn(TunnelBody) -> anyhow::Result<Request<TunnelBody>>, |
| 438 | body: celld::js::RequestBody, |
| 439 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 440 | let key = format!("{}#{kind}", peer.addr); |
| 441 | let replay = match &body { |
| 442 | celld::js::RequestBody::Bytes(bytes) => Some(bytes.clone()), |
| 443 | celld::js::RequestBody::Stream(_) => None, |
| 444 | }; |
| 445 | let body = match body { |
| 446 | celld::js::RequestBody::Bytes(bytes) => full_body(bytes), |
| 447 | celld::js::RequestBody::Stream(stream_id) => { |
| 448 | let payload = celld::js::take_body_stream(stream_id) |
| 449 | .map_err(|error| anyhow::anyhow!("take tunnel body: {error}"))?; |
| 450 | stream_body(payload) |
| 451 | } |
| 452 | }; |
| 453 | let mut body = Some(body); |
| 454 | if let Some(sender) = checkout(&key) { |
| 455 | match send_on_tunnel(&key, sender, build(body.take().unwrap())?).await { |
| 456 | Ok(response) => { |
| 457 | return Ok(response); |
| 458 | } |
| 459 | Err(error) => { |
| 460 | let Some(bytes) = replay else { |
| 461 | return Err(error); |
| 462 | }; |
| 463 | body = Some(full_body(bytes)); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | let sender = establish(peer, kind).await?; |
| 468 | send_on_tunnel(&key, sender, build(body.take().unwrap())?).await |
| 469 | } |
| 470 | |
| 471 | async fn send_on_tunnel( |
| 472 | key: &str, |
| 473 | mut sender: TunnelSender, |
| 474 | request: Request<TunnelBody>, |
| 475 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 476 | let response = sender.send_request(request).await?; |
| 477 | let reusable = |
| 478 | (response.status() != StatusCode::SWITCHING_PROTOCOLS).then(|| (key.to_string(), sender)); |
| 479 | Ok(response.map(|body| PooledResponseBody { body, reusable })) |
| 480 | } |
| 481 | |
| 482 | /// An inner response owns its tunnel until the body finishes successfully. |
| 483 | /// Returning the sender at the response head makes active replies consume the |
| 484 | /// idle-pool bound. Sustained RPC concurrency then creates and discards one |
| 485 | /// upgraded TCP connection for every overflow call. |
| 486 | pub(crate) struct PooledResponseBody { |
| 487 | body: Incoming, |
| 488 | reusable: Option<(String, TunnelSender)>, |
| 489 | } |
| 490 | |
| 491 | impl Body for PooledResponseBody { |
| 492 | type Data = Bytes; |
| 493 | type Error = hyper::Error; |
| 494 | |
| 495 | fn poll_frame( |
| 496 | mut self: std::pin::Pin<&mut Self>, |
| 497 | cx: &mut std::task::Context<'_>, |
| 498 | ) -> std::task::Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> { |
| 499 | match std::pin::Pin::new(&mut self.body).poll_frame(cx) { |
| 500 | std::task::Poll::Ready(None) => { |
| 501 | if let Some((key, sender)) = self.reusable.take() { |
| 502 | park(&key, sender); |
| 503 | } |
| 504 | std::task::Poll::Ready(None) |
| 505 | } |
| 506 | std::task::Poll::Ready(Some(Err(error))) => { |
| 507 | // The unread or failed stream cannot carry another request. |
| 508 | self.reusable.take(); |
| 509 | std::task::Poll::Ready(Some(Err(error))) |
| 510 | } |
| 511 | other => other, |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | fn is_end_stream(&self) -> bool { |
| 516 | // Force one final poll while the sender is still attached. A zero-byte |
| 517 | // response can otherwise skip `poll_frame` and close a reusable tunnel. |
| 518 | self.reusable.is_none() && self.body.is_end_stream() |
| 519 | } |
| 520 | |
| 521 | fn size_hint(&self) -> hyper::body::SizeHint { |
| 522 | self.body.size_hint() |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | pub(crate) async fn fetch( |
| 527 | peer: &Peer<'_>, |
| 528 | control: &TunnelControl, |
| 529 | url: String, |
| 530 | method: String, |
| 531 | headers: Vec<(String, String)>, |
| 532 | body: celld::js::RequestBody, |
| 533 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 534 | send_inner( |
| 535 | peer, |
| 536 | "do", |
| 537 | |body| inner_request(control, &url, &method, &headers, body), |
| 538 | body, |
| 539 | ) |
| 540 | .await |
| 541 | } |
| 542 | |
| 543 | pub(crate) const METHOD_HEADER: &str = "x-cells-rpc-method"; |
| 544 | |
| 545 | /// One inner request, one RPC: the method name rides a header, the |
| 546 | /// arguments ride the body, and the content type says which encoding the |
| 547 | /// caller used. |
| 548 | async fn serve_rpc(upgraded: hyper::upgrade::Upgraded, app: AppHandle) { |
| 549 | let service = service_fn(move |inner: Request<Incoming>| { |
| 550 | let app = app.clone(); |
| 551 | async move { |
| 552 | let Some(scope) = inner |
| 553 | .headers() |
| 554 | .get(SCOPE_HEADER) |
| 555 | .and_then(|value| value.to_str().ok()) |
| 556 | .map(str::to_string) |
| 557 | .filter(|scope| celld_logic::cell::valid_cell_scope(scope)) |
| 558 | else { |
| 559 | return Ok::<_, Infallible>(peer_response(malformed_scope())); |
| 560 | }; |
| 561 | let name = inner |
| 562 | .headers() |
| 563 | .get(NAME_HEADER) |
| 564 | .and_then(|value| value.to_str().ok()) |
| 565 | .map(str::to_string); |
| 566 | let structured = inner |
| 567 | .headers() |
| 568 | .get(hyper::header::CONTENT_TYPE) |
| 569 | .is_some_and(|value| value.as_bytes() == b"application/octet-stream"); |
| 570 | let Some(method) = inner |
| 571 | .headers() |
| 572 | .get(METHOD_HEADER) |
| 573 | .and_then(|value| value.to_str().ok()) |
| 574 | .map(str::to_string) |
| 575 | else { |
| 576 | return Ok::<_, Infallible>(peer_response(response( |
| 577 | StatusCode::BAD_REQUEST, |
| 578 | "RPC method header is missing", |
| 579 | ))); |
| 580 | }; |
| 581 | let body = |
| 582 | match collect_limited_body(inner.into_body(), MAX_PEER_FORWARD_BODY_BYTES).await { |
| 583 | Ok(body) => body, |
| 584 | Err(error) => { |
| 585 | return Ok(peer_response(body_read_error("tunnel RPC", error))); |
| 586 | } |
| 587 | }; |
| 588 | let args = if structured { |
| 589 | celld::js::RpcData::V8(body) |
| 590 | } else { |
| 591 | match String::from_utf8(body.to_vec()) { |
| 592 | Ok(json) => celld::js::RpcData::Json(json), |
| 593 | Err(_) => { |
| 594 | return Ok(peer_response(response( |
| 595 | StatusCode::BAD_REQUEST, |
| 596 | "JSON RPC arguments are not UTF-8", |
| 597 | ))); |
| 598 | } |
| 599 | } |
| 600 | }; |
| 601 | let reply = dispatch_forwarded_rpc(app, scope, name, method, args).await; |
| 602 | Ok(reply) |
| 603 | } |
| 604 | }); |
| 605 | let _ = hyper::server::conn::http1::Builder::new() |
| 606 | .serve_connection(upgraded, service) |
| 607 | .await; |
| 608 | } |
| 609 | |
| 610 | /// Node A: one RPC through the pooled rpc tunnel. |
| 611 | pub(crate) async fn rpc( |
| 612 | peer: &Peer<'_>, |
| 613 | scope: &str, |
| 614 | name: Option<&str>, |
| 615 | method: &str, |
| 616 | args: &celld::js::RpcData, |
| 617 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 618 | let (content_type, payload) = match args { |
| 619 | celld::js::RpcData::Json(json) => ("application/json", Bytes::from(json.clone())), |
| 620 | celld::js::RpcData::V8(bytes) => ("application/octet-stream", bytes.clone()), |
| 621 | }; |
| 622 | send_inner( |
| 623 | peer, |
| 624 | "rpc", |
| 625 | |body| { |
| 626 | let mut inner = Request::builder() |
| 627 | .method("POST") |
| 628 | .uri("/") |
| 629 | .header(SCOPE_HEADER, scope) |
| 630 | .header(METHOD_HEADER, method) |
| 631 | .header(hyper::header::CONTENT_TYPE, content_type); |
| 632 | if let Some(name) = name { |
| 633 | inner = inner.header(NAME_HEADER, name); |
| 634 | } |
| 635 | Ok(inner.body(body)?) |
| 636 | }, |
| 637 | celld::js::RequestBody::Bytes(payload), |
| 638 | ) |
| 639 | .await |
| 640 | } |
| 641 | |
| 642 | /// The owner half of a tunneled WebSocket 101, parked until the caller's own |
| 643 | /// client socket finishes upgrading. |
| 644 | static TUNNEL_UPGRADES: std::sync::OnceLock< |
| 645 | std::sync::Mutex<HashMap<u64, hyper::upgrade::OnUpgrade>>, |
| 646 | > = std::sync::OnceLock::new(); |
| 647 | static NEXT_TUNNEL_UPGRADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); |
| 648 | |
| 649 | pub(crate) fn park_upgrade(upgrade: hyper::upgrade::OnUpgrade) -> u64 { |
| 650 | let id = NEXT_TUNNEL_UPGRADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 651 | TUNNEL_UPGRADES |
| 652 | .get_or_init(Default::default) |
| 653 | .lock() |
| 654 | .unwrap() |
| 655 | .insert(id, upgrade); |
| 656 | id |
| 657 | } |
| 658 | |
| 659 | fn remove_upgrade(parked: u64) -> Option<hyper::upgrade::OnUpgrade> { |
| 660 | TUNNEL_UPGRADES |
| 661 | .get_or_init(Default::default) |
| 662 | .lock() |
| 663 | .unwrap() |
| 664 | .remove(&parked) |
| 665 | } |
| 666 | |
| 667 | /// Own one parked upgrade after its numeric id returns from JavaScript. |
| 668 | /// |
| 669 | /// The id itself releases nothing. Binding it to this value makes every early |
| 670 | /// response exit and every cancelled executor task remove the stored upgrade. |
| 671 | /// A successful splice consumes the same value and takes the connection once. |
| 672 | pub(crate) struct TunnelUpgradeClaim { |
| 673 | upgrade: hyper::upgrade::OnUpgrade, |
| 674 | } |
| 675 | |
| 676 | pub(crate) fn claim_upgrade(parked: u64) -> anyhow::Result<TunnelUpgradeClaim> { |
| 677 | let upgrade = remove_upgrade(parked) |
| 678 | .ok_or_else(|| anyhow::anyhow!("tunneled upgrade {parked} is gone"))?; |
| 679 | Ok(TunnelUpgradeClaim { upgrade }) |
| 680 | } |
| 681 | |
| 682 | impl TunnelUpgradeClaim { |
| 683 | fn into_upgrade(self) -> hyper::upgrade::OnUpgrade { |
| 684 | self.upgrade |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | /// Splice the upgraded client socket to the tunneled owner: the hop stops |
| 689 | /// dispatching WebSocket frames and copies bytes until either side closes. |
| 690 | pub(crate) async fn splice<S>(client: S, parked: TunnelUpgradeClaim) -> anyhow::Result<()> |
| 691 | where |
| 692 | S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, |
| 693 | { |
| 694 | let upgrade = parked.into_upgrade(); |
| 695 | let inner = upgrade.await?; |
| 696 | let inner = TokioIo::new(inner); |
| 697 | let (mut client_read, mut client_write) = tokio::io::split(client); |
| 698 | let (mut inner_read, mut inner_write) = tokio::io::split(inner); |
| 699 | celld::asyncrt::select! { |
| 700 | _ = tokio::io::copy(&mut client_read, &mut inner_write) => { |
| 701 | // The client went away; the owner sees EOF through the tunnel |
| 702 | // and runs its own close dispatch. |
| 703 | } |
| 704 | can_append_close = copy_owner_to_client(&mut inner_read, &mut client_write) => { |
| 705 | // A second Close fails browser channels. An incomplete frame |
| 706 | // would consume a synthetic Close as payload, so only append at |
| 707 | // a frame boundary before the owner starts closing. |
| 708 | if can_append_close { |
| 709 | let client = client_read.unsplit(client_write); |
| 710 | let mut ws = fastwebsockets::WebSocket::after_handshake( |
| 711 | client, |
| 712 | fastwebsockets::Role::Server, |
| 713 | ); |
| 714 | let _ = ws |
| 715 | .write_frame(fastwebsockets::Frame::close(1012, b"owner unavailable")) |
| 716 | .await; |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | Ok(()) |
| 721 | } |
| 722 | |
| 723 | /// Return whether owner EOF or a read error leaves room for a failure Close. |
| 724 | /// A client write failure ends the splice without any further writes. |
| 725 | async fn copy_owner_to_client<R, W>(owner: &mut R, client: &mut W) -> bool |
| 726 | where |
| 727 | R: tokio::io::AsyncRead + Unpin, |
| 728 | W: tokio::io::AsyncWrite + Unpin, |
| 729 | { |
| 730 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 731 | |
| 732 | let mut scanner = celld_logic::schedule::WebSocketCloseScanner::default(); |
| 733 | let mut buffer = [0u8; 8192]; |
| 734 | loop { |
| 735 | let read = match owner.read(&mut buffer).await { |
| 736 | Ok(0) | Err(_) => return scanner.can_append_close(), |
| 737 | Ok(read) => read, |
| 738 | }; |
| 739 | if client.write_all(&buffer[..read]).await.is_err() { |
| 740 | return false; |
| 741 | } |
| 742 | scanner.observe(&buffer[..read]); |
| 743 | // Flush before waiting for more owner bytes, including a peer's |
| 744 | // closing-handshake response. Buffered writers must make progress. |
| 745 | if client.flush().await.is_err() { |
| 746 | return false; |
| 747 | } |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | type TunnelBody = http_body_util::combinators::UnsyncBoxBody<Bytes, std::io::Error>; |
| 752 | |
| 753 | fn full_body(bytes: Bytes) -> TunnelBody { |
| 754 | BodyExt::boxed_unsync(http_body_util::Full::new(bytes).map_err(|never| match never {})) |
| 755 | } |
| 756 | |
| 757 | fn stream_body(payload: HttpChunkStream) -> TunnelBody { |
| 758 | let frames = payload.map(|chunk| { |
| 759 | chunk |
| 760 | .map(|data| hyper::body::Frame::data(Bytes::from(data))) |
| 761 | .map_err(std::io::Error::other) |
| 762 | }); |
| 763 | BodyExt::boxed_unsync(http_body_util::StreamBody::new(frames)) |
| 764 | } |
| 765 | |
| 766 | /// The inner response body as the chunk stream the reply path already |
| 767 | /// speaks. |
| 768 | pub(crate) fn response_stream(body: PooledResponseBody) -> HttpChunkStream { |
| 769 | Box::pin( |
| 770 | http_body_util::BodyStream::new(body) |
| 771 | .try_filter_map(|frame| async move { Ok(frame.into_data().ok()) }) |
| 772 | .map_ok(|data: Bytes| data.to_vec()) |
| 773 | .map_err(|error| error.to_string()), |
| 774 | ) |
| 775 | } |
| 776 | |
| 777 | #[cfg(all(test, celld_internal_tests))] |
| 778 | mod private_tests { |
| 779 | include!(env!("CELLD_CONFORMANCE_PEER_TUNNEL_TESTS")); |
| 780 | } |