| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | // The binary contains connection, startup, shutdown, and V8 shell code. The |
| 4 | // library Actor owns the execution domain and its routed adapters. |
| 5 | #![allow(clippy::disallowed_methods)] |
| 6 | |
| 7 | //! Runnable celld vertical slice. |
| 8 | //! |
| 9 | //! One actor serializes every event through `celld-logic`; the actor polls its |
| 10 | //! mailbox, timers, and in-flight effect futures together. This is the |
| 11 | //! execution shape required for monotonic lease ticks to fence the node even |
| 12 | //! when a storage operation remains hung, without spawning a task per effect. |
| 13 | |
| 14 | use anyhow::Context as _; |
| 15 | use celld::actor::*; |
| 16 | use celld::bucket::Bucket; |
| 17 | use celld::fleet; |
| 18 | use celld::generation::{ |
| 19 | DeploymentGraph, Generation, GenerationOptions, ReloadOutcome, ReloadRequest, FIRST_GENERATION, |
| 20 | }; |
| 21 | use celld::js::{ |
| 22 | ArmGate, AssetCallReq, Compat, DoCallReq, HttpResponse, HttpResponseWebSocket, QueueBinding, |
| 23 | QueueDispatchReq, RpcCallReq, SvcCallReq, SvcRpcReq, WorkerConfigOptions, WorkflowBinding, |
| 24 | }; |
| 25 | use celld::ownership_store::{now_ms, BucketOwnership}; |
| 26 | use celld::peer_auth::{self, PeerAuth}; |
| 27 | use celld::protocol::DeployPointer; |
| 28 | use celld::runtime::{Replication, RuntimeFetch, RuntimeManager, RuntimeOptions, ServiceFetch}; |
| 29 | use celld_logic::{RequestError, Route, WebSocketKind}; |
| 30 | use futures_util::stream::{FuturesUnordered, StreamExt}; |
| 31 | use http_body_util::combinators::UnsyncBoxBody; |
| 32 | use http_body_util::{BodyExt, Full, Limited, StreamBody}; |
| 33 | use hyper::body::{Body as _, Bytes, Frame, Incoming}; |
| 34 | use hyper::server::conn::http1; |
| 35 | use hyper::service::service_fn; |
| 36 | use hyper::{Request, Response, StatusCode}; |
| 37 | use hyper_util::rt::TokioIo; |
| 38 | use std::convert::Infallible; |
| 39 | use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; |
| 40 | use std::sync::Arc; |
| 41 | use std::time::Instant; |
| 42 | use tokio::sync::{mpsc, oneshot, watch}; |
| 43 | |
| 44 | // glibc's malloc serializes its arenas behind futexes, and under load the |
| 45 | // sixteen worker threads spent up to half a millisecond blocked per |
| 46 | // acquisition. On a 16-core host jemalloc measured 20% more hello-world |
| 47 | // throughput than glibc (mimalloc 11%), and returned the ~7% of the machine |
| 48 | // that arena-lock sleeps reported as idle. |
| 49 | #[global_allocator] |
| 50 | static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; |
| 51 | |
| 52 | /// Let an admitted HTTP request finish, then close the transport even when a |
| 53 | /// response stream or a client keep-alive does not settle. The semantic drain |
| 54 | /// continues after this bound, so durability and resident activity still use |
| 55 | /// the complete shutdown grace. |
| 56 | const CONNECTION_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(2); |
| 57 | |
| 58 | /// Retry a failed shutdown accept quickly enough to keep peer and health |
| 59 | /// traffic available, then reduce repeated error work while the listener is |
| 60 | /// unavailable. The complete shutdown deadline still bounds every retry. |
| 61 | const SHUTDOWN_ACCEPT_RETRY_INITIAL: std::time::Duration = std::time::Duration::from_millis(10); |
| 62 | const SHUTDOWN_ACCEPT_RETRY_MAX: std::time::Duration = std::time::Duration::from_secs(1); |
| 63 | |
| 64 | /// The lossy stdout writer's flush handle. Every exit path uses |
| 65 | /// `std::process::exit`, which skips destructors — but the last lines before |
| 66 | /// an exit are the fence forensics, exactly the lines that must survive. |
| 67 | static LOG_GUARD: std::sync::Mutex<Option<tracing_appender::non_blocking::WorkerGuard>> = |
| 68 | std::sync::Mutex::new(None); |
| 69 | |
| 70 | #[cfg(all(test, celld_internal_tests))] |
| 71 | // Keep the client open until the child exits, so the accepted connection |
| 72 | // reaches the real drain-time HTTP path instead of closing immediately. |
| 73 | static SHUTDOWN_ACCEPT_FAILURE_CLIENT: std::sync::Mutex<Option<std::net::TcpStream>> = |
| 74 | std::sync::Mutex::new(None); |
| 75 | |
| 76 | #[cfg(all(test, celld_internal_tests))] |
| 77 | fn shutdown_accept_failure_test_checkpoint(active: bool, step: &'static str) { |
| 78 | if active { |
| 79 | // The tracing writer is deliberately lossy and asynchronous. This |
| 80 | // process regression needs every cleanup checkpoint to remain |
| 81 | // visible and ordered when the child exits through process::exit. |
| 82 | celld::cli_output::Output::new(celld::cli_output::Format::Text) |
| 83 | .line(format_args!( |
| 84 | "shutdown accept failure test checkpoint: {step}" |
| 85 | )) |
| 86 | .expect("write the shutdown accept failure test checkpoint"); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | static CONNECTION_ERRORS_TOTAL: AtomicU64 = AtomicU64::new(0); |
| 91 | static CONNECTION_ERRORS_REPORTED: AtomicU64 = AtomicU64::new(0); |
| 92 | static CONNECTION_ERROR_LAST_LOG_MS: AtomicU64 = AtomicU64::new(0); |
| 93 | static CONNECTION_ERRORS_INCOMPLETE: AtomicU64 = AtomicU64::new(0); |
| 94 | static CONNECTION_ERRORS_TIMEOUT: AtomicU64 = AtomicU64::new(0); |
| 95 | static CONNECTION_ERRORS_OTHER: AtomicU64 = AtomicU64::new(0); |
| 96 | |
| 97 | fn record_connection_error( |
| 98 | error: &hyper::Error, |
| 99 | surface: HttpSurface, |
| 100 | peer: Option<std::net::SocketAddr>, |
| 101 | ) { |
| 102 | static STARTED: std::sync::OnceLock<Instant> = std::sync::OnceLock::new(); |
| 103 | let total = CONNECTION_ERRORS_TOTAL.fetch_add(1, Ordering::Relaxed) + 1; |
| 104 | let (cause, cause_total) = if error.is_incomplete_message() { |
| 105 | ( |
| 106 | "incomplete_message", |
| 107 | CONNECTION_ERRORS_INCOMPLETE.fetch_add(1, Ordering::Relaxed) + 1, |
| 108 | ) |
| 109 | } else if error.is_timeout() { |
| 110 | ( |
| 111 | "timeout", |
| 112 | CONNECTION_ERRORS_TIMEOUT.fetch_add(1, Ordering::Relaxed) + 1, |
| 113 | ) |
| 114 | } else { |
| 115 | ( |
| 116 | "other", |
| 117 | CONNECTION_ERRORS_OTHER.fetch_add(1, Ordering::Relaxed) + 1, |
| 118 | ) |
| 119 | }; |
| 120 | let elapsed_ms = STARTED.get_or_init(Instant::now).elapsed().as_millis() as u64; |
| 121 | let last = CONNECTION_ERROR_LAST_LOG_MS.load(Ordering::Relaxed); |
| 122 | let observed = elapsed_ms.max(1); |
| 123 | if (last != 0 && elapsed_ms.saturating_sub(last) < 1_000) |
| 124 | || CONNECTION_ERROR_LAST_LOG_MS |
| 125 | .compare_exchange(last, observed, Ordering::Relaxed, Ordering::Relaxed) |
| 126 | .is_err() |
| 127 | { |
| 128 | return; |
| 129 | } |
| 130 | let reported = CONNECTION_ERRORS_REPORTED.swap(total, Ordering::Relaxed); |
| 131 | tracing::warn!( |
| 132 | event = "http_connection_failures", |
| 133 | total, |
| 134 | since_last = total.saturating_sub(reported), |
| 135 | cause, |
| 136 | cause_total, |
| 137 | surface = surface.name(), |
| 138 | ?peer, |
| 139 | %error, |
| 140 | "HTTP connections failed" |
| 141 | ); |
| 142 | } |
| 143 | |
| 144 | fn exit_flushed(code: i32) -> ! { |
| 145 | drop(LOG_GUARD.lock().unwrap().take()); |
| 146 | std::process::exit(code); |
| 147 | } |
| 148 | |
| 149 | /// Await shutdown work only while the orchestrator-compatible process budget |
| 150 | /// remains. A zero budget does not poll the future, so best-effort store and |
| 151 | /// diagnostic work cannot begin after the absolute deadline. |
| 152 | async fn before_process_deadline<F>(deadline: tokio::time::Instant, future: F) -> Option<F::Output> |
| 153 | where |
| 154 | F: std::future::Future, |
| 155 | { |
| 156 | let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 157 | if remaining.is_zero() { |
| 158 | return None; |
| 159 | } |
| 160 | tokio::time::timeout(remaining, future).await.ok() |
| 161 | } |
| 162 | |
| 163 | /// Finish process-wide WebSocket frame work before connection tasks can |
| 164 | /// unregister the sockets that receive those frames. |
| 165 | async fn flush_shutdown_connections<Frames, Connections>( |
| 166 | process_deadline: tokio::time::Instant, |
| 167 | flush_frames: Frames, |
| 168 | flush_connections: Connections, |
| 169 | ) where |
| 170 | Frames: std::future::Future<Output = ()>, |
| 171 | Connections: std::future::Future<Output = ()>, |
| 172 | { |
| 173 | // The frames a flush still holds are behind a durability gate, and a |
| 174 | // socket whose peer is gone can never deliver them: a `celld dev` stop |
| 175 | // on OrbStack sat here for its whole process deadline once the |
| 176 | // container behind an outbound socket had been destroyed. The grace is |
| 177 | // for frames that can still land; the durability of the writes behind |
| 178 | // them is the quiesce that follows, not this wait. |
| 179 | match before_process_deadline( |
| 180 | process_deadline, |
| 181 | tokio::time::timeout(CONNECTION_DRAIN_GRACE, flush_frames), |
| 182 | ) |
| 183 | .await |
| 184 | { |
| 185 | None => return, |
| 186 | Some(Err(_)) => tracing::warn!( |
| 187 | event = "shutdown_frame_flush_cut", |
| 188 | grace_ms = CONNECTION_DRAIN_GRACE.as_millis() as u64, |
| 189 | "WebSocket frames still held at the flush grace were dropped" |
| 190 | ), |
| 191 | Some(Ok(())) => {} |
| 192 | } |
| 193 | let _ = before_process_deadline( |
| 194 | process_deadline, |
| 195 | tokio::time::timeout(CONNECTION_DRAIN_GRACE, flush_connections), |
| 196 | ) |
| 197 | .await; |
| 198 | } |
| 199 | |
| 200 | // Keep the runtime owner and the follower fallback in one consumed selection. |
| 201 | // The process must finalize this value before it starts application services, |
| 202 | // so a caller cannot forget the follower-only owner on a non-runtime path. |
| 203 | struct DurabilityOwnerSelection { |
| 204 | runtime_owner: Option<celld::node_log::DurabilityOwner>, |
| 205 | follower: Option<Arc<celld::node_log::FollowerStore>>, |
| 206 | } |
| 207 | |
| 208 | impl DurabilityOwnerSelection { |
| 209 | fn new(follower: Option<Arc<celld::node_log::FollowerStore>>) -> Self { |
| 210 | Self { |
| 211 | runtime_owner: None, |
| 212 | follower, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn install_runtime(&mut self, owner: celld::node_log::DurabilityOwner) { |
| 217 | assert!( |
| 218 | self.runtime_owner.is_none(), |
| 219 | "the runtime durability owner was already installed" |
| 220 | ); |
| 221 | self.runtime_owner = Some(owner); |
| 222 | } |
| 223 | |
| 224 | fn select(self) -> Option<celld::node_log::DurabilityOwner> { |
| 225 | self.runtime_owner.or_else(|| { |
| 226 | self.follower |
| 227 | .map(celld::node_log::DurabilityOwner::new_follower) |
| 228 | }) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // Keep the phase-one durability result inside the complete preparation |
| 233 | // decision. A timeout runs fallback, so it must override a successful drain. |
| 234 | fn clean_reload_is_eligible( |
| 235 | durability_quiesced: bool, |
| 236 | drained: bool, |
| 237 | shutdown_mode: ShutdownMode, |
| 238 | ) -> bool { |
| 239 | durability_quiesced && drained && shutdown_mode == ShutdownMode::Preserve |
| 240 | } |
| 241 | |
| 242 | type HttpReply = Response<UnsyncBoxBody<Bytes, std::io::Error>>; |
| 243 | |
| 244 | const STALE_ROUTE_HEADER: &str = "x-cells-route-error"; |
| 245 | const STALE_ROUTE_VALUE: &str = "stale-owner"; |
| 246 | const DURABLE_OBJECT_ROUTING_ERROR_MARKER: &str = "__CELLD_DO_ROUTING_ERROR__:"; |
| 247 | |
| 248 | fn owner_unreachable(scope: &str, owner: &str, source: anyhow::Error) -> anyhow::Error { |
| 249 | // Record how the attempt failed, not just that it did. `connect` is the |
| 250 | // one that decides whether a retry is safe -- a request that never left |
| 251 | // this node may be re-sent, a truncated read may not, because the owner |
| 252 | // already ran it. Without these an operator cannot tell an unreachable |
| 253 | // peer from one that answered badly, and neither can a bug report. |
| 254 | let transport = source.downcast_ref::<reqwest::Error>(); |
| 255 | // The full chain, because the root cause is the actionable part: a |
| 256 | // "connect error" one level down still hides refused vs. out-of-fds. |
| 257 | let cause = format!("{source:#}"); |
| 258 | tracing::warn!( |
| 259 | %scope, |
| 260 | %owner, |
| 261 | error = %source, |
| 262 | %cause, |
| 263 | connect = transport.is_some_and(reqwest::Error::is_connect), |
| 264 | timeout = transport.is_some_and(reqwest::Error::is_timeout), |
| 265 | request = transport.is_some_and(reqwest::Error::is_request), |
| 266 | body = transport.is_some_and(reqwest::Error::is_body), |
| 267 | decode = transport.is_some_and(reqwest::Error::is_decode), |
| 268 | "peer owner unreachable" |
| 269 | ); |
| 270 | let detail = serde_json::json!({ |
| 271 | "scope": scope, |
| 272 | "owner": owner, |
| 273 | }); |
| 274 | source.context(format!("{DURABLE_OBJECT_ROUTING_ERROR_MARKER}{detail}")) |
| 275 | } |
| 276 | |
| 277 | fn response(status: StatusCode, body: impl Into<Bytes>) -> HttpReply { |
| 278 | Response::builder() |
| 279 | .status(status) |
| 280 | .header("content-type", "application/json") |
| 281 | .body( |
| 282 | Full::new(body.into()) |
| 283 | .map_err(|never| match never {}) |
| 284 | .boxed_unsync(), |
| 285 | ) |
| 286 | .expect("static HTTP response") |
| 287 | } |
| 288 | |
| 289 | fn asset_response(response: axum::response::Response) -> HttpReply { |
| 290 | response.map(|body| body.map_err(std::io::Error::other).boxed_unsync()) |
| 291 | } |
| 292 | |
| 293 | fn peer_response(mut response: HttpReply) -> HttpReply { |
| 294 | response.headers_mut().insert( |
| 295 | hyper::header::HeaderName::from_static(peer_auth::RESPONSE_VERSION_HEADER), |
| 296 | hyper::header::HeaderValue::from_static(peer_auth::PROTOCOL_VERSION_TEXT), |
| 297 | ); |
| 298 | response |
| 299 | } |
| 300 | |
| 301 | /// Decides whether a Worker-set response header reaches the caller. The |
| 302 | /// `connection` and `transfer-encoding` headers describe the Worker-side hop, |
| 303 | /// and the host frames every body it sends, so a Worker `content-length` is |
| 304 | /// stale framing it must not repeat — except on a HEAD response, where the |
| 305 | /// body the host measures is empty and the Worker's value is the only |
| 306 | /// representation length the client can get. RFC 9110 forbids the header on a |
| 307 | /// 1xx or 204 status, so those never carry one even on a HEAD path. |
| 308 | fn forwards_worker_header( |
| 309 | name: &str, |
| 310 | preserve_representation_length: bool, |
| 311 | status: StatusCode, |
| 312 | ) -> bool { |
| 313 | !matches!( |
| 314 | name.to_ascii_lowercase().as_str(), |
| 315 | "connection" | "transfer-encoding" |
| 316 | ) && (!name.eq_ignore_ascii_case("content-length") |
| 317 | || (preserve_representation_length |
| 318 | && !status.is_informational() |
| 319 | && status != StatusCode::NO_CONTENT)) |
| 320 | } |
| 321 | |
| 322 | fn runtime_response( |
| 323 | worker_response: celld::js::HttpResponse, |
| 324 | preserve_representation_length: bool, |
| 325 | ) -> HttpReply { |
| 326 | let Ok(status) = StatusCode::from_u16(worker_response.status) else { |
| 327 | return response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker status"); |
| 328 | }; |
| 329 | let mut builder = Response::builder().status(status); |
| 330 | for (name, value) in worker_response.headers { |
| 331 | if !forwards_worker_header(&name, preserve_representation_length, status) { |
| 332 | continue; |
| 333 | } |
| 334 | builder = builder.header(name, value); |
| 335 | } |
| 336 | let body = match worker_response.stream { |
| 337 | Some(stream) => { |
| 338 | let chunks = stream.map(|chunk| { |
| 339 | chunk |
| 340 | .map(|bytes| Frame::data(Bytes::from(bytes))) |
| 341 | .map_err(std::io::Error::other) |
| 342 | }); |
| 343 | StreamBody::new(chunks).boxed_unsync() |
| 344 | } |
| 345 | None => Full::new(Bytes::from(worker_response.body)) |
| 346 | .map_err(|never| match never {}) |
| 347 | .boxed_unsync(), |
| 348 | }; |
| 349 | builder |
| 350 | .body(body) |
| 351 | .unwrap_or_else(|_| response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker headers")) |
| 352 | } |
| 353 | |
| 354 | #[derive(Debug)] |
| 355 | struct StalePeerRoute { |
| 356 | scope: String, |
| 357 | } |
| 358 | |
| 359 | impl std::fmt::Display for StalePeerRoute { |
| 360 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 361 | write!(formatter, "peer no longer owns {}", self.scope) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | impl std::error::Error for StalePeerRoute {} |
| 366 | |
| 367 | #[derive(Debug)] |
| 368 | struct RoutedRequestError(RequestError); |
| 369 | |
| 370 | /// The gate's verdict as the answer's error, with the handler's own failure |
| 371 | /// kept below it when the answer was one: the client needs the verdict, and |
| 372 | /// the operator reading the chain needs what the handler said too. The |
| 373 | /// verdict stays on top, so the routed-error match still finds it. |
| 374 | fn local_request_error(failure: LocalRequestFailure) -> anyhow::Error { |
| 375 | match failure { |
| 376 | LocalRequestFailure::Handler(error) => error, |
| 377 | LocalRequestFailure::OutputGate { verdict, handler } => match handler { |
| 378 | Some(handler) => handler.context(RoutedRequestError(verdict)), |
| 379 | None => anyhow::Error::new(RoutedRequestError(verdict)), |
| 380 | }, |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | /// Preserve the owner's durability verdict and handler failure in a peer reply. |
| 385 | fn peer_gate_failure(verdict: RequestError, handler: Option<&anyhow::Error>) -> HttpReply { |
| 386 | let detail = match handler { |
| 387 | Some(handler) => format!("; the handler failed: {handler:#}"), |
| 388 | None => String::new(), |
| 389 | }; |
| 390 | peer_response(response( |
| 391 | StatusCode::INTERNAL_SERVER_ERROR, |
| 392 | format!("durability unproven: {verdict:?}{detail}"), |
| 393 | )) |
| 394 | } |
| 395 | |
| 396 | impl std::fmt::Display for RoutedRequestError { |
| 397 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 398 | write!(formatter, "route failed: {:?}", self.0) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | impl std::error::Error for RoutedRequestError {} |
| 403 | |
| 404 | fn classify_remote_attempt(error: &anyhow::Error) -> celld_logic::routing::Attempt { |
| 405 | if error.downcast_ref::<StalePeerRoute>().is_some() |
| 406 | || error |
| 407 | .downcast_ref::<peer_tunnel::StaleTunnelRoute>() |
| 408 | .is_some() |
| 409 | { |
| 410 | celld_logic::routing::Attempt::NotOwner |
| 411 | } else if error |
| 412 | .downcast_ref::<reqwest::Error>() |
| 413 | .is_some_and(reqwest::Error::is_connect) |
| 414 | { |
| 415 | celld_logic::routing::Attempt::NeverConnected |
| 416 | } else { |
| 417 | celld_logic::routing::Attempt::Ambiguous |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 422 | enum RemoteRetryAction { |
| 423 | Stop, |
| 424 | Redispatch, |
| 425 | WaitForOwner, |
| 426 | } |
| 427 | |
| 428 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 429 | enum RemoteRetryOutcome { |
| 430 | Ready, |
| 431 | Stop, |
| 432 | Cancelled, |
| 433 | } |
| 434 | |
| 435 | /// Keep the one-retry transport policy, but do not spend that retry on an |
| 436 | /// ownership generation which a reachable peer already rejected. |
| 437 | /// |
| 438 | /// A replacement can bind the prior address while the prior session's lease |
| 439 | /// is still live. The new process then gives a definitive `NotOwner` answer |
| 440 | /// for the old `(node, epoch)`. An immediate redispatch resolves that same |
| 441 | /// generation and fails a safe application retry before ownership can move. |
| 442 | struct RemoteRouteRetry { |
| 443 | dispatcher: celld_logic::routing::Dispatcher, |
| 444 | generation: Option<(String, u64)>, |
| 445 | blocked: bool, |
| 446 | deadline_ms: u64, |
| 447 | next_wait_ms: u64, |
| 448 | } |
| 449 | |
| 450 | impl RemoteRouteRetry { |
| 451 | const INITIAL_WAIT_MS: u64 = 10; |
| 452 | const MAX_WAIT_MS: u64 = 250; |
| 453 | |
| 454 | fn new(operation_deadline_ms: u64) -> Self { |
| 455 | Self { |
| 456 | dispatcher: celld_logic::routing::Dispatcher::default(), |
| 457 | generation: None, |
| 458 | blocked: false, |
| 459 | deadline_ms: celld::asyncrt::mono_ms().saturating_add(operation_deadline_ms), |
| 460 | next_wait_ms: Self::INITIAL_WAIT_MS, |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /// Return true when this route is known not to be usable yet. |
| 465 | fn observe(&mut self, node: &str, epoch: u64) -> bool { |
| 466 | let changed = self |
| 467 | .generation |
| 468 | .as_ref() |
| 469 | .is_none_or(|(current_node, current_epoch)| { |
| 470 | current_node != node || *current_epoch != epoch |
| 471 | }); |
| 472 | if changed { |
| 473 | self.generation = Some((node.to_string(), epoch)); |
| 474 | self.blocked = false; |
| 475 | self.dispatcher = celld_logic::routing::Dispatcher::default(); |
| 476 | self.next_wait_ms = Self::INITIAL_WAIT_MS; |
| 477 | } |
| 478 | self.blocked |
| 479 | } |
| 480 | |
| 481 | fn failed(&mut self, attempt: celld_logic::routing::Attempt) -> RemoteRetryAction { |
| 482 | match attempt { |
| 483 | celld_logic::routing::Attempt::Ambiguous => RemoteRetryAction::Stop, |
| 484 | celld_logic::routing::Attempt::NotOwner => { |
| 485 | if !self.dispatcher.redispatch(attempt) { |
| 486 | return RemoteRetryAction::Stop; |
| 487 | } |
| 488 | self.blocked = true; |
| 489 | RemoteRetryAction::WaitForOwner |
| 490 | } |
| 491 | celld_logic::routing::Attempt::NeverConnected |
| 492 | if self.dispatcher.redispatch(attempt) => |
| 493 | { |
| 494 | RemoteRetryAction::Redispatch |
| 495 | } |
| 496 | celld_logic::routing::Attempt::NeverConnected => RemoteRetryAction::Stop, |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /// Apply one failed attempt's policy, then invalidate only when another |
| 501 | /// dispatch is allowed. The observed generation ties the retry budget, |
| 502 | /// diagnostic, and invalidation to the same owner. |
| 503 | async fn retry( |
| 504 | &mut self, |
| 505 | app: &AppHandle, |
| 506 | scope: &str, |
| 507 | attempt: celld_logic::routing::Attempt, |
| 508 | cancel: Option<&mut oneshot::Receiver<()>>, |
| 509 | surface: Option<&'static str>, |
| 510 | ) -> RemoteRetryOutcome { |
| 511 | let action = self.failed(attempt); |
| 512 | let (node, epoch) = self.generation.as_ref().expect("an observed remote route"); |
| 513 | tracing::warn!( |
| 514 | event = "remote_route_retry", |
| 515 | %scope, |
| 516 | %node, |
| 517 | epoch, |
| 518 | ?attempt, |
| 519 | ?action, |
| 520 | surface, |
| 521 | "a peer attempt changed the remote route retry state" |
| 522 | ); |
| 523 | let outcome = match action { |
| 524 | RemoteRetryAction::Stop => RemoteRetryOutcome::Stop, |
| 525 | RemoteRetryAction::Redispatch => RemoteRetryOutcome::Ready, |
| 526 | RemoteRetryAction::WaitForOwner => self.wait(cancel).await, |
| 527 | }; |
| 528 | if outcome == RemoteRetryOutcome::Ready { |
| 529 | self.invalidate(app, scope).await; |
| 530 | } |
| 531 | outcome |
| 532 | } |
| 533 | |
| 534 | async fn invalidate(&self, app: &AppHandle, scope: &str) { |
| 535 | let (node, epoch) = self.generation.as_ref().expect("an observed remote route"); |
| 536 | app.invalidate_remote(scope.to_string(), node.clone(), *epoch) |
| 537 | .await; |
| 538 | } |
| 539 | |
| 540 | async fn wait(&mut self, cancel: Option<&mut oneshot::Receiver<()>>) -> RemoteRetryOutcome { |
| 541 | let remaining_ms = self.deadline_ms.saturating_sub(celld::asyncrt::mono_ms()); |
| 542 | if remaining_ms == 0 { |
| 543 | return RemoteRetryOutcome::Stop; |
| 544 | } |
| 545 | let wait = std::time::Duration::from_millis(remaining_ms.min(self.next_wait_ms)); |
| 546 | self.next_wait_ms = self.next_wait_ms.saturating_mul(2).min(Self::MAX_WAIT_MS); |
| 547 | match cancel { |
| 548 | Some(cancel) => celld::asyncrt::select_biased! { |
| 549 | "a lifecycle cancellation wins a tie with route retry backoff"; |
| 550 | _ = cancel => RemoteRetryOutcome::Cancelled, |
| 551 | _ = celld::asyncrt::sleep(wait) => RemoteRetryOutcome::Ready, |
| 552 | }, |
| 553 | None => { |
| 554 | celld::asyncrt::sleep(wait).await; |
| 555 | RemoteRetryOutcome::Ready |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | struct WebSocketRouteTiming { |
| 562 | started: Instant, |
| 563 | route_resolution_us: u64, |
| 564 | dispatch_us: u64, |
| 565 | attempts: u8, |
| 566 | } |
| 567 | |
| 568 | impl WebSocketRouteTiming { |
| 569 | fn emit( |
| 570 | &self, |
| 571 | app: &AppHandle, |
| 572 | scope: &str, |
| 573 | request_id: Option<celld::js::RequestId>, |
| 574 | outcome: &str, |
| 575 | route: &str, |
| 576 | peer_node: &str, |
| 577 | ) { |
| 578 | let request_id = request_id |
| 579 | .map(celld::js::request_id_string) |
| 580 | .unwrap_or_default(); |
| 581 | let (node, region) = app |
| 582 | .runtime |
| 583 | .as_ref() |
| 584 | .map_or(("", ""), |runtime| (runtime.node(), runtime.region())); |
| 585 | tracing::debug!( |
| 586 | target: "timing", |
| 587 | event = "websocket_route_timing", |
| 588 | outcome, |
| 589 | route, |
| 590 | peer_node, |
| 591 | scope, |
| 592 | request_id, |
| 593 | node, |
| 594 | region, |
| 595 | runtime_version = env!("CARGO_PKG_VERSION"), |
| 596 | attempts = self.attempts, |
| 597 | total_us = self.started.elapsed().as_micros() as u64, |
| 598 | route_resolution_us = self.route_resolution_us, |
| 599 | dispatch_us = self.dispatch_us, |
| 600 | "WebSocket cell request resolved" |
| 601 | ); |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | /// The output gate for an effect raised inside a handler, as opposed to the |
| 606 | /// handler's own response. |
| 607 | /// |
| 608 | /// Every in-handler channel arrives here holding a `GateReq`. Reuses the routed |
| 609 | /// machinery: `request` pins the cell (no eviction mid-wait) and the core gate |
| 610 | /// decides. `Ok` releases the held effect; `Err` breaks the call, as a routed |
| 611 | /// gate failure would. |
| 612 | async fn dispatch_gate(app: AppHandle, req: celld::js::GateReq) { |
| 613 | let routed = match app.request(req.scope.clone()).await { |
| 614 | Ok(routed) => routed, |
| 615 | Err(error) => { |
| 616 | let _ = req.reply.send(Err(error)); |
| 617 | return; |
| 618 | } |
| 619 | }; |
| 620 | // The guard pins the cell and releases the request on drop, so the else |
| 621 | // branch does not leak the just-acquired request. |
| 622 | let _activity = app.activity(routed.request, req.scope.clone()); |
| 623 | let result = if routed.route == Route::Local { |
| 624 | app.gate_output(routed.request, req.ticket).await |
| 625 | } else { |
| 626 | // The owning isolate should route the cell locally; if it moved off the |
| 627 | // node mid-call, fail closed rather than acknowledge an unproven write. |
| 628 | Err(RequestError::NodeFenced) |
| 629 | }; |
| 630 | let _ = req.reply.send(result); |
| 631 | } |
| 632 | |
| 633 | /// Propagates a forwarding-side cancellation over the authenticated peer |
| 634 | /// protocol. Dropping a Reqwest future does not guarantee that its pooled |
| 635 | /// HTTP/1 transport closes, so the owner cannot use transport EOF alone. |
| 636 | struct RemoteFetchAbortGuard { |
| 637 | http: reqwest::Client, |
| 638 | auth: Arc<PeerAuth>, |
| 639 | node: String, |
| 640 | addr: String, |
| 641 | scope: String, |
| 642 | request: Option<celld::js::RequestId>, |
| 643 | phase: &'static str, |
| 644 | } |
| 645 | |
| 646 | impl RemoteFetchAbortGuard { |
| 647 | fn new( |
| 648 | app: &AppHandle, |
| 649 | node: String, |
| 650 | addr: String, |
| 651 | scope: String, |
| 652 | request: Option<celld::js::RequestId>, |
| 653 | ) -> Self { |
| 654 | Self { |
| 655 | http: app.peer_http.clone(), |
| 656 | auth: app.peer_auth.clone(), |
| 657 | node, |
| 658 | addr, |
| 659 | scope, |
| 660 | request, |
| 661 | phase: "response_head", |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | fn body_active(&mut self) { |
| 666 | self.phase = "response_body"; |
| 667 | } |
| 668 | |
| 669 | fn disarm(&mut self) { |
| 670 | self.request = None; |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | impl Drop for RemoteFetchAbortGuard { |
| 675 | fn drop(&mut self) { |
| 676 | let Some(request) = self.request.take() else { |
| 677 | return; |
| 678 | }; |
| 679 | let http = self.http.clone(); |
| 680 | let auth = self.auth.clone(); |
| 681 | let node = self.node.clone(); |
| 682 | let addr = self.addr.clone(); |
| 683 | let scope = self.scope.clone(); |
| 684 | let phase = self.phase; |
| 685 | celld::asyncrt::op_handle().spawn(async move { |
| 686 | let abort = send_peer_abort(http, auth, node.clone(), addr, scope.clone(), request); |
| 687 | match tokio::time::timeout(std::time::Duration::from_secs(2), abort).await { |
| 688 | Ok(Ok(())) => tracing::debug!( |
| 689 | event = "peer_fetch_abort_sent", |
| 690 | %node, |
| 691 | %scope, |
| 692 | request_id = %celld::js::request_id_string(request), |
| 693 | phase, |
| 694 | "propagated a disconnected caller to the cell owner" |
| 695 | ), |
| 696 | Ok(Err(error)) => tracing::debug!( |
| 697 | event = "peer_fetch_abort_failed", |
| 698 | %node, |
| 699 | %scope, |
| 700 | %error, |
| 701 | "could not propagate a disconnected caller to the cell owner" |
| 702 | ), |
| 703 | Err(_) => tracing::debug!( |
| 704 | event = "peer_fetch_abort_timed_out", |
| 705 | %node, |
| 706 | %scope, |
| 707 | "timed out propagating a disconnected caller to the cell owner" |
| 708 | ), |
| 709 | } |
| 710 | }); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | async fn send_peer_abort( |
| 715 | http: reqwest::Client, |
| 716 | auth: Arc<PeerAuth>, |
| 717 | node: String, |
| 718 | addr: String, |
| 719 | scope: String, |
| 720 | request: celld::js::RequestId, |
| 721 | ) -> anyhow::Result<()> { |
| 722 | let encoded_scope = |
| 723 | percent_encoding::utf8_percent_encode(&scope, percent_encoding::NON_ALPHANUMERIC); |
| 724 | let path = format!( |
| 725 | "/peer/abort/{encoded_scope}/{}", |
| 726 | celld::js::request_id_string(request) |
| 727 | ); |
| 728 | let request = auth.sign( |
| 729 | http.post(format!("http://{addr}{path}")), |
| 730 | "POST", |
| 731 | &path, |
| 732 | &[], |
| 733 | &node, |
| 734 | )?; |
| 735 | let response = request.body(Vec::new()).send().await?; |
| 736 | peer_auth::validate_response(response.headers())?; |
| 737 | anyhow::ensure!( |
| 738 | response.status().is_success(), |
| 739 | "peer abort failed with {}", |
| 740 | response.status() |
| 741 | ); |
| 742 | Ok(()) |
| 743 | } |
| 744 | |
| 745 | /// Call the reserved cron cell's arm endpoint, through the ordinary Durable |
| 746 | /// Object routing path so ownership resolution and remote forwarding are the |
| 747 | /// ones every other call gets. |
| 748 | async fn arm_cron_schedule(app: AppHandle, cell: String) -> anyhow::Result<()> { |
| 749 | let (reply, receive) = tokio::sync::oneshot::channel(); |
| 750 | let body = celld::js::RequestBody::Bytes(Bytes::new()); |
| 751 | dispatch_do_call( |
| 752 | app, |
| 753 | DoCallReq { |
| 754 | request_id: None, |
| 755 | cancel: None, |
| 756 | deliver_abort_to_handler: false, |
| 757 | scope: cell, |
| 758 | name: None, |
| 759 | url: "https://cron.celld.internal/arm".to_string(), |
| 760 | method: "POST".to_string(), |
| 761 | body_guard: celld::js::RequestBodyGuard::of(&body), |
| 762 | body, |
| 763 | headers: Vec::new(), |
| 764 | reply, |
| 765 | order: None, |
| 766 | parent: None, |
| 767 | }, |
| 768 | ) |
| 769 | .await; |
| 770 | let response = receive.await.context("cron arm dispatch dropped")??; |
| 771 | if !(200..300).contains(&response.status) { |
| 772 | anyhow::bail!("cron arm returned status {}", response.status); |
| 773 | } |
| 774 | Ok(()) |
| 775 | } |
| 776 | |
| 777 | /// Arm the current deployment's cron schedule, if it declares one. |
| 778 | /// |
| 779 | /// A cron cell has no client to wake it, so somebody has to make the first |
| 780 | /// call; every node makes it, and ownership CAS decides which one keeps the |
| 781 | /// cell while the others route to that owner. No new election, no reserved |
| 782 | /// node -- the same arbiter that makes an alarm fire once per fleet makes a |
| 783 | /// cron trigger fire once too. Boot and adoption both come through here, so |
| 784 | /// a schedule change arrives with the deployment that carries it. |
| 785 | fn spawn_cron_arm(app: AppHandle) { |
| 786 | let Some(cell) = app.runtime.as_ref().and_then(|runtime| runtime.cron_cell()) else { |
| 787 | return; |
| 788 | }; |
| 789 | tokio::spawn(async move { |
| 790 | // Routing needs node authority, exactly as the wake scan does. |
| 791 | let deadline = Instant::now() + std::time::Duration::from_secs(30); |
| 792 | while !app.healthy().await { |
| 793 | if Instant::now() >= deadline { |
| 794 | tracing::warn!(cell, "cron schedule not armed: no node authority"); |
| 795 | return; |
| 796 | } |
| 797 | tokio::time::sleep(std::time::Duration::from_millis(10)).await; |
| 798 | } |
| 799 | // A failed arm leaves the schedule silent until the next adoption, |
| 800 | // so retry rather than log once. The backoff is bounded because a |
| 801 | // fleet that cannot route for a minute has a larger problem. |
| 802 | for attempt in 0..5 { |
| 803 | match arm_cron_schedule(app.clone(), cell.clone()).await { |
| 804 | Ok(()) => return, |
| 805 | Err(error) if attempt == 4 => { |
| 806 | tracing::error!(cell, %error, "cron schedule not armed"); |
| 807 | } |
| 808 | Err(error) => { |
| 809 | tracing::warn!(cell, %error, attempt, "cron arm failed, retrying"); |
| 810 | tokio::time::sleep(std::time::Duration::from_millis(500 << attempt.min(5))) |
| 811 | .await; |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | }); |
| 816 | } |
| 817 | |
| 818 | /// Adopt the deployment `pointer` names. |
| 819 | /// |
| 820 | /// The same two calls boot makes -- `DeploymentGraph::load` and |
| 821 | /// `Generation::build` -- then the flip and the cron arm. A build that fails |
| 822 | /// leaves the current generation serving; nothing has changed until `adopt`. |
| 823 | async fn adopt_deployment( |
| 824 | app: &AppHandle, |
| 825 | bucket: &Bucket, |
| 826 | node: &str, |
| 827 | region: &str, |
| 828 | pointer: DeployPointer, |
| 829 | force: bool, |
| 830 | ) -> ReloadOutcome { |
| 831 | let Some(runtime) = app.runtime.as_ref() else { |
| 832 | return ReloadOutcome::Failed { |
| 833 | version: pointer.version, |
| 834 | prefix: pointer.prefix, |
| 835 | error: "this node has no Worker runtime".to_string(), |
| 836 | }; |
| 837 | }; |
| 838 | let current = runtime.generation(); |
| 839 | if !force && pointer.version == current.version() && pointer.prefix == current.prefix() { |
| 840 | return ReloadOutcome::Unchanged { |
| 841 | generation: current.id(), |
| 842 | version: current.version().to_string(), |
| 843 | }; |
| 844 | } |
| 845 | let failed = |error: String| ReloadOutcome::Failed { |
| 846 | version: pointer.version.clone(), |
| 847 | prefix: pointer.prefix.clone(), |
| 848 | error, |
| 849 | }; |
| 850 | let graph = match DeploymentGraph::load(bucket, node.to_string()).await { |
| 851 | Ok(graph) => graph, |
| 852 | Err(error) => return failed(format!("{error:#}")), |
| 853 | }; |
| 854 | let id = runtime.next_generation_id(); |
| 855 | let options = GenerationOptions { |
| 856 | node: node.to_string(), |
| 857 | region: region.to_string(), |
| 858 | }; |
| 859 | // Building compiles every script, so it runs on a blocking thread. |
| 860 | let built = tokio::task::spawn_blocking(move || Generation::build(id, graph, options)).await; |
| 861 | let generation = match built { |
| 862 | Ok(Ok(generation)) => generation, |
| 863 | Ok(Err(error)) => return failed(format!("{error:#}")), |
| 864 | Err(error) => return failed(format!("generation build panicked: {error}")), |
| 865 | }; |
| 866 | let adopted = runtime.adopt(generation); |
| 867 | // Tell the core, so resident cells move to the new generation at their |
| 868 | // safe points. The reserved cells move at once, ahead of the cron arm |
| 869 | // below, which must reach a cron cell already running the new schedule. |
| 870 | let _ = app.tx.send(Message::GenerationChanged { |
| 871 | generation: adopted.id(), |
| 872 | max_age_ms: celld::generation::max_age().as_millis() as u64, |
| 873 | eager_classes: adopted.reserved_classes(), |
| 874 | }); |
| 875 | spawn_cron_arm(app.clone()); |
| 876 | ReloadOutcome::Adopted { |
| 877 | generation: adopted.id(), |
| 878 | version: adopted.version().to_string(), |
| 879 | prefix: adopted.prefix().to_string(), |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | /// The pointer watcher: the node's one reader of `deploy/current.json` |
| 884 | /// after boot. |
| 885 | /// |
| 886 | /// It polls on a slow interval and adopts what the pointer names through |
| 887 | /// `adopt_deployment`; a `POST /reload` or a managed notification only makes |
| 888 | /// it look now. The pointer is the authority, so a missed nudge degrades to |
| 889 | /// "adopts one interval later". A version that failed to build is remembered |
| 890 | /// and not retried until the pointer names something else or a reload is |
| 891 | /// forced: a broken bundle must not recompile every interval on every node. |
| 892 | fn start_pointer_watcher( |
| 893 | app: AppHandle, |
| 894 | bucket: Bucket, |
| 895 | node: String, |
| 896 | region: String, |
| 897 | mut requests: celld::generation::ReloadReceiver, |
| 898 | ) { |
| 899 | tokio::spawn(async move { |
| 900 | let period = celld::generation::poll_interval(); |
| 901 | let mut tick = tokio::time::interval_at(tokio::time::Instant::now() + period, period); |
| 902 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 903 | let mut failed: Option<ReloadOutcome> = None; |
| 904 | loop { |
| 905 | let request = celld::asyncrt::select! { |
| 906 | _ = tick.tick() => ReloadRequest { force: false, reply: None }, |
| 907 | request = requests.recv() => match request { |
| 908 | Some(request) => request, |
| 909 | None => return, |
| 910 | }, |
| 911 | }; |
| 912 | let outcome = match fleet::read_current_pointer(&bucket).await { |
| 913 | Err(error) => { |
| 914 | tracing::warn!(event = "deployment_pointer_unreadable", %error); |
| 915 | ReloadOutcome::Failed { |
| 916 | version: String::new(), |
| 917 | prefix: String::new(), |
| 918 | error: format!("{error:#}"), |
| 919 | } |
| 920 | } |
| 921 | Ok(pointer) => match &failed { |
| 922 | Some(ReloadOutcome::Failed { |
| 923 | version, prefix, .. |
| 924 | }) if !request.force |
| 925 | && version == &pointer.version |
| 926 | && prefix == &pointer.prefix => |
| 927 | { |
| 928 | failed.clone().expect("matched above") |
| 929 | } |
| 930 | _ => { |
| 931 | adopt_deployment(&app, &bucket, &node, ®ion, pointer, request.force) |
| 932 | .await |
| 933 | } |
| 934 | }, |
| 935 | }; |
| 936 | match &outcome { |
| 937 | ReloadOutcome::Adopted { |
| 938 | generation, |
| 939 | version, |
| 940 | prefix, |
| 941 | } => { |
| 942 | failed = None; |
| 943 | tracing::info!( |
| 944 | event = "deployment_adopted", |
| 945 | generation, |
| 946 | version = %version, |
| 947 | prefix = %prefix, |
| 948 | "deployment adopted in place" |
| 949 | ); |
| 950 | } |
| 951 | ReloadOutcome::Unchanged { .. } => {} |
| 952 | ReloadOutcome::Failed { |
| 953 | version, |
| 954 | prefix, |
| 955 | error, |
| 956 | } => { |
| 957 | if failed.as_ref() != Some(&outcome) { |
| 958 | tracing::error!( |
| 959 | event = "deployment_adoption_failed", |
| 960 | version = %version, |
| 961 | prefix = %prefix, |
| 962 | %error, |
| 963 | "deployment did not build; the current generation keeps serving" |
| 964 | ); |
| 965 | } |
| 966 | if !version.is_empty() { |
| 967 | failed = Some(outcome.clone()); |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | if let Some(reply) = request.reply { |
| 972 | let _ = reply.send(outcome); |
| 973 | } |
| 974 | } |
| 975 | }); |
| 976 | } |
| 977 | |
| 978 | /// `POST /reload`: adopt the pointer's deployment now and report the outcome. |
| 979 | /// Forced, so an unchanged pointer still builds a new generation and a vars |
| 980 | /// file edit takes effect. |
| 981 | /// Pause or resume balancing. The node publishes the flag in its lease, and |
| 982 | /// one paused lease stops every donor in the fleet, so an operator pauses |
| 983 | /// the fleet from any node and resumes it from the same one. |
| 984 | fn internal_rebalance_switch(paused: bool) -> HttpReply { |
| 985 | if !celld::ownership_store::set_rebalance_paused(paused) { |
| 986 | return response(StatusCode::CONFLICT, "this node publishes no lease"); |
| 987 | } |
| 988 | response(StatusCode::OK, format!("{{\"rebalance_paused\":{paused}}}")) |
| 989 | } |
| 990 | |
| 991 | async fn internal_reload(app: AppHandle) -> HttpReply { |
| 992 | let (reply, receive) = tokio::sync::oneshot::channel(); |
| 993 | let sent = app |
| 994 | .reload |
| 995 | .send(ReloadRequest { |
| 996 | force: true, |
| 997 | reply: Some(reply), |
| 998 | }) |
| 999 | .is_ok(); |
| 1000 | let outcome = if sent { receive.await.ok() } else { None }; |
| 1001 | let (status, body) = match outcome { |
| 1002 | Some(ReloadOutcome::Adopted { |
| 1003 | generation, |
| 1004 | version, |
| 1005 | prefix, |
| 1006 | }) => ( |
| 1007 | StatusCode::OK, |
| 1008 | serde_json::json!({ |
| 1009 | "ok": true, |
| 1010 | "outcome": "adopted", |
| 1011 | "generation": generation, |
| 1012 | "version": version, |
| 1013 | "prefix": prefix, |
| 1014 | }), |
| 1015 | ), |
| 1016 | Some(ReloadOutcome::Unchanged { |
| 1017 | generation, |
| 1018 | version, |
| 1019 | }) => ( |
| 1020 | StatusCode::OK, |
| 1021 | serde_json::json!({ |
| 1022 | "ok": true, |
| 1023 | "outcome": "unchanged", |
| 1024 | "generation": generation, |
| 1025 | "version": version, |
| 1026 | }), |
| 1027 | ), |
| 1028 | Some(ReloadOutcome::Failed { |
| 1029 | version, |
| 1030 | prefix, |
| 1031 | error, |
| 1032 | }) => ( |
| 1033 | StatusCode::UNPROCESSABLE_ENTITY, |
| 1034 | serde_json::json!({ |
| 1035 | "ok": false, |
| 1036 | "outcome": "failed", |
| 1037 | "version": version, |
| 1038 | "prefix": prefix, |
| 1039 | "error": error, |
| 1040 | }), |
| 1041 | ), |
| 1042 | None => ( |
| 1043 | StatusCode::SERVICE_UNAVAILABLE, |
| 1044 | serde_json::json!({ |
| 1045 | "ok": false, |
| 1046 | "outcome": "unavailable", |
| 1047 | "error": "this node has no deployment pointer to reload from", |
| 1048 | }), |
| 1049 | ), |
| 1050 | }; |
| 1051 | response(status, body.to_string()) |
| 1052 | } |
| 1053 | |
| 1054 | fn local_dispatch_request_id( |
| 1055 | request_id: Option<celld::js::RequestId>, |
| 1056 | ) -> Option<celld::js::RequestId> { |
| 1057 | // Internal Queue, cron, alarm, and peer calls have no client request ID, |
| 1058 | // but a local handler still needs an identity in the abort registry. The |
| 1059 | // drain cancels by core request and resolves that identity through the |
| 1060 | // activity pin; leaving it absent makes a busy internal handler impossible |
| 1061 | // to stop before the process deadline. |
| 1062 | Some(request_id.unwrap_or_else(celld::js::next_request_id)) |
| 1063 | } |
| 1064 | |
| 1065 | async fn dispatch_do_call(app: AppHandle, call: DoCallReq) { |
| 1066 | let DoCallReq { |
| 1067 | request_id, |
| 1068 | cancel, |
| 1069 | deliver_abort_to_handler, |
| 1070 | scope, |
| 1071 | name, |
| 1072 | url, |
| 1073 | method, |
| 1074 | body, |
| 1075 | mut body_guard, |
| 1076 | headers, |
| 1077 | reply, |
| 1078 | order, |
| 1079 | parent, |
| 1080 | } = call; |
| 1081 | let mut cancel = cancel; |
| 1082 | let mut order = order; |
| 1083 | let mut websocket_timing = headers |
| 1084 | .iter() |
| 1085 | .any(|(name, value)| { |
| 1086 | name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket") |
| 1087 | }) |
| 1088 | .then(|| WebSocketRouteTiming { |
| 1089 | started: Instant::now(), |
| 1090 | route_resolution_us: 0, |
| 1091 | dispatch_us: 0, |
| 1092 | attempts: 0, |
| 1093 | }); |
| 1094 | let operation = async { |
| 1095 | // Reclaims a streamed body abandoned by an early error below. A local |
| 1096 | // target or the peer HTTP body takes ownership before this guard is |
| 1097 | // disarmed. |
| 1098 | anyhow::ensure!( |
| 1099 | celld_logic::cell::valid_cell_scope(&scope), |
| 1100 | "cell scope is malformed or exceeds the fleet storage limit" |
| 1101 | ); |
| 1102 | let mut dispatcher = RemoteRouteRetry::new(app.operation_deadline_ms); |
| 1103 | loop { |
| 1104 | if let Some(timing) = websocket_timing.as_mut() { |
| 1105 | timing.attempts = timing.attempts.saturating_add(1); |
| 1106 | } |
| 1107 | let route_started = Instant::now(); |
| 1108 | // A disconnect before routing completes has executed no handler, |
| 1109 | // so cancel the core request and release its activation admission. |
| 1110 | // Once routing completes, the same signal moves into the local or |
| 1111 | // remote dispatch below and aborts work that did start. |
| 1112 | let route = app.request(scope.clone()); |
| 1113 | let routed = if deliver_abort_to_handler { |
| 1114 | // Workerd delivers an explicit JavaScript AbortSignal to the |
| 1115 | // target request. Resolve the route first, then give the |
| 1116 | // already-fired receiver to fetch_cell so the handler sees |
| 1117 | // request.signal and its waitUntil work can continue. |
| 1118 | route.await |
| 1119 | } else { |
| 1120 | match cancel.as_mut() { |
| 1121 | Some(cancel) => celld::asyncrt::select_biased! { |
| 1122 | "a cancellation that ties route resolution prevents dispatch from starting"; |
| 1123 | _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")), |
| 1124 | routed = route => routed, |
| 1125 | }, |
| 1126 | None => route.await, |
| 1127 | } |
| 1128 | }; |
| 1129 | let routed = match routed { |
| 1130 | Ok(routed) => routed, |
| 1131 | Err(error) => { |
| 1132 | if let Some(timing) = websocket_timing.as_mut() { |
| 1133 | timing.route_resolution_us = timing |
| 1134 | .route_resolution_us |
| 1135 | .saturating_add(route_started.elapsed().as_micros() as u64); |
| 1136 | timing.emit(&app, &scope, request_id, "route_error", "", ""); |
| 1137 | } |
| 1138 | break Err(anyhow::Error::new(RoutedRequestError(error))); |
| 1139 | } |
| 1140 | }; |
| 1141 | if let Some(timing) = websocket_timing.as_mut() { |
| 1142 | timing.route_resolution_us = timing |
| 1143 | .route_resolution_us |
| 1144 | .saturating_add(route_started.elapsed().as_micros() as u64); |
| 1145 | } |
| 1146 | let Routed { request, route } = routed; |
| 1147 | let (node, addr, epoch, peer_protocol) = match route { |
| 1148 | Route::Local => { |
| 1149 | let dispatch_started = Instant::now(); |
| 1150 | let local_request_id = local_dispatch_request_id(request_id); |
| 1151 | let local = |
| 1152 | app.local_request(request, scope.clone(), local_request_id, "local"); |
| 1153 | let completed = local |
| 1154 | .run(async { |
| 1155 | let runtime = app.runtime.as_ref().context("no cell runtime")?; |
| 1156 | let response = runtime |
| 1157 | .fetch_cell( |
| 1158 | scope.clone(), |
| 1159 | name, |
| 1160 | RuntimeFetch { |
| 1161 | url, |
| 1162 | method, |
| 1163 | body, |
| 1164 | headers, |
| 1165 | request_id: local_request_id, |
| 1166 | // Moved on the first attempt and gone on |
| 1167 | // a retry, which is right: a retry is a |
| 1168 | // second delivery of a call whose place |
| 1169 | // in the order was already taken. |
| 1170 | order: order.take(), |
| 1171 | parent, |
| 1172 | }, |
| 1173 | cancel.take(), |
| 1174 | ) |
| 1175 | .await?; |
| 1176 | // `fetch_cell` cannot return a response until the cell |
| 1177 | // has installed its request context. That context now |
| 1178 | // owns an unread tail through its waitUntil work. |
| 1179 | body_guard.disarm(); |
| 1180 | if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket { |
| 1181 | let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) |
| 1182 | { |
| 1183 | WebSocketKind::Hibernatable |
| 1184 | } else { |
| 1185 | WebSocketKind::Regular |
| 1186 | }; |
| 1187 | app.websocket_opened(target.scope.clone(), target.id, kind) |
| 1188 | .await?; |
| 1189 | } |
| 1190 | Ok(response) |
| 1191 | }) |
| 1192 | .await; |
| 1193 | let activity = completed.activity; |
| 1194 | let result = completed.result.map_err(local_request_error); |
| 1195 | let result = match result { |
| 1196 | Ok(mut response) => { |
| 1197 | let body_active = response.stream.is_some(); |
| 1198 | activity.set_phase("response_body", true, body_active); |
| 1199 | if let Some(stream) = response.stream.take() { |
| 1200 | response.stream = |
| 1201 | Some(local_response_stream(stream, activity, || {})); |
| 1202 | } else { |
| 1203 | drop(activity); |
| 1204 | } |
| 1205 | Ok(response) |
| 1206 | } |
| 1207 | Err(error) => Err(error), |
| 1208 | }; |
| 1209 | if let Some(timing) = websocket_timing.as_mut() { |
| 1210 | timing.dispatch_us = timing |
| 1211 | .dispatch_us |
| 1212 | .saturating_add(dispatch_started.elapsed().as_micros() as u64); |
| 1213 | timing.emit( |
| 1214 | &app, |
| 1215 | &scope, |
| 1216 | request_id, |
| 1217 | if result.is_ok() { "ok" } else { "error" }, |
| 1218 | "local", |
| 1219 | app.runtime.as_ref().map_or("", RuntimeManager::node), |
| 1220 | ); |
| 1221 | } |
| 1222 | break result; |
| 1223 | } |
| 1224 | Route::Remote { |
| 1225 | node, |
| 1226 | addr, |
| 1227 | epoch, |
| 1228 | peer_protocol, |
| 1229 | } => (node, addr, epoch, peer_protocol), |
| 1230 | }; |
| 1231 | if dispatcher.observe(&node, epoch) { |
| 1232 | let cancel = if deliver_abort_to_handler { |
| 1233 | None |
| 1234 | } else { |
| 1235 | cancel.as_mut() |
| 1236 | }; |
| 1237 | match dispatcher.wait(cancel).await { |
| 1238 | RemoteRetryOutcome::Ready => { |
| 1239 | dispatcher.invalidate(&app, &scope).await; |
| 1240 | continue; |
| 1241 | } |
| 1242 | RemoteRetryOutcome::Cancelled => { |
| 1243 | break Err(anyhow::anyhow!("Durable Object call cancelled")); |
| 1244 | } |
| 1245 | RemoteRetryOutcome::Stop => { |
| 1246 | break Err(anyhow::anyhow!( |
| 1247 | "remote owner remained stale until the retry deadline" |
| 1248 | )); |
| 1249 | } |
| 1250 | } |
| 1251 | } |
| 1252 | let dispatch_started = Instant::now(); |
| 1253 | let streamed_attempt = matches!(body, celld::js::RequestBody::Stream(_)); |
| 1254 | let remote_call = async { |
| 1255 | anyhow::ensure!( |
| 1256 | peer_protocol == peer_auth::PROTOCOL_VERSION, |
| 1257 | "peer {node} speaks incompatible protocol {peer_protocol}" |
| 1258 | ); |
| 1259 | { |
| 1260 | let control = peer_tunnel::TunnelControl { |
| 1261 | scope: scope.clone(), |
| 1262 | name: name.clone(), |
| 1263 | request_id, |
| 1264 | capacity_handoff: epoch == 0, |
| 1265 | }; |
| 1266 | let attempt_body = match &body { |
| 1267 | celld::js::RequestBody::Bytes(bytes) => { |
| 1268 | celld::js::RequestBody::Bytes(bytes.clone()) |
| 1269 | } |
| 1270 | celld::js::RequestBody::Stream(stream_id) => { |
| 1271 | celld::js::RequestBody::Stream(*stream_id) |
| 1272 | } |
| 1273 | }; |
| 1274 | let mut abort = RemoteFetchAbortGuard::new( |
| 1275 | &app, |
| 1276 | node.clone(), |
| 1277 | addr.clone(), |
| 1278 | scope.clone(), |
| 1279 | request_id, |
| 1280 | ); |
| 1281 | let response = peer_tunnel::fetch( |
| 1282 | &peer_tunnel::Peer { |
| 1283 | http: &app.peer_http, |
| 1284 | auth: &app.peer_auth, |
| 1285 | addr: &addr, |
| 1286 | node: &node, |
| 1287 | }, |
| 1288 | &control, |
| 1289 | url.clone(), |
| 1290 | method.clone(), |
| 1291 | headers.clone(), |
| 1292 | attempt_body, |
| 1293 | ) |
| 1294 | .await |
| 1295 | .map_err(|error| owner_unreachable(&scope, &addr, error))?; |
| 1296 | // Only after the tunnel has taken the stream: `disarm` |
| 1297 | // releases the guard's registry claim, and a claim that |
| 1298 | // drops to zero deletes the entry, so disarming before |
| 1299 | // the take deletes the body out from under the attempt. |
| 1300 | // An error above keeps the guard armed so an untaken |
| 1301 | // stream is still cleaned up. |
| 1302 | body_guard.disarm(); |
| 1303 | if response |
| 1304 | .headers() |
| 1305 | .get(STALE_ROUTE_HEADER) |
| 1306 | .is_some_and(|value| value == STALE_ROUTE_VALUE) |
| 1307 | { |
| 1308 | abort.disarm(); |
| 1309 | return Err(owner_unreachable( |
| 1310 | &scope, |
| 1311 | &addr, |
| 1312 | anyhow::Error::new(StalePeerRoute { |
| 1313 | scope: scope.clone(), |
| 1314 | }), |
| 1315 | )); |
| 1316 | } |
| 1317 | let status = response.status().as_u16(); |
| 1318 | if status == 101 { |
| 1319 | // A tunneled upgrade: the inner 101 is the cell's |
| 1320 | // own handshake for this client's key. Park the |
| 1321 | // inner upgrade; once this node's client socket |
| 1322 | // upgrades, the two splice and the hop copies |
| 1323 | // bytes. The handshake fields are dropped because |
| 1324 | // the client-facing 101 regenerates them. |
| 1325 | let response_headers = response |
| 1326 | .headers() |
| 1327 | .iter() |
| 1328 | .filter(|(header, _)| { |
| 1329 | let header = header.as_str(); |
| 1330 | header != "upgrade" |
| 1331 | && header != "connection" |
| 1332 | && header != "sec-websocket-accept" |
| 1333 | }) |
| 1334 | .filter_map(|(header, value)| { |
| 1335 | value |
| 1336 | .to_str() |
| 1337 | .ok() |
| 1338 | .map(|value| (header.to_string(), value.to_string())) |
| 1339 | }) |
| 1340 | .collect(); |
| 1341 | abort.disarm(); |
| 1342 | let mut response = response; |
| 1343 | let parked = peer_tunnel::park_upgrade(hyper::upgrade::on(&mut response)); |
| 1344 | return Ok(HttpResponse { |
| 1345 | status, |
| 1346 | headers: response_headers, |
| 1347 | body: Vec::new(), |
| 1348 | websocket: Some(HttpResponseWebSocket::Cell(celld::js::WsTarget { |
| 1349 | id: 0, |
| 1350 | scope: scope.clone(), |
| 1351 | tunnel: Some(parked), |
| 1352 | })), |
| 1353 | stream: None, |
| 1354 | write_position: None, |
| 1355 | observed_position: None, |
| 1356 | }); |
| 1357 | } |
| 1358 | let response_headers = response |
| 1359 | .headers() |
| 1360 | .iter() |
| 1361 | .filter_map(|(header, value)| { |
| 1362 | value |
| 1363 | .to_str() |
| 1364 | .ok() |
| 1365 | .map(|value| (header.to_string(), value.to_string())) |
| 1366 | }) |
| 1367 | .collect(); |
| 1368 | let stream = forwarder_response_stream( |
| 1369 | peer_tunnel::response_stream(response.into_body()), |
| 1370 | abort, |
| 1371 | ); |
| 1372 | Ok(HttpResponse { |
| 1373 | status, |
| 1374 | headers: response_headers, |
| 1375 | body: Vec::new(), |
| 1376 | websocket: None, |
| 1377 | stream: Some(stream), |
| 1378 | // A proxied remote response wrote on the owner, not |
| 1379 | // here. |
| 1380 | write_position: None, |
| 1381 | observed_position: None, |
| 1382 | }) |
| 1383 | } |
| 1384 | }; |
| 1385 | let remote = match cancel.as_mut() { |
| 1386 | Some(cancel) => celld::asyncrt::select_biased! { |
| 1387 | "a cancellation that ties the remote response prevents returning abandoned work"; |
| 1388 | _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")), |
| 1389 | remote = remote_call => remote, |
| 1390 | }, |
| 1391 | None => remote_call.await, |
| 1392 | }; |
| 1393 | if let Some(timing) = websocket_timing.as_mut() { |
| 1394 | timing.dispatch_us = timing |
| 1395 | .dispatch_us |
| 1396 | .saturating_add(dispatch_started.elapsed().as_micros() as u64); |
| 1397 | } |
| 1398 | match remote { |
| 1399 | Ok(response) => { |
| 1400 | if let Some(timing) = websocket_timing.as_ref() { |
| 1401 | timing.emit(&app, &scope, request_id, "ok", "remote", &node); |
| 1402 | } |
| 1403 | break Ok(response); |
| 1404 | } |
| 1405 | Err(error) => { |
| 1406 | // A streamed upload is not replayable after the HTTP |
| 1407 | // client starts pulling it. Retrying would send only the |
| 1408 | // unread suffix as a new request, so fail this attempt |
| 1409 | // instead of manufacturing a truncated body. |
| 1410 | if streamed_attempt { |
| 1411 | break Err(error); |
| 1412 | } |
| 1413 | // Epoch zero is a candidate, not an owner. A peer refusal |
| 1414 | // proves this attempt did not execute and must not consume |
| 1415 | // the ordinary one-owner stale-route budget; |
| 1416 | // the core excludes that exact load sample before the |
| 1417 | // next deterministic placement decision. |
| 1418 | let capacity_refused = epoch == 0 |
| 1419 | && error |
| 1420 | .chain() |
| 1421 | .any(|cause| cause.downcast_ref::<StalePeerRoute>().is_some()); |
| 1422 | if capacity_refused { |
| 1423 | app.invalidate_remote(scope.clone(), node, epoch).await; |
| 1424 | // Pace this unbounded retry. Each attempt now costs a |
| 1425 | // fresh tunnel connection, and a tight loop against a |
| 1426 | // candidate that is still restoring floods the client |
| 1427 | // ephemeral-port range into TIME_WAIT (os error 49), |
| 1428 | // which then poisons every dial for the next 15s. |
| 1429 | tokio::time::sleep(std::time::Duration::from_millis(25)).await; |
| 1430 | continue; |
| 1431 | } |
| 1432 | let cancel = if deliver_abort_to_handler { |
| 1433 | None |
| 1434 | } else { |
| 1435 | cancel.as_mut() |
| 1436 | }; |
| 1437 | match dispatcher |
| 1438 | .retry(&app, &scope, classify_remote_attempt(&error), cancel, None) |
| 1439 | .await |
| 1440 | { |
| 1441 | RemoteRetryOutcome::Ready => continue, |
| 1442 | RemoteRetryOutcome::Cancelled => { |
| 1443 | break Err(anyhow::anyhow!("Durable Object call cancelled")); |
| 1444 | } |
| 1445 | RemoteRetryOutcome::Stop => {} |
| 1446 | } |
| 1447 | if let Some(timing) = websocket_timing.as_ref() { |
| 1448 | timing.emit(&app, &scope, request_id, "error", "remote", &node); |
| 1449 | } |
| 1450 | break Err(error); |
| 1451 | } |
| 1452 | } |
| 1453 | } |
| 1454 | }; |
| 1455 | let result = operation.await; |
| 1456 | let _ = reply.send(result); |
| 1457 | } |
| 1458 | |
| 1459 | async fn dispatch_rpc_call(app: AppHandle, call: RpcCallReq) { |
| 1460 | let RpcCallReq { |
| 1461 | scope, |
| 1462 | name, |
| 1463 | method, |
| 1464 | args, |
| 1465 | reply, |
| 1466 | } = call; |
| 1467 | let result = async { |
| 1468 | anyhow::ensure!( |
| 1469 | celld_logic::cell::valid_cell_scope(&scope), |
| 1470 | "cell scope is malformed or exceeds the fleet storage limit" |
| 1471 | ); |
| 1472 | let mut dispatcher = RemoteRouteRetry::new(app.operation_deadline_ms); |
| 1473 | loop { |
| 1474 | let Routed { request, route } = app |
| 1475 | .request(scope.clone()) |
| 1476 | .await |
| 1477 | .map_err(|error| anyhow::anyhow!("route RPC {scope}: {error:?}"))?; |
| 1478 | let (node, addr, epoch, peer_protocol) = match route { |
| 1479 | Route::Local => { |
| 1480 | let local_request_id = local_dispatch_request_id(None); |
| 1481 | let completed = app |
| 1482 | .local_request(request, scope.clone(), local_request_id, "local") |
| 1483 | .run(async { |
| 1484 | app.runtime |
| 1485 | .as_ref() |
| 1486 | .context("no cell runtime")? |
| 1487 | .rpc(scope, name, method, args, local_request_id) |
| 1488 | .await |
| 1489 | }) |
| 1490 | .await; |
| 1491 | return Ok(completed.result.map_err(local_request_error)?.data); |
| 1492 | } |
| 1493 | Route::Remote { |
| 1494 | node, |
| 1495 | addr, |
| 1496 | epoch, |
| 1497 | peer_protocol, |
| 1498 | } => (node, addr, epoch, peer_protocol), |
| 1499 | }; |
| 1500 | if dispatcher.observe(&node, epoch) { |
| 1501 | match dispatcher.wait(None).await { |
| 1502 | RemoteRetryOutcome::Ready => { |
| 1503 | dispatcher.invalidate(&app, &scope).await; |
| 1504 | continue; |
| 1505 | } |
| 1506 | RemoteRetryOutcome::Stop => { |
| 1507 | anyhow::bail!("remote RPC owner remained stale until the retry deadline") |
| 1508 | } |
| 1509 | RemoteRetryOutcome::Cancelled => unreachable!("RPC route waits have no cancel"), |
| 1510 | } |
| 1511 | } |
| 1512 | anyhow::ensure!( |
| 1513 | peer_protocol == peer_auth::PROTOCOL_VERSION, |
| 1514 | "peer {node} speaks incompatible protocol {peer_protocol}" |
| 1515 | ); |
| 1516 | let expects_structured_response = matches!(args, celld::js::RpcData::V8(_)); |
| 1517 | { |
| 1518 | let response = peer_tunnel::rpc( |
| 1519 | &peer_tunnel::Peer { |
| 1520 | http: &app.peer_http, |
| 1521 | auth: &app.peer_auth, |
| 1522 | addr: &addr, |
| 1523 | node: &node, |
| 1524 | }, |
| 1525 | &scope, |
| 1526 | name.as_deref(), |
| 1527 | &method, |
| 1528 | &args, |
| 1529 | ) |
| 1530 | .await; |
| 1531 | // Classify failures before response decoding. An explicit stale |
| 1532 | // owner ran nothing; a failed or truncated reply after execution |
| 1533 | // remains ambiguous and cannot justify another RPC invocation. |
| 1534 | let attempt = match &response { |
| 1535 | Err(error) => Some(classify_remote_attempt(error)), |
| 1536 | Ok(response) |
| 1537 | if response |
| 1538 | .headers() |
| 1539 | .get(STALE_ROUTE_HEADER) |
| 1540 | .is_some_and(|value| value == STALE_ROUTE_VALUE) => |
| 1541 | { |
| 1542 | Some(celld_logic::routing::Attempt::NotOwner) |
| 1543 | } |
| 1544 | Ok(_) => None, |
| 1545 | }; |
| 1546 | if let Some(attempt) = attempt { |
| 1547 | match dispatcher |
| 1548 | .retry(&app, &scope, attempt, None, Some("rpc")) |
| 1549 | .await |
| 1550 | { |
| 1551 | RemoteRetryOutcome::Ready => continue, |
| 1552 | RemoteRetryOutcome::Cancelled => { |
| 1553 | unreachable!("RPC route waits have no cancel") |
| 1554 | } |
| 1555 | RemoteRetryOutcome::Stop => match response { |
| 1556 | Err(error) => anyhow::bail!("remote RPC transport failed: {error:#}"), |
| 1557 | Ok(_) => anyhow::bail!("remote RPC owner was stale"), |
| 1558 | }, |
| 1559 | } |
| 1560 | } |
| 1561 | let response = response?; |
| 1562 | if response.status() == StatusCode::SERVICE_UNAVAILABLE |
| 1563 | && response |
| 1564 | .headers() |
| 1565 | .get("x-celld-overload") |
| 1566 | .is_some_and(|value| value == "cell") |
| 1567 | { |
| 1568 | return Err(anyhow::Error::new(celld::js::CellOverloaded)); |
| 1569 | } |
| 1570 | anyhow::ensure!( |
| 1571 | response.status().is_success(), |
| 1572 | "remote RPC failed with {}", |
| 1573 | response.status() |
| 1574 | ); |
| 1575 | let body = response |
| 1576 | .into_body() |
| 1577 | .collect() |
| 1578 | .await |
| 1579 | .map_err(|error| anyhow::anyhow!("remote RPC body: {error}"))? |
| 1580 | .to_bytes(); |
| 1581 | return Ok(if expects_structured_response { |
| 1582 | celld::js::RpcData::V8(body) |
| 1583 | } else { |
| 1584 | celld::js::RpcData::Json(String::from_utf8_lossy(&body).into_owned()) |
| 1585 | }); |
| 1586 | } |
| 1587 | } |
| 1588 | } |
| 1589 | .await; |
| 1590 | let _ = reply.send(result); |
| 1591 | } |
| 1592 | |
| 1593 | async fn request_payload( |
| 1594 | request: Request<Incoming>, |
| 1595 | trust_forwarded_headers: bool, |
| 1596 | max_body_bytes: usize, |
| 1597 | ) -> Result<(String, String, Vec<u8>, Vec<(String, String)>), HttpReply> { |
| 1598 | let (parts, body) = request.into_parts(); |
| 1599 | let body = collect_limited_body(body, max_body_bytes) |
| 1600 | .await |
| 1601 | .map_err(|error| body_read_error("request", error))?; |
| 1602 | let headers = parts |
| 1603 | .headers |
| 1604 | .iter() |
| 1605 | .filter_map(|(name, value)| { |
| 1606 | value |
| 1607 | .to_str() |
| 1608 | .ok() |
| 1609 | .map(|value| (name.to_string(), value.to_string())) |
| 1610 | }) |
| 1611 | .collect(); |
| 1612 | Ok(( |
| 1613 | request_url(&parts, trust_forwarded_headers), |
| 1614 | parts.method.to_string(), |
| 1615 | body.to_vec(), |
| 1616 | headers, |
| 1617 | )) |
| 1618 | } |
| 1619 | |
| 1620 | /// A body at or above this many bytes reaches the Worker as a stream. |
| 1621 | /// |
| 1622 | /// A small body crosses as bytes. The host makes one copy, and the handler |
| 1623 | /// reads that copy with no asynchronous operation. A large body crosses as |
| 1624 | /// a stream, because one copy of a large body costs more than the |
| 1625 | /// operations that read it in parts. The host also streams a body that |
| 1626 | /// declares no length, because the host cannot know the size of that body. |
| 1627 | const INGRESS_STREAM_THRESHOLD: u64 = 1 << 20; |
| 1628 | /// Peer fetches and RPC calls can carry the same application data as public |
| 1629 | /// ingress. The frame needs room for its bounded metadata in addition to the |
| 1630 | /// application body. |
| 1631 | const MAX_PEER_FORWARD_BODY_BYTES: usize = DEFAULT_MAX_REQUEST_BODY_BYTES + (1 << 20); |
| 1632 | /// Operator requests carry JSON commands, migration SQL, or workflow event |
| 1633 | /// arguments. The 64 MiB ceiling leaves headroom above the 32 MiB D1 result |
| 1634 | /// contract without giving an operator route the 1 GiB forwarding allowance. |
| 1635 | const MAX_PEER_PROTOCOL_BODY_BYTES: usize = 64 << 20; |
| 1636 | /// Control messages contain identifiers and counters, not application data. |
| 1637 | const MAX_PEER_CONTROL_BODY_BYTES: usize = 64 << 10; |
| 1638 | const INTERNAL_LOG_APPEND_PATH: &str = "/peer/log/append"; |
| 1639 | /// A streamed body crosses the isolate boundary through a string-only error |
| 1640 | /// channel. Keep one private marker in that string so the HTTP entry point can |
| 1641 | /// restore status 413; a generic stream error would turn the refusal into 500. |
| 1642 | const BODY_LIMIT_STREAM_ERROR: &str = "celld request body limit exceeded"; |
| 1643 | |
| 1644 | enum BodyReadError { |
| 1645 | TooLarge, |
| 1646 | Invalid(String), |
| 1647 | } |
| 1648 | |
| 1649 | async fn collect_limited_body(body: Incoming, limit: usize) -> Result<Bytes, BodyReadError> { |
| 1650 | if body.size_hint().lower() > limit as u64 { |
| 1651 | return Err(BodyReadError::TooLarge); |
| 1652 | } |
| 1653 | Limited::new(body, limit) |
| 1654 | .collect() |
| 1655 | .await |
| 1656 | .map(|body| body.to_bytes()) |
| 1657 | .map_err(|error| { |
| 1658 | if error |
| 1659 | .downcast_ref::<http_body_util::LengthLimitError>() |
| 1660 | .is_some() |
| 1661 | { |
| 1662 | BodyReadError::TooLarge |
| 1663 | } else { |
| 1664 | BodyReadError::Invalid(error.to_string()) |
| 1665 | } |
| 1666 | }) |
| 1667 | } |
| 1668 | |
| 1669 | fn body_read_error(context: &str, error: BodyReadError) -> HttpReply { |
| 1670 | match error { |
| 1671 | BodyReadError::TooLarge => { |
| 1672 | response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large") |
| 1673 | } |
| 1674 | BodyReadError::Invalid(error) => response( |
| 1675 | StatusCode::BAD_REQUEST, |
| 1676 | format!("invalid {context} body: {error}"), |
| 1677 | ), |
| 1678 | } |
| 1679 | } |
| 1680 | |
| 1681 | fn request_body_limit_error(error: &anyhow::Error) -> bool { |
| 1682 | // The Worker runtime adds context around a host-stream failure, so inspect |
| 1683 | // the chain instead of requiring the marker to remain the top-level error. |
| 1684 | error |
| 1685 | .chain() |
| 1686 | .any(|cause| cause.to_string().contains(BODY_LIMIT_STREAM_ERROR)) |
| 1687 | } |
| 1688 | |
| 1689 | fn cell_overload_error(error: &anyhow::Error) -> bool { |
| 1690 | error.chain().any(|cause| { |
| 1691 | cause.downcast_ref::<celld::js::CellOverloaded>().is_some() |
| 1692 | // A Queue producer call crosses V8's promise boundary before the |
| 1693 | // public Worker response fails. The opaque text marker prevents an |
| 1694 | // application error from accidentally receiving the 503 contract. |
| 1695 | || cause |
| 1696 | .to_string() |
| 1697 | .contains(celld::js::CELL_OVERLOAD_ERROR_MARKER) |
| 1698 | }) |
| 1699 | } |
| 1700 | |
| 1701 | fn cell_overload_response() -> HttpReply { |
| 1702 | let mut refused = response( |
| 1703 | StatusCode::SERVICE_UNAVAILABLE, |
| 1704 | "{\"error\":\"cell admission refused\"}", |
| 1705 | ); |
| 1706 | refused.headers_mut().insert( |
| 1707 | hyper::header::RETRY_AFTER, |
| 1708 | hyper::header::HeaderValue::from_static("1"), |
| 1709 | ); |
| 1710 | refused.headers_mut().insert( |
| 1711 | hyper::header::HeaderName::from_static("x-celld-overload"), |
| 1712 | hyper::header::HeaderValue::from_static("cell"), |
| 1713 | ); |
| 1714 | refused |
| 1715 | } |
| 1716 | |
| 1717 | // The peer parser returns before a streamed body can cross its limit, so this |
| 1718 | // error arrives from the Worker and must retain the ingress 413 contract. |
| 1719 | fn internal_do_worker_error(error: anyhow::Error) -> HttpReply { |
| 1720 | if request_body_limit_error(&error) { |
| 1721 | return response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large"); |
| 1722 | } |
| 1723 | if cell_overload_error(&error) { |
| 1724 | return cell_overload_response(); |
| 1725 | } |
| 1726 | response( |
| 1727 | StatusCode::INTERNAL_SERVER_ERROR, |
| 1728 | format!("cell Worker failed: {error:#}"), |
| 1729 | ) |
| 1730 | } |
| 1731 | |
| 1732 | /// Divide an ingress request into its metadata and a body that the Worker |
| 1733 | /// can read. The function streams the body if one copy of the body costs |
| 1734 | /// more than the operations that read it in parts. |
| 1735 | async fn ingress_payload( |
| 1736 | request: Request<Incoming>, |
| 1737 | trust_forwarded_headers: bool, |
| 1738 | max_body_bytes: usize, |
| 1739 | ) -> Result< |
| 1740 | ( |
| 1741 | String, |
| 1742 | String, |
| 1743 | celld::js::RequestBody, |
| 1744 | Vec<(String, String)>, |
| 1745 | ), |
| 1746 | HttpReply, |
| 1747 | > { |
| 1748 | let declared = request |
| 1749 | .headers() |
| 1750 | .get(hyper::header::CONTENT_LENGTH) |
| 1751 | .and_then(|value| value.to_str().ok()) |
| 1752 | .and_then(|value| value.parse::<u64>().ok()); |
| 1753 | if declared.is_some_and(|length| length > max_body_bytes as u64) { |
| 1754 | return Err(response( |
| 1755 | StatusCode::PAYLOAD_TOO_LARGE, |
| 1756 | "request body too large", |
| 1757 | )); |
| 1758 | } |
| 1759 | let (url, method, body, headers, held) = |
| 1760 | ingress_payload_parts(request, trust_forwarded_headers, max_body_bytes).map_err( |
| 1761 | |error| { |
| 1762 | response( |
| 1763 | StatusCode::SERVICE_UNAVAILABLE, |
| 1764 | format!("request body stream: {error}"), |
| 1765 | ) |
| 1766 | }, |
| 1767 | )?; |
| 1768 | // The host collects a small body here. A read failure at this point |
| 1769 | // can still return status 400. A streamed body has no such point, |
| 1770 | // because that body fails while the handler reads it. The failure |
| 1771 | // surfaces there instead. |
| 1772 | let body = match held { |
| 1773 | None => body, |
| 1774 | Some(held) => match collect_limited_body(held, max_body_bytes).await { |
| 1775 | Ok(collected) => celld::js::RequestBody::Bytes(collected), |
| 1776 | Err(error) => return Err(body_read_error("request", error)), |
| 1777 | }, |
| 1778 | }; |
| 1779 | Ok((url, method, body, headers)) |
| 1780 | } |
| 1781 | |
| 1782 | type IngressPayloadParts = ( |
| 1783 | String, |
| 1784 | String, |
| 1785 | celld::js::RequestBody, |
| 1786 | Vec<(String, String)>, |
| 1787 | Option<Incoming>, |
| 1788 | ); |
| 1789 | |
| 1790 | fn ingress_payload_parts( |
| 1791 | request: Request<Incoming>, |
| 1792 | trust_forwarded_headers: bool, |
| 1793 | max_body_bytes: usize, |
| 1794 | ) -> Result<IngressPayloadParts, String> { |
| 1795 | let (parts, body) = request.into_parts(); |
| 1796 | let headers: Vec<(String, String)> = parts |
| 1797 | .headers |
| 1798 | .iter() |
| 1799 | .filter_map(|(name, value)| { |
| 1800 | value |
| 1801 | .to_str() |
| 1802 | .ok() |
| 1803 | .map(|value| (name.to_string(), value.to_string())) |
| 1804 | }) |
| 1805 | .collect(); |
| 1806 | let url = request_url(&parts, trust_forwarded_headers); |
| 1807 | let method = parts.method.to_string(); |
| 1808 | let declared = parts |
| 1809 | .headers |
| 1810 | .get(hyper::header::CONTENT_LENGTH) |
| 1811 | .and_then(|value| value.to_str().ok()) |
| 1812 | .and_then(|value| value.parse::<u64>().ok()); |
| 1813 | // A method that carries no body does not stream. There is nothing to |
| 1814 | // pull, and a stream costs the handler one operation to learn this. |
| 1815 | let bodyless = |
| 1816 | matches!(parts.method, hyper::Method::GET | hyper::Method::HEAD) || declared == Some(0); |
| 1817 | if bodyless || declared.is_some_and(|length| length < INGRESS_STREAM_THRESHOLD) { |
| 1818 | return Ok(( |
| 1819 | url, |
| 1820 | method, |
| 1821 | celld::js::RequestBody::Bytes(Bytes::new()), |
| 1822 | headers, |
| 1823 | Some(body), |
| 1824 | )); |
| 1825 | } |
| 1826 | let chunks = Limited::new(body, max_body_bytes) |
| 1827 | .into_data_stream() |
| 1828 | .map(|chunk| { |
| 1829 | chunk.map(|bytes| bytes.to_vec()).map_err(|error| { |
| 1830 | if error |
| 1831 | .downcast_ref::<http_body_util::LengthLimitError>() |
| 1832 | .is_some() |
| 1833 | { |
| 1834 | BODY_LIMIT_STREAM_ERROR.to_string() |
| 1835 | } else { |
| 1836 | error.to_string() |
| 1837 | } |
| 1838 | }) |
| 1839 | }); |
| 1840 | let stream_id = celld::js::register_body_stream(Box::pin(chunks))?; |
| 1841 | Ok(( |
| 1842 | url, |
| 1843 | method, |
| 1844 | celld::js::RequestBody::Stream(stream_id), |
| 1845 | headers, |
| 1846 | None, |
| 1847 | )) |
| 1848 | } |
| 1849 | |
| 1850 | /// The refusal every path arm gives a cell scope that fails the charset gate. |
| 1851 | /// |
| 1852 | /// A scope taken from a URL segment reaches `db_path`, which joins it under the |
| 1853 | /// data directory, and the replication client, which builds a bucket key from |
| 1854 | /// it, so a scope carrying its own path segments walks out of both. The gate |
| 1855 | /// itself is reified in `celld_logic::cell`, next to the peer-identity gate it |
| 1856 | /// mirrors. |
| 1857 | fn malformed_scope() -> HttpReply { |
| 1858 | response( |
| 1859 | StatusCode::BAD_REQUEST, |
| 1860 | "{\"error\":\"malformed_cell_scope\"}", |
| 1861 | ) |
| 1862 | } |
| 1863 | |
| 1864 | /// Can celld put this host in `request.url`? |
| 1865 | /// |
| 1866 | /// `celld_logic::http::authority_decision` returns the complete sans-IO |
| 1867 | /// decision. A Punycode label is the one part that decision cannot settle, |
| 1868 | /// because deciding it is the whole of IDNA: `xn--a` passes every other rule |
| 1869 | /// and still makes `new URL(request.url)` throw inside a Worker. |
| 1870 | /// |
| 1871 | /// So celld runs a parser only when the decision requires one. The parser is |
| 1872 | /// the same `url::Url::parse` that backs `URL` in the isolate, therefore this |
| 1873 | /// check agrees with the Worker by construction rather than by a rule celld |
| 1874 | /// keeps in step by hand. |
| 1875 | fn well_formed_host(host: &str) -> Option<&str> { |
| 1876 | match celld_logic::http::authority_decision(host) { |
| 1877 | celld_logic::http::AuthorityDecision::Reject => None, |
| 1878 | celld_logic::http::AuthorityDecision::Use(host) => Some(host), |
| 1879 | celld_logic::http::AuthorityDecision::NeedsUrlParser(host) => { |
| 1880 | url::Url::parse(&format!("http://{host}/")) |
| 1881 | .is_ok() |
| 1882 | .then_some(host) |
| 1883 | } |
| 1884 | } |
| 1885 | } |
| 1886 | |
| 1887 | /// `request.url` controls application routing and absolute links, so celld |
| 1888 | /// does not let an untrusted forwarding header or request-target authority set |
| 1889 | /// its scheme or host. The path and query always come from the request target. |
| 1890 | /// The host comes from `Host`, and the scheme is `http` because celld does not |
| 1891 | /// terminate TLS. |
| 1892 | /// |
| 1893 | /// An operator can set `--trust-forwarded-headers` when a trusted proxy |
| 1894 | /// replaces both forwarded headers. The trusted read takes the last value |
| 1895 | /// because a proxy can append its value after a client-supplied value. |
| 1896 | /// |
| 1897 | /// The host and the scheme are validated whatever their source. `Host` is |
| 1898 | /// client-controlled whenever no proxy sits in front, which is the default, so |
| 1899 | /// trusting its source is not the same as trusting its shape: an unchecked |
| 1900 | /// value moves the path into a fragment or a query. `well_formed_host` is the |
| 1901 | /// gate. A value that fails it is dropped rather than repaired, and the next |
| 1902 | /// source in the chain applies. |
| 1903 | /// A malformed `X-Forwarded-Host` therefore falls through to `Host`, and only |
| 1904 | /// an empty chain reaches the fallback host. `Host` can still carry a client |
| 1905 | /// value in that case, because a proxy often forwards it rather than replacing |
| 1906 | /// it, so the fall-through trades a known-safe host for a well-formed one. The |
| 1907 | /// gate is what makes that trade safe: neither value can reshape the URL, and |
| 1908 | /// no hostname in `request.url` is trustworthy anyway. |
| 1909 | fn request_url(parts: &hyper::http::request::Parts, trust_forwarded_headers: bool) -> String { |
| 1910 | // A header can arrive as several lines as well as one comma-joined line, |
| 1911 | // and `HeaderMap::get` returns only the first line. Select the actual final |
| 1912 | // field before validating it. Skipping an unusable final field would expose |
| 1913 | // an earlier client value again, which is the defect this gate prevents. |
| 1914 | let last_value = |name: &str| { |
| 1915 | parts |
| 1916 | .headers |
| 1917 | .get_all(name) |
| 1918 | .into_iter() |
| 1919 | .next_back() |
| 1920 | .and_then(|value| value.to_str().ok()) |
| 1921 | .and_then(|value| value.split(',').next_back()) |
| 1922 | .map(str::trim) |
| 1923 | .filter(|value| !value.is_empty()) |
| 1924 | }; |
| 1925 | let first_value = |name: &str| { |
| 1926 | parts |
| 1927 | .headers |
| 1928 | .get(name) |
| 1929 | .and_then(|value| value.to_str().ok()) |
| 1930 | .and_then(|value| value.split(',').next()) |
| 1931 | .map(str::trim) |
| 1932 | .filter(|value| !value.is_empty()) |
| 1933 | }; |
| 1934 | let forwarded = |name: &str| trust_forwarded_headers.then(|| last_value(name)).flatten(); |
| 1935 | |
| 1936 | // The gate applies per source, not once at the end of the chain, so a |
| 1937 | // malformed forwarded value falls through to `Host` instead of discarding |
| 1938 | // the whole chain. |
| 1939 | let host = forwarded("x-forwarded-host") |
| 1940 | .and_then(well_formed_host) |
| 1941 | .or_else(|| first_value("host").and_then(well_formed_host)) |
| 1942 | .unwrap_or("celld.local"); |
| 1943 | let canonical = |scheme: &str| celld_logic::http::canonical_scheme(scheme); |
| 1944 | let scheme = forwarded("x-forwarded-proto") |
| 1945 | .and_then(canonical) |
| 1946 | .unwrap_or("http"); |
| 1947 | let path_and_query = parts |
| 1948 | .uri |
| 1949 | .path_and_query() |
| 1950 | .map_or("/", hyper::http::uri::PathAndQuery::as_str); |
| 1951 | format!("{scheme}://{host}{path_and_query}") |
| 1952 | } |
| 1953 | |
| 1954 | /// Send a fetch to a cell through the dispatcher a Durable Object call from |
| 1955 | /// inside a Worker goes through. |
| 1956 | /// |
| 1957 | /// Public ingress used to resolve the route itself and, on finding another |
| 1958 | /// owner, answer with a 307 and a JSON description of where the cell lived -- |
| 1959 | /// with no Location header, so nothing could follow it. A fleet behind a load |
| 1960 | /// balancer serves a cell only from the node that happens to own it, which is |
| 1961 | /// to say it does not serve a fleet at all. |
| 1962 | /// |
| 1963 | /// Going through `dispatch_do_call` also inherits the redispatch policy and |
| 1964 | /// the cancellation channel, so a client that hangs up reaches the owner |
| 1965 | /// rather than only the node it connected to. `/do/` and `/runtime/` share this: |
| 1966 | /// they differ in what they authenticate, not in how they reach a cell. |
| 1967 | async fn dispatch_cell_fetch( |
| 1968 | cell: String, |
| 1969 | name: Option<String>, |
| 1970 | url: String, |
| 1971 | method: String, |
| 1972 | body: celld::js::RequestBody, |
| 1973 | headers: Vec<(String, String)>, |
| 1974 | ) -> HttpReply { |
| 1975 | let preserve_representation_length = method.eq_ignore_ascii_case("HEAD"); |
| 1976 | let (reply, receive) = oneshot::channel(); |
| 1977 | let (cancel_tx, cancel) = oneshot::channel(); |
| 1978 | let accepted = celld::js::submit_do_call(celld::js::DoCallReq { |
| 1979 | // Named, and named here: the abort fires only for a call that carries |
| 1980 | // both an id and a cancel signal, so leaving this None silently costs |
| 1981 | // the cancellation rather than failing. |
| 1982 | request_id: Some(celld::js::next_request_id()), |
| 1983 | cancel: Some(cancel), |
| 1984 | deliver_abort_to_handler: false, |
| 1985 | scope: cell, |
| 1986 | name, |
| 1987 | url, |
| 1988 | method, |
| 1989 | body_guard: celld::js::RequestBodyGuard::of(&body), |
| 1990 | body, |
| 1991 | headers, |
| 1992 | reply, |
| 1993 | // An ingress call has no caller in this process to be ordered against. |
| 1994 | order: None, |
| 1995 | // Cross-node trace propagation is not available here, so a direct-DO |
| 1996 | // ingress starts without a remote parent. |
| 1997 | parent: None, |
| 1998 | }); |
| 1999 | if !accepted { |
| 2000 | return response( |
| 2001 | StatusCode::SERVICE_UNAVAILABLE, |
| 2002 | "{\"error\":\"dispatcher unavailable\"}", |
| 2003 | ); |
| 2004 | } |
| 2005 | let _hangup = HangUp(Some(cancel_tx)); |
| 2006 | match receive.await { |
| 2007 | Ok(Ok(worker_response)) => { |
| 2008 | runtime_response(worker_response, preserve_representation_length) |
| 2009 | } |
| 2010 | Ok(Err(error)) if request_body_limit_error(&error) => { |
| 2011 | response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large") |
| 2012 | } |
| 2013 | Ok(Err(error)) if cell_overload_error(&error) => cell_overload_response(), |
| 2014 | Ok(Err(error)) => match error.downcast_ref::<RoutedRequestError>() { |
| 2015 | Some(error) => response( |
| 2016 | StatusCode::SERVICE_UNAVAILABLE, |
| 2017 | format!("{{\"error\":\"{:?}\"}}", error.0), |
| 2018 | ), |
| 2019 | None => response( |
| 2020 | StatusCode::SERVICE_UNAVAILABLE, |
| 2021 | format!("cell Worker failed: {error:#}"), |
| 2022 | ), |
| 2023 | }, |
| 2024 | Err(_) => response( |
| 2025 | StatusCode::SERVICE_UNAVAILABLE, |
| 2026 | "{\"error\":\"dispatcher dropped the call\"}", |
| 2027 | ), |
| 2028 | } |
| 2029 | } |
| 2030 | |
| 2031 | /// One forwarded cell fetch, after transport decode. |
| 2032 | pub(crate) struct ForwardedFetch { |
| 2033 | pub(crate) name: Option<String>, |
| 2034 | pub(crate) url: String, |
| 2035 | pub(crate) method: String, |
| 2036 | pub(crate) headers: Vec<(String, String)>, |
| 2037 | pub(crate) request_id: Option<celld::js::RequestId>, |
| 2038 | pub(crate) capacity_handoff: bool, |
| 2039 | } |
| 2040 | |
| 2041 | pub(crate) enum ForwardedFetchOutcome { |
| 2042 | /// A plain application response, headers truthful — no sidecars. |
| 2043 | Reply(HttpReply), |
| 2044 | /// The cell accepted a WebSocket, already registered with the core. |
| 2045 | /// The transport decides how the 101 reaches the caller. |
| 2046 | WebSocket { |
| 2047 | target: celld::js::WsTarget, |
| 2048 | headers: Vec<(String, String)>, |
| 2049 | }, |
| 2050 | } |
| 2051 | |
| 2052 | pub(crate) async fn dispatch_forwarded_fetch( |
| 2053 | app: AppHandle, |
| 2054 | scope: String, |
| 2055 | fetch: ForwardedFetch, |
| 2056 | request_body: celld::js::RequestBody, |
| 2057 | ) -> ForwardedFetchOutcome { |
| 2058 | let ForwardedFetch { |
| 2059 | name, |
| 2060 | url, |
| 2061 | method, |
| 2062 | headers, |
| 2063 | request_id, |
| 2064 | capacity_handoff, |
| 2065 | } = fetch; |
| 2066 | let _request_body_guard = celld::js::RequestBodyGuard::of(&request_body); |
| 2067 | let preserve_representation_length = method.eq_ignore_ascii_case("HEAD"); |
| 2068 | let routed = if capacity_handoff { |
| 2069 | app.capacity_request(scope.clone()).await |
| 2070 | } else { |
| 2071 | app.request(scope.clone()).await |
| 2072 | }; |
| 2073 | let result = match routed { |
| 2074 | Ok(Routed { |
| 2075 | request, |
| 2076 | route: Route::Local, |
| 2077 | }) => { |
| 2078 | let local = app.local_request(request, scope.clone(), request_id, "forwarded"); |
| 2079 | let Some(runtime) = &app.runtime else { |
| 2080 | return ForwardedFetchOutcome::Reply(response( |
| 2081 | StatusCode::SERVICE_UNAVAILABLE, |
| 2082 | "no cell runtime", |
| 2083 | )); |
| 2084 | }; |
| 2085 | let abort_scope = scope.clone(); |
| 2086 | // The forwarding node hangs up when its own client does, so this |
| 2087 | // connection going away is the cancellation signal reaching the |
| 2088 | // owner -- and it arrives as a drop, which is why it is a guard |
| 2089 | // rather than the channel `fetch_cell` takes. Without it a handler |
| 2090 | // keeps running on the owner for a client that left the node it |
| 2091 | // dialled. |
| 2092 | let mut abort = AbortPeerFetchOnHangUp { |
| 2093 | runtime: runtime.clone(), |
| 2094 | scope: abort_scope, |
| 2095 | request_id, |
| 2096 | drain_pins: app.drain_pins.clone(), |
| 2097 | handler_active: true, |
| 2098 | }; |
| 2099 | let completed = local |
| 2100 | .run(async { |
| 2101 | let result = runtime |
| 2102 | .fetch_cell( |
| 2103 | scope, |
| 2104 | name, |
| 2105 | RuntimeFetch { |
| 2106 | url, |
| 2107 | method, |
| 2108 | body: request_body, |
| 2109 | headers, |
| 2110 | request_id, |
| 2111 | // A peer's call has no caller in this process, and the |
| 2112 | // peer protocol does not carry trace context. |
| 2113 | order: None, |
| 2114 | parent: None, |
| 2115 | }, |
| 2116 | None, |
| 2117 | ) |
| 2118 | .await; |
| 2119 | // The handler has answered in both arms; a hang-up during the |
| 2120 | // gate wait below cancels the request's remaining work, not a |
| 2121 | // handler that is still running. |
| 2122 | abort.handler_answered(); |
| 2123 | result |
| 2124 | }) |
| 2125 | .await; |
| 2126 | let activity = completed.activity; |
| 2127 | let result = match completed.result { |
| 2128 | Ok(answer) => Ok(answer), |
| 2129 | Err(LocalRequestFailure::Handler(error)) => Err(error), |
| 2130 | Err(LocalRequestFailure::OutputGate { verdict, handler }) => { |
| 2131 | return ForwardedFetchOutcome::Reply(peer_gate_failure( |
| 2132 | verdict, |
| 2133 | handler.as_ref(), |
| 2134 | )); |
| 2135 | } |
| 2136 | }; |
| 2137 | match result { |
| 2138 | Ok(mut worker_response) => { |
| 2139 | if let Some(HttpResponseWebSocket::Cell(target)) = &worker_response.websocket { |
| 2140 | let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) { |
| 2141 | WebSocketKind::Hibernatable |
| 2142 | } else { |
| 2143 | WebSocketKind::Regular |
| 2144 | }; |
| 2145 | if let Err(error) = app |
| 2146 | .websocket_opened(target.scope.clone(), target.id, kind) |
| 2147 | .await |
| 2148 | { |
| 2149 | return ForwardedFetchOutcome::Reply(peer_response(response( |
| 2150 | StatusCode::SERVICE_UNAVAILABLE, |
| 2151 | format!("WebSocket core registration failed: {error:#}"), |
| 2152 | ))); |
| 2153 | } |
| 2154 | } |
| 2155 | if let Some(HttpResponseWebSocket::Cell(target)) = |
| 2156 | worker_response.websocket.take() |
| 2157 | { |
| 2158 | abort.disarm(); |
| 2159 | drop(activity); |
| 2160 | return ForwardedFetchOutcome::WebSocket { |
| 2161 | target, |
| 2162 | headers: worker_response.headers, |
| 2163 | }; |
| 2164 | } |
| 2165 | let body_active = worker_response.stream.is_some(); |
| 2166 | activity.set_phase("response_body", true, body_active); |
| 2167 | if let Some(stream) = worker_response.stream.take() { |
| 2168 | worker_response.stream = |
| 2169 | Some(local_response_stream(stream, activity, move || { |
| 2170 | abort.disarm() |
| 2171 | })); |
| 2172 | } else { |
| 2173 | abort.disarm(); |
| 2174 | drop(activity); |
| 2175 | } |
| 2176 | runtime_response(worker_response, preserve_representation_length) |
| 2177 | } |
| 2178 | Err(error) => internal_do_worker_error(error), |
| 2179 | } |
| 2180 | } |
| 2181 | Ok(Routed { |
| 2182 | route: Route::Remote { .. }, |
| 2183 | .. |
| 2184 | }) => { |
| 2185 | let mut stale = response(StatusCode::CONFLICT, "stale route"); |
| 2186 | stale.headers_mut().insert( |
| 2187 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 2188 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 2189 | ); |
| 2190 | stale |
| 2191 | } |
| 2192 | Err(RequestError::CapacityExhausted) => { |
| 2193 | let mut stale = response(StatusCode::CONFLICT, "capacity exhausted"); |
| 2194 | stale.headers_mut().insert( |
| 2195 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 2196 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 2197 | ); |
| 2198 | stale |
| 2199 | } |
| 2200 | Err(error) => response( |
| 2201 | StatusCode::SERVICE_UNAVAILABLE, |
| 2202 | format!("route failed: {error:?}"), |
| 2203 | ), |
| 2204 | }; |
| 2205 | ForwardedFetchOutcome::Reply(peer_response(result)) |
| 2206 | } |
| 2207 | |
| 2208 | async fn internal_abort(request: Request<Incoming>, app: AppHandle, path: String) -> HttpReply { |
| 2209 | let (parts, body) = request.into_parts(); |
| 2210 | let body = match collect_limited_body(body, MAX_PEER_CONTROL_BODY_BYTES).await { |
| 2211 | Ok(body) => body, |
| 2212 | Err(error) => return peer_response(body_read_error("abort", error)), |
| 2213 | }; |
| 2214 | let path_and_query = parts |
| 2215 | .uri |
| 2216 | .path_and_query() |
| 2217 | .map_or_else(|| parts.uri.path().to_string(), ToString::to_string); |
| 2218 | if let Err(error) = app.peer_auth.verify( |
| 2219 | &parts.method, |
| 2220 | &path_and_query, |
| 2221 | &parts.headers, |
| 2222 | &body, |
| 2223 | app.peer_auth.source(), |
| 2224 | ) { |
| 2225 | let mut denied = response(error.status(), error.message()); |
| 2226 | if matches!(error, peer_auth::VerifyError::WrongTarget) { |
| 2227 | denied.headers_mut().insert( |
| 2228 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 2229 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 2230 | ); |
| 2231 | } |
| 2232 | return peer_response(denied); |
| 2233 | } |
| 2234 | if parts.method != hyper::Method::POST { |
| 2235 | return peer_response(response( |
| 2236 | StatusCode::METHOD_NOT_ALLOWED, |
| 2237 | "method not allowed", |
| 2238 | )); |
| 2239 | } |
| 2240 | let Some((encoded_scope, encoded_request)) = path |
| 2241 | .strip_prefix("/peer/abort/") |
| 2242 | .and_then(|rest| rest.rsplit_once('/')) |
| 2243 | else { |
| 2244 | return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort target")); |
| 2245 | }; |
| 2246 | let scope = match percent_encoding::percent_decode_str(encoded_scope).decode_utf8() { |
| 2247 | Ok(scope) => scope.into_owned(), |
| 2248 | Err(_) => return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort scope")), |
| 2249 | }; |
| 2250 | if !celld_logic::cell::valid_cell_scope(&scope) { |
| 2251 | return peer_response(malformed_scope()); |
| 2252 | } |
| 2253 | let Some(request_id) = celld::js::parse_request_id(encoded_request) else { |
| 2254 | return peer_response(response(StatusCode::BAD_REQUEST, "invalid request id")); |
| 2255 | }; |
| 2256 | let result = match &app.runtime { |
| 2257 | Some(runtime) => { |
| 2258 | // The signed target is the exact node session that received the |
| 2259 | // forwarded fetch. A cancellation must not route the cell again: |
| 2260 | // routing can activate work solely to cancel a request that never |
| 2261 | // arrived, and the request id is already process-wide. |
| 2262 | let phase = app |
| 2263 | .drain_pins |
| 2264 | .cancel_request(request_id, "peer_abort_received"); |
| 2265 | if phase.is_none() || phase == Some("handler") { |
| 2266 | runtime.abort_fetch(&scope, request_id); |
| 2267 | } |
| 2268 | response(StatusCode::NO_CONTENT, Bytes::new()) |
| 2269 | } |
| 2270 | None => response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime"), |
| 2271 | }; |
| 2272 | peer_response(result) |
| 2273 | } |
| 2274 | |
| 2275 | pub(crate) async fn dispatch_forwarded_rpc( |
| 2276 | app: AppHandle, |
| 2277 | scope: String, |
| 2278 | name: Option<String>, |
| 2279 | rpc_method: String, |
| 2280 | args: celld::js::RpcData, |
| 2281 | ) -> HttpReply { |
| 2282 | let result = match app.request(scope.clone()).await { |
| 2283 | Ok(Routed { |
| 2284 | request, |
| 2285 | route: Route::Local, |
| 2286 | }) => { |
| 2287 | let local_request_id = local_dispatch_request_id(None); |
| 2288 | let local = app.local_request(request, scope.clone(), local_request_id, "local"); |
| 2289 | let Some(runtime) = &app.runtime else { |
| 2290 | return peer_response(response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime")); |
| 2291 | }; |
| 2292 | let completed = local |
| 2293 | .run(runtime.rpc(scope, name, rpc_method, args, local_request_id)) |
| 2294 | .await; |
| 2295 | match completed.result { |
| 2296 | Ok(outcome) => Ok(outcome.data), |
| 2297 | Err(LocalRequestFailure::Handler(error)) => Err(error), |
| 2298 | Err(LocalRequestFailure::OutputGate { verdict, handler }) => { |
| 2299 | return peer_gate_failure(verdict, handler.as_ref()); |
| 2300 | } |
| 2301 | } |
| 2302 | } |
| 2303 | Ok(Routed { |
| 2304 | route: Route::Remote { .. }, |
| 2305 | .. |
| 2306 | }) => { |
| 2307 | let mut stale = response(StatusCode::CONFLICT, "stale route"); |
| 2308 | stale.headers_mut().insert( |
| 2309 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 2310 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 2311 | ); |
| 2312 | return peer_response(stale); |
| 2313 | } |
| 2314 | Err(error) => Err(anyhow::anyhow!("route failed: {error:?}")), |
| 2315 | }; |
| 2316 | match result { |
| 2317 | Ok(celld::js::RpcData::Json(json)) => peer_response( |
| 2318 | Response::builder() |
| 2319 | .status(StatusCode::OK) |
| 2320 | .header("content-type", "application/json") |
| 2321 | .body( |
| 2322 | Full::new(Bytes::from(json)) |
| 2323 | .map_err(|never| match never {}) |
| 2324 | .boxed_unsync(), |
| 2325 | ) |
| 2326 | .expect("RPC JSON response"), |
| 2327 | ), |
| 2328 | Ok(celld::js::RpcData::V8(bytes)) => peer_response( |
| 2329 | Response::builder() |
| 2330 | .status(StatusCode::OK) |
| 2331 | .header("content-type", "application/octet-stream") |
| 2332 | .body( |
| 2333 | Full::new(bytes) |
| 2334 | .map_err(|never| match never {}) |
| 2335 | .boxed_unsync(), |
| 2336 | ) |
| 2337 | .expect("RPC clone response"), |
| 2338 | ), |
| 2339 | Err(error) if cell_overload_error(&error) => peer_response(cell_overload_response()), |
| 2340 | Err(error) => peer_response(response( |
| 2341 | StatusCode::INTERNAL_SERVER_ERROR, |
| 2342 | format!("RPC failed: {error:#}"), |
| 2343 | )), |
| 2344 | } |
| 2345 | } |
| 2346 | |
| 2347 | #[path = "main/peer_tunnel.rs"] |
| 2348 | mod peer_tunnel; |
| 2349 | #[path = "main/websocket.rs"] |
| 2350 | mod websocket; |
| 2351 | use websocket::{handle_websocket, outbound_websocket_task}; |
| 2352 | |
| 2353 | async fn handle_ingress( |
| 2354 | request: Request<Incoming>, |
| 2355 | app: AppHandle, |
| 2356 | connection: ConnectionWorkerRequests, |
| 2357 | ) -> HttpReply { |
| 2358 | if matches!(*request.method(), hyper::Method::GET | hyper::Method::HEAD) { |
| 2359 | // One snapshot for the asset decision and the Worker it may fall |
| 2360 | // into, so a deployment adopted mid-request cannot serve the new |
| 2361 | // generation's index with the old generation's Worker. |
| 2362 | let generation = app.runtime.as_ref().map(RuntimeManager::generation); |
| 2363 | if let Some(resolver) = generation.as_deref().and_then(Generation::ingress_assets) { |
| 2364 | let path = request.uri().path(); |
| 2365 | if !resolver.should_run_worker_first(path) { |
| 2366 | let head = request.method() == hyper::Method::HEAD; |
| 2367 | match resolver |
| 2368 | .ingress_response(path, request.uri().query(), head, request.headers()) |
| 2369 | .await |
| 2370 | { |
| 2371 | Ok(Some(response)) => return asset_response(response), |
| 2372 | Ok(None) if resolver.asset_only() => { |
| 2373 | return response(StatusCode::NOT_FOUND, "Not found"); |
| 2374 | } |
| 2375 | Ok(None) => {} |
| 2376 | Err(error) => { |
| 2377 | eprintln!("celld asset response failed for {path}: {error:#}"); |
| 2378 | return response( |
| 2379 | StatusCode::BAD_GATEWAY, |
| 2380 | "Active deployment asset is unavailable", |
| 2381 | ); |
| 2382 | } |
| 2383 | } |
| 2384 | } |
| 2385 | } |
| 2386 | } |
| 2387 | |
| 2388 | let (url, method, body, headers) = match ingress_payload( |
| 2389 | request, |
| 2390 | app.trust_forwarded_headers, |
| 2391 | app.max_request_body_bytes, |
| 2392 | ) |
| 2393 | .await |
| 2394 | { |
| 2395 | Ok(payload) => payload, |
| 2396 | Err(response) => return response, |
| 2397 | }; |
| 2398 | let preserve_representation_length = method.eq_ignore_ascii_case("HEAD"); |
| 2399 | match app |
| 2400 | .fetch_worker(url, method, body, headers, connection) |
| 2401 | .await |
| 2402 | { |
| 2403 | Ok(worker_response) => runtime_response(worker_response, preserve_representation_length), |
| 2404 | Err(error) if request_body_limit_error(&error) => { |
| 2405 | response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large") |
| 2406 | } |
| 2407 | Err(error) if cell_overload_error(&error) => cell_overload_response(), |
| 2408 | Err(error) => match error.downcast_ref::<celld::pool::AdmitError>() { |
| 2409 | // Saturation is not a failure of the request. Answering it now |
| 2410 | // lets the caller retry or shed; holding the connection until its |
| 2411 | // own deadline is what a node with no capacity used to do. |
| 2412 | Some(refused @ celld::pool::AdmitError::Refused(_)) => response( |
| 2413 | StatusCode::SERVICE_UNAVAILABLE, |
| 2414 | format!("Worker refused: {refused}"), |
| 2415 | ), |
| 2416 | // A build failure is a fault, not saturation. |
| 2417 | Some(celld::pool::AdmitError::Build(_)) | None => response( |
| 2418 | StatusCode::INTERNAL_SERVER_ERROR, |
| 2419 | format!("Worker failed: {error:#}"), |
| 2420 | ), |
| 2421 | }, |
| 2422 | } |
| 2423 | } |
| 2424 | |
| 2425 | async fn dispatch_asset_call(app: AppHandle, call: AssetCallReq) { |
| 2426 | let generation = app |
| 2427 | .runtime |
| 2428 | .as_ref() |
| 2429 | .map(|runtime| runtime.generation_by_id(call.generation)); |
| 2430 | let response = match generation.as_deref().and_then(|g| g.assets(&call.script)) { |
| 2431 | Some(resolver) => { |
| 2432 | resolver |
| 2433 | .binding_response(&call.url, &call.method, &call.headers) |
| 2434 | .await |
| 2435 | } |
| 2436 | None => Err(anyhow::anyhow!( |
| 2437 | "no asset resolver for script {}", |
| 2438 | call.script |
| 2439 | )), |
| 2440 | }; |
| 2441 | let _ = call.reply.send(response); |
| 2442 | } |
| 2443 | |
| 2444 | async fn dispatch_service_call(app: AppHandle, call: SvcCallReq) { |
| 2445 | // The target request owns a streamed body once it starts. Keep a fallback |
| 2446 | // guard here as well, so a missing runtime or a cancellation before |
| 2447 | // admission cannot leave the source in the process registry. |
| 2448 | let mut body_guard = call.body_guard; |
| 2449 | let response = match &app.runtime { |
| 2450 | Some(runtime) => { |
| 2451 | runtime |
| 2452 | .fetch_service(ServiceFetch { |
| 2453 | generation: call.generation, |
| 2454 | script: call.script, |
| 2455 | entrypoint: call.entrypoint, |
| 2456 | url: call.url, |
| 2457 | method: call.method, |
| 2458 | body: call.body, |
| 2459 | headers: call.headers, |
| 2460 | cancel: call.cancel, |
| 2461 | }) |
| 2462 | .await |
| 2463 | } |
| 2464 | None => Err(anyhow::anyhow!("no Worker runtime")), |
| 2465 | }; |
| 2466 | if response.is_ok() { |
| 2467 | // A successful response proves that the target installed its request |
| 2468 | // context. Keep an unread tail there until its waitUntil work ends. |
| 2469 | body_guard.disarm(); |
| 2470 | } |
| 2471 | let _ = call.reply.send(response); |
| 2472 | } |
| 2473 | |
| 2474 | async fn dispatch_service_rpc(app: AppHandle, call: SvcRpcReq) { |
| 2475 | let response = match &app.runtime { |
| 2476 | Some(runtime) => { |
| 2477 | runtime |
| 2478 | .rpc_service( |
| 2479 | call.generation, |
| 2480 | &call.script, |
| 2481 | call.entrypoint, |
| 2482 | call.props, |
| 2483 | call.operation, |
| 2484 | ) |
| 2485 | .await |
| 2486 | } |
| 2487 | None => Err(anyhow::anyhow!("no Worker runtime")), |
| 2488 | }; |
| 2489 | let _ = call.reply.send(response); |
| 2490 | } |
| 2491 | |
| 2492 | async fn dispatch_queue_batch(app: AppHandle, call: QueueDispatchReq) { |
| 2493 | let QueueDispatchReq { |
| 2494 | scope, |
| 2495 | generation, |
| 2496 | script, |
| 2497 | lease_id, |
| 2498 | leases, |
| 2499 | batch, |
| 2500 | } = call; |
| 2501 | let queue = batch.queue.clone(); |
| 2502 | let result = match &app.runtime { |
| 2503 | Some(runtime) => runtime.queue_service(generation, &script, batch).await, |
| 2504 | None => Err(anyhow::anyhow!("no Worker runtime")), |
| 2505 | }; |
| 2506 | let result = match result { |
| 2507 | Ok(result) => result, |
| 2508 | Err(error) => { |
| 2509 | tracing::warn!(%scope, %queue, %script, %error, "Queue dispatch failed; its lease will expire"); |
| 2510 | return; |
| 2511 | } |
| 2512 | }; |
| 2513 | let outcome = match result.outcome { |
| 2514 | celld::js::QueueOutcome::Ok => "ok", |
| 2515 | celld::js::QueueOutcome::Exception => "exception", |
| 2516 | }; |
| 2517 | let body = serde_json::json!({ |
| 2518 | "leaseId": lease_id, |
| 2519 | "leases": leases, |
| 2520 | "outcome": outcome, |
| 2521 | "error": result.error, |
| 2522 | "ackAll": result.ack_all, |
| 2523 | "retryBatch": { |
| 2524 | "retry": result.retry_batch.retry, |
| 2525 | "delaySeconds": result.retry_batch.delay_seconds, |
| 2526 | }, |
| 2527 | "explicitAcks": result.explicit_acks, |
| 2528 | "retryMessages": result.retry_messages.into_iter().map(|retry| serde_json::json!({ |
| 2529 | "msgId": retry.msg_id, |
| 2530 | "delaySeconds": retry.delay_seconds, |
| 2531 | })).collect::<Vec<_>>(), |
| 2532 | }); |
| 2533 | let body = celld::js::RequestBody::Bytes(body.to_string().into_bytes().into()); |
| 2534 | let (reply, receive) = oneshot::channel(); |
| 2535 | dispatch_do_call( |
| 2536 | app, |
| 2537 | DoCallReq { |
| 2538 | request_id: None, |
| 2539 | cancel: None, |
| 2540 | deliver_abort_to_handler: false, |
| 2541 | scope: scope.clone(), |
| 2542 | name: None, |
| 2543 | url: "https://queue.celld.internal/__qSettle".to_string(), |
| 2544 | method: "POST".to_string(), |
| 2545 | body_guard: celld::js::RequestBodyGuard::of(&body), |
| 2546 | body, |
| 2547 | headers: vec![("content-type".to_string(), "application/json".to_string())], |
| 2548 | reply, |
| 2549 | order: None, |
| 2550 | parent: None, |
| 2551 | }, |
| 2552 | ) |
| 2553 | .await; |
| 2554 | match receive.await { |
| 2555 | Ok(Ok(response)) if (200..300).contains(&response.status) => {} |
| 2556 | Ok(Ok(response)) => tracing::warn!( |
| 2557 | %scope, |
| 2558 | %queue, |
| 2559 | status = response.status, |
| 2560 | "Queue settlement was refused; its lease will expire" |
| 2561 | ), |
| 2562 | Ok(Err(error)) => tracing::warn!( |
| 2563 | %scope, |
| 2564 | %queue, |
| 2565 | %error, |
| 2566 | "Queue settlement routing failed; its lease will expire" |
| 2567 | ), |
| 2568 | Err(error) => tracing::warn!( |
| 2569 | %scope, |
| 2570 | %queue, |
| 2571 | %error, |
| 2572 | "Queue settlement dispatcher dropped; its lease will expire" |
| 2573 | ), |
| 2574 | } |
| 2575 | } |
| 2576 | |
| 2577 | async fn internal_probe(request: Request<Incoming>, app: AppHandle) -> HttpReply { |
| 2578 | let (parts, body) = request.into_parts(); |
| 2579 | let body = match collect_limited_body(body, MAX_PEER_CONTROL_BODY_BYTES).await { |
| 2580 | Ok(body) => body, |
| 2581 | Err(error) => return peer_response(body_read_error("probe", error)), |
| 2582 | }; |
| 2583 | let path_and_query = parts |
| 2584 | .uri |
| 2585 | .path_and_query() |
| 2586 | .map_or_else(|| parts.uri.path().to_string(), ToString::to_string); |
| 2587 | if let Err(error) = app.peer_auth.verify( |
| 2588 | &parts.method, |
| 2589 | &path_and_query, |
| 2590 | &parts.headers, |
| 2591 | &body, |
| 2592 | app.peer_auth.source(), |
| 2593 | ) { |
| 2594 | return peer_response(response(error.status(), error.message())); |
| 2595 | } |
| 2596 | if parts.method != hyper::Method::GET { |
| 2597 | return peer_response(response( |
| 2598 | StatusCode::METHOD_NOT_ALLOWED, |
| 2599 | "method not allowed", |
| 2600 | )); |
| 2601 | } |
| 2602 | let Some(challenge) = parts |
| 2603 | .headers |
| 2604 | .get("x-cells-probe-challenge") |
| 2605 | .and_then(|value| value.to_str().ok()) |
| 2606 | else { |
| 2607 | return peer_response(response(StatusCode::BAD_REQUEST, "missing probe challenge")); |
| 2608 | }; |
| 2609 | match celld::peer_probe::respond(app.peer_auth.source(), &app.advertise, challenge) { |
| 2610 | Ok(probe) => match serde_json::to_vec(&probe) { |
| 2611 | Ok(body) => peer_response(response(StatusCode::OK, body)), |
| 2612 | Err(_) => peer_response(response( |
| 2613 | StatusCode::INTERNAL_SERVER_ERROR, |
| 2614 | "encode probe response", |
| 2615 | )), |
| 2616 | }, |
| 2617 | Err(_) => peer_response(response(StatusCode::BAD_REQUEST, "invalid probe challenge")), |
| 2618 | } |
| 2619 | } |
| 2620 | |
| 2621 | /// Adopt one released cell for a terminating peer. A successful response |
| 2622 | /// proves that this node acquired the next ownership epoch. The restored |
| 2623 | /// runtime remains dormant until real traffic needs it. If another peer won |
| 2624 | /// the race, the response identifies that current owner. |
| 2625 | async fn internal_handoff(request: Request<Incoming>, app: AppHandle) -> HttpReply { |
| 2626 | if app.is_draining() { |
| 2627 | return peer_response(response( |
| 2628 | StatusCode::SERVICE_UNAVAILABLE, |
| 2629 | "{\"ok\":false,\"draining\":true}", |
| 2630 | )); |
| 2631 | } |
| 2632 | let (parts, body) = request.into_parts(); |
| 2633 | let body = match collect_limited_body(body, MAX_PEER_CONTROL_BODY_BYTES).await { |
| 2634 | Ok(body) => body, |
| 2635 | Err(error) => return peer_response(body_read_error("handoff", error)), |
| 2636 | }; |
| 2637 | let path_and_query = parts |
| 2638 | .uri |
| 2639 | .path_and_query() |
| 2640 | .map_or_else(|| parts.uri.path().to_string(), ToString::to_string); |
| 2641 | if let Err(error) = app.peer_auth.verify( |
| 2642 | &parts.method, |
| 2643 | &path_and_query, |
| 2644 | &parts.headers, |
| 2645 | &body, |
| 2646 | app.peer_auth.source(), |
| 2647 | ) { |
| 2648 | return peer_response(response(error.status(), error.message())); |
| 2649 | } |
| 2650 | if parts.method != hyper::Method::POST { |
| 2651 | return peer_response(response( |
| 2652 | StatusCode::METHOD_NOT_ALLOWED, |
| 2653 | "method not allowed", |
| 2654 | )); |
| 2655 | } |
| 2656 | let request: HandoffRequest = match serde_json::from_slice::<HandoffRequest>(&body) { |
| 2657 | Ok(request) if !request.cell.is_empty() && request.released_epoch > 0 => request, |
| 2658 | Ok(_) => { |
| 2659 | return peer_response(response( |
| 2660 | StatusCode::BAD_REQUEST, |
| 2661 | "invalid handoff cell or epoch", |
| 2662 | )); |
| 2663 | } |
| 2664 | Err(error) => { |
| 2665 | return peer_response(response( |
| 2666 | StatusCode::BAD_REQUEST, |
| 2667 | format!("invalid handoff JSON: {error}"), |
| 2668 | )); |
| 2669 | } |
| 2670 | }; |
| 2671 | let mut attempt = app |
| 2672 | .accept_handoff(request.cell.clone(), request.released_epoch) |
| 2673 | .await; |
| 2674 | // Concurrent traffic commonly leaves this successor with a cached route |
| 2675 | // to the donor. The signed release says that exact generation is stale. |
| 2676 | // Retire it and resolve the owner record again; otherwise the successor |
| 2677 | // redirects the donor back to itself forever and no cell is adopted. |
| 2678 | if let Ok(HandoffAttempt::CurrentOwner(owner)) = &attempt { |
| 2679 | if owner.epoch <= request.released_epoch { |
| 2680 | app.invalidate_remote(request.cell.clone(), owner.node.clone(), owner.epoch) |
| 2681 | .await; |
| 2682 | attempt = app |
| 2683 | .accept_handoff(request.cell.clone(), request.released_epoch) |
| 2684 | .await; |
| 2685 | } |
| 2686 | } |
| 2687 | let (status, result) = match attempt { |
| 2688 | Ok(HandoffAttempt::Accepted(owner)) if owner.epoch > request.released_epoch => ( |
| 2689 | StatusCode::OK, |
| 2690 | HandoffResponse { |
| 2691 | node: owner.node, |
| 2692 | addr: owner.addr, |
| 2693 | epoch: owner.epoch, |
| 2694 | peer_protocol: owner.peer_protocol, |
| 2695 | published: true, |
| 2696 | }, |
| 2697 | ), |
| 2698 | Ok(HandoffAttempt::CurrentOwner(owner)) => ( |
| 2699 | StatusCode::CONFLICT, |
| 2700 | HandoffResponse { |
| 2701 | node: owner.node, |
| 2702 | addr: owner.addr, |
| 2703 | epoch: owner.epoch, |
| 2704 | peer_protocol: owner.peer_protocol, |
| 2705 | published: false, |
| 2706 | }, |
| 2707 | ), |
| 2708 | Ok(HandoffAttempt::Accepted(_)) | Ok(HandoffAttempt::Refused) | Err(_) => { |
| 2709 | return peer_response(response( |
| 2710 | StatusCode::SERVICE_UNAVAILABLE, |
| 2711 | "handoff capacity unavailable", |
| 2712 | )); |
| 2713 | } |
| 2714 | }; |
| 2715 | match serde_json::to_vec(&result) { |
| 2716 | Ok(body) => peer_response(response(status, body)), |
| 2717 | Err(_) => peer_response(response( |
| 2718 | StatusCode::INTERNAL_SERVER_ERROR, |
| 2719 | "encode handoff response", |
| 2720 | )), |
| 2721 | } |
| 2722 | } |
| 2723 | |
| 2724 | /// The log tier's follower endpoints (crate::node_log): append fsyncs |
| 2725 | /// entries and answers the ack-all vote, seal persists the fence mark |
| 2726 | /// before replying, tail hands recovery the held fragment. Fleet-HMAC |
| 2727 | /// verified like every internal peer surface. |
| 2728 | async fn internal_log(request: Request<Incoming>, app: AppHandle, path: String) -> HttpReply { |
| 2729 | let Some(follower) = app.follower.clone() else { |
| 2730 | return peer_response(response(StatusCode::NOT_FOUND, "no follower store")); |
| 2731 | }; |
| 2732 | let entered = celld::asyncrt::mono_us(); |
| 2733 | let (mut parts, body) = request.into_parts(); |
| 2734 | let body_limit = if path == INTERNAL_LOG_APPEND_PATH { |
| 2735 | // An append includes the LTX bytes from an application transaction, |
| 2736 | // so it needs the same allowance as other application-data routes. |
| 2737 | MAX_PEER_FORWARD_BODY_BYTES |
| 2738 | } else { |
| 2739 | MAX_PEER_CONTROL_BODY_BYTES |
| 2740 | }; |
| 2741 | let body = match collect_limited_body(body, body_limit).await { |
| 2742 | Ok(body) => body, |
| 2743 | Err(error) => return peer_response(body_read_error("log", error)), |
| 2744 | }; |
| 2745 | let path_and_query = parts |
| 2746 | .uri |
| 2747 | .path_and_query() |
| 2748 | .map_or_else(|| parts.uri.path().to_string(), ToString::to_string); |
| 2749 | if let Err(error) = app.peer_auth.verify( |
| 2750 | &parts.method, |
| 2751 | &path_and_query, |
| 2752 | &parts.headers, |
| 2753 | &body, |
| 2754 | app.peer_auth.source(), |
| 2755 | ) { |
| 2756 | return peer_response(response(error.status(), error.message())); |
| 2757 | } |
| 2758 | if parts.method != hyper::Method::POST { |
| 2759 | return peer_response(response( |
| 2760 | StatusCode::METHOD_NOT_ALLOWED, |
| 2761 | "method not allowed", |
| 2762 | )); |
| 2763 | } |
| 2764 | if path == "/peer/log/stream" { |
| 2765 | // The ordered append stream (the ordered-transport design): |
| 2766 | // the handshake is fleet-HMAC verified above like every log route, |
| 2767 | // the 101 carries the response auth the leader validates before it |
| 2768 | // upgrades, and the upgraded duplex is served by one reader so |
| 2769 | // apply order equals arrival order. |
| 2770 | let Some(upgrade) = parts.extensions.remove::<hyper::upgrade::OnUpgrade>() else { |
| 2771 | return peer_response(response( |
| 2772 | StatusCode::BAD_REQUEST, |
| 2773 | "stream requires an upgradable connection", |
| 2774 | )); |
| 2775 | }; |
| 2776 | let store = follower.clone(); |
| 2777 | celld::asyncrt::spawn(async move { |
| 2778 | match upgrade.await { |
| 2779 | Ok(upgraded) => { |
| 2780 | let io = TokioIo::new(upgraded); |
| 2781 | if let Err(error) = celld::node_log::serve_log_stream(io, store).await { |
| 2782 | tracing::debug!(%error, "log stream ended"); |
| 2783 | } |
| 2784 | } |
| 2785 | Err(error) => tracing::debug!(%error, "log stream upgrade failed"), |
| 2786 | } |
| 2787 | }) |
| 2788 | .detach(); |
| 2789 | let mut reply = response(StatusCode::SWITCHING_PROTOCOLS, ""); |
| 2790 | reply.headers_mut().insert( |
| 2791 | hyper::header::UPGRADE, |
| 2792 | hyper::header::HeaderValue::from_static("celld-log-stream"), |
| 2793 | ); |
| 2794 | reply.headers_mut().insert( |
| 2795 | hyper::header::CONNECTION, |
| 2796 | hyper::header::HeaderValue::from_static("upgrade"), |
| 2797 | ); |
| 2798 | return peer_response(reply); |
| 2799 | } |
| 2800 | let result: anyhow::Result<Vec<u8>> = match path.as_str() { |
| 2801 | // The append body and the tail response are binary — the entries |
| 2802 | // dominate both — while every control message stays JSON. |
| 2803 | INTERNAL_LOG_APPEND_PATH => match celld::node_log::decode_append(&body) { |
| 2804 | Ok(req) => { |
| 2805 | let collected = celld::asyncrt::mono_us(); |
| 2806 | let resp = follower.append(req).await; |
| 2807 | tracing::info!( |
| 2808 | event = "log_append_router", |
| 2809 | collect_ms = collected.saturating_sub(entered) / 1000, |
| 2810 | append_ms = (celld::asyncrt::mono_us() - collected) / 1000, |
| 2811 | body_len = body.len(), |
| 2812 | "append routed" |
| 2813 | ); |
| 2814 | serde_json::to_vec(&resp).map_err(Into::into) |
| 2815 | } |
| 2816 | Err(error) => Err(error), |
| 2817 | }, |
| 2818 | "/peer/log/seal" => match serde_json::from_slice::<celld::node_log::SealReq>(&body) { |
| 2819 | Ok(req) => match follower.seal(&req).await { |
| 2820 | Ok(resp) => serde_json::to_vec(&resp).map_err(Into::into), |
| 2821 | Err(error) => Err(error), |
| 2822 | }, |
| 2823 | Err(error) => Err(error.into()), |
| 2824 | }, |
| 2825 | "/peer/log/tail" => serde_json::from_slice::<celld::node_log::TailReq>(&body) |
| 2826 | .map_err(anyhow::Error::from) |
| 2827 | .map(|req| celld::node_log::encode_tail_resp(&follower.tail(&req))), |
| 2828 | _ => Err(anyhow::anyhow!("unknown log endpoint")), |
| 2829 | }; |
| 2830 | match result { |
| 2831 | Ok(body) => peer_response(response(StatusCode::OK, body)), |
| 2832 | Err(error) => peer_response(response(StatusCode::BAD_REQUEST, format!("{error:#}"))), |
| 2833 | } |
| 2834 | } |
| 2835 | |
| 2836 | async fn handle_public( |
| 2837 | request: Request<Incoming>, |
| 2838 | app: AppHandle, |
| 2839 | connection: ConnectionWorkerRequests, |
| 2840 | ) -> Result<HttpReply, Infallible> { |
| 2841 | let path = request.uri().path().to_string(); |
| 2842 | let draining = app.is_draining(); |
| 2843 | let _public_admission = if path == "/.well-known/celld/health" { |
| 2844 | None |
| 2845 | } else { |
| 2846 | let Some(admission) = app.admit_public() else { |
| 2847 | let mut refused = response( |
| 2848 | StatusCode::SERVICE_UNAVAILABLE, |
| 2849 | "{\"ok\":false,\"draining\":true}", |
| 2850 | ); |
| 2851 | refused.headers_mut().insert( |
| 2852 | hyper::header::RETRY_AFTER, |
| 2853 | hyper::header::HeaderValue::from_static("1"), |
| 2854 | ); |
| 2855 | refused.headers_mut().insert( |
| 2856 | hyper::header::CONNECTION, |
| 2857 | hyper::header::HeaderValue::from_static("close"), |
| 2858 | ); |
| 2859 | return Ok(refused); |
| 2860 | }; |
| 2861 | Some(admission) |
| 2862 | }; |
| 2863 | if path != "/.well-known/celld/health" |
| 2864 | && app.runtime.is_some() |
| 2865 | && fastwebsockets::upgrade::is_upgrade_request(&request) |
| 2866 | { |
| 2867 | return Ok(handle_websocket(request, app).await); |
| 2868 | } |
| 2869 | let mut result = match path.as_str() { |
| 2870 | "/.well-known/celld/health" |
| 2871 | if !app.is_draining() && app.fleet_ready() && app.healthy().await => |
| 2872 | { |
| 2873 | response(StatusCode::OK, "{\"ok\":true}") |
| 2874 | } |
| 2875 | "/.well-known/celld/health" => response(StatusCode::SERVICE_UNAVAILABLE, "{\"ok\":false}"), |
| 2876 | _ if app.runtime.is_some() => handle_ingress(request, app, connection).await, |
| 2877 | _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"), |
| 2878 | }; |
| 2879 | if draining { |
| 2880 | result.headers_mut().insert( |
| 2881 | hyper::header::CONNECTION, |
| 2882 | hyper::header::HeaderValue::from_static("close"), |
| 2883 | ); |
| 2884 | } |
| 2885 | Ok(result) |
| 2886 | } |
| 2887 | |
| 2888 | async fn handle_internal( |
| 2889 | request: Request<Incoming>, |
| 2890 | app: AppHandle, |
| 2891 | shutdown: mpsc::UnboundedSender<ShutdownMode>, |
| 2892 | ) -> Result<HttpReply, Infallible> { |
| 2893 | let path = request.uri().path().to_string(); |
| 2894 | let draining = app.is_draining(); |
| 2895 | let result = match path.as_str() { |
| 2896 | "/peer/probe" => internal_probe(request, app).await, |
| 2897 | "/peer/handoff" => internal_handoff(request, app).await, |
| 2898 | _ if path.starts_with("/peer/log/") => internal_log(request, app, path.clone()).await, |
| 2899 | "/state" => response(StatusCode::OK, app.snapshot().await), |
| 2900 | "/reload" if request.method() != hyper::Method::POST => { |
| 2901 | response(StatusCode::METHOD_NOT_ALLOWED, "method not allowed") |
| 2902 | } |
| 2903 | "/reload" => internal_reload(app).await, |
| 2904 | "/rebalance/pause" | "/rebalance/resume" if request.method() != hyper::Method::POST => { |
| 2905 | response(StatusCode::METHOD_NOT_ALLOWED, "method not allowed") |
| 2906 | } |
| 2907 | "/rebalance/pause" | "/rebalance/resume" => { |
| 2908 | internal_rebalance_switch(path == "/rebalance/pause") |
| 2909 | } |
| 2910 | "/shutdown" if request.method() != hyper::Method::POST => { |
| 2911 | response(StatusCode::METHOD_NOT_ALLOWED, "method not allowed") |
| 2912 | } |
| 2913 | "/shutdown" => { |
| 2914 | let preserve_ownership = request |
| 2915 | .uri() |
| 2916 | .query() |
| 2917 | .is_some_and(|query| query.split('&').any(|part| part == "handoff=preserve")); |
| 2918 | let mode = if preserve_ownership { |
| 2919 | ShutdownMode::Preserve |
| 2920 | } else { |
| 2921 | ShutdownMode::Handoff |
| 2922 | }; |
| 2923 | let _ = shutdown.send(mode); |
| 2924 | response(StatusCode::OK, "{\"ok\":true}") |
| 2925 | } |
| 2926 | _ if path.starts_with("/peer/abort/") && app.runtime.is_some() => { |
| 2927 | internal_abort(request, app, path).await |
| 2928 | } |
| 2929 | "/peer/tunnel" if app.runtime.is_some() => { |
| 2930 | if peer_tunnel::is_tunnel_request(&request) { |
| 2931 | peer_tunnel::accept(request, app) |
| 2932 | } else { |
| 2933 | peer_response(response( |
| 2934 | StatusCode::BAD_REQUEST, |
| 2935 | "tunnel establishment must upgrade", |
| 2936 | )) |
| 2937 | } |
| 2938 | } |
| 2939 | // The operator CLIs' way in (`celld d1`, queues, workflows): the same |
| 2940 | // forwarding dispatch `/do/` uses, with the fleet authentication |
| 2941 | // `/do/` does not have. A runtime class holds application data and |
| 2942 | // answers an operator protocol — arbitrary SQL for D1 — so it must |
| 2943 | // not be reachable from an unauthenticated route; `/do/` refuses a |
| 2944 | // reserved scope below and sends the caller here. |
| 2945 | // |
| 2946 | // It is one route rather than one per class on purpose. D1's design |
| 2947 | // page records what writing the second by hand would cost: the |
| 2948 | // refusal on the *other* route has to be widened in the same change, |
| 2949 | // and gating only the new route "would have left the hole open". |
| 2950 | // With one entrance and one refusal, a class added to |
| 2951 | // `RESERVED_CLASSES` inherits both. (The pre-v5 `/__d1/` alias died |
| 2952 | // with the v0.4.0 stop-the-world upgrade; the CLI in this tree sends |
| 2953 | // `/runtime/`.) |
| 2954 | _ if path.starts_with("/runtime/") && app.runtime.is_some() => { |
| 2955 | let scope = path |
| 2956 | .strip_prefix("/runtime/") |
| 2957 | .expect("matched the prefix") |
| 2958 | .to_string(); |
| 2959 | if !celld_logic::cell::valid_cell_scope(&scope) { |
| 2960 | return Ok(peer_response(malformed_scope())); |
| 2961 | } |
| 2962 | // The mirror of `/do/`'s refusal: that route serves every ordinary |
| 2963 | // Durable Object and no reserved one, this route serves the |
| 2964 | // reserved ones and nothing else. Without the check, a signed |
| 2965 | // request could drive a user's Durable Object through a route |
| 2966 | // whose only contract is an operator protocol. |
| 2967 | if !celld::deploy::is_reserved_scope(&scope) { |
| 2968 | return Ok(peer_response(response( |
| 2969 | StatusCode::FORBIDDEN, |
| 2970 | "{\"error\":\"only a runtime class is served on /runtime/; use /do/ for a Durable Object\"}", |
| 2971 | ))); |
| 2972 | } |
| 2973 | let operator_query = request.uri().query().map(str::to_owned); |
| 2974 | let method = request.method().clone(); |
| 2975 | let path_and_query = request |
| 2976 | .uri() |
| 2977 | .path_and_query() |
| 2978 | .map_or_else(|| request.uri().path().to_string(), ToString::to_string); |
| 2979 | let request_headers = request.headers().clone(); |
| 2980 | let body = match collect_limited_body(request.into_body(), MAX_PEER_PROTOCOL_BODY_BYTES) |
| 2981 | .await |
| 2982 | { |
| 2983 | Ok(body) => body, |
| 2984 | Err(error) => return Ok(peer_response(body_read_error("operator cell", error))), |
| 2985 | }; |
| 2986 | if let Err(error) = app.peer_auth.verify( |
| 2987 | &method, |
| 2988 | &path_and_query, |
| 2989 | &request_headers, |
| 2990 | &body, |
| 2991 | app.peer_auth.source(), |
| 2992 | ) { |
| 2993 | return Ok(peer_response(response(error.status(), error.message()))); |
| 2994 | } |
| 2995 | let mut name = None; |
| 2996 | for (key, value) in url::form_urlencoded::parse( |
| 2997 | operator_query.as_deref().unwrap_or_default().as_bytes(), |
| 2998 | ) { |
| 2999 | if key != "name" || name.is_some() || value.is_empty() { |
| 3000 | return Ok(peer_response(response( |
| 3001 | StatusCode::BAD_REQUEST, |
| 3002 | "{\"error\":\"invalid operator query\"}", |
| 3003 | ))); |
| 3004 | } |
| 3005 | name = Some(value.into_owned()); |
| 3006 | } |
| 3007 | // A Queue needs its name before its constructor chooses a |
| 3008 | // consumer. The runtime also proves that this name hashes to the |
| 3009 | // requested scope before it exposes the identity to JavaScript. |
| 3010 | dispatch_cell_fetch( |
| 3011 | scope, |
| 3012 | name, |
| 3013 | "http://cell/".to_string(), |
| 3014 | "POST".to_string(), |
| 3015 | celld::js::RequestBody::Bytes(body), |
| 3016 | vec![("content-type".to_string(), "application/json".to_string())], |
| 3017 | ) |
| 3018 | .await |
| 3019 | } |
| 3020 | _ if path.starts_with("/do/") && app.runtime.is_some() => { |
| 3021 | let runtime = app.runtime.as_ref().expect("checked runtime"); |
| 3022 | let cell = match runtime.cell_scope(&path[4..]) { |
| 3023 | Ok(cell) => cell, |
| 3024 | Err(error) => { |
| 3025 | return Ok(response(StatusCode::BAD_REQUEST, format!("{error:#}"))); |
| 3026 | } |
| 3027 | }; |
| 3028 | // This route has no authentication, so it must reach no reserved |
| 3029 | // class at all. A reserved cell's whole fetch surface is an |
| 3030 | // operator protocol — arbitrary SQL for D1, create/terminate/ |
| 3031 | // events for a workflow — and its scope is an HMAC over names that |
| 3032 | // sit in the project's config rather than a secret. |
| 3033 | // |
| 3034 | // One question, not one per class. Two hand-written refusals stood |
| 3035 | // here before, and a third reserved class would have needed a third |
| 3036 | // that nothing forces anyone to write. `is_reserved_scope` closes |
| 3037 | // the door for every class in `RESERVED_CLASSES`; the hint below |
| 3038 | // is the only part that is per-class, and a class without one still |
| 3039 | // gets refused. |
| 3040 | if let Some(class) = celld::deploy::reserved_class_of(&cell) { |
| 3041 | let hint = celld::deploy::operator_hint(class); |
| 3042 | return Ok(response( |
| 3043 | StatusCode::FORBIDDEN, |
| 3044 | format!( |
| 3045 | "{{\"error\":\"{class} is a runtime class and is not reachable over /do/; {hint}\"}}" |
| 3046 | ), |
| 3047 | )); |
| 3048 | } |
| 3049 | let (url, method, body, headers) = match ingress_payload( |
| 3050 | request, |
| 3051 | app.trust_forwarded_headers, |
| 3052 | app.max_request_body_bytes, |
| 3053 | ) |
| 3054 | .await |
| 3055 | { |
| 3056 | Ok(payload) => payload, |
| 3057 | Err(response) => return Ok(response), |
| 3058 | }; |
| 3059 | dispatch_cell_fetch(cell, None, url, method, body, headers).await |
| 3060 | } |
| 3061 | _ if path.starts_with("/cell/") && !celld_logic::cell::valid_cell_scope(&path[6..]) => { |
| 3062 | malformed_scope() |
| 3063 | } |
| 3064 | _ if path.starts_with("/cell/") => { |
| 3065 | let cell = path[6..].to_string(); |
| 3066 | match app.request(cell.clone()).await { |
| 3067 | Ok(Routed { |
| 3068 | request, |
| 3069 | route: Route::Local, |
| 3070 | }) => { |
| 3071 | let _activity = app.activity(request, cell.clone()); |
| 3072 | response( |
| 3073 | StatusCode::OK, |
| 3074 | format!("{{\"route\":\"local\",\"cell\":{cell:?}}}"), |
| 3075 | ) |
| 3076 | } |
| 3077 | Ok(Routed { |
| 3078 | route: |
| 3079 | Route::Remote { |
| 3080 | node, |
| 3081 | addr, |
| 3082 | epoch, |
| 3083 | peer_protocol, |
| 3084 | }, |
| 3085 | .. |
| 3086 | }) => response( |
| 3087 | StatusCode::TEMPORARY_REDIRECT, |
| 3088 | format!( |
| 3089 | "{{\"route\":\"remote\",\"node\":{node:?},\"addr\":{addr:?},\"epoch\":{epoch},\"peer_protocol\":{peer_protocol}}}" |
| 3090 | ), |
| 3091 | ), |
| 3092 | Err(error) => response( |
| 3093 | StatusCode::SERVICE_UNAVAILABLE, |
| 3094 | format!("{{\"error\":\"{error:?}\"}}"), |
| 3095 | ), |
| 3096 | } |
| 3097 | } |
| 3098 | _ if path.starts_with("/evict/") && !celld_logic::cell::valid_cell_scope(&path[7..]) => { |
| 3099 | malformed_scope() |
| 3100 | } |
| 3101 | _ if path.starts_with("/evict/") => { |
| 3102 | app.evict(path[7..].to_string()).await; |
| 3103 | response(StatusCode::OK, "{\"ok\":true}") |
| 3104 | } |
| 3105 | _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"), |
| 3106 | }; |
| 3107 | // Close the connection behind any response sent while draining, so |
| 3108 | // keep-alive clients reconnect to a healthy node and the drain loop |
| 3109 | // can finish. A request that raced the drain flag converges on its |
| 3110 | // next request, which hits the gate above. |
| 3111 | let mut result = result; |
| 3112 | // A 101 is exempt: `Connection: close` on it breaks the upgrade, and a |
| 3113 | // tunnel establishment during a drain is exactly how a draining owner |
| 3114 | // keeps serving the calls its handoff has not yet moved. The upgraded |
| 3115 | // connection leaves keep-alive rotation on its own when the call ends. |
| 3116 | if draining && result.status() != StatusCode::SWITCHING_PROTOCOLS { |
| 3117 | result.headers_mut().insert( |
| 3118 | hyper::header::CONNECTION, |
| 3119 | hyper::header::HeaderValue::from_static("close"), |
| 3120 | ); |
| 3121 | } |
| 3122 | Ok(result) |
| 3123 | } |
| 3124 | |
| 3125 | #[derive(Clone, Copy)] |
| 3126 | enum HttpSurface { |
| 3127 | Public, |
| 3128 | Internal, |
| 3129 | Recovery, |
| 3130 | } |
| 3131 | |
| 3132 | impl HttpSurface { |
| 3133 | fn name(self) -> &'static str { |
| 3134 | match self { |
| 3135 | Self::Public => "public", |
| 3136 | Self::Internal => "internal", |
| 3137 | Self::Recovery => "recovery", |
| 3138 | } |
| 3139 | } |
| 3140 | } |
| 3141 | |
| 3142 | struct ShutdownConnection { |
| 3143 | stream: tokio::net::TcpStream, |
| 3144 | surface: HttpSurface, |
| 3145 | received: oneshot::Sender<()>, |
| 3146 | #[cfg(all(test, celld_internal_tests))] |
| 3147 | recovered_after_error: bool, |
| 3148 | } |
| 3149 | |
| 3150 | fn spawn_shutdown_acceptor( |
| 3151 | listener: tokio::net::TcpListener, |
| 3152 | surface: HttpSurface, |
| 3153 | connections: mpsc::Sender<ShutdownConnection>, |
| 3154 | #[cfg(all(test, celld_internal_tests))] mut fail_next_for_test: bool, |
| 3155 | ) { |
| 3156 | // Shutdown selects finish whenever a timer, request, or actor message |
| 3157 | // wins. Keep each listener's accept and retry waits in one task so those |
| 3158 | // unrelated events cannot cancel a wait or reset its retry delay. |
| 3159 | tokio::spawn(async move { |
| 3160 | let mut retry_delay = SHUTDOWN_ACCEPT_RETRY_INITIAL; |
| 3161 | let mut recovering = false; |
| 3162 | #[cfg(all(test, celld_internal_tests))] |
| 3163 | let mut connect_after_failure_for_test = false; |
| 3164 | loop { |
| 3165 | #[cfg(all(test, celld_internal_tests))] |
| 3166 | let inject_failure = std::mem::take(&mut fail_next_for_test); |
| 3167 | #[cfg(all(test, celld_internal_tests))] |
| 3168 | let accepted = if inject_failure { |
| 3169 | Err(std::io::Error::new( |
| 3170 | std::io::ErrorKind::ConnectionAborted, |
| 3171 | "injected listener accept failure during shutdown", |
| 3172 | )) |
| 3173 | } else if std::mem::take(&mut connect_after_failure_for_test) { |
| 3174 | let retry_address = listener |
| 3175 | .local_addr() |
| 3176 | .expect("read the shutdown accept failure test listener address"); |
| 3177 | // Connect before polling accept, so the injected transition |
| 3178 | // does not depend on an operating-system readiness- |
| 3179 | // notification race after the error. |
| 3180 | let connection = std::net::TcpStream::connect(retry_address) |
| 3181 | .expect("connect after the injected shutdown accept failure"); |
| 3182 | *SHUTDOWN_ACCEPT_FAILURE_CLIENT |
| 3183 | .lock() |
| 3184 | .expect("lock the shutdown accept failure test connection") = Some(connection); |
| 3185 | listener.accept().await |
| 3186 | } else { |
| 3187 | listener.accept().await |
| 3188 | }; |
| 3189 | #[cfg(not(all(test, celld_internal_tests)))] |
| 3190 | let accepted = listener.accept().await; |
| 3191 | match accepted { |
| 3192 | Ok((stream, _)) => { |
| 3193 | if recovering { |
| 3194 | tracing::info!( |
| 3195 | event = "shutdown_accept_recovered", |
| 3196 | surface = surface.name(), |
| 3197 | "accepted {} connection after a shutdown accept error", |
| 3198 | surface.name() |
| 3199 | ); |
| 3200 | } |
| 3201 | let (received, wait_until_received) = oneshot::channel(); |
| 3202 | let connection = ShutdownConnection { |
| 3203 | stream, |
| 3204 | surface, |
| 3205 | received, |
| 3206 | #[cfg(all(test, celld_internal_tests))] |
| 3207 | recovered_after_error: recovering, |
| 3208 | }; |
| 3209 | if connections.send(connection).await.is_err() { |
| 3210 | return; |
| 3211 | } |
| 3212 | let _ = wait_until_received.await; |
| 3213 | retry_delay = SHUTDOWN_ACCEPT_RETRY_INITIAL; |
| 3214 | recovering = false; |
| 3215 | } |
| 3216 | Err(error) => { |
| 3217 | tracing::warn!( |
| 3218 | event = "shutdown_accept_failed", |
| 3219 | surface = surface.name(), |
| 3220 | retry_ms = retry_delay.as_millis(), |
| 3221 | %error, |
| 3222 | "could not accept {} connection during shutdown; retrying", |
| 3223 | surface.name() |
| 3224 | ); |
| 3225 | #[cfg(all(test, celld_internal_tests))] |
| 3226 | if inject_failure { |
| 3227 | shutdown_accept_failure_test_checkpoint(true, "listener failure observed"); |
| 3228 | connect_after_failure_for_test = true; |
| 3229 | } |
| 3230 | recovering = true; |
| 3231 | tokio::time::sleep(retry_delay).await; |
| 3232 | retry_delay = retry_delay.saturating_mul(2).min(SHUTDOWN_ACCEPT_RETRY_MAX); |
| 3233 | } |
| 3234 | } |
| 3235 | } |
| 3236 | }); |
| 3237 | } |
| 3238 | |
| 3239 | fn serve_http_connection( |
| 3240 | stream: tokio::net::TcpStream, |
| 3241 | surface: HttpSurface, |
| 3242 | app: AppHandle, |
| 3243 | shutdown: mpsc::UnboundedSender<ShutdownMode>, |
| 3244 | mut connection_drain: watch::Receiver<bool>, |
| 3245 | connection_grace: std::time::Duration, |
| 3246 | ) -> ConnectionFuture { |
| 3247 | // Nagle + delayed-ACK stalls small request/response exchanges by tens |
| 3248 | // of milliseconds; the log tier's append acks measured it directly (a |
| 3249 | // ~70 ms floor on a sub-millisecond VPC path). Responses must leave |
| 3250 | // when written, on every surface. |
| 3251 | let _ = stream.set_nodelay(true); |
| 3252 | Box::pin(async move { |
| 3253 | let peer = stream.peer_addr().ok(); |
| 3254 | // Serve on the runtime, not on this task. `main` drives its loop with |
| 3255 | // `block_on`, so serving there put every connection on one core. |
| 3256 | // Awaiting the spawned task keeps shutdown tracking unchanged. |
| 3257 | let served = tokio::spawn(async move { |
| 3258 | let connection_requests = ConnectionWorkerRequests::default(); |
| 3259 | let service_requests = connection_requests.clone(); |
| 3260 | let service = service_fn(move |request| { |
| 3261 | let app = app.clone(); |
| 3262 | let shutdown = shutdown.clone(); |
| 3263 | let service_requests = service_requests.clone(); |
| 3264 | async move { |
| 3265 | match surface { |
| 3266 | HttpSurface::Public => handle_public(request, app, service_requests).await, |
| 3267 | HttpSurface::Internal => handle_internal(request, app, shutdown).await, |
| 3268 | HttpSurface::Recovery => { |
| 3269 | let path = request.uri().path().to_string(); |
| 3270 | Ok(match path.as_str() { |
| 3271 | "/peer/log/seal" | "/peer/log/tail" => { |
| 3272 | internal_log(request, app, path).await |
| 3273 | } |
| 3274 | _ => response( |
| 3275 | StatusCode::SERVICE_UNAVAILABLE, |
| 3276 | "predecessor recovery in progress", |
| 3277 | ), |
| 3278 | }) |
| 3279 | } |
| 3280 | } |
| 3281 | } |
| 3282 | }); |
| 3283 | let connection = http1::Builder::new() |
| 3284 | // Reclaim a connection that never sends a complete request |
| 3285 | // head. The timeout also bounds an idle keep-alive waiting |
| 3286 | // for its next request. |
| 3287 | .timer(hyper_util::rt::TokioTimer::new()) |
| 3288 | .header_read_timeout(std::time::Duration::from_secs(30)) |
| 3289 | .serve_connection(TokioIo::new(stream), service) |
| 3290 | .with_upgrades(); |
| 3291 | tokio::pin!(connection); |
| 3292 | let result = celld::asyncrt::select! { |
| 3293 | result = &mut connection => Some(result), |
| 3294 | _ = connection_drain.changed() => { |
| 3295 | connection.as_mut().graceful_shutdown(); |
| 3296 | tokio::time::timeout(connection_grace, &mut connection) |
| 3297 | .await |
| 3298 | .ok() |
| 3299 | } |
| 3300 | }; |
| 3301 | connection_requests.abort_all(); |
| 3302 | match result { |
| 3303 | Some(Err(error)) => record_connection_error(&error, surface, peer), |
| 3304 | None => tracing::warn!( |
| 3305 | event = "connection_drain_forced", |
| 3306 | grace_ms = connection_grace.as_millis(), |
| 3307 | "forced an HTTP connection closed after its graceful drain" |
| 3308 | ), |
| 3309 | Some(Ok(())) => {} |
| 3310 | } |
| 3311 | }); |
| 3312 | let _ = served.await; |
| 3313 | }) |
| 3314 | } |
| 3315 | |
| 3316 | /// Serve the surviving follower disks before recovering this node's own |
| 3317 | /// predecessor. After a correlated restart, every predecessor can need a |
| 3318 | /// fragment on another restarting node. Waiting to accept until recovery |
| 3319 | /// finishes makes those intact disks look lost and seals out acked writes. |
| 3320 | /// Only authenticated seal and tail requests run here: the actor has no |
| 3321 | /// lease yet, so neither application work nor new log appends can run. |
| 3322 | async fn recover_with_follower_listener( |
| 3323 | listener: &tokio::net::TcpListener, |
| 3324 | app: AppHandle, |
| 3325 | recovery: impl std::future::Future<Output = anyhow::Result<()>>, |
| 3326 | ) -> anyhow::Result<()> { |
| 3327 | let (drain_tx, drain_rx) = watch::channel(false); |
| 3328 | let (shutdown_tx, _shutdown_rx) = mpsc::unbounded_channel(); |
| 3329 | let mut connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new(); |
| 3330 | tokio::pin!(recovery); |
| 3331 | let result = loop { |
| 3332 | celld::asyncrt::select! { |
| 3333 | result = &mut recovery => break result, |
| 3334 | accepted = listener.accept() => { |
| 3335 | match accepted { |
| 3336 | Ok((stream, _)) => connections.push(serve_http_connection( |
| 3337 | stream, |
| 3338 | HttpSurface::Recovery, |
| 3339 | app.clone(), |
| 3340 | shutdown_tx.clone(), |
| 3341 | drain_rx.clone(), |
| 3342 | CONNECTION_DRAIN_GRACE, |
| 3343 | )), |
| 3344 | Err(error) => break Err(error.into()), |
| 3345 | } |
| 3346 | } |
| 3347 | Some(()) = connections.next(), if !connections.is_empty() => {} |
| 3348 | } |
| 3349 | }; |
| 3350 | // Retire the recovery-only keep-alives on either outcome, so no stale |
| 3351 | // service survives into normal operation or an unsuccessful boot. |
| 3352 | let _ = drain_tx.send(true); |
| 3353 | while connections.next().await.is_some() {} |
| 3354 | result |
| 3355 | } |
| 3356 | #[path = "main/cli.rs"] |
| 3357 | mod cli; |
| 3358 | use cli::{action_from_process, print_help, Action}; |
| 3359 | |
| 3360 | #[cfg(all(test, celld_internal_tests))] |
| 3361 | fn shutdown_accept_failure_test_action() -> Action { |
| 3362 | let listen = std::env::var("CELLD_DRAIN_ACCEPT_FAILURE_LISTEN") |
| 3363 | .map(celld::startup::Listen::Explicit) |
| 3364 | .unwrap_or(celld::startup::Listen::LoopbackEphemeral); |
| 3365 | Action::Run(cli::Settings { |
| 3366 | control_plane: false, |
| 3367 | bucket: None, |
| 3368 | load_deployment: false, |
| 3369 | endpoint: None, |
| 3370 | region: "test".to_string(), |
| 3371 | listen, |
| 3372 | internal_listen: celld::startup::Listen::LoopbackEphemeral, |
| 3373 | advertise: None, |
| 3374 | unsafe_public_advertise: false, |
| 3375 | trust_forwarded_headers: false, |
| 3376 | dev_store: None, |
| 3377 | }) |
| 3378 | } |
| 3379 | |
| 3380 | fn node_bucket( |
| 3381 | settings: &cli::Settings, |
| 3382 | managed: Option<&celld::control_plane::ManagedStorageConfig>, |
| 3383 | lease: bool, |
| 3384 | ) -> anyhow::Result<celld::bucket::Bucket> { |
| 3385 | if let Some(database) = &settings.dev_store { |
| 3386 | anyhow::ensure!( |
| 3387 | managed.is_none(), |
| 3388 | "a development node cannot use managed storage" |
| 3389 | ); |
| 3390 | return celld::dev::open_local_bucket(database); |
| 3391 | } |
| 3392 | let bucket = settings |
| 3393 | .bucket |
| 3394 | .as_deref() |
| 3395 | .context("the node has no fleet bucket")?; |
| 3396 | if lease { |
| 3397 | fleet::lease_bucket_client_with_credentials( |
| 3398 | bucket, |
| 3399 | settings.endpoint.as_deref(), |
| 3400 | &settings.region, |
| 3401 | managed, |
| 3402 | ) |
| 3403 | } else { |
| 3404 | fleet::bucket_client_with_credentials( |
| 3405 | bucket, |
| 3406 | settings.endpoint.as_deref(), |
| 3407 | &settings.region, |
| 3408 | managed, |
| 3409 | ) |
| 3410 | } |
| 3411 | } |
| 3412 | |
| 3413 | /// The shutdown handoff parks the successor dormant, so the batch does not |
| 3414 | /// start restore work there. The fleet drain token also admits one donor at a |
| 3415 | /// time. Keep enough ownership operations in flight to overlap object-store |
| 3416 | /// latency: a width of 8 evacuated only about 110 cells inside the default |
| 3417 | /// 40-second process deadline. |
| 3418 | const DEFAULT_MAX_CONCURRENT_RELEASES: usize = 128; |
| 3419 | /// The actor refreshes the counts a node lease publishes once per sample. |
| 3420 | const LOAD_SAMPLE_PERIOD: std::time::Duration = std::time::Duration::from_secs(1); |
| 3421 | /// How often a node with balancing off samples the fleet leases for the |
| 3422 | /// bucket-format gate: the balancing default, one shared fleet sample. |
| 3423 | const FORMAT_GATE_SAMPLE_MS: u64 = 5_000; |
| 3424 | /// One lease renewal plus one load sample bound how stale a peer's count is, |
| 3425 | /// so a batch every five seconds sees its predecessor before it plans. |
| 3426 | const DEFAULT_REBALANCE_INTERVAL_MS: u64 = 5_000; |
| 3427 | const DEFAULT_REBALANCE_BATCH_CELLS: usize = 32; |
| 3428 | /// Preserved SQLite snapshots make a same-node wake a rename instead of a |
| 3429 | /// remote restore, but must not grow with the lifetime population of a node. |
| 3430 | /// The walk is O(cached cells), so keep it off the hot maintenance cadence. |
| 3431 | const LOCAL_CACHE_PRUNE_PERIOD: std::time::Duration = std::time::Duration::from_secs(60); |
| 3432 | |
| 3433 | fn main() -> anyhow::Result<()> { |
| 3434 | celld::env_vars::validate()?; |
| 3435 | // Parse the telemetry group once, before any command or runtime work. |
| 3436 | // Its specialized values share the strict scalar parsers in env_vars. |
| 3437 | let telemetry_config = celld::telemetry::Config::from_env()?; |
| 3438 | rustls::crypto::ring::default_provider() |
| 3439 | .install_default() |
| 3440 | .ok(); |
| 3441 | // Before the runtime exists, so every worker thread inherits a PKRU that |
| 3442 | // grants access to V8's pointer-table protection key. |
| 3443 | celld::runtime::init_v8(); |
| 3444 | let mut builder = tokio::runtime::Builder::new_multi_thread(); |
| 3445 | builder.enable_all(); |
| 3446 | if let Some(workers) = celld::env_vars::positive::<usize>("CELLD_TOKIO_THREADS")? { |
| 3447 | builder.worker_threads(workers); |
| 3448 | } |
| 3449 | builder.build()?.block_on(async_main(telemetry_config)) |
| 3450 | } |
| 3451 | |
| 3452 | async fn async_main(telemetry_config: Option<celld::telemetry::Config>) -> anyhow::Result<()> { |
| 3453 | #[cfg(all(test, celld_internal_tests))] |
| 3454 | let shutdown_accept_failure_test_active = |
| 3455 | std::env::var_os("CELLD_DRAIN_ACCEPT_FAILURE_CHILD").is_some(); |
| 3456 | #[cfg(all(test, celld_internal_tests))] |
| 3457 | let action = if shutdown_accept_failure_test_active { |
| 3458 | shutdown_accept_failure_test_action() |
| 3459 | } else { |
| 3460 | action_from_process()? |
| 3461 | }; |
| 3462 | #[cfg(not(all(test, celld_internal_tests)))] |
| 3463 | let action = action_from_process()?; |
| 3464 | celld::asyncrt::set_host_handle(tokio::runtime::Handle::current()); |
| 3465 | // Docker and journald can stop consuming the process pipe during a log |
| 3466 | // burst. Logging must lose diagnostics under that backpressure rather |
| 3467 | // than block the Tokio workers that route requests and renew authority. |
| 3468 | // Parsed before the subscriber exists, because where the log goes depends |
| 3469 | // on which invocation this is: a node logs to stdout, and a CLI subcommand |
| 3470 | // must keep stdout for its answer. |
| 3471 | let log_filter = if matches!( |
| 3472 | &action, |
| 3473 | Action::Dev(arguments) if !arguments.iter().any(|argument| argument == "--logs") |
| 3474 | ) { |
| 3475 | // `celld dev` is an application-facing supervisor. Its default view |
| 3476 | // must stay concise even when the parent inherited a broad RUST_LOG; |
| 3477 | // --logs is the explicit opt-in to that diagnostic stream. |
| 3478 | tracing_subscriber::EnvFilter::new("error") |
| 3479 | } else { |
| 3480 | tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()) |
| 3481 | }; |
| 3482 | let (log_sink, log_is_terminal): (Box<dyn std::io::Write + Send>, bool) = |
| 3483 | if action.stdout_is_data() { |
| 3484 | ( |
| 3485 | Box::new(std::io::stderr()), |
| 3486 | std::io::IsTerminal::is_terminal(&std::io::stderr()), |
| 3487 | ) |
| 3488 | } else { |
| 3489 | ( |
| 3490 | Box::new(std::io::stdout()), |
| 3491 | std::io::IsTerminal::is_terminal(&std::io::stdout()), |
| 3492 | ) |
| 3493 | }; |
| 3494 | let (log_writer, log_guard) = tracing_appender::non_blocking::NonBlockingBuilder::default() |
| 3495 | .buffered_lines_limit(8_192) |
| 3496 | .lossy(true) |
| 3497 | .finish(log_sink); |
| 3498 | *LOG_GUARD.lock().unwrap() = Some(log_guard); |
| 3499 | tracing_subscriber::fmt() |
| 3500 | .with_writer(log_writer) |
| 3501 | // The custom writer defeats fmt's own TTY detection, and journald |
| 3502 | // must not receive ANSI escapes. |
| 3503 | .with_ansi(log_is_terminal) |
| 3504 | .with_env_filter(log_filter) |
| 3505 | .init(); |
| 3506 | // After the subscriber, because this reports whether the allocator agreed |
| 3507 | // to return freed pages on a timer. A node without that thread holds |
| 3508 | // retention until a thread allocates again, which is the condition behind |
| 3509 | // issue #36, so the operator has to be able to read the answer. |
| 3510 | celld::memory::tune_allocator(); |
| 3511 | let mut settings = match action { |
| 3512 | Action::Deploy(arguments) => return fleet::run_deploy(arguments).await, |
| 3513 | Action::Dev(arguments) => return celld::dev::run(arguments).await, |
| 3514 | Action::Cell(arguments) => return celld::cell_cli::run(arguments).await, |
| 3515 | Action::D1(arguments) => return celld::d1_cli::run(arguments).await, |
| 3516 | Action::Kv(arguments) => return celld::kv_cli::run(arguments).await, |
| 3517 | Action::Queue(arguments) => return celld::queue_cli::run(arguments).await, |
| 3518 | Action::Connect(arguments) => { |
| 3519 | return celld::control_plane::handle_connect_command(arguments).await |
| 3520 | } |
| 3521 | Action::Credentials(arguments) => { |
| 3522 | return celld::control_plane::handle_credentials_command(arguments).await |
| 3523 | } |
| 3524 | Action::Token(arguments) => { |
| 3525 | return celld::control_plane::handle_token_command(arguments).await |
| 3526 | } |
| 3527 | Action::Disconnect(arguments) => { |
| 3528 | return celld::control_plane::handle_disconnect_command(arguments).await |
| 3529 | } |
| 3530 | Action::Help => { |
| 3531 | print_help()?; |
| 3532 | return Ok(()); |
| 3533 | } |
| 3534 | Action::Version => { |
| 3535 | let profile = if cfg!(debug_assertions) { |
| 3536 | " (debug)" |
| 3537 | } else { |
| 3538 | "" |
| 3539 | }; |
| 3540 | celld::cli_output::Output::new(celld::cli_output::Format::Text) |
| 3541 | .line(format_args!("celld {}{profile}", env!("CARGO_PKG_VERSION")))?; |
| 3542 | return Ok(()); |
| 3543 | } |
| 3544 | Action::Diagnose { |
| 3545 | mut settings, |
| 3546 | peers, |
| 3547 | read_only, |
| 3548 | json, |
| 3549 | } => { |
| 3550 | let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?; |
| 3551 | let internal = |
| 3552 | celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings { |
| 3553 | listen: settings.internal_listen.clone(), |
| 3554 | advertise: settings.advertise.clone(), |
| 3555 | unsafe_public_advertise: settings.unsafe_public_advertise, |
| 3556 | }) |
| 3557 | .await?; |
| 3558 | // The bind proves the address is free; diagnose never serves on it, |
| 3559 | // and an operator should not read this line as a running listener. |
| 3560 | // These reach the terminal through `fleet::diagnose`, so that one |
| 3561 | // `Output` renders every check and `--json` stays parseable. |
| 3562 | let preamble = vec![ |
| 3563 | celld::fleet::Check::ok( |
| 3564 | format!("listen {}", ingress.listen), |
| 3565 | "bind check; diagnose does not serve", |
| 3566 | ), |
| 3567 | celld::fleet::Check::ok( |
| 3568 | format!("internal listen {}", internal.listen), |
| 3569 | "bind check; diagnose does not serve", |
| 3570 | ), |
| 3571 | celld::fleet::Check::ok( |
| 3572 | format!("advertise {}", internal.advertise), |
| 3573 | format!( |
| 3574 | "{}; direct reachability is not inferred", |
| 3575 | internal.advertise.scope() |
| 3576 | ), |
| 3577 | ), |
| 3578 | ]; |
| 3579 | let managed_storage = if settings.control_plane { |
| 3580 | match celld::control_plane::installation_storage().context( |
| 3581 | "managed diagnostics require an existing enrollment; run `celld --control-plane` first", |
| 3582 | )? { |
| 3583 | celld::control_plane::InstallationStorageConfig::Managed(storage) => { |
| 3584 | settings.bucket = Some(storage.bucket.clone()); |
| 3585 | settings.endpoint = Some(storage.endpoint.clone()); |
| 3586 | settings.region = storage.region.clone(); |
| 3587 | Some(storage) |
| 3588 | } |
| 3589 | celld::control_plane::InstallationStorageConfig::Byo(storage) => { |
| 3590 | settings.bucket = Some(storage.bucket); |
| 3591 | settings.endpoint = storage.endpoint; |
| 3592 | settings.region = storage.region; |
| 3593 | None |
| 3594 | } |
| 3595 | } |
| 3596 | } else { |
| 3597 | None |
| 3598 | }; |
| 3599 | let bucket = settings |
| 3600 | .bucket |
| 3601 | .ok_or_else(|| anyhow::anyhow!("celld diagnose requires --bucket"))?; |
| 3602 | let client = fleet::bucket_client_with_credentials( |
| 3603 | &bucket, |
| 3604 | settings.endpoint.as_deref(), |
| 3605 | &settings.region, |
| 3606 | managed_storage.as_ref(), |
| 3607 | )?; |
| 3608 | return fleet::diagnose( |
| 3609 | &client, |
| 3610 | peers, |
| 3611 | settings.unsafe_public_advertise, |
| 3612 | read_only, |
| 3613 | json, |
| 3614 | preamble, |
| 3615 | ) |
| 3616 | .await; |
| 3617 | } |
| 3618 | Action::Run(settings) => settings, |
| 3619 | }; |
| 3620 | celld::startup::raise_file_limit(); |
| 3621 | let max_resident = celld::env_vars::optional("CELLD_MAX_RESIDENT_CELLS")? |
| 3622 | // celld has no resident ceiling unless the operator configures one. |
| 3623 | // The clean-sheet prototype originally defaulted to eight, which |
| 3624 | // introduced eviction churn in otherwise unconstrained workloads and |
| 3625 | // made cancellation semantics depend on cold-reactivation latency. |
| 3626 | .unwrap_or(usize::MAX); |
| 3627 | let max_request_body_bytes = celld::env_vars::positive_or( |
| 3628 | "CELLD_MAX_REQUEST_BODY_BYTES", |
| 3629 | DEFAULT_MAX_REQUEST_BODY_BYTES, |
| 3630 | )?; |
| 3631 | anyhow::ensure!( |
| 3632 | max_request_body_bytes <= DEFAULT_MAX_REQUEST_BODY_BYTES, |
| 3633 | "CELLD_MAX_REQUEST_BODY_BYTES cannot exceed {DEFAULT_MAX_REQUEST_BODY_BYTES}" |
| 3634 | ); |
| 3635 | let local_cache_max_bytes = local_cache_max_bytes_from_environment()?; |
| 3636 | let fail_publish_once = std::env::var_os("CELLD_TEST_FAIL_PUBLISH_ONCE").is_some(); |
| 3637 | let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?; |
| 3638 | let internal = |
| 3639 | celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings { |
| 3640 | listen: settings.internal_listen.clone(), |
| 3641 | advertise: settings.advertise.clone(), |
| 3642 | unsafe_public_advertise: settings.unsafe_public_advertise, |
| 3643 | }) |
| 3644 | .await?; |
| 3645 | let advertise = internal.advertise.to_string(); |
| 3646 | let listen = ingress.listen.to_string(); |
| 3647 | let listener = ingress.listener; |
| 3648 | let internal_listener = internal.listener; |
| 3649 | let mut adapter_credential_version = None; |
| 3650 | let managed_storage = if settings.control_plane { |
| 3651 | if let Some(spec) = settings.bucket.take() { |
| 3652 | let (backend, name, prefix) = celld::bucket::split_spec(&spec); |
| 3653 | // The control plane issues and validates S3-compatible storage |
| 3654 | // only. Parse through the same seam as Bucket::open so scheme |
| 3655 | // case cannot change this decision or the eventual backend. |
| 3656 | anyhow::ensure!( |
| 3657 | backend == celld::bucket::StorageBackend::S3, |
| 3658 | "--control-plane storage is S3-compatible; a {}:// bucket runs without it", |
| 3659 | match backend { |
| 3660 | celld::bucket::StorageBackend::Gcs => "gs", |
| 3661 | celld::bucket::StorageBackend::Azure => "az", |
| 3662 | celld::bucket::StorageBackend::S3 => "s3", |
| 3663 | celld::bucket::StorageBackend::Local => "dev", |
| 3664 | } |
| 3665 | ); |
| 3666 | // The control plane issues one bucket per fleet and its enrollment |
| 3667 | // API rejects a prefix. Install the parsed S3 name because the API |
| 3668 | // accepts a name, while every engine bucket path accepts a spec. |
| 3669 | anyhow::ensure!( |
| 3670 | prefix.is_empty(), |
| 3671 | "--control-plane does not accept a --bucket prefix" |
| 3672 | ); |
| 3673 | settings.bucket = Some(name.to_string()); |
| 3674 | } |
| 3675 | let requested_byo = |
| 3676 | settings |
| 3677 | .bucket |
| 3678 | .as_ref() |
| 3679 | .map(|bucket| celld::control_plane::ByoStorageConfig { |
| 3680 | bucket: bucket.clone(), |
| 3681 | endpoint: settings.endpoint.clone(), |
| 3682 | region: settings.region.clone(), |
| 3683 | }); |
| 3684 | celld::control_plane::connect_on_startup_with_storage(requested_byo).await?; |
| 3685 | settings.load_deployment = true; |
| 3686 | let (storage, credential_version) = |
| 3687 | celld::control_plane::installation_storage_with_version()?; |
| 3688 | adapter_credential_version = Some(credential_version); |
| 3689 | match storage { |
| 3690 | celld::control_plane::InstallationStorageConfig::Managed(storage) => { |
| 3691 | settings.bucket = Some(storage.bucket.clone()); |
| 3692 | settings.endpoint = Some(storage.endpoint.clone()); |
| 3693 | settings.region = storage.region.clone(); |
| 3694 | Some(storage) |
| 3695 | } |
| 3696 | celld::control_plane::InstallationStorageConfig::Byo(storage) => { |
| 3697 | settings.bucket = Some(storage.bucket); |
| 3698 | settings.endpoint = storage.endpoint; |
| 3699 | settings.region = storage.region; |
| 3700 | None |
| 3701 | } |
| 3702 | } |
| 3703 | } else { |
| 3704 | None |
| 3705 | }; |
| 3706 | let storage_credentials = |
| 3707 | managed_storage |
| 3708 | .as_ref() |
| 3709 | .map(|storage| celld::replication::StorageCredentials { |
| 3710 | access_key_id: storage.access_key_id.clone(), |
| 3711 | secret_access_key: storage.secret_access_key.clone(), |
| 3712 | session_token: storage.session_token.clone(), |
| 3713 | }); |
| 3714 | let (tx, rx) = mpsc::unbounded_channel(); |
| 3715 | let sample_tx = tx.clone(); |
| 3716 | let alarm_tx = tx.clone(); |
| 3717 | let alarm_observer: celld::runtime::AlarmObserver = Arc::new(move |cell, alarm| { |
| 3718 | let _ = alarm_tx.send(Message::AlarmObserved { |
| 3719 | cell, |
| 3720 | alarm, |
| 3721 | covered: false, |
| 3722 | }); |
| 3723 | }); |
| 3724 | let (fence_tx, mut fence_rx) = mpsc::unbounded_channel(); |
| 3725 | let node = std::env::var("CELLD_NODE").unwrap_or_else(|_| random_node_session_id()); |
| 3726 | let clean_reload_node = node.clone(); |
| 3727 | celld::control_plane::install_reexec_node_session_id(&node)?; |
| 3728 | let probe_public_key = celld::peer_probe::install_signer()?; |
| 3729 | // Cold routes are object-store latency, not compute: the default is |
| 3730 | // derived from the thread count but far above it. See |
| 3731 | // `machine::default_max_activations` for the measurements. |
| 3732 | let max_activations = |
| 3733 | celld::env_vars::positive::<usize>("CELLD_ACTIVATIONS")?.unwrap_or_else(|| { |
| 3734 | celld::machine::default_max_activations( |
| 3735 | std::thread::available_parallelism() |
| 3736 | .map(usize::from) |
| 3737 | .unwrap_or(1), |
| 3738 | ) |
| 3739 | }); |
| 3740 | let placement_weight = celld::env_vars::positive::<u64>("CELLD_PLACEMENT_WEIGHT")? |
| 3741 | .unwrap_or_else(|| { |
| 3742 | std::thread::available_parallelism() |
| 3743 | .map(|cpus| cpus.get() as u64) |
| 3744 | .unwrap_or(1) |
| 3745 | }); |
| 3746 | let rebalance_interval_ms = celld::env_vars::optional::<u64>("CELLD_REBALANCE_INTERVAL_MS")? |
| 3747 | .unwrap_or(DEFAULT_REBALANCE_INTERVAL_MS); |
| 3748 | // The shared fleet sample's interval: the balancing interval, or the |
| 3749 | // format gate's when balancing is off. Every reader of the sample, the |
| 3750 | // balancing tick, placement and recruitment, judges freshness by it. |
| 3751 | let fleet_sample_ms = if rebalance_interval_ms > 0 { |
| 3752 | rebalance_interval_ms |
| 3753 | } else { |
| 3754 | FORMAT_GATE_SAMPLE_MS |
| 3755 | }; |
| 3756 | let max_releases = celld::env_vars::positive::<usize>("CELLD_RELEASES")? |
| 3757 | .unwrap_or(DEFAULT_MAX_CONCURRENT_RELEASES); |
| 3758 | let data_dir = std::env::var_os("CELLD_TEST_DATA_DIR") |
| 3759 | .or_else(|| std::env::var_os("CELLD_WATCH")) |
| 3760 | .map(std::path::PathBuf::from) |
| 3761 | .unwrap_or_else(|| std::env::temp_dir().join(format!("celld-{}", std::process::id()))); |
| 3762 | let mut deploy_agent = None; |
| 3763 | // The channel `POST /reload` and a managed notification nudge the pointer |
| 3764 | // watcher through. Without a deployment bucket the receiver is dropped |
| 3765 | // and a reload reports that there is no pointer to reload from. |
| 3766 | let (reload_tx, reload_rx) = celld::generation::reload_channel(); |
| 3767 | let (runtime, ownership, peer_key, wake_scan, deploy_bucket) = |
| 3768 | if settings.bucket.is_some() && settings.load_deployment { |
| 3769 | let client = node_bucket(&settings, managed_storage.as_ref(), false)?; |
| 3770 | if settings.control_plane { |
| 3771 | fleet::validate_managed_bucket(&client).await?; |
| 3772 | } else { |
| 3773 | fleet::validate_bucket(&client).await?; |
| 3774 | } |
| 3775 | celld::wake_format::ensure_ready(&client).await?; |
| 3776 | // The list above proves the bucket answers; it does not prove the |
| 3777 | // store enforces the conditional writes or ranged reads that a |
| 3778 | // cell needs. Test both contracts here before the node serves. |
| 3779 | fleet::probe_storage_before_serving(&client, settings.control_plane).await?; |
| 3780 | let lease_client = node_bucket(&settings, managed_storage.as_ref(), true)?; |
| 3781 | if settings.control_plane { |
| 3782 | celld::control_plane::wait_for_initial_deployment(&client).await?; |
| 3783 | deploy_agent = Some(client.clone()); |
| 3784 | } else { |
| 3785 | // A self-hosted node can start before its first `celld |
| 3786 | // deploy`; wait for the pointer instead of exiting, or |
| 3787 | // systemd restarts the node in a loop until a deployment |
| 3788 | // exists. Managed mode already waited above. |
| 3789 | fleet::wait_for_deployment_pointer(&client).await?; |
| 3790 | } |
| 3791 | let peer_key = peer_auth::load_or_create(&client).await?; |
| 3792 | let graph = DeploymentGraph::load(&client, node.clone()).await?; |
| 3793 | let wake = Arc::new(celld::wake::WakeFlusher::new()); |
| 3794 | celld::js::set_arm_gate(ArmGate { |
| 3795 | bucket: client.clone(), |
| 3796 | flusher: wake.clone(), |
| 3797 | }); |
| 3798 | // An `r2_buckets` binding lives in the fleet bucket, under the |
| 3799 | // reserved `r2/<bucket_name>/` prefix. celld runs on blob storage |
| 3800 | // rather than providing it, so a binding gets the store the node |
| 3801 | // already holds credentials for instead of a second one. |
| 3802 | celld::js::set_r2_store(client.clone()); |
| 3803 | // celld treats replication as a node service, not as a property |
| 3804 | // of today's manifest. Start it even for a stateless deployment |
| 3805 | // so a later deployment can introduce cells without changing the |
| 3806 | // durability contract underneath the node. |
| 3807 | let replication = Some(Replication::start( |
| 3808 | client.clone(), |
| 3809 | &data_dir, |
| 3810 | settings.endpoint.clone(), |
| 3811 | settings.region.clone(), |
| 3812 | storage_credentials.clone(), |
| 3813 | )?); |
| 3814 | // The same two calls a reload makes: there is no boot-only way from |
| 3815 | // a deployment to a serving generation. |
| 3816 | let generation = Generation::build( |
| 3817 | FIRST_GENERATION, |
| 3818 | graph, |
| 3819 | GenerationOptions { |
| 3820 | node: node.clone(), |
| 3821 | region: settings.region.clone(), |
| 3822 | }, |
| 3823 | )?; |
| 3824 | let runtime = RuntimeManager::start( |
| 3825 | generation, |
| 3826 | RuntimeOptions { |
| 3827 | data_dir: data_dir.clone(), |
| 3828 | replication, |
| 3829 | wake: Some(wake.clone()), |
| 3830 | alarm_observer: alarm_observer.clone(), |
| 3831 | node: node.clone(), |
| 3832 | region: settings.region.clone(), |
| 3833 | bucket: Some(client.clone()), |
| 3834 | }, |
| 3835 | )?; |
| 3836 | let deploy_bucket = Some(client.clone()); |
| 3837 | let bucket_ownership = Arc::new( |
| 3838 | BucketOwnership::new( |
| 3839 | client.clone(), |
| 3840 | lease_client, |
| 3841 | node.clone(), |
| 3842 | probe_public_key.clone(), |
| 3843 | ) |
| 3844 | .with_lease_ttl_ms(lease_ttl_ms_from_environment()) |
| 3845 | .with_fleet_sample_ms(fleet_sample_ms), |
| 3846 | ); |
| 3847 | let wake_scan = Some((client, bucket_ownership.clone())); |
| 3848 | let ownership = Ownership::Bucket(bucket_ownership); |
| 3849 | ( |
| 3850 | Some(runtime), |
| 3851 | Some(ownership), |
| 3852 | peer_key, |
| 3853 | wake_scan, |
| 3854 | deploy_bucket, |
| 3855 | ) |
| 3856 | } else if let Ok(script_path) = std::env::var("CELLD_TEST_SCRIPT_PATH") { |
| 3857 | let source = std::fs::read_to_string(&script_path)?; |
| 3858 | let do_classes = std::env::var("CELLD_TEST_DO_CLASSES") |
| 3859 | .unwrap_or_default() |
| 3860 | .split(',') |
| 3861 | .map(str::trim) |
| 3862 | .filter(|value| !value.is_empty()) |
| 3863 | .map(str::to_string) |
| 3864 | .collect(); |
| 3865 | let bindings = std::env::var("CELLD_TEST_DO_BINDINGS") |
| 3866 | .unwrap_or_default() |
| 3867 | .split(',') |
| 3868 | .filter_map(|value| value.split_once('=')) |
| 3869 | .map(|(name, class)| (name.trim().to_string(), class.trim().to_string())) |
| 3870 | .filter(|(name, class)| !name.is_empty() && !class.is_empty()) |
| 3871 | .collect(); |
| 3872 | // `BINDING=database` pairs, the local-script equivalent of |
| 3873 | // `d1_databases` in a deployed project. |
| 3874 | let d1_bindings: Vec<(String, String)> = std::env::var("CELLD_TEST_D1_BINDINGS") |
| 3875 | .unwrap_or_default() |
| 3876 | .split(',') |
| 3877 | .filter_map(|value| value.split_once('=')) |
| 3878 | .map(|(name, database)| (name.trim().to_string(), database.trim().to_string())) |
| 3879 | .filter(|(name, database)| !name.is_empty() && !database.is_empty()) |
| 3880 | .collect(); |
| 3881 | // `BINDING=namespace-id`, the `CELLD_TEST_D1_BINDINGS` shape. Day one, |
| 3882 | // for the reason D1's and Workflows' equivalents landed on day one: |
| 3883 | // every runtime test needs it. |
| 3884 | let kv_bindings: Vec<(String, String)> = std::env::var("CELLD_LOCAL_KV_BINDINGS") |
| 3885 | .unwrap_or_default() |
| 3886 | .split(',') |
| 3887 | .filter_map(|value| value.split_once('=')) |
| 3888 | .map(|(name, id)| (name.trim().to_string(), id.trim().to_string())) |
| 3889 | .filter(|(name, id)| !name.is_empty() && !id.is_empty()) |
| 3890 | .collect(); |
| 3891 | // `BINDING=queue`, the local-script equivalent of one Wrangler Queue |
| 3892 | // producer. A local binding has no configuration object for a default |
| 3893 | // delay, so it uses the Queue default of zero. |
| 3894 | let queue_bindings: Vec<QueueBinding> = std::env::var("CELLD_LOCAL_QUEUE_BINDINGS") |
| 3895 | .unwrap_or_default() |
| 3896 | .split(',') |
| 3897 | .filter_map(|value| value.split_once('=')) |
| 3898 | .map(|(environment, queue)| QueueBinding { |
| 3899 | environment: environment.trim().to_string(), |
| 3900 | queue: queue.trim().to_string(), |
| 3901 | delivery_delay: 0, |
| 3902 | }) |
| 3903 | .filter(|binding| !binding.environment.is_empty() && !binding.queue.is_empty()) |
| 3904 | .collect(); |
| 3905 | for binding in &queue_bindings { |
| 3906 | anyhow::ensure!( |
| 3907 | celld_logic::cell::valid_cell_scope(&binding.queue), |
| 3908 | "local Queue binding {} has a queue name that cannot name a cell: {:?}", |
| 3909 | binding.environment, |
| 3910 | binding.queue, |
| 3911 | ); |
| 3912 | } |
| 3913 | // `BINDING=bucket` pairs, the local-script equivalent of |
| 3914 | // `r2_buckets` in a deployed project. |
| 3915 | let r2_bindings: Vec<(String, String)> = std::env::var("CELLD_TEST_R2_BINDINGS") |
| 3916 | .unwrap_or_default() |
| 3917 | .split(',') |
| 3918 | .filter_map(|value| value.split_once('=')) |
| 3919 | .map(|(name, bucket)| (name.trim().to_string(), bucket.trim().to_string())) |
| 3920 | .filter(|(name, bucket)| !name.is_empty() && !bucket.is_empty()) |
| 3921 | .collect(); |
| 3922 | let mut do_classes: Vec<String> = do_classes; |
| 3923 | if !d1_bindings.is_empty() { |
| 3924 | do_classes.push(celld::deploy::D1_CLASS.to_string()); |
| 3925 | } |
| 3926 | if !kv_bindings.is_empty() { |
| 3927 | do_classes.push(celld::deploy::KV_CLASS.to_string()); |
| 3928 | } |
| 3929 | if !queue_bindings.is_empty() { |
| 3930 | do_classes.push(celld::deploy::QUEUE_CLASS.to_string()); |
| 3931 | } |
| 3932 | let workflow_bindings: Vec<WorkflowBinding> = |
| 3933 | std::env::var("CELLD_LOCAL_WORKFLOW_BINDINGS") |
| 3934 | .unwrap_or_default() |
| 3935 | .split(',') |
| 3936 | .filter_map(|value| { |
| 3937 | let (binding, rest) = value.split_once('=')?; |
| 3938 | let (name, class) = rest.split_once('=')?; |
| 3939 | Some(WorkflowBinding { |
| 3940 | environment: binding.trim().to_string(), |
| 3941 | workflow: name.trim().to_string(), |
| 3942 | class: class.trim().to_string(), |
| 3943 | }) |
| 3944 | }) |
| 3945 | .filter(|binding| { |
| 3946 | !binding.environment.is_empty() |
| 3947 | && !binding.workflow.is_empty() |
| 3948 | && !binding.class.is_empty() |
| 3949 | }) |
| 3950 | .collect(); |
| 3951 | // Resolved before the config is built, because the reserved workflow |
| 3952 | // class is script-scoped and `do_classes` has to carry the scoped name. |
| 3953 | let script_name = std::env::var("CELLD_TEST_SCRIPT_NAME") |
| 3954 | .unwrap_or_else(|_| "celld-local".to_string()); |
| 3955 | if !workflow_bindings.is_empty() { |
| 3956 | do_classes.push(celld::deploy::workflow_class(&script_name)); |
| 3957 | } |
| 3958 | let crons: Vec<String> = std::env::var("CELLD_TEST_CRONS") |
| 3959 | .unwrap_or_default() |
| 3960 | .split(';') |
| 3961 | .map(str::trim) |
| 3962 | .filter(|value| !value.is_empty()) |
| 3963 | .map(str::to_string) |
| 3964 | .collect(); |
| 3965 | let options = WorkerConfigOptions { |
| 3966 | src: source, |
| 3967 | script_name, |
| 3968 | do_classes, |
| 3969 | bindings, |
| 3970 | r2_bindings, |
| 3971 | d1_bindings, |
| 3972 | kv_bindings, |
| 3973 | queue_bindings, |
| 3974 | queue_consumers: Vec::new(), |
| 3975 | workflow_bindings, |
| 3976 | vars: Vec::new(), |
| 3977 | node: node.clone(), |
| 3978 | modules: Vec::new(), |
| 3979 | compat: Compat::default(), |
| 3980 | }; |
| 3981 | let (ownership, peer_key, wake, wake_scan) = if settings.bucket.is_some() { |
| 3982 | let client = node_bucket(&settings, managed_storage.as_ref(), false)?; |
| 3983 | celld::wake_format::ensure_ready(&client).await?; |
| 3984 | let lease_client = node_bucket(&settings, managed_storage.as_ref(), true)?; |
| 3985 | let peer_key = peer_auth::load_or_create(&client).await?; |
| 3986 | let wake = Arc::new(celld::wake::WakeFlusher::new()); |
| 3987 | celld::js::set_arm_gate(ArmGate { |
| 3988 | bucket: client.clone(), |
| 3989 | flusher: wake.clone(), |
| 3990 | }); |
| 3991 | celld::js::set_r2_store(client.clone()); |
| 3992 | let bucket_ownership = Arc::new( |
| 3993 | BucketOwnership::new( |
| 3994 | client.clone(), |
| 3995 | lease_client, |
| 3996 | node.clone(), |
| 3997 | probe_public_key.clone(), |
| 3998 | ) |
| 3999 | .with_lease_ttl_ms(lease_ttl_ms_from_environment()) |
| 4000 | .with_fleet_sample_ms(fleet_sample_ms), |
| 4001 | ); |
| 4002 | let wake_scan = Some((client, bucket_ownership.clone())); |
| 4003 | ( |
| 4004 | Some(Ownership::Bucket(bucket_ownership)), |
| 4005 | peer_key, |
| 4006 | Some(wake), |
| 4007 | wake_scan, |
| 4008 | ) |
| 4009 | } else { |
| 4010 | (None, random_peer_key(), None, None) |
| 4011 | }; |
| 4012 | // A local script is a one-script deployment with no pointer behind |
| 4013 | // it, built through the same function as a bucket deployment. |
| 4014 | let script_name = options.script_name.clone(); |
| 4015 | let generation = Generation::build( |
| 4016 | FIRST_GENERATION, |
| 4017 | DeploymentGraph::single(fleet::LoadedDeployment { |
| 4018 | options, |
| 4019 | script_name, |
| 4020 | version: "local".to_string(), |
| 4021 | prefix: script_path.clone(), |
| 4022 | asset_binding: None, |
| 4023 | // A bare script has no wrangler config, so this names the |
| 4024 | // loaders the way `CELLD_TEST_DO_CLASSES` names a class: |
| 4025 | // a comma-separated list, because a config can declare |
| 4026 | // more than one loader. It is the local-script equivalent |
| 4027 | // of `worker_loaders`, and not a production switch: a |
| 4028 | // deployed project reaches a loader only through its own |
| 4029 | // config. |
| 4030 | loader_bindings: std::env::var("CELLD_TEST_WORKER_LOADER") |
| 4031 | .unwrap_or_default() |
| 4032 | .split(',') |
| 4033 | .map(str::trim) |
| 4034 | .filter(|name| !name.is_empty()) |
| 4035 | .map(str::to_string) |
| 4036 | .collect(), |
| 4037 | assets: None, |
| 4038 | services: Vec::new(), |
| 4039 | crons, |
| 4040 | containers: Vec::new(), |
| 4041 | fence_image: None, |
| 4042 | }), |
| 4043 | GenerationOptions { |
| 4044 | node: node.clone(), |
| 4045 | region: settings.region.clone(), |
| 4046 | }, |
| 4047 | )?; |
| 4048 | ( |
| 4049 | Some(RuntimeManager::start( |
| 4050 | generation, |
| 4051 | RuntimeOptions { |
| 4052 | data_dir: data_dir.clone(), |
| 4053 | replication: None, |
| 4054 | wake: wake.clone(), |
| 4055 | alarm_observer: alarm_observer.clone(), |
| 4056 | node: node.clone(), |
| 4057 | region: settings.region.clone(), |
| 4058 | bucket: None, |
| 4059 | }, |
| 4060 | )?), |
| 4061 | ownership, |
| 4062 | peer_key, |
| 4063 | wake_scan, |
| 4064 | None, |
| 4065 | ) |
| 4066 | } else { |
| 4067 | let (ownership, peer_key) = if settings.bucket.is_some() { |
| 4068 | let client = node_bucket(&settings, managed_storage.as_ref(), false)?; |
| 4069 | celld::wake_format::ensure_ready(&client).await?; |
| 4070 | let lease_client = node_bucket(&settings, managed_storage.as_ref(), true)?; |
| 4071 | let peer_key = peer_auth::load_or_create(&client).await?; |
| 4072 | ( |
| 4073 | Some(Ownership::Bucket(Arc::new( |
| 4074 | BucketOwnership::new( |
| 4075 | client, |
| 4076 | lease_client, |
| 4077 | node.clone(), |
| 4078 | probe_public_key.clone(), |
| 4079 | ) |
| 4080 | .with_lease_ttl_ms(lease_ttl_ms_from_environment()) |
| 4081 | .with_fleet_sample_ms(fleet_sample_ms), |
| 4082 | ))), |
| 4083 | peer_key, |
| 4084 | ) |
| 4085 | } else { |
| 4086 | (None, random_peer_key()) |
| 4087 | }; |
| 4088 | (None, ownership, peer_key, None, None) |
| 4089 | }; |
| 4090 | if let Some(config) = &telemetry_config { |
| 4091 | let sink_bucket = match &config.sink { |
| 4092 | celld::telemetry::SinkChoice::Bucket => { |
| 4093 | if settings.bucket.is_none() { |
| 4094 | anyhow::bail!( |
| 4095 | "CELLD_OTEL=1 but this node has no bucket; the \ |
| 4096 | bucket sink needs one (CELLD_BUCKET), or choose \ |
| 4097 | CELLD_OTEL=http://collector:4318" |
| 4098 | ); |
| 4099 | } |
| 4100 | // Its own client even for the fleet bucket: each open is its |
| 4101 | // own transport (bucket.rs), so telemetry PUT bursts never |
| 4102 | // share a connection pool with ownership traffic. |
| 4103 | Some(if let Some(bucket) = config.bucket_override.as_deref() { |
| 4104 | fleet::bucket_client_with_credentials( |
| 4105 | bucket, |
| 4106 | settings.endpoint.as_deref(), |
| 4107 | &settings.region, |
| 4108 | managed_storage.as_ref(), |
| 4109 | )? |
| 4110 | } else { |
| 4111 | node_bucket(&settings, managed_storage.as_ref(), false)? |
| 4112 | }) |
| 4113 | } |
| 4114 | // The collector path needs no bucket at all. |
| 4115 | celld::telemetry::SinkChoice::Otlp { .. } => None, |
| 4116 | }; |
| 4117 | celld::telemetry::init(config, sink_bucket, node.clone(), settings.region.clone())?; |
| 4118 | } |
| 4119 | let peer_auth = Arc::new(PeerAuth::new(peer_key, node.clone())?); |
| 4120 | // Connect-only timeout: a peer request may legitimately run through a |
| 4121 | // restore, but a handshake that never completes provably ran nothing. |
| 4122 | let peer_http = reqwest::Client::builder() |
| 4123 | .connect_timeout(PEER_CONNECT_TIMEOUT) |
| 4124 | // Nagle against delayed ACKs costs tens of milliseconds on every |
| 4125 | // multi-segment peer body. Peer requests are latency-bound, so the |
| 4126 | // socket must write eagerly. |
| 4127 | .tcp_nodelay(true) |
| 4128 | .build() |
| 4129 | .unwrap(); |
| 4130 | let resume_generation = celld::runtime::take_clean_reload_generation(&data_dir, &node); |
| 4131 | let clean_reload_candidate = resume_generation.is_some(); |
| 4132 | let drain_pins = DrainPinRegistry::default(); |
| 4133 | let actor = Actor::from_environment_with_services( |
| 4134 | AdmissionLimits { |
| 4135 | resident: max_resident, |
| 4136 | activations: max_activations, |
| 4137 | releases: max_releases, |
| 4138 | placement_weight, |
| 4139 | }, |
| 4140 | fail_publish_once, |
| 4141 | fence_tx, |
| 4142 | ActorServices { |
| 4143 | runtime: runtime.clone(), |
| 4144 | drain_pins: drain_pins.clone(), |
| 4145 | ownership, |
| 4146 | peer_http: peer_http.clone(), |
| 4147 | peer_auth: peer_auth.clone(), |
| 4148 | }, |
| 4149 | ActorIdentity { |
| 4150 | node: node.clone(), |
| 4151 | advertise: advertise.clone(), |
| 4152 | region: settings.region.clone(), |
| 4153 | }, |
| 4154 | resume_generation, |
| 4155 | ) |
| 4156 | .await?; |
| 4157 | let process_generation = actor.lease_spec.generation.clone(); |
| 4158 | let ownership_name = actor.ownership.name(); |
| 4159 | // Keep the fleet reader beside the readiness task before the actor moves |
| 4160 | // to its isolated thread. Both handles share the same lease adapter, so |
| 4161 | // readiness evaluates exactly the records that placement publishes. |
| 4162 | let ready_ownership = match &actor.ownership { |
| 4163 | Ownership::Bucket(ownership) => Some(ownership.clone()), |
| 4164 | Ownership::Memory(_) => None, |
| 4165 | }; |
| 4166 | let fleet_bucket = ready_ownership |
| 4167 | .as_ref() |
| 4168 | .map(|ownership| ownership.bucket_client()); |
| 4169 | let explorer_replication = runtime.as_ref().and_then(RuntimeManager::replication); |
| 4170 | let local_cache_replication = explorer_replication.clone(); |
| 4171 | let (websocket_tx, mut websocket_rx) = mpsc::unbounded_channel(); |
| 4172 | // The log tier's follower store (crate::node_log): fragments other |
| 4173 | // leaders replicate here live under the node's data dir beside the cell |
| 4174 | // databases. |
| 4175 | let follower = match &actor.ownership { |
| 4176 | Ownership::Bucket(bucket_ownership) if settings.bucket.is_some() => { |
| 4177 | Some(Arc::new(celld::node_log::FollowerStore::new( |
| 4178 | &data_dir, |
| 4179 | Some(Arc::new(bucket_ownership.bucket_client())), |
| 4180 | &node, |
| 4181 | ))) |
| 4182 | } |
| 4183 | _ => None, |
| 4184 | }; |
| 4185 | #[cfg(all(test, celld_internal_tests))] |
| 4186 | let follower = follower.or_else(|| { |
| 4187 | shutdown_accept_failure_test_active |
| 4188 | .then(|| Arc::new(celld::node_log::FollowerStore::new(&data_dir, None, &node))) |
| 4189 | }); |
| 4190 | let app = AppHandle { |
| 4191 | tx, |
| 4192 | runtime, |
| 4193 | reload: reload_tx.clone(), |
| 4194 | peer_http, |
| 4195 | peer_auth, |
| 4196 | advertise: advertise.clone(), |
| 4197 | websockets: websocket_tx, |
| 4198 | draining: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 4199 | fleet_ready: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 4200 | public_in_flight: Arc::new(AtomicUsize::new(0)), |
| 4201 | drain_pins, |
| 4202 | trust_forwarded_headers: settings.trust_forwarded_headers, |
| 4203 | max_outbound_websockets: celld::env_vars::positive_or( |
| 4204 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 4205 | DEFAULT_MAX_OUTBOUND_WEBSOCKETS, |
| 4206 | )?, |
| 4207 | max_request_body_bytes, |
| 4208 | operation_deadline_ms: celld::actor::operation_deadline_ms()?, |
| 4209 | follower: follower.clone(), |
| 4210 | }; |
| 4211 | |
| 4212 | // The in-fleet log tier, v0. The takeover interlock is installed in |
| 4213 | // every posture — a bucket-posture node can take over from a |
| 4214 | // fleet-posture one and must find a complete bucket — while shipping |
| 4215 | // requires the explicit fleet posture. |
| 4216 | // Fleet is the default: without a healthy follower, writes need bucket |
| 4217 | // proof. Maintenance recruits up to two followers; one healthy follower |
| 4218 | // is sufficient for fleet proof. CELLD_DURABILITY=bucket always requires |
| 4219 | // bucket proof, including when peers are available. |
| 4220 | let durability = std::env::var("CELLD_DURABILITY").unwrap_or_else(|_| "fleet".into()); |
| 4221 | anyhow::ensure!( |
| 4222 | matches!(durability.as_str(), "bucket" | "fleet"), |
| 4223 | "CELLD_DURABILITY must be `bucket` or `fleet`" |
| 4224 | ); |
| 4225 | let mut durability_owner = DurabilityOwnerSelection::new(follower.clone()); |
| 4226 | if let Ownership::Bucket(bucket_ownership) = &actor.ownership { |
| 4227 | if let (Some(replication), Some(spec)) = ( |
| 4228 | app.runtime.as_ref().and_then(RuntimeManager::replication), |
| 4229 | settings.bucket.clone(), |
| 4230 | ) { |
| 4231 | let _ = spec; |
| 4232 | let log_bucket = Arc::new(bucket_ownership.bucket_client()); |
| 4233 | let ltx = replication.ltx(); |
| 4234 | // Bundle the paced tiering: one PUT per node-flush instead of |
| 4235 | // one per cell-transaction — the Class A collapse, measured at |
| 4236 | // 208x against per-transaction PUTs. The shipper and the bundle |
| 4237 | // sink are installed as one durability registration. |
| 4238 | let nudge_tx = app.tx.clone(); |
| 4239 | let own_log = Arc::new(celld::node_log::OwnLog { |
| 4240 | ownership: bucket_ownership.clone(), |
| 4241 | nudge: Box::new(move || { |
| 4242 | let _ = nudge_tx.send(Message::NudgeNodeLease); |
| 4243 | }), |
| 4244 | write_lock: tokio::sync::Mutex::new(()), |
| 4245 | }); |
| 4246 | let manager = Arc::new(celld::node_log::NodeLogManager::new( |
| 4247 | &format!("{node}/{process_generation}"), |
| 4248 | log_bucket, |
| 4249 | own_log, |
| 4250 | ltx.clone(), |
| 4251 | app.peer_auth.clone(), |
| 4252 | celld::node_log::eviction_policy_from_env()?, |
| 4253 | )); |
| 4254 | *actor.node_log.lock().unwrap() = Some(manager.clone()); |
| 4255 | // Recovery-before-install is fatal for every posture: the |
| 4256 | // predecessor's folded state lives in the lease record this |
| 4257 | // session is about to replace, and the install writes a fresh |
| 4258 | // log — so an unrecovered predecessor must stop the boot, or |
| 4259 | // the install erases the only evidence recovery was needed. |
| 4260 | // The ladder waits out the predecessor's own lease because the |
| 4261 | // fence recheck refuses a live lease, retries with backoff, |
| 4262 | // and exits on exhaustion. Serve the retained follower disks |
| 4263 | // throughout the ladder, including retry backoffs, so a fleet |
| 4264 | // restart can recover without waiting for another node's lease. |
| 4265 | recover_with_follower_listener(&internal_listener, app.clone(), async { |
| 4266 | let ttl_backoff = |
| 4267 | std::time::Duration::from_millis(actor.lease_spec.ttl_ms.max(1_000)); |
| 4268 | let mut recovered = Ok(()); |
| 4269 | // A boot waits behind a peer's live recovery claim and takes |
| 4270 | // it over only once its heartbeat is stale, so one attempt |
| 4271 | // can legitimately last as long as the peer's gather. The |
| 4272 | // bound is a backstop against a wedge, not a pace. |
| 4273 | for attempt in 1..=4u32 { |
| 4274 | recovered = match tokio::time::timeout( |
| 4275 | std::time::Duration::from_secs(15 * 60), |
| 4276 | manager.recover_self(), |
| 4277 | ) |
| 4278 | .await |
| 4279 | { |
| 4280 | Ok(result) => result, |
| 4281 | Err(_) => Err(anyhow::anyhow!("predecessor recovery timed out")), |
| 4282 | }; |
| 4283 | if recovered.is_ok() || attempt == 4 { |
| 4284 | break; |
| 4285 | } |
| 4286 | if let Err(error) = recovered.as_ref() { |
| 4287 | eprintln!("celld predecessor recovery attempt {attempt} failed: {error:#}"); |
| 4288 | } |
| 4289 | // At least one full TTL between attempts, so a |
| 4290 | // refused-because-live predecessor lease has expired |
| 4291 | // by the retry. |
| 4292 | tokio::time::sleep(ttl_backoff.saturating_mul(attempt)).await; |
| 4293 | } |
| 4294 | recovered.map_err(|error| { |
| 4295 | anyhow::anyhow!( |
| 4296 | "refusing to install a lease over an unrecovered \ |
| 4297 | predecessor log: {error:#}" |
| 4298 | ) |
| 4299 | }) |
| 4300 | }) |
| 4301 | .await?; |
| 4302 | let mut owner = celld::node_log::DurabilityOwner::new(manager, durability == "fleet"); |
| 4303 | owner.start_background(follower.clone()); |
| 4304 | durability_owner.install_runtime(owner); |
| 4305 | } |
| 4306 | } |
| 4307 | let mut durability_owner = durability_owner.select(); |
| 4308 | let (do_call_tx, mut do_call_rx) = mpsc::unbounded_channel(); |
| 4309 | celld::js::set_do_call_tx(do_call_tx); |
| 4310 | let (gate_tx, mut gate_rx) = mpsc::unbounded_channel(); |
| 4311 | celld::js::set_gate_tx(gate_tx); |
| 4312 | let (rpc_call_tx, mut rpc_call_rx) = mpsc::unbounded_channel(); |
| 4313 | celld::js::set_rpc_call_tx(rpc_call_tx); |
| 4314 | let (service_call_tx, mut service_call_rx) = mpsc::unbounded_channel(); |
| 4315 | celld::js::set_svc_call_tx(service_call_tx); |
| 4316 | let (service_rpc_tx, mut service_rpc_rx) = mpsc::unbounded_channel(); |
| 4317 | celld::js::set_svc_rpc_tx(service_rpc_tx); |
| 4318 | let (queue_dispatch_tx, mut queue_dispatch_rx) = mpsc::unbounded_channel(); |
| 4319 | celld::js::set_queue_dispatch_tx(queue_dispatch_tx); |
| 4320 | let (asset_call_tx, mut asset_call_rx) = mpsc::unbounded_channel(); |
| 4321 | celld::js::set_asset_call_tx(asset_call_tx); |
| 4322 | let (outbound_ws_tx, mut outbound_ws_rx) = mpsc::unbounded_channel(); |
| 4323 | celld::js::set_outbound_ws_tx(outbound_ws_tx); |
| 4324 | // KV large values live in the fleet bucket. The cloneable handle follows |
| 4325 | // the R2 binding's startup pattern, so independent cells issue bucket I/O |
| 4326 | // independently instead of queueing behind one task. Blob I/O takes no |
| 4327 | // part in the drain ordering: a blob is written before its row, so an |
| 4328 | // interrupted write leaves collectable bytes and never a dangling row. |
| 4329 | if let Ownership::Bucket(bucket_ownership) = &actor.ownership { |
| 4330 | celld::js::set_kv_blob_store(bucket_ownership.bucket_client()); |
| 4331 | } |
| 4332 | // The core is a serial ownership actor, not a Worker executor. It owns the |
| 4333 | // node lease timer, so ingress, proxy retries, and restore completions must |
| 4334 | // not consume every scheduler turn it needs. Its isolated single-thread |
| 4335 | // runtime also keeps state transitions ordered exactly as the deterministic |
| 4336 | // executor models them. Request work, restores, and blocking scans stay on |
| 4337 | // the shared runtime and report their results back as messages. |
| 4338 | let (actor_exit_tx, mut actor_exit_rx) = mpsc::unbounded_channel(); |
| 4339 | std::thread::Builder::new() |
| 4340 | .name("celld-core".into()) |
| 4341 | .spawn(move || { |
| 4342 | let result = tokio::runtime::Builder::new_current_thread() |
| 4343 | .enable_all() |
| 4344 | .build() |
| 4345 | .map_err(|error| error.to_string()) |
| 4346 | .map(|runtime| runtime.block_on(actor.run(rx))); |
| 4347 | let _ = actor_exit_tx.send(result); |
| 4348 | })?; |
| 4349 | |
| 4350 | // The sampler is a plain ticker: it measures and posts, and decides |
| 4351 | // nothing. Everything downstream of the numbers -- the latch, the target, |
| 4352 | // which cell goes -- is in the core, so a sample sequence replays. |
| 4353 | { |
| 4354 | celld::asyncrt::spawn(async move { |
| 4355 | let mut tick = celld::asyncrt::interval(LOAD_SAMPLE_PERIOD); |
| 4356 | tick.set_missed_tick_behavior(celld::asyncrt::MissedTickBehavior::Delay); |
| 4357 | loop { |
| 4358 | tick.tick().await; |
| 4359 | if sample_tx.send(Message::SampleLoad).is_err() { |
| 4360 | return; |
| 4361 | } |
| 4362 | } |
| 4363 | }) |
| 4364 | .detach(); |
| 4365 | } |
| 4366 | |
| 4367 | // The fleet-aware first-readiness gate: withhold the first health 200 |
| 4368 | // until no donor is mid-handoff and every live peer publishes successor |
| 4369 | // capacity. CELLD_READY_FLEET_GATE_MS bounds the silent wait before celld |
| 4370 | // reports the blocking condition, but it cannot make an unsafe fleet |
| 4371 | // ready. Orchestrators key rollout advance on readiness, so a fail-open |
| 4372 | // deadline would erase the only signal that prevents another donor. The |
| 4373 | // gate is one-shot: once open, fleet state never demotes readiness, and a |
| 4374 | // gated node still serves its owned cells through peers. |
| 4375 | let ready_gate_ms: u64 = celld::env_vars::with_default("CELLD_READY_FLEET_GATE_MS", 120_000)?; |
| 4376 | match (&ready_ownership, ready_gate_ms) { |
| 4377 | (Some(ownership), gate_ms) if gate_ms > 0 => { |
| 4378 | let ownership = ownership.clone(); |
| 4379 | let bucket = ownership.bucket_client(); |
| 4380 | let gate_node = node.clone(); |
| 4381 | let gate_flag = app.fleet_ready.clone(); |
| 4382 | let max_restoring = max_activations as u64; |
| 4383 | tokio::spawn(async move { |
| 4384 | let started = std::time::Instant::now(); |
| 4385 | let mut deadline_reported = false; |
| 4386 | let mut tick = tokio::time::interval(std::time::Duration::from_secs(1)); |
| 4387 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 4388 | loop { |
| 4389 | tick.tick().await; |
| 4390 | let (current, peers) = tokio::join!( |
| 4391 | celld::drain_token::read(&bucket), |
| 4392 | ownership.read_capacity_peers() |
| 4393 | ); |
| 4394 | // Judge lease and token expiry after the I/O. A slow list |
| 4395 | // must not make a record live at the time before the read. |
| 4396 | let now_ms = celld::ownership_store::now_ms(); |
| 4397 | let status = match (¤t, &peers) { |
| 4398 | (Ok(current), Ok(peers)) => celld_logic::drain::fleet_status( |
| 4399 | current.as_ref().and_then(|current| current.token.as_ref()), |
| 4400 | &gate_node, |
| 4401 | now_ms, |
| 4402 | peers, |
| 4403 | max_restoring, |
| 4404 | ), |
| 4405 | // An unreadable store is not settled; the deadline |
| 4406 | // bounds the wait. |
| 4407 | _ => Err(celld_logic::drain::FleetUnsettled::Unreadable), |
| 4408 | }; |
| 4409 | let waited_ms = started.elapsed().as_millis() as u64; |
| 4410 | if status.is_ok() { |
| 4411 | let readiness_reason = if peers.as_ref().ok().is_some_and(|peers| { |
| 4412 | celld_logic::drain::joining_contributes_successor_capacity( |
| 4413 | peers, &gate_node, now_ms, |
| 4414 | ) |
| 4415 | }) { |
| 4416 | "successor_capacity" |
| 4417 | } else { |
| 4418 | "fleet_settled" |
| 4419 | }; |
| 4420 | gate_flag.store(true, std::sync::atomic::Ordering::SeqCst); |
| 4421 | tracing::info!( |
| 4422 | event = "ready_gate_open", |
| 4423 | readiness_reason, |
| 4424 | waited_ms, |
| 4425 | "the fleet is settled; serving readiness is open" |
| 4426 | ); |
| 4427 | return; |
| 4428 | } |
| 4429 | if waited_ms >= gate_ms && !deadline_reported { |
| 4430 | deadline_reported = true; |
| 4431 | let holder = current |
| 4432 | .as_ref() |
| 4433 | .ok() |
| 4434 | .and_then(|current| current.as_ref()) |
| 4435 | .and_then(|current| current.token.as_ref()) |
| 4436 | .map(|token| token.node.as_str()) |
| 4437 | .unwrap_or_default(); |
| 4438 | tracing::warn!( |
| 4439 | event = "ready_gate_expired", |
| 4440 | holder, |
| 4441 | reason = ?status.err(), |
| 4442 | waited_ms, |
| 4443 | "the ready-gate observation deadline expired; readiness stays closed" |
| 4444 | ); |
| 4445 | } |
| 4446 | } |
| 4447 | }); |
| 4448 | } |
| 4449 | _ => app |
| 4450 | .fleet_ready |
| 4451 | .store(true, std::sync::atomic::Ordering::SeqCst), |
| 4452 | } |
| 4453 | |
| 4454 | // Ownership balancing. Each node reads the shared fleet sample and, when it |
| 4455 | // is the densest node and a peer has room, hands a bounded batch of idle |
| 4456 | // cells through the drain's release-and-adopt pipeline. Cell moves need |
| 4457 | // no fleet-wide lock: the per-cell ownership CAS is the authority, and the |
| 4458 | // densest-node rule elects one donor per consistent sample. A donor |
| 4459 | // plans again only from leases sampled after its last batch had one |
| 4460 | // load-sample period to reach them, so no plan mixes counts from before |
| 4461 | // a batch with counts from after it. |
| 4462 | // |
| 4463 | // The same lease sample carries the bucket-format gate |
| 4464 | // (celld_logic::format): a node pages a large takeover only while every |
| 4465 | // live lease reads a paged epoch. The loop therefore runs even with |
| 4466 | // balancing off, at the balancing interval or FORMAT_GATE_SAMPLE_MS, and |
| 4467 | // the gate is judged before any balancing condition can skip the tick. |
| 4468 | // Off until the first sample, so a takeover in the first seconds of a |
| 4469 | // process clones, which is always safe. |
| 4470 | if let Some(ownership) = ready_ownership.clone() { |
| 4471 | let app = app.clone(); |
| 4472 | let node = node.clone(); |
| 4473 | let replication = explorer_replication.clone(); |
| 4474 | let sample_ms = fleet_sample_ms; |
| 4475 | tokio::spawn(async move { |
| 4476 | let mut tick = tokio::time::interval(std::time::Duration::from_millis(sample_ms)); |
| 4477 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 4478 | let mut settled_after_ms = 0; |
| 4479 | loop { |
| 4480 | tick.tick().await; |
| 4481 | let now_ms = celld::ownership_store::now_ms(); |
| 4482 | // The view is judged at the instant the sample was taken. |
| 4483 | // Its leases are copies that age while the real nodes renew, |
| 4484 | // and nodes started together renew in lock-step, so judged |
| 4485 | // at this node's clock a view a few seconds old shows every |
| 4486 | // lease dead at once: on the 2026-09-05 fleet that closed the |
| 4487 | // gate and skipped balancing on a third of the ticks. |
| 4488 | let (view_ms, peers) = match ownership.read_shared_capacity_peers(sample_ms).await { |
| 4489 | Ok(view) => view, |
| 4490 | Err(error) => { |
| 4491 | // At info with the chain: a failed tick closes the |
| 4492 | // format gate, and a fleet run has to say why. |
| 4493 | tracing::info!(event = "fleet_sample_failed", error = format!("{error:#}")); |
| 4494 | // A missing or in-flight refresh cannot keep granting |
| 4495 | // format permission from an earlier fleet membership. |
| 4496 | (now_ms, Vec::new()) |
| 4497 | } |
| 4498 | }; |
| 4499 | if let Some(replication) = &replication { |
| 4500 | let format = celld_logic::format::BUCKET_FORMAT; |
| 4501 | let open = celld_logic::format::fleet_reads(&peers, view_ms, format); |
| 4502 | if replication.set_paged_fleet(open) != open { |
| 4503 | tracing::info!( |
| 4504 | event = "paged_gate", |
| 4505 | open, |
| 4506 | format, |
| 4507 | live_leases = peers.iter().filter(|p| p.expires_ms > view_ms).count(), |
| 4508 | view_age_ms = now_ms.saturating_sub(view_ms), |
| 4509 | "every live lease reads a paged epoch, or one does not" |
| 4510 | ); |
| 4511 | } |
| 4512 | } |
| 4513 | if rebalance_interval_ms == 0 { |
| 4514 | continue; |
| 4515 | } |
| 4516 | let paused = ownership |
| 4517 | .live() |
| 4518 | .rebalance_paused |
| 4519 | .load(std::sync::atomic::Ordering::Relaxed); |
| 4520 | if !app.fleet_ready() || app.is_draining() || paused { |
| 4521 | continue; |
| 4522 | } |
| 4523 | // One batch outstanding at a time, but one cell must not |
| 4524 | // hold the fleet: a cell whose proof cannot finish stays in |
| 4525 | // flight for a long time, and the densest node is the only |
| 4526 | // donor. Plan around it with the rest of the batch. |
| 4527 | let status = app.drain_status().await; |
| 4528 | let in_flight = |
| 4529 | status.quiescing + status.evicting + status.releasing + status.adopting; |
| 4530 | if in_flight >= DEFAULT_REBALANCE_BATCH_CELLS { |
| 4531 | continue; |
| 4532 | } |
| 4533 | let Some(cells) = celld_logic::rebalance::surplus( |
| 4534 | &peers, |
| 4535 | &node, |
| 4536 | view_ms, |
| 4537 | ownership.lease_ttl_ms(), |
| 4538 | settled_after_ms, |
| 4539 | DEFAULT_REBALANCE_BATCH_CELLS - in_flight, |
| 4540 | ) else { |
| 4541 | continue; |
| 4542 | }; |
| 4543 | tracing::info!( |
| 4544 | event = "rebalance_batch", |
| 4545 | cells, |
| 4546 | "handing idle cells to peers below their ownership target" |
| 4547 | ); |
| 4548 | if app.tx.send(Message::Rebalance { cells }).is_err() { |
| 4549 | return; |
| 4550 | } |
| 4551 | settled_after_ms = now_ms + LOAD_SAMPLE_PERIOD.as_millis() as u64; |
| 4552 | } |
| 4553 | }); |
| 4554 | } |
| 4555 | |
| 4556 | if let Some((client, ownership)) = wake_scan { |
| 4557 | let authority_wait_seconds = if clean_reload_candidate { 60 } else { 10 }; |
| 4558 | let deadline = Instant::now() + std::time::Duration::from_secs(authority_wait_seconds); |
| 4559 | while !app.healthy().await { |
| 4560 | if Instant::now() >= deadline { |
| 4561 | anyhow::bail!("node authority was not established before wake scan"); |
| 4562 | } |
| 4563 | tokio::time::sleep(std::time::Duration::from_millis(10)).await; |
| 4564 | } |
| 4565 | // The boot scan acts for the fleet: it is what finds the alarms this |
| 4566 | // node's previous incarnation left behind, and any orphan that came |
| 4567 | // due while nothing was watching. It probes like the elected waker |
| 4568 | // does, so a rolling restart does not send every node the whole |
| 4569 | // fleet's due set once each. |
| 4570 | let boot_ms = now_ms(); |
| 4571 | let live = celld::dead_node_gc::live_nodes(&client, boot_ms).await; |
| 4572 | let due = celld::wake::due_scan(&client, boot_ms as i64).await; |
| 4573 | for (cell, entry_ms) in celld::wake::elected_due(&ownership, &node, &live, due).await { |
| 4574 | let _ = app.tx.send(Message::WakeHint { |
| 4575 | cell, |
| 4576 | entry_ms, |
| 4577 | scope: celld_logic::WakeHintScope::Fleet, |
| 4578 | }); |
| 4579 | } |
| 4580 | |
| 4581 | // And again, on a timer, for the rest of the process's life. |
| 4582 | // |
| 4583 | // The boot scan alone only covers alarms that came due while nothing |
| 4584 | // was watching *before this node started*. A node that dies while |
| 4585 | // this one is already running leaves its cells with armed alarms and |
| 4586 | // no owner, and nothing would look at them again until this process |
| 4587 | // restarted -- an alarm silently not firing, which is the one thing a |
| 4588 | // Durable Object is not allowed to do. |
| 4589 | // |
| 4590 | // Every node lists the due entries on its tick, because a node's own |
| 4591 | // dormant cells can carry alarms it has never loaded (a cell that |
| 4592 | // arrived by an ownership-only handoff), and only that node can wake |
| 4593 | // them. But only the node that holds the advisory waker role acts for |
| 4594 | // the fleet: it reads each due cell's owner outside the activation |
| 4595 | // queue and hints the orphans, while every other node hints with |
| 4596 | // `Owned` scope, which the core answers from memory. Before that |
| 4597 | // split, every node pushed the whole fleet's due set through its own |
| 4598 | // activation queue, one permit and one owner read per entry, and its |
| 4599 | // own alarm wakes queued behind them. |
| 4600 | // |
| 4601 | // Every decision about a hinted entry still stays in the core: a |
| 4602 | // hint for a cell this node already serves is ignored, and one for a |
| 4603 | // cell with a live owner elsewhere resolves to that owner rather |
| 4604 | // than stealing it. |
| 4605 | let tick_ms = celld::env_vars::positive::<u64>("CELLD_WAKER_TICK_MS")?.unwrap_or(60_000); |
| 4606 | celld::asyncrt::spawn(celld::wake::run_periodic( |
| 4607 | client, |
| 4608 | ownership, |
| 4609 | node.clone(), |
| 4610 | app.tx.clone(), |
| 4611 | tick_ms, |
| 4612 | )) |
| 4613 | .detach(); |
| 4614 | } |
| 4615 | |
| 4616 | // Arm the schedule, then watch the pointer. Adoption arms it again, so |
| 4617 | // a cron change travels with the deployment that carries it. |
| 4618 | spawn_cron_arm(app.clone()); |
| 4619 | if let Some(bucket) = deploy_bucket { |
| 4620 | start_pointer_watcher( |
| 4621 | app.clone(), |
| 4622 | bucket, |
| 4623 | node.clone(), |
| 4624 | settings.region.clone(), |
| 4625 | reload_rx, |
| 4626 | ); |
| 4627 | } |
| 4628 | if let Some(client) = deploy_agent { |
| 4629 | celld::control_plane::start_deploy_agent(client.clone(), reload_tx.clone()); |
| 4630 | let presence_app = app.clone(); |
| 4631 | celld::control_plane::start_presence_agent(celld::control_plane::PresenceRuntime { |
| 4632 | s3: client, |
| 4633 | replication: explorer_replication, |
| 4634 | node_session_id: node, |
| 4635 | advertise, |
| 4636 | listen, |
| 4637 | credential_version: adapter_credential_version |
| 4638 | .expect("managed adapters have a credential version"), |
| 4639 | snapshot: Arc::new(move || { |
| 4640 | let app = presence_app.clone(); |
| 4641 | Box::pin(async move { app.presence().await }) |
| 4642 | }), |
| 4643 | reload: reload_tx.clone(), |
| 4644 | }); |
| 4645 | } |
| 4646 | |
| 4647 | celld::cli_output::Output::new(celld::cli_output::Format::Text).line(format_args!( |
| 4648 | "celld listening on {} (ownership={ownership_name})", |
| 4649 | listener.local_addr()? |
| 4650 | ))?; |
| 4651 | celld::cli_output::Output::new(celld::cli_output::Format::Text).line(format_args!( |
| 4652 | "celld internal listening on {} (advertise={})", |
| 4653 | internal_listener.local_addr()?, |
| 4654 | app.advertise |
| 4655 | ))?; |
| 4656 | let (shutdown_tx, mut shutdown_rx) = mpsc::unbounded_channel(); |
| 4657 | #[cfg(all(test, celld_internal_tests))] |
| 4658 | if shutdown_accept_failure_test_active { |
| 4659 | let _ = shutdown_tx.send(ShutdownMode::Handoff); |
| 4660 | } |
| 4661 | // A SIGTERM (systemd stop, `docker stop`, a Kubernetes pod delete) or a |
| 4662 | // SIGINT begins the same graceful shutdown as `POST /shutdown`, so the |
| 4663 | // orchestrator's ordinary stop drains and hands off instead of killing. |
| 4664 | let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; |
| 4665 | let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?; |
| 4666 | let (connection_drain_tx, connection_drain) = watch::channel(false); |
| 4667 | let shutdown_timing = celld::env_vars::shutdown_timing()?; |
| 4668 | let drain_ms = shutdown_timing.drain_no_progress_ms; |
| 4669 | let shutdown_total_ms = shutdown_timing.total_ms; |
| 4670 | let drain_token_wait_ms = shutdown_timing.drain_token_wait_ms; |
| 4671 | // A hung connection must not consume the whole preserve budget: the |
| 4672 | // semantic drain and the clean-reload certificate come out of the same |
| 4673 | // deadline. |
| 4674 | let connection_grace = |
| 4675 | CONNECTION_DRAIN_GRACE.min(std::time::Duration::from_millis(drain_ms / 4)); |
| 4676 | let mut connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new(); |
| 4677 | let mut do_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new(); |
| 4678 | let mut gate_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new(); |
| 4679 | let mut service_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new(); |
| 4680 | let mut queue_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new(); |
| 4681 | let mut asset_calls: FuturesUnordered<AssetCallFuture> = FuturesUnordered::new(); |
| 4682 | let mut websockets: FuturesUnordered<WebSocketFuture> = FuturesUnordered::new(); |
| 4683 | let mut cache_prunes: FuturesUnordered<CachePruneFuture> = FuturesUnordered::new(); |
| 4684 | let mut replication_health = tokio::time::interval(std::time::Duration::from_millis(250)); |
| 4685 | let mut local_cache_prune = tokio::time::interval_at( |
| 4686 | tokio::time::Instant::now() + LOCAL_CACHE_PRUNE_PERIOD, |
| 4687 | LOCAL_CACHE_PRUNE_PERIOD, |
| 4688 | ); |
| 4689 | local_cache_prune.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 4690 | let shutdown_mode = loop { |
| 4691 | celld::asyncrt::select! { |
| 4692 | connection = listener.accept() => { |
| 4693 | let (stream, _) = connection?; |
| 4694 | connections.push(serve_http_connection( |
| 4695 | stream, |
| 4696 | HttpSurface::Public, |
| 4697 | app.clone(), |
| 4698 | shutdown_tx.clone(), |
| 4699 | connection_drain.clone(), |
| 4700 | connection_grace, |
| 4701 | )); |
| 4702 | } |
| 4703 | connection = internal_listener.accept() => { |
| 4704 | let (stream, _) = connection?; |
| 4705 | connections.push(serve_http_connection( |
| 4706 | stream, |
| 4707 | HttpSurface::Internal, |
| 4708 | app.clone(), |
| 4709 | shutdown_tx.clone(), |
| 4710 | connection_drain.clone(), |
| 4711 | connection_grace, |
| 4712 | )); |
| 4713 | } |
| 4714 | Some(()) = connections.next(), if !connections.is_empty() => {} |
| 4715 | call = do_call_rx.recv() => { |
| 4716 | let Some(call) = call else { |
| 4717 | anyhow::bail!("Durable Object call channel closed"); |
| 4718 | }; |
| 4719 | do_calls.push(Box::pin(dispatch_do_call(app.clone(), call))); |
| 4720 | } |
| 4721 | Some(()) = do_calls.next(), if !do_calls.is_empty() => {} |
| 4722 | req = gate_rx.recv() => { |
| 4723 | let Some(req) = req else { |
| 4724 | anyhow::bail!("output-gate channel closed"); |
| 4725 | }; |
| 4726 | gate_calls.push(Box::pin(dispatch_gate(app.clone(), req))); |
| 4727 | } |
| 4728 | Some(()) = gate_calls.next(), if !gate_calls.is_empty() => {} |
| 4729 | call = service_call_rx.recv() => { |
| 4730 | let Some(call) = call else { |
| 4731 | anyhow::bail!("service call channel closed"); |
| 4732 | }; |
| 4733 | service_calls.push(Box::pin(dispatch_service_call(app.clone(), call))); |
| 4734 | } |
| 4735 | call = service_rpc_rx.recv() => { |
| 4736 | let Some(call) = call else { |
| 4737 | anyhow::bail!("service RPC channel closed"); |
| 4738 | }; |
| 4739 | service_calls.push(Box::pin(dispatch_service_rpc(app.clone(), call))); |
| 4740 | } |
| 4741 | Some(()) = service_calls.next(), if !service_calls.is_empty() => {} |
| 4742 | call = queue_dispatch_rx.recv() => { |
| 4743 | let Some(call) = call else { |
| 4744 | anyhow::bail!("Queue dispatch channel closed"); |
| 4745 | }; |
| 4746 | queue_calls.push(Box::pin(dispatch_queue_batch(app.clone(), call))); |
| 4747 | } |
| 4748 | Some(()) = queue_calls.next(), if !queue_calls.is_empty() => {} |
| 4749 | call = rpc_call_rx.recv() => { |
| 4750 | let Some(call) = call else { |
| 4751 | anyhow::bail!("Durable Object RPC channel closed"); |
| 4752 | }; |
| 4753 | do_calls.push(Box::pin(dispatch_rpc_call(app.clone(), call))); |
| 4754 | } |
| 4755 | call = asset_call_rx.recv() => { |
| 4756 | let Some(call) = call else { |
| 4757 | anyhow::bail!("asset call channel closed"); |
| 4758 | }; |
| 4759 | asset_calls.push(Box::pin(dispatch_asset_call(app.clone(), call))); |
| 4760 | } |
| 4761 | Some(()) = asset_calls.next(), if !asset_calls.is_empty() => {} |
| 4762 | socket = websocket_rx.recv() => { |
| 4763 | let Some(socket) = socket else { |
| 4764 | anyhow::bail!("WebSocket channel closed"); |
| 4765 | }; |
| 4766 | websockets.push(socket); |
| 4767 | } |
| 4768 | Some(()) = websockets.next(), if !websockets.is_empty() => {} |
| 4769 | _ = local_cache_prune.tick(), if local_cache_replication.is_some() |
| 4770 | && local_cache_max_bytes.is_some() && cache_prunes.is_empty() => { |
| 4771 | let replication = local_cache_replication.clone().unwrap(); |
| 4772 | let max_bytes = local_cache_max_bytes.unwrap(); |
| 4773 | cache_prunes.push(Box::pin(async move { |
| 4774 | let result = celld::asyncrt::blocking(move || { |
| 4775 | replication.prune_local_cache(max_bytes) |
| 4776 | }).await; |
| 4777 | (max_bytes, result) |
| 4778 | })); |
| 4779 | } |
| 4780 | Some((max_bytes, result)) = cache_prunes.next(), if !cache_prunes.is_empty() => { |
| 4781 | match result { |
| 4782 | Ok(Ok((kept, evicted, bytes))) if evicted > 0 => { |
| 4783 | tracing::info!( |
| 4784 | event = "local_cache_pruned", |
| 4785 | kept, |
| 4786 | evicted, |
| 4787 | bytes, |
| 4788 | max_bytes, |
| 4789 | "pruned least-recently-used eviction snapshots" |
| 4790 | ); |
| 4791 | } |
| 4792 | Ok(Ok(_)) => {} |
| 4793 | Ok(Err(error)) => { |
| 4794 | tracing::warn!(%error, "local cache inventory failed"); |
| 4795 | } |
| 4796 | Err(error) => { |
| 4797 | tracing::warn!(%error, "local cache pruning task failed"); |
| 4798 | } |
| 4799 | } |
| 4800 | } |
| 4801 | outbound = outbound_ws_rx.recv() => { |
| 4802 | let Some(outbound) = outbound else { |
| 4803 | anyhow::bail!("outbound WebSocket channel closed"); |
| 4804 | }; |
| 4805 | let app = app.clone(); |
| 4806 | websockets.push(Box::pin(async move { |
| 4807 | if let Err(error) = outbound_websocket_task(app, outbound).await { |
| 4808 | eprintln!("celld outbound WebSocket failed: {error:#}"); |
| 4809 | } |
| 4810 | })); |
| 4811 | } |
| 4812 | mode = shutdown_rx.recv() => break mode.unwrap_or(ShutdownMode::Handoff), |
| 4813 | _ = sigterm.recv() => break ShutdownMode::Handoff, |
| 4814 | _ = sigint.recv() => break ShutdownMode::Handoff, |
| 4815 | code = fence_rx.recv() => { |
| 4816 | exit_flushed(code.unwrap_or(3)); |
| 4817 | } |
| 4818 | actor_exit = actor_exit_rx.recv() => { |
| 4819 | let error = match actor_exit { |
| 4820 | Some(Err(error)) => error, |
| 4821 | Some(Ok(())) => "the core actor stopped unexpectedly".to_string(), |
| 4822 | None => "the core actor thread panicked".to_string(), |
| 4823 | }; |
| 4824 | tracing::error!( |
| 4825 | event = "core_actor_exit", |
| 4826 | %error, |
| 4827 | "SELF-FENCE: the core actor exited unexpectedly" |
| 4828 | ); |
| 4829 | exit_flushed(3); |
| 4830 | } |
| 4831 | _ = replication_health.tick() => { |
| 4832 | if let Some(runtime) = &app.runtime { |
| 4833 | match runtime.replication_status() { |
| 4834 | Ok(None) => {} |
| 4835 | Ok(Some(status)) => { |
| 4836 | eprintln!("SELF-FENCE: replication process exited unexpectedly: {status}"); |
| 4837 | exit_flushed(3); |
| 4838 | } |
| 4839 | Err(error) => { |
| 4840 | eprintln!("SELF-FENCE: replication process health check failed: {error}"); |
| 4841 | exit_flushed(3); |
| 4842 | } |
| 4843 | } |
| 4844 | } |
| 4845 | } |
| 4846 | } |
| 4847 | }; |
| 4848 | // This deadline starts at the stop signal and covers token acquisition, |
| 4849 | // request drain, ownership handoff, transport flush, and local durability |
| 4850 | // shutdown. Progress can extend only the inner stall deadline. The |
| 4851 | // absolute bound leaves the orchestrator time to observe an orderly exit |
| 4852 | // instead of replacing a progressing donor with SIGKILL. |
| 4853 | let shutdown_started = tokio::time::Instant::now(); |
| 4854 | let process_deadline = shutdown_started + std::time::Duration::from_millis(shutdown_total_ms); |
| 4855 | // A donor normally spends its complete budget making safe handoff |
| 4856 | // progress. Reserve at most one second, and never more than ten percent of |
| 4857 | // a short configured budget, for the token CAS. Otherwise a deadline-cut |
| 4858 | // donor leaves the replacement behind the 120-second token TTL and turns |
| 4859 | // serialization into artificial rollout recovery. |
| 4860 | let token_release_reserve_ms = if shutdown_mode == ShutdownMode::Handoff |
| 4861 | && fleet_bucket.is_some() |
| 4862 | && drain_token_wait_ms > 0 |
| 4863 | { |
| 4864 | (shutdown_total_ms / 10).min(1_000) |
| 4865 | } else { |
| 4866 | 0 |
| 4867 | }; |
| 4868 | let handoff_deadline = |
| 4869 | process_deadline - std::time::Duration::from_millis(token_release_reserve_ms); |
| 4870 | // Stop public admission immediately. Before a handoff changes any cell |
| 4871 | // lifecycle, finish the public requests which crossed the old admission |
| 4872 | // gate. A DO call reaches its output gate only after it writes, so |
| 4873 | // beginning the final durability cut first would let that call cross the |
| 4874 | // cut without a core activity pin. Peer connections stay open: |
| 4875 | // cells outside the current batch must remain reachable during handoff. |
| 4876 | app.draining |
| 4877 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 4878 | let stall_window = std::time::Duration::from_millis(drain_ms); |
| 4879 | // New drain-time connections need a fresh watch version. A receiver cloned |
| 4880 | // from `connection_drain` after its signal would close immediately, before |
| 4881 | // it could serve a health response or authenticated peer request. |
| 4882 | let (drain_connection_tx, drain_connection) = watch::channel(false); |
| 4883 | let mut drain_connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new(); |
| 4884 | // Each acceptor waits until this loop receives its previous connection. |
| 4885 | // One surface therefore cannot occupy both slots and block the other. |
| 4886 | let (shutdown_connection_tx, mut shutdown_connection_rx) = mpsc::channel(2); |
| 4887 | #[cfg(all(test, celld_internal_tests))] |
| 4888 | let mut shutdown_accept_failure_recovered_for_test = !shutdown_accept_failure_test_active; |
| 4889 | #[cfg(all(test, celld_internal_tests))] |
| 4890 | shutdown_accept_failure_test_checkpoint( |
| 4891 | shutdown_accept_failure_test_active, |
| 4892 | "listener failure armed", |
| 4893 | ); |
| 4894 | #[cfg(all(test, celld_internal_tests))] |
| 4895 | { |
| 4896 | spawn_shutdown_acceptor( |
| 4897 | listener, |
| 4898 | HttpSurface::Public, |
| 4899 | shutdown_connection_tx.clone(), |
| 4900 | shutdown_accept_failure_test_active, |
| 4901 | ); |
| 4902 | spawn_shutdown_acceptor( |
| 4903 | internal_listener, |
| 4904 | HttpSurface::Internal, |
| 4905 | shutdown_connection_tx, |
| 4906 | false, |
| 4907 | ); |
| 4908 | } |
| 4909 | #[cfg(not(all(test, celld_internal_tests)))] |
| 4910 | { |
| 4911 | spawn_shutdown_acceptor( |
| 4912 | listener, |
| 4913 | HttpSurface::Public, |
| 4914 | shutdown_connection_tx.clone(), |
| 4915 | ); |
| 4916 | spawn_shutdown_acceptor( |
| 4917 | internal_listener, |
| 4918 | HttpSurface::Internal, |
| 4919 | shutdown_connection_tx, |
| 4920 | ); |
| 4921 | } |
| 4922 | let mut drain_token_hold: Option<celld::drain_token::Hold> = None; |
| 4923 | let handoff_started = if shutdown_mode == ShutdownMode::Handoff { |
| 4924 | // Serialize donors: claim the fleet drain token beside the |
| 4925 | // admitted-request drain, so simultaneous stop signals hand off one |
| 4926 | // node at a time. A waiting donor keeps serving peers and refuses |
| 4927 | // new handoffs because it is already draining. The wait has its own |
| 4928 | // bound inside the task; the pre-drain deadline never covers it. |
| 4929 | let drain_token: Arc<std::sync::Mutex<Option<celld::drain_token::Outcome>>> = |
| 4930 | Arc::new(std::sync::Mutex::new(None)); |
| 4931 | match &fleet_bucket { |
| 4932 | Some(bucket) if drain_token_wait_ms > 0 => { |
| 4933 | let bucket = bucket.clone(); |
| 4934 | let slot = drain_token.clone(); |
| 4935 | let token_node = clean_reload_node.clone(); |
| 4936 | let baseline_ownership = ready_ownership.clone(); |
| 4937 | let wait = std::time::Duration::from_millis(drain_token_wait_ms) |
| 4938 | .min(handoff_deadline.saturating_duration_since(tokio::time::Instant::now())); |
| 4939 | tokio::spawn(async move { |
| 4940 | let now_ms = celld::ownership_store::now_ms(); |
| 4941 | let restoration_baseline = match baseline_ownership { |
| 4942 | Some(ownership) => match ownership.read_capacity_peers().await { |
| 4943 | Ok(peers) => { |
| 4944 | let mut baseline = peers |
| 4945 | .into_iter() |
| 4946 | .filter(|peer| peer.expires_ms > now_ms) |
| 4947 | .map(|peer| celld_logic::drain::RestorationBaseline { |
| 4948 | node: peer.node, |
| 4949 | restoring: peer.restoring, |
| 4950 | }) |
| 4951 | .collect::<Vec<_>>(); |
| 4952 | baseline.sort_by(|left, right| left.node.cmp(&right.node)); |
| 4953 | baseline |
| 4954 | } |
| 4955 | Err(error) => { |
| 4956 | tracing::warn!( |
| 4957 | event = "drain_restoration_baseline_unavailable", |
| 4958 | %error, |
| 4959 | "the donor could not snapshot the pre-drain restore baseline" |
| 4960 | ); |
| 4961 | Vec::new() |
| 4962 | } |
| 4963 | }, |
| 4964 | None => Vec::new(), |
| 4965 | }; |
| 4966 | tracing::info!( |
| 4967 | event = "drain_restoration_baseline", |
| 4968 | nodes = restoration_baseline.len(), |
| 4969 | maximum = restoration_baseline |
| 4970 | .iter() |
| 4971 | .map(|baseline| baseline.restoring) |
| 4972 | .max() |
| 4973 | .unwrap_or(0), |
| 4974 | "captured the pre-drain restore baseline" |
| 4975 | ); |
| 4976 | let outcome = celld::drain_token::acquire( |
| 4977 | &bucket, |
| 4978 | &token_node, |
| 4979 | wait, |
| 4980 | restoration_baseline, |
| 4981 | ) |
| 4982 | .await; |
| 4983 | *slot.lock().expect("drain token slot") = Some(outcome); |
| 4984 | }); |
| 4985 | } |
| 4986 | _ => { |
| 4987 | *drain_token.lock().expect("drain token slot") = |
| 4988 | Some(celld::drain_token::Outcome::Disabled); |
| 4989 | } |
| 4990 | } |
| 4991 | let pre_drain_deadline = (tokio::time::Instant::now() + stall_window).min(handoff_deadline); |
| 4992 | let mut pre_drain_tick = tokio::time::interval(std::time::Duration::from_millis(5)); |
| 4993 | let mut admitted = None; |
| 4994 | let admitted_drained = loop { |
| 4995 | if admitted.is_none() && app.public_in_flight() == 0 { |
| 4996 | admitted = Some(true); |
| 4997 | } |
| 4998 | if let Some(admitted_drained) = admitted { |
| 4999 | let token_ready = drain_token.lock().expect("drain token slot").is_some(); |
| 5000 | #[cfg(all(test, celld_internal_tests))] |
| 5001 | let token_ready = token_ready && shutdown_accept_failure_recovered_for_test; |
| 5002 | if token_ready { |
| 5003 | break admitted_drained; |
| 5004 | } |
| 5005 | } |
| 5006 | celld::asyncrt::select! { |
| 5007 | _ = tokio::time::sleep_until(pre_drain_deadline), if admitted.is_none() => { |
| 5008 | admitted = Some(false); |
| 5009 | } |
| 5010 | _ = tokio::time::sleep_until(handoff_deadline) => break false, |
| 5011 | _ = pre_drain_tick.tick() => {} |
| 5012 | connection = shutdown_connection_rx.recv() => { |
| 5013 | let Some(connection) = connection else { |
| 5014 | anyhow::bail!("shutdown listener tasks stopped during pre-drain"); |
| 5015 | }; |
| 5016 | drain_connections.push(serve_http_connection( |
| 5017 | connection.stream, |
| 5018 | connection.surface, |
| 5019 | app.clone(), |
| 5020 | shutdown_tx.clone(), |
| 5021 | drain_connection.clone(), |
| 5022 | connection_grace, |
| 5023 | )); |
| 5024 | #[cfg(all(test, celld_internal_tests))] |
| 5025 | if connection.recovered_after_error { |
| 5026 | shutdown_accept_failure_recovered_for_test = true; |
| 5027 | } |
| 5028 | let _ = connection.received.send(()); |
| 5029 | } |
| 5030 | Some(_) = drain_connections.next(), if !drain_connections.is_empty() => {} |
| 5031 | Some(_) = connections.next(), if !connections.is_empty() => {} |
| 5032 | call = do_call_rx.recv() => { |
| 5033 | let Some(call) = call else { |
| 5034 | anyhow::bail!("Durable Object call channel closed during shutdown pre-drain"); |
| 5035 | }; |
| 5036 | do_calls.push(Box::pin(dispatch_do_call(app.clone(), call))); |
| 5037 | } |
| 5038 | Some(_) = do_calls.next(), if !do_calls.is_empty() => {} |
| 5039 | req = gate_rx.recv() => { |
| 5040 | let Some(req) = req else { |
| 5041 | anyhow::bail!("output-gate channel closed during shutdown pre-drain"); |
| 5042 | }; |
| 5043 | gate_calls.push(Box::pin(dispatch_gate(app.clone(), req))); |
| 5044 | } |
| 5045 | Some(_) = gate_calls.next(), if !gate_calls.is_empty() => {} |
| 5046 | call = service_call_rx.recv() => { |
| 5047 | let Some(call) = call else { |
| 5048 | anyhow::bail!("service call channel closed during shutdown pre-drain"); |
| 5049 | }; |
| 5050 | service_calls.push(Box::pin(dispatch_service_call(app.clone(), call))); |
| 5051 | } |
| 5052 | call = service_rpc_rx.recv() => { |
| 5053 | let Some(call) = call else { |
| 5054 | anyhow::bail!("service RPC channel closed during shutdown pre-drain"); |
| 5055 | }; |
| 5056 | service_calls.push(Box::pin(dispatch_service_rpc(app.clone(), call))); |
| 5057 | } |
| 5058 | Some(_) = service_calls.next(), if !service_calls.is_empty() => {} |
| 5059 | call = queue_dispatch_rx.recv() => { |
| 5060 | let Some(call) = call else { |
| 5061 | anyhow::bail!("Queue dispatch channel closed during shutdown pre-drain"); |
| 5062 | }; |
| 5063 | queue_calls.push(Box::pin(dispatch_queue_batch(app.clone(), call))); |
| 5064 | } |
| 5065 | Some(_) = queue_calls.next(), if !queue_calls.is_empty() => {} |
| 5066 | call = rpc_call_rx.recv() => { |
| 5067 | let Some(call) = call else { |
| 5068 | anyhow::bail!("Durable Object RPC channel closed during shutdown pre-drain"); |
| 5069 | }; |
| 5070 | do_calls.push(Box::pin(dispatch_rpc_call(app.clone(), call))); |
| 5071 | } |
| 5072 | call = asset_call_rx.recv() => { |
| 5073 | let Some(call) = call else { |
| 5074 | anyhow::bail!("asset call channel closed during shutdown pre-drain"); |
| 5075 | }; |
| 5076 | asset_calls.push(Box::pin(dispatch_asset_call(app.clone(), call))); |
| 5077 | } |
| 5078 | Some(_) = asset_calls.next(), if !asset_calls.is_empty() => {} |
| 5079 | code = fence_rx.recv() => exit_flushed(code.unwrap_or(3)), |
| 5080 | actor_exit = actor_exit_rx.recv() => { |
| 5081 | let error = match actor_exit { |
| 5082 | Some(Err(error)) => error, |
| 5083 | Some(Ok(())) => "the core actor stopped unexpectedly".to_string(), |
| 5084 | None => "the core actor thread panicked".to_string(), |
| 5085 | }; |
| 5086 | tracing::error!(event = "core_actor_exit", %error, "SELF-FENCE during shutdown pre-drain"); |
| 5087 | exit_flushed(3); |
| 5088 | } |
| 5089 | } |
| 5090 | }; |
| 5091 | drain_token_hold = match drain_token.lock().expect("drain token slot").take() { |
| 5092 | Some(celld::drain_token::Outcome::Acquired(hold)) => Some(hold), |
| 5093 | _ => None, |
| 5094 | }; |
| 5095 | if !admitted_drained { |
| 5096 | tracing::warn!( |
| 5097 | event = "shutdown_pre_drain_forced", |
| 5098 | public_in_flight = app.public_in_flight(), |
| 5099 | do_calls = do_calls.len(), |
| 5100 | gate_calls = gate_calls.len(), |
| 5101 | service_calls = service_calls.len(), |
| 5102 | queue_calls = queue_calls.len(), |
| 5103 | asset_calls = asset_calls.len(), |
| 5104 | grace_ms = stall_window.as_millis(), |
| 5105 | "shutdown reached its admitted-request deadline before cell handoff" |
| 5106 | ); |
| 5107 | } |
| 5108 | if admitted_drained { |
| 5109 | let _ = app.tx.send(Message::ReleaseAll); |
| 5110 | } |
| 5111 | admitted_drained |
| 5112 | } else { |
| 5113 | let _ = connection_drain_tx.send(true); |
| 5114 | let _ = app.tx.send(Message::BeginPreserve); |
| 5115 | true |
| 5116 | }; |
| 5117 | // Progress extends the stall deadline, but never the complete process |
| 5118 | // deadline. A deadline-cut cell keeps its durable owner record and follows |
| 5119 | // the same lease-expiry recovery path as an abrupt process loss. |
| 5120 | let mut stall_deadline = (tokio::time::Instant::now() + stall_window).min(handoff_deadline); |
| 5121 | let mut handed_off = 0; |
| 5122 | let mut process_deadline_fired = false; |
| 5123 | let mut handoff = tokio::time::interval(std::time::Duration::from_millis(50)); |
| 5124 | let mut containers_reaped = false; |
| 5125 | let drained = if shutdown_mode == ShutdownMode::Handoff && !handoff_started { |
| 5126 | false |
| 5127 | } else { |
| 5128 | loop { |
| 5129 | let requests_drained = connections.is_empty() |
| 5130 | && do_calls.is_empty() |
| 5131 | && gate_calls.is_empty() |
| 5132 | && service_calls.is_empty() |
| 5133 | && queue_calls.is_empty() |
| 5134 | && asset_calls.is_empty(); |
| 5135 | let shell_drained = requests_drained && websockets.is_empty(); |
| 5136 | // The actor can be busy driving an immediate-effect failure loop, so |
| 5137 | // a status request is not itself allowed to bypass the drain deadline. |
| 5138 | let status = before_process_deadline( |
| 5139 | handoff_deadline, |
| 5140 | tokio::time::timeout(std::time::Duration::from_millis(50), app.drain_status()), |
| 5141 | ) |
| 5142 | .await |
| 5143 | .and_then(Result::ok); |
| 5144 | if shutdown_mode == ShutdownMode::Handoff |
| 5145 | && status.is_some_and(|status| status.handed_off > handed_off) |
| 5146 | { |
| 5147 | handed_off = status.expect("checked drain status").handed_off; |
| 5148 | stall_deadline = (tokio::time::Instant::now() + stall_window).min(handoff_deadline); |
| 5149 | } |
| 5150 | // A drain that makes progress can outlive the token TTL, so the |
| 5151 | // holder renews and only a dead holder lets the token lapse. |
| 5152 | let renew_due = drain_token_hold.as_ref().is_some_and(|hold| { |
| 5153 | celld::drain_token::renew_due(hold, celld::ownership_store::now_ms()) |
| 5154 | }); |
| 5155 | if renew_due { |
| 5156 | let mut lost = false; |
| 5157 | if let (Some(bucket), Some(hold)) = (&fleet_bucket, drain_token_hold.as_mut()) { |
| 5158 | let Some(renewed) = before_process_deadline( |
| 5159 | handoff_deadline, |
| 5160 | celld::drain_token::renew(bucket, &clean_reload_node, hold), |
| 5161 | ) |
| 5162 | .await |
| 5163 | else { |
| 5164 | process_deadline_fired = true; |
| 5165 | break false; |
| 5166 | }; |
| 5167 | lost = !renewed; |
| 5168 | } |
| 5169 | if lost { |
| 5170 | drain_token_hold = None; |
| 5171 | } |
| 5172 | } |
| 5173 | let core_drained = status.is_some_and(|status| match shutdown_mode { |
| 5174 | ShutdownMode::Handoff => { |
| 5175 | status.occupied == 0 |
| 5176 | && status.activating == 0 |
| 5177 | && status.quiescing == 0 |
| 5178 | && status.evicting == 0 |
| 5179 | && status.releasing == 0 |
| 5180 | && status.adopting == 0 |
| 5181 | } |
| 5182 | ShutdownMode::Preserve => status.activating == 0 && status.evicting == 0, |
| 5183 | }); |
| 5184 | let completely_drained = match shutdown_mode { |
| 5185 | ShutdownMode::Handoff => core_drained, |
| 5186 | ShutdownMode::Preserve => shell_drained && core_drained, |
| 5187 | }; |
| 5188 | if completely_drained { |
| 5189 | break true; |
| 5190 | } |
| 5191 | // A preserve drain keeps its objects resident, so a socket an |
| 5192 | // object holds into its container never ends on its own and |
| 5193 | // the drain would sit out its whole deadline on it (the Sandbox |
| 5194 | // SDK's RPC transport is one such socket). The containers are |
| 5195 | // destroyed at exit anyway; destroying them once every request |
| 5196 | // has answered ends those sockets now. |
| 5197 | if !containers_reaped |
| 5198 | && shutdown_mode == ShutdownMode::Preserve |
| 5199 | && requests_drained |
| 5200 | && core_drained |
| 5201 | { |
| 5202 | containers_reaped = true; |
| 5203 | before_process_deadline(handoff_deadline, celld::container::shutdown()).await; |
| 5204 | continue; |
| 5205 | } |
| 5206 | celld::asyncrt::select! { |
| 5207 | _ = tokio::time::sleep_until(stall_deadline) => { |
| 5208 | process_deadline_fired = tokio::time::Instant::now() >= handoff_deadline; |
| 5209 | break false; |
| 5210 | }, |
| 5211 | _ = handoff.tick() => {} |
| 5212 | connection = shutdown_connection_rx.recv() => { |
| 5213 | let Some(connection) = connection else { |
| 5214 | anyhow::bail!("shutdown listener tasks stopped during drain"); |
| 5215 | }; |
| 5216 | drain_connections.push(serve_http_connection( |
| 5217 | connection.stream, |
| 5218 | connection.surface, |
| 5219 | app.clone(), |
| 5220 | shutdown_tx.clone(), |
| 5221 | drain_connection.clone(), |
| 5222 | connection_grace, |
| 5223 | )); |
| 5224 | let _ = connection.received.send(()); |
| 5225 | } |
| 5226 | Some(_) = drain_connections.next(), if !drain_connections.is_empty() => {} |
| 5227 | Some(_) = connections.next(), if !connections.is_empty() => {} |
| 5228 | call = do_call_rx.recv() => { |
| 5229 | let Some(call) = call else { |
| 5230 | anyhow::bail!("Durable Object call channel closed during shutdown"); |
| 5231 | }; |
| 5232 | do_calls.push(Box::pin(dispatch_do_call(app.clone(), call))); |
| 5233 | } |
| 5234 | Some(_) = do_calls.next(), if !do_calls.is_empty() => {} |
| 5235 | req = gate_rx.recv() => { |
| 5236 | let Some(req) = req else { |
| 5237 | anyhow::bail!("output-gate channel closed during shutdown"); |
| 5238 | }; |
| 5239 | gate_calls.push(Box::pin(dispatch_gate(app.clone(), req))); |
| 5240 | } |
| 5241 | Some(_) = gate_calls.next(), if !gate_calls.is_empty() => {} |
| 5242 | call = service_call_rx.recv() => { |
| 5243 | let Some(call) = call else { |
| 5244 | anyhow::bail!("service call channel closed during shutdown"); |
| 5245 | }; |
| 5246 | service_calls.push(Box::pin(dispatch_service_call(app.clone(), call))); |
| 5247 | } |
| 5248 | call = service_rpc_rx.recv() => { |
| 5249 | let Some(call) = call else { |
| 5250 | anyhow::bail!("service RPC channel closed during shutdown"); |
| 5251 | }; |
| 5252 | service_calls.push(Box::pin(dispatch_service_rpc(app.clone(), call))); |
| 5253 | } |
| 5254 | Some(_) = service_calls.next(), if !service_calls.is_empty() => {} |
| 5255 | call = queue_dispatch_rx.recv() => { |
| 5256 | let Some(call) = call else { |
| 5257 | anyhow::bail!("Queue dispatch channel closed during shutdown"); |
| 5258 | }; |
| 5259 | queue_calls.push(Box::pin(dispatch_queue_batch(app.clone(), call))); |
| 5260 | } |
| 5261 | Some(_) = queue_calls.next(), if !queue_calls.is_empty() => {} |
| 5262 | call = rpc_call_rx.recv() => { |
| 5263 | let Some(call) = call else { |
| 5264 | anyhow::bail!("Durable Object RPC channel closed during shutdown"); |
| 5265 | }; |
| 5266 | do_calls.push(Box::pin(dispatch_rpc_call(app.clone(), call))); |
| 5267 | } |
| 5268 | call = asset_call_rx.recv() => { |
| 5269 | let Some(call) = call else { |
| 5270 | anyhow::bail!("asset call channel closed during shutdown"); |
| 5271 | }; |
| 5272 | asset_calls.push(Box::pin(dispatch_asset_call(app.clone(), call))); |
| 5273 | } |
| 5274 | Some(_) = asset_calls.next(), if !asset_calls.is_empty() => {} |
| 5275 | socket = websocket_rx.recv() => { |
| 5276 | let Some(socket) = socket else { |
| 5277 | anyhow::bail!("WebSocket channel closed during shutdown"); |
| 5278 | }; |
| 5279 | websockets.push(socket); |
| 5280 | } |
| 5281 | outbound = outbound_ws_rx.recv() => { |
| 5282 | let Some(outbound) = outbound else { |
| 5283 | anyhow::bail!("outbound WebSocket channel closed during shutdown"); |
| 5284 | }; |
| 5285 | let app = app.clone(); |
| 5286 | websockets.push(Box::pin(async move { |
| 5287 | if let Err(error) = outbound_websocket_task(app, outbound).await { |
| 5288 | eprintln!("celld outbound WebSocket failed: {error:#}"); |
| 5289 | } |
| 5290 | })); |
| 5291 | } |
| 5292 | Some(_) = websockets.next(), if !websockets.is_empty() => {} |
| 5293 | code = fence_rx.recv() => exit_flushed(code.unwrap_or(3)), |
| 5294 | actor_exit = actor_exit_rx.recv() => { |
| 5295 | let error = match actor_exit { |
| 5296 | Some(Err(error)) => error, |
| 5297 | Some(Ok(())) => "the core actor stopped unexpectedly".to_string(), |
| 5298 | None => "the core actor thread panicked".to_string(), |
| 5299 | }; |
| 5300 | tracing::error!(event = "core_actor_exit", %error, "SELF-FENCE during shutdown"); |
| 5301 | exit_flushed(3); |
| 5302 | } |
| 5303 | } |
| 5304 | } |
| 5305 | }; |
| 5306 | let _ = connection_drain_tx.send(true); |
| 5307 | let _ = drain_connection_tx.send(true); |
| 5308 | // Release the token whether or not the drain completed: the process is |
| 5309 | // about to exit either way, and the next donor must not wait out the TTL. |
| 5310 | // The connection flush below needs nothing from the token, so releasing |
| 5311 | // first keeps the next donor off the TTL during the flush grace. |
| 5312 | if let (Some(bucket), Some(hold)) = (&fleet_bucket, drain_token_hold.take()) { |
| 5313 | if before_process_deadline( |
| 5314 | process_deadline, |
| 5315 | celld::drain_token::release(bucket, &clean_reload_node, hold), |
| 5316 | ) |
| 5317 | .await |
| 5318 | .is_none() |
| 5319 | { |
| 5320 | tracing::warn!( |
| 5321 | event = "drain_token_release_deadline", |
| 5322 | "the process deadline skipped or cancelled the drain token release; the TTL bounds the residue" |
| 5323 | ); |
| 5324 | } |
| 5325 | } |
| 5326 | #[cfg(all(test, celld_internal_tests))] |
| 5327 | shutdown_accept_failure_test_checkpoint( |
| 5328 | shutdown_accept_failure_test_active, |
| 5329 | "drain token release finished", |
| 5330 | ); |
| 5331 | if !handoff_started { |
| 5332 | tracing::error!( |
| 5333 | event = "shutdown_handoff_not_started", |
| 5334 | drain_ms, |
| 5335 | admitted_public = app.public_in_flight(), |
| 5336 | "the shutdown pre-drain did not finish" |
| 5337 | ); |
| 5338 | } else if !drained && shutdown_mode == ShutdownMode::Handoff { |
| 5339 | let drain_state = before_process_deadline( |
| 5340 | process_deadline, |
| 5341 | tokio::time::timeout(std::time::Duration::from_millis(50), app.snapshot()), |
| 5342 | ) |
| 5343 | .await |
| 5344 | .and_then(Result::ok) |
| 5345 | .unwrap_or_else(|| "{\"error\":\"process_deadline\"}".to_string()); |
| 5346 | match before_process_deadline( |
| 5347 | process_deadline, |
| 5348 | tokio::time::timeout( |
| 5349 | std::time::Duration::from_millis(50), |
| 5350 | app.drain_status(), |
| 5351 | ), |
| 5352 | ) |
| 5353 | .await |
| 5354 | .and_then(Result::ok) |
| 5355 | { |
| 5356 | Some(status) => tracing::error!( |
| 5357 | event = "shutdown_handoff_stalled", |
| 5358 | drain_ms, |
| 5359 | shutdown_total_ms, |
| 5360 | process_deadline_fired, |
| 5361 | occupied = status.occupied, |
| 5362 | activating = status.activating, |
| 5363 | quiescing = status.quiescing, |
| 5364 | evicting = status.evicting, |
| 5365 | releasing = status.releasing, |
| 5366 | adopting = status.adopting, |
| 5367 | handed_off = status.handed_off, |
| 5368 | drain_state, |
| 5369 | "the shutdown handoff made no progress" |
| 5370 | ), |
| 5371 | None => tracing::error!( |
| 5372 | event = "shutdown_handoff_stalled", |
| 5373 | drain_ms, |
| 5374 | shutdown_total_ms, |
| 5375 | process_deadline_fired, |
| 5376 | drain_state, |
| 5377 | "the shutdown handoff made no observable progress because the core status was unavailable" |
| 5378 | ), |
| 5379 | } |
| 5380 | } else if !drained { |
| 5381 | eprintln!( |
| 5382 | "celld preserve drain reached its {drain_ms}ms deadline: connections={} do_calls={} gate_calls={} service_calls={} queue_calls={} asset_calls={} websockets={}", |
| 5383 | connections.len(), |
| 5384 | do_calls.len(), |
| 5385 | gate_calls.len(), |
| 5386 | service_calls.len(), |
| 5387 | queue_calls.len(), |
| 5388 | asset_calls.len(), |
| 5389 | websockets.len(), |
| 5390 | ); |
| 5391 | } |
| 5392 | // Let every accepted connection FINISH its current response before the |
| 5393 | // process exits. The demand-driven drain can complete in milliseconds |
| 5394 | // on a quiet node, and exit_flushed is a hard process::exit — without |
| 5395 | // this wait, a diagnostic request accepted during the drain window is |
| 5396 | // reset mid-response, and a WebSocket close frame written during the |
| 5397 | // release races the exit (#262). The watches above already told each |
| 5398 | // connection to close after the response it is serving, so this drains |
| 5399 | // fast; the grace only bounds a stuck peer. The dispatch sets (do_calls, |
| 5400 | // gate_calls, service_calls, asset_calls) are NOT polled here: a |
| 5401 | // connection whose response depends on one stalls for the grace and is |
| 5402 | // then cut, so a drain-window internal route must never dispatch into a |
| 5403 | // cell. Today none does — /state, /health, and /peer/abort answer from the |
| 5404 | // shell. |
| 5405 | // The backstop for a handoff cut by its deadline: a cell left behind |
| 5406 | // must not leave its container running until the next start of this |
| 5407 | // node reaps it. Idempotent after the preserve drain's own call. |
| 5408 | before_process_deadline(process_deadline, celld::container::shutdown()).await; |
| 5409 | let flush_connections = async { |
| 5410 | while drain_connections.next().await.is_some() {} |
| 5411 | while connections.next().await.is_some() {} |
| 5412 | while websockets.next().await.is_some() {} |
| 5413 | }; |
| 5414 | flush_shutdown_connections( |
| 5415 | process_deadline, |
| 5416 | celld::js::ws_await_all_flushes(), |
| 5417 | flush_connections, |
| 5418 | ) |
| 5419 | .await; |
| 5420 | // The graceful-shutdown drain point: seal our node-log record so the |
| 5421 | // next incarnation starts with no gather. Guarded inside — it seals |
| 5422 | // only when every shipped frame is bucket-covered. |
| 5423 | let durability_quiesced = if let Some(owner) = &mut durability_owner { |
| 5424 | let remaining = process_deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 5425 | let completed = if remaining.is_zero() { |
| 5426 | owner.stop_local_now(); |
| 5427 | false |
| 5428 | } else { |
| 5429 | owner.quiesce_and_seal_within(remaining).await |
| 5430 | }; |
| 5431 | if !completed { |
| 5432 | eprintln!("celld durability quiesce exceeded the process deadline"); |
| 5433 | } |
| 5434 | completed |
| 5435 | } else { |
| 5436 | true |
| 5437 | }; |
| 5438 | #[cfg(all(test, celld_internal_tests))] |
| 5439 | shutdown_accept_failure_test_checkpoint( |
| 5440 | shutdown_accept_failure_test_active, |
| 5441 | "durability quiesce finished", |
| 5442 | ); |
| 5443 | // Preparation captures and uploads each stopped cell's exact database |
| 5444 | // position. A failed proof abandons the marker and leaves normal startup |
| 5445 | // to reconcile the preserved files against bucket coverage. |
| 5446 | if clean_reload_is_eligible(durability_quiesced, drained, shutdown_mode) { |
| 5447 | let presence = before_process_deadline(process_deadline, app.presence()).await; |
| 5448 | let prepared = match (&app.runtime, presence) { |
| 5449 | (Some(runtime), Some(Some(presence))) => { |
| 5450 | before_process_deadline( |
| 5451 | process_deadline, |
| 5452 | runtime.prepare_clean_reload(&presence.cells), |
| 5453 | ) |
| 5454 | .await |
| 5455 | } |
| 5456 | (_, Some(None)) | (None, Some(Some(_))) => Some(Err(anyhow::anyhow!( |
| 5457 | "clean reload requires a runtime and a resident snapshot" |
| 5458 | ))), |
| 5459 | (_, None) => None, |
| 5460 | }; |
| 5461 | match prepared { |
| 5462 | Some(Ok(pruned)) => { |
| 5463 | match before_process_deadline(process_deadline, app.healthy()).await { |
| 5464 | Some(true) => match celld::runtime::write_clean_reload_marker( |
| 5465 | &data_dir, |
| 5466 | &clean_reload_node, |
| 5467 | &process_generation, |
| 5468 | ) { |
| 5469 | Ok(()) => tracing::info!( |
| 5470 | event = "clean_reload_prepared", |
| 5471 | stale_live_databases_pruned = pruned, |
| 5472 | "prepared local cells for an exact-generation reload" |
| 5473 | ), |
| 5474 | Err(error) => tracing::warn!( |
| 5475 | event = "clean_reload_abandoned", |
| 5476 | %error, |
| 5477 | "could not publish the clean local reload certificate" |
| 5478 | ), |
| 5479 | }, |
| 5480 | Some(false) => tracing::warn!( |
| 5481 | event = "clean_reload_abandoned", |
| 5482 | "node authority was lost while local cells were closing" |
| 5483 | ), |
| 5484 | None => tracing::warn!( |
| 5485 | event = "clean_reload_abandoned", |
| 5486 | "the process deadline skipped the final authority check" |
| 5487 | ), |
| 5488 | } |
| 5489 | } |
| 5490 | Some(Err(error)) => tracing::warn!( |
| 5491 | event = "clean_reload_abandoned", |
| 5492 | %error, |
| 5493 | "local reload preparation failed; replacement will use normal recovery" |
| 5494 | ), |
| 5495 | None => tracing::warn!( |
| 5496 | event = "clean_reload_abandoned", |
| 5497 | "local reload preparation exceeded the shutdown deadline" |
| 5498 | ), |
| 5499 | } |
| 5500 | } |
| 5501 | if let Some(owner) = &mut durability_owner { |
| 5502 | let remaining = process_deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 5503 | let completed = if remaining.is_zero() { |
| 5504 | owner.stop_local_now(); |
| 5505 | false |
| 5506 | } else { |
| 5507 | owner.shutdown_local_within(remaining).await |
| 5508 | }; |
| 5509 | if !completed { |
| 5510 | eprintln!("celld local durability shutdown exceeded the process deadline"); |
| 5511 | } |
| 5512 | } |
| 5513 | #[cfg(all(test, celld_internal_tests))] |
| 5514 | shutdown_accept_failure_test_checkpoint( |
| 5515 | shutdown_accept_failure_test_active, |
| 5516 | "local durability shutdown finished", |
| 5517 | ); |
| 5518 | // Exit without unwinding. Returning from here drops the tokio runtime |
| 5519 | // and the V8 platform underneath tasks and isolates that are still |
| 5520 | // alive -- on a deadline-cut drain that teardown segfaults (status 139 |
| 5521 | // observed fleet-wide, 2026-08-10). Nothing below needs a destructor: |
| 5522 | // every release the drain completed proved durability first, and a |
| 5523 | // cell the deadline cut off keeps its owner record exactly as a kill |
| 5524 | // would have left it. |
| 5525 | #[cfg(all(test, celld_internal_tests))] |
| 5526 | shutdown_accept_failure_test_checkpoint( |
| 5527 | shutdown_accept_failure_test_active, |
| 5528 | "final log flush reached", |
| 5529 | ); |
| 5530 | exit_flushed(0); |
| 5531 | } |
| 5532 | |
| 5533 | use celld::machine::{ |
| 5534 | lease_ttl_ms_from_environment, local_cache_max_bytes_from_environment, random_node_session_id, |
| 5535 | random_peer_key, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, PEER_CONNECT_TIMEOUT, |
| 5536 | }; |
| 5537 | |
| 5538 | /// Signals cancellation when the connection handling this request goes away. |
| 5539 | struct HangUp(Option<oneshot::Sender<()>>); |
| 5540 | |
| 5541 | impl Drop for HangUp { |
| 5542 | fn drop(&mut self) { |
| 5543 | if let Some(tx) = self.0.take() { |
| 5544 | let _ = tx.send(()); |
| 5545 | } |
| 5546 | } |
| 5547 | } |
| 5548 | |
| 5549 | /// Abandons a forwarded fetch on the owner when the peer connection carrying |
| 5550 | /// it goes away. After the handler answers, a drop cancels only its response |
| 5551 | /// body pin because the isolate has no unanswered request left to abort. |
| 5552 | struct AbortPeerFetchOnHangUp { |
| 5553 | runtime: RuntimeManager, |
| 5554 | scope: String, |
| 5555 | request_id: Option<celld::js::RequestId>, |
| 5556 | drain_pins: DrainPinRegistry, |
| 5557 | handler_active: bool, |
| 5558 | } |
| 5559 | |
| 5560 | impl AbortPeerFetchOnHangUp { |
| 5561 | fn disarm(&mut self) { |
| 5562 | self.request_id = None; |
| 5563 | } |
| 5564 | |
| 5565 | fn handler_answered(&mut self) { |
| 5566 | self.handler_active = false; |
| 5567 | } |
| 5568 | } |
| 5569 | |
| 5570 | impl Drop for AbortPeerFetchOnHangUp { |
| 5571 | fn drop(&mut self) { |
| 5572 | if let Some(request_id) = self.request_id { |
| 5573 | let _ = self |
| 5574 | .drain_pins |
| 5575 | .cancel_request(request_id, "peer_connection_closed"); |
| 5576 | if self.handler_active { |
| 5577 | self.runtime.abort_fetch(&self.scope, request_id); |
| 5578 | } |
| 5579 | } |
| 5580 | } |
| 5581 | } |
| 5582 | |
| 5583 | fn forwarder_response_stream( |
| 5584 | stream: celld::js::HttpChunkStream, |
| 5585 | mut abort: RemoteFetchAbortGuard, |
| 5586 | ) -> celld::js::HttpChunkStream { |
| 5587 | abort.body_active(); |
| 5588 | Box::pin(futures_util::stream::unfold( |
| 5589 | (stream, Some(abort)), |
| 5590 | |(mut stream, mut abort)| async move { |
| 5591 | match stream.next().await { |
| 5592 | Some(chunk) => { |
| 5593 | // An upstream body error already ended the owner |
| 5594 | // transport. A second connection carrying an abort adds |
| 5595 | // no signal; only a downstream drop while the upstream is |
| 5596 | // still live needs the explicit peer request. |
| 5597 | if chunk.is_err() { |
| 5598 | if let Some(mut abort) = abort.take() { |
| 5599 | abort.disarm(); |
| 5600 | } |
| 5601 | } |
| 5602 | Some((chunk, (stream, abort))) |
| 5603 | } |
| 5604 | None => { |
| 5605 | if let Some(mut abort) = abort.take() { |
| 5606 | abort.disarm(); |
| 5607 | } |
| 5608 | None |
| 5609 | } |
| 5610 | } |
| 5611 | }, |
| 5612 | )) |
| 5613 | } |
| 5614 | |
| 5615 | // The body owns the activity until EOF, cancellation, or drop. A forwarded |
| 5616 | // body also owns its peer-abort guard: disarm it at EOF, but retain it on a |
| 5617 | // dropped body so the owner cancels work for the disconnected peer. |
| 5618 | fn local_response_stream( |
| 5619 | stream: celld::js::HttpChunkStream, |
| 5620 | activity: ActivityGuard, |
| 5621 | on_finish: impl FnOnce() + Send + 'static, |
| 5622 | ) -> celld::js::HttpChunkStream { |
| 5623 | let cancellation = activity.cancellation(); |
| 5624 | Box::pin(futures_util::stream::unfold( |
| 5625 | (stream, activity, on_finish, cancellation), |
| 5626 | |(mut stream, activity, on_finish, mut cancellation)| async move { |
| 5627 | let chunk = if *cancellation.borrow() { |
| 5628 | None |
| 5629 | } else { |
| 5630 | celld::asyncrt::select! { |
| 5631 | chunk = stream.next() => chunk, |
| 5632 | changed = cancellation.changed() => { |
| 5633 | let _ = changed; |
| 5634 | None |
| 5635 | } |
| 5636 | } |
| 5637 | }; |
| 5638 | match chunk { |
| 5639 | Some(chunk) => Some((chunk, (stream, activity, on_finish, cancellation))), |
| 5640 | None => { |
| 5641 | on_finish(); |
| 5642 | drop(activity); |
| 5643 | None |
| 5644 | } |
| 5645 | } |
| 5646 | }, |
| 5647 | )) |
| 5648 | } |
| 5649 | |
| 5650 | #[cfg(all(test, celld_internal_tests))] |
| 5651 | mod durability_lifecycle_private { |
| 5652 | include!(env!("CELLD_CONFORMANCE_MAIN_DURABILITY_TESTS")); |
| 5653 | } |