| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | // Fleet CLI and peer-diagnostic work executes outside the Actor execution |
| 4 | // domain. |
| 5 | #![allow(clippy::disallowed_methods)] |
| 6 | // Diagnose used to split by verdict rather than by kind, so a redirect kept |
| 7 | // the passes and lost the failures. Every check now goes through `Output`. |
| 8 | |
| 9 | //! Production bucket deployment adapters reused by the clean-sheet host. |
| 10 | |
| 11 | use crate::bucket::{Bucket, StorageProbeVerdict}; |
| 12 | use crate::deploy; |
| 13 | use crate::js::{ModuleSource, WorkerConfigOptions}; |
| 14 | use crate::ownership_store::NodeLeaseWire; |
| 15 | use crate::protocol::{DeployPointer, Manifest, ModuleKind, Rollout}; |
| 16 | use anyhow::{bail, Context}; |
| 17 | use std::borrow::Cow; |
| 18 | |
| 19 | use crate::cli_output::Format; |
| 20 | use crate::cli_output::Output; |
| 21 | use crate::cli_output::Record; |
| 22 | use crate::note; |
| 23 | |
| 24 | /// What a deployment produced. |
| 25 | /// |
| 26 | /// Deploy is a narrative, so its progress belongs on stderr — but the |
| 27 | /// version is the datum a release script reads back, so it stays a row on |
| 28 | /// stdout rather than a line to grep out of the prose. |
| 29 | pub(crate) struct Deployed { |
| 30 | worker: String, |
| 31 | version: String, |
| 32 | location: String, |
| 33 | dry_run: bool, |
| 34 | } |
| 35 | |
| 36 | impl Record for Deployed { |
| 37 | fn json(&self) -> serde_json::Value { |
| 38 | serde_json::json!({ |
| 39 | "worker": self.worker, |
| 40 | "version": self.version, |
| 41 | "location": self.location, |
| 42 | "dry_run": self.dry_run, |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | fn text(&self) -> Cow<'_, str> { |
| 47 | Cow::Owned(if self.dry_run { |
| 48 | format!( |
| 49 | "Current Version ID: {} (dry run; nothing written)", |
| 50 | self.version |
| 51 | ) |
| 52 | } else { |
| 53 | format!("Current Version ID: {}", self.version) |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// One diagnostic verdict. |
| 59 | /// |
| 60 | /// Every check is a row, whatever its verdict. The old shape sent `ok` and |
| 61 | /// `skip` to stdout and `fail` to stderr, so `celld diagnose > report.txt` |
| 62 | /// saved the passes and lost the failures. The exit code still carries the |
| 63 | /// summary, so a redirect and `$?` together say everything. |
| 64 | pub struct Check { |
| 65 | verdict: &'static str, |
| 66 | subject: String, |
| 67 | detail: String, |
| 68 | } |
| 69 | |
| 70 | impl Check { |
| 71 | fn new(verdict: &'static str, subject: impl Into<String>, detail: impl Into<String>) -> Self { |
| 72 | Self { |
| 73 | verdict, |
| 74 | subject: subject.into(), |
| 75 | detail: detail.into(), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | pub fn ok(subject: impl Into<String>, detail: impl Into<String>) -> Self { |
| 80 | Self::new("ok", subject, detail) |
| 81 | } |
| 82 | |
| 83 | pub fn fail(subject: impl Into<String>, detail: impl Into<String>) -> Self { |
| 84 | Self::new("fail", subject, detail) |
| 85 | } |
| 86 | |
| 87 | pub fn skip(subject: impl Into<String>, detail: impl Into<String>) -> Self { |
| 88 | Self::new("skip", subject, detail) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | impl Record for Check { |
| 93 | fn json(&self) -> serde_json::Value { |
| 94 | serde_json::json!({ |
| 95 | "verdict": self.verdict, |
| 96 | "check": self.subject, |
| 97 | "detail": self.detail, |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | fn text(&self) -> Cow<'_, str> { |
| 102 | // The long-standing shape: `ok bucket ...`, `fail peer X: ...`. |
| 103 | Cow::Owned(if self.detail.is_empty() { |
| 104 | format!("{} {}", self.verdict, self.subject) |
| 105 | } else { |
| 106 | format!("{} {}: {}", self.verdict, self.subject, self.detail) |
| 107 | }) |
| 108 | } |
| 109 | } |
| 110 | use std::time::Duration; |
| 111 | use tracing::info; |
| 112 | |
| 113 | pub fn bucket_client(bucket: &str, endpoint: Option<&str>, region: &str) -> anyhow::Result<Bucket> { |
| 114 | bucket_client_with_credentials(bucket, endpoint, region, None) |
| 115 | } |
| 116 | |
| 117 | /// Build the authority-heartbeat client on its own HTTP connection pool. |
| 118 | /// |
| 119 | /// Node lease traffic must not queue behind ordinary ownership, deployment, |
| 120 | /// or replica requests. Every `Bucket::open` builds its own transport, so a |
| 121 | /// dedicated instance keeps the safety lane isolated, and the `celld-lease` |
| 122 | /// app tag labels it in black-box storage traces. |
| 123 | pub fn lease_bucket_client_with_credentials( |
| 124 | bucket: &str, |
| 125 | endpoint: Option<&str>, |
| 126 | region: &str, |
| 127 | managed: Option<&crate::control_plane::ManagedStorageConfig>, |
| 128 | ) -> anyhow::Result<Bucket> { |
| 129 | open(bucket, endpoint, region, managed, Some("celld-lease")) |
| 130 | } |
| 131 | |
| 132 | pub fn bucket_client_with_credentials( |
| 133 | bucket: &str, |
| 134 | endpoint: Option<&str>, |
| 135 | region: &str, |
| 136 | managed: Option<&crate::control_plane::ManagedStorageConfig>, |
| 137 | ) -> anyhow::Result<Bucket> { |
| 138 | open(bucket, endpoint, region, managed, None) |
| 139 | } |
| 140 | |
| 141 | fn open( |
| 142 | bucket: &str, |
| 143 | endpoint: Option<&str>, |
| 144 | region: &str, |
| 145 | managed: Option<&crate::control_plane::ManagedStorageConfig>, |
| 146 | app: Option<&str>, |
| 147 | ) -> anyhow::Result<Bucket> { |
| 148 | let credentials = managed.map(|managed| crate::bucket::StaticCredentials { |
| 149 | access_key_id: managed.access_key_id.clone(), |
| 150 | secret_access_key: managed.secret_access_key.clone(), |
| 151 | session_token: managed.session_token.clone(), |
| 152 | }); |
| 153 | Bucket::open(bucket, endpoint, region, credentials, app) |
| 154 | } |
| 155 | |
| 156 | pub async fn validate_bucket(bucket: &Bucket) -> anyhow::Result<()> { |
| 157 | bucket.validate().await.with_context(|| { |
| 158 | format!( |
| 159 | "bucket unavailable or inaccessible: {}://{}", |
| 160 | bucket.scheme(), |
| 161 | bucket.name |
| 162 | ) |
| 163 | }) |
| 164 | } |
| 165 | |
| 166 | /// Validate storage issued by the Managed Control Plane and preserve the |
| 167 | /// operator-visible failure vocabulary. Newly issued provider credentials can |
| 168 | /// take a moment to propagate, so only the final rejection is authoritative. |
| 169 | pub async fn validate_managed_bucket(bucket: &Bucket) -> anyhow::Result<()> { |
| 170 | const RETRIES: u32 = 5; |
| 171 | for attempt in 1..=RETRIES { |
| 172 | match validate_managed_bucket_once(bucket, attempt == RETRIES).await { |
| 173 | Ok(()) => return Ok(()), |
| 174 | Err(error) if attempt == RETRIES => return Err(error), |
| 175 | Err(_) => { |
| 176 | info!( |
| 177 | bucket = %bucket.name, |
| 178 | attempt, |
| 179 | "storage credential not accepted yet; retrying" |
| 180 | ); |
| 181 | tokio::time::sleep(Duration::from_millis(500 * u64::from(attempt))).await; |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | unreachable!("loop returns on the final attempt") |
| 186 | } |
| 187 | |
| 188 | async fn validate_managed_bucket_once(bucket: &Bucket, report: bool) -> anyhow::Result<()> { |
| 189 | match bucket.validate().await { |
| 190 | Ok(()) => Ok(()), |
| 191 | Err(error) if crate::bucket::is_unauthorized(&error) => { |
| 192 | if report { |
| 193 | crate::control_plane::report_managed_runtime_state( |
| 194 | crate::control_plane::ManagedRuntimeState::CredentialRevoked, |
| 195 | ); |
| 196 | bail!( |
| 197 | "managed storage credential was rejected or revoked for {}://{}", |
| 198 | bucket.scheme(), |
| 199 | bucket.name |
| 200 | ); |
| 201 | } |
| 202 | bail!( |
| 203 | "managed storage credential was not accepted yet for {}://{}", |
| 204 | bucket.scheme(), |
| 205 | bucket.name |
| 206 | ); |
| 207 | } |
| 208 | Err(error) => { |
| 209 | if report { |
| 210 | crate::control_plane::report_managed_runtime_state( |
| 211 | crate::control_plane::ManagedRuntimeState::BucketUnavailable, |
| 212 | ); |
| 213 | } |
| 214 | Err(error).with_context(|| { |
| 215 | format!( |
| 216 | "bucket unavailable or inaccessible: {}://{}", |
| 217 | bucket.scheme(), |
| 218 | bucket.name |
| 219 | ) |
| 220 | }) |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Test the one bucket capability a fleet cannot run without. |
| 226 | /// |
| 227 | /// A list proves the bucket answers a request. It does not prove the |
| 228 | /// store keeps the conditional write, and some stores accept the |
| 229 | /// precondition header and then ignore it. A fleet on such a store loses |
| 230 | /// a cell to two owners, or dies in a self-fence loop, minutes after an |
| 231 | /// operator read `ok bucket`. So diagnose provokes the rejections a |
| 232 | /// conforming store must produce. |
| 233 | /// |
| 234 | /// The probe writes and deletes one small object, which a read-only |
| 235 | /// credential cannot do; `--read-only` skips it for that operator. |
| 236 | async fn probe_storage(out: &mut Output, bucket: &Bucket, read_only: bool) -> anyhow::Result<()> { |
| 237 | if read_only { |
| 238 | out.row(&Check::skip("bucket write probe", "--read-only"))?; |
| 239 | return Ok(()); |
| 240 | } |
| 241 | match bucket.probe_cas().await { |
| 242 | Ok(()) => { |
| 243 | out.row(&Check::ok( |
| 244 | "bucket conditional write", |
| 245 | "create, reject-create, update, reject-stale", |
| 246 | ))?; |
| 247 | Ok(()) |
| 248 | } |
| 249 | Err(error) => { |
| 250 | let detail = if crate::bucket::is_unauthorized(&error) { |
| 251 | "the credential cannot write to the bucket, and a celld node requires write \ |
| 252 | access; pass --read-only to diagnose with a read-only credential" |
| 253 | .to_string() |
| 254 | } else { |
| 255 | format!("{error:#}") |
| 256 | }; |
| 257 | out.row(&Check::fail("bucket conditional write", detail))?; |
| 258 | bail!("bucket failed the storage conformance probe") |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /// Test the required conditional writes and ranged reads before a node serves, |
| 264 | /// and refuse to start when the store proves it cannot support celld. |
| 265 | /// |
| 266 | /// The two probe outcomes get different answers on purpose. A violation |
| 267 | /// is a property of the store: it never clears. A node that serves anyway can |
| 268 | /// share a cell with another owner or fail when it reads stored cell data. |
| 269 | /// Refusing to start reports the permanent problem before either failure. |
| 270 | /// |
| 271 | /// An ambiguous error is not that. `put_cas` runs with transport retries off, |
| 272 | /// so a slow or dropped connection answers `Err`. The complete probe retries |
| 273 | /// with a fresh key twice, then preserves the existing warn-and-serve result. |
| 274 | /// |
| 275 | /// `managed` reports the refusal to the Managed Control Plane, the way |
| 276 | /// [`validate_managed_bucket`] reports its own failures. Without it an |
| 277 | /// enrolled installation that refuses to serve leaves only local stderr |
| 278 | /// behind, so the operator who most needs the reason cannot read it. |
| 279 | pub async fn probe_storage_before_serving(bucket: &Bucket, managed: bool) -> anyhow::Result<()> { |
| 280 | const ATTEMPTS: usize = 3; |
| 281 | for attempt in 1..=ATTEMPTS { |
| 282 | match bucket.probe_startup_storage_steps().await { |
| 283 | Ok(StorageProbeVerdict::Conformant) => return Ok(()), |
| 284 | Ok(StorageProbeVerdict::Violation(reason)) => { |
| 285 | if managed { |
| 286 | crate::control_plane::report_managed_runtime_state( |
| 287 | crate::control_plane::ManagedRuntimeState::StorageContractViolated, |
| 288 | ); |
| 289 | } |
| 290 | bail!( |
| 291 | "the bucket does not keep the storage contract, so celld cannot serve cells \ |
| 292 | safely on it: {reason}. Use a store that supports the required operations" |
| 293 | ) |
| 294 | } |
| 295 | Err(error) if attempt < ATTEMPTS => { |
| 296 | tracing::warn!( |
| 297 | attempt, |
| 298 | attempts = ATTEMPTS, |
| 299 | error = format!("{error:#}"), |
| 300 | "could not verify the bucket storage contract; retrying" |
| 301 | ); |
| 302 | } |
| 303 | Err(error) => { |
| 304 | tracing::warn!( |
| 305 | attempts = ATTEMPTS, |
| 306 | error = format!("{error:#}"), |
| 307 | "could not verify the bucket storage contract; starting anyway" |
| 308 | ); |
| 309 | return Ok(()); |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | unreachable!("the storage probe loop always returns on its last attempt") |
| 314 | } |
| 315 | |
| 316 | pub async fn diagnose( |
| 317 | bucket: &Bucket, |
| 318 | peers: Vec<String>, |
| 319 | unsafe_public_advertise: bool, |
| 320 | read_only: bool, |
| 321 | json: bool, |
| 322 | // Checks the caller already made, printed through this command's one |
| 323 | // `Output`. The listener binds happen before a bucket is even opened, |
| 324 | // and printing them from there put three text lines in front of the |
| 325 | // JSON, which broke `celld diagnose --json | jq` at its first line. |
| 326 | preamble: Vec<Check>, |
| 327 | ) -> anyhow::Result<()> { |
| 328 | let mut out = Output::new(if json { Format::Json } else { Format::Text }); |
| 329 | for check in &preamble { |
| 330 | out.row(check)?; |
| 331 | } |
| 332 | // Every verdict is flushed before the exit status is decided, so a |
| 333 | // failing diagnosis still leaves the operator the checks that passed. |
| 334 | let verdict = |
| 335 | diagnose_checks(&mut out, bucket, peers, unsafe_public_advertise, read_only).await; |
| 336 | out.finish()?; |
| 337 | verdict |
| 338 | } |
| 339 | |
| 340 | async fn diagnose_checks( |
| 341 | out: &mut Output, |
| 342 | bucket: &Bucket, |
| 343 | peers: Vec<String>, |
| 344 | unsafe_public_advertise: bool, |
| 345 | read_only: bool, |
| 346 | ) -> anyhow::Result<()> { |
| 347 | validate_bucket(bucket).await?; |
| 348 | out.row(&Check::ok( |
| 349 | format!("bucket {}://{}", bucket.scheme(), bucket.name), |
| 350 | "", |
| 351 | ))?; |
| 352 | // A store that cannot fence makes every peer result moot, so the |
| 353 | // storage verdict comes before the fleet walk. |
| 354 | probe_storage(out, bucket, read_only).await?; |
| 355 | |
| 356 | let enumerated = peers.is_empty(); |
| 357 | let peers = if enumerated { |
| 358 | let peers = node_lease_ids(bucket).await?; |
| 359 | out.row(&Check::ok( |
| 360 | "fleet", |
| 361 | format!("{} node lease(s) enumerated", peers.len()), |
| 362 | ))?; |
| 363 | peers |
| 364 | } else { |
| 365 | peers |
| 366 | }; |
| 367 | if peers.is_empty() { |
| 368 | return Ok(()); |
| 369 | } |
| 370 | let http = reqwest::Client::builder() |
| 371 | .connect_timeout(Duration::from_secs(3)) |
| 372 | .timeout(Duration::from_secs(5)) |
| 373 | .redirect(reqwest::redirect::Policy::none()) |
| 374 | .build() |
| 375 | .context("build peer diagnostic client")?; |
| 376 | let auth = crate::peer_auth::PeerAuth::new( |
| 377 | crate::peer_auth::load_existing(bucket).await?, |
| 378 | "diagnostic", |
| 379 | )?; |
| 380 | let mut failures = 0_usize; |
| 381 | let mut expired = 0_usize; |
| 382 | for peer in peers { |
| 383 | let node = match live_node_lease(bucket, &peer).await { |
| 384 | Ok(Some(node)) => node, |
| 385 | Ok(None) if enumerated => { |
| 386 | expired += 1; |
| 387 | out.row(&Check::skip(format!("peer {peer}"), "lease is expired"))?; |
| 388 | continue; |
| 389 | } |
| 390 | Ok(None) => { |
| 391 | failures += 1; |
| 392 | out.row(&Check::fail( |
| 393 | format!("peer {peer}"), |
| 394 | format!("node {peer} lease is expired"), |
| 395 | ))?; |
| 396 | continue; |
| 397 | } |
| 398 | Err(error) => { |
| 399 | failures += 1; |
| 400 | out.row(&Check::fail(format!("peer {peer}"), format!("{error}")))?; |
| 401 | continue; |
| 402 | } |
| 403 | }; |
| 404 | let advertise = match crate::startup::parse_advertise(&node.addr) { |
| 405 | Ok(advertise) => advertise, |
| 406 | Err(error) => { |
| 407 | failures += 1; |
| 408 | out.row(&Check::fail( |
| 409 | format!("peer {peer}"), |
| 410 | format!("malformed advertise address {:?}: {error}", node.addr), |
| 411 | ))?; |
| 412 | continue; |
| 413 | } |
| 414 | }; |
| 415 | if advertise.is_public_ip() && !unsafe_public_advertise { |
| 416 | failures += 1; |
| 417 | out.row(&Check::fail( |
| 418 | format!("peer {peer}"), |
| 419 | format!( |
| 420 | "unsafe public advertise address {}; use a private overlay or \ |
| 421 | --unsafe-public-advertise", |
| 422 | node.addr |
| 423 | ), |
| 424 | ))?; |
| 425 | continue; |
| 426 | } |
| 427 | if let Err(error) = crate::peer_probe::probe(&http, &node, &auth).await { |
| 428 | failures += 1; |
| 429 | out.row(&Check::fail( |
| 430 | format!("peer {peer} at {}", node.addr), |
| 431 | format!("{error}"), |
| 432 | ))?; |
| 433 | continue; |
| 434 | } |
| 435 | let load_age_ms = if node.load.sampled_ms == 0 { |
| 436 | "unknown".to_string() |
| 437 | } else { |
| 438 | crate::ownership_store::now_ms() |
| 439 | .saturating_sub(node.load.sampled_ms) |
| 440 | .to_string() |
| 441 | }; |
| 442 | // A 1-byte RSS is the sentinel a platform without /proc leaves behind, |
| 443 | // not a measurement. Report it the way the load age already reports a |
| 444 | // missing sample, so no operator reads it as a real number. |
| 445 | let rss_bytes = if node.load.rss_bytes <= 1 { |
| 446 | "unknown".to_string() |
| 447 | } else { |
| 448 | node.load.rss_bytes.to_string() |
| 449 | }; |
| 450 | // The shedding decision reads the in-use figure, not the resident set |
| 451 | // size, so a diagnosis that prints only the latter cannot explain why |
| 452 | // a node sheds. A node from before this field reports nothing, which |
| 453 | // is not the same as zero. |
| 454 | let in_use_bytes = node |
| 455 | .load |
| 456 | .in_use_bytes |
| 457 | .map_or_else(|| "unknown".to_string(), |bytes| bytes.to_string()); |
| 458 | let owned_cells = node |
| 459 | .load |
| 460 | .owned_cells |
| 461 | .map_or_else(|| "unknown".to_string(), |cells| cells.to_string()); |
| 462 | out.row(&Check::ok( |
| 463 | format!("peer {} at {}", node.node, node.addr), |
| 464 | format!( |
| 465 | "(signed direct probe) protocol={} owned_cells={} resident_cells={} \ |
| 466 | websockets={} rss_bytes={} in_use_bytes={} cpu_percent={:.2} fds={}/{} \ |
| 467 | pressured={} shed_cells={} restoring={} load_age_ms={}", |
| 468 | node.peer_protocol, |
| 469 | owned_cells, |
| 470 | node.load.resident_cells, |
| 471 | node.load.host_websockets, |
| 472 | rss_bytes, |
| 473 | in_use_bytes, |
| 474 | node.load.cpu_percent_x100 as f64 / 100.0, |
| 475 | node.load.open_fds, |
| 476 | node.load.fd_limit, |
| 477 | node.load.pressured, |
| 478 | node.load.shed_cells, |
| 479 | node.load.restoring, |
| 480 | load_age_ms, |
| 481 | ), |
| 482 | ))?; |
| 483 | } |
| 484 | if expired > 0 { |
| 485 | out.row(&Check::ok( |
| 486 | "fleet", |
| 487 | format!("skipped {expired} expired node lease(s)"), |
| 488 | ))?; |
| 489 | } |
| 490 | if failures > 0 { |
| 491 | bail!("fleet diagnostics failed for {failures} peer(s)"); |
| 492 | } |
| 493 | Ok(()) |
| 494 | } |
| 495 | |
| 496 | pub(crate) async fn live_node_lease( |
| 497 | bucket: &Bucket, |
| 498 | peer: &str, |
| 499 | ) -> anyhow::Result<Option<NodeLeaseWire>> { |
| 500 | let key = format!("nodes/{peer}.json"); |
| 501 | let node: NodeLeaseWire = serde_json::from_str(&get_string(bucket, &key).await?) |
| 502 | .with_context(|| format!("decode {}://{}/{key}", bucket.scheme(), bucket.name))?; |
| 503 | if node.node != peer { |
| 504 | bail!( |
| 505 | "node lease {key} identifies unexpected node {:?}", |
| 506 | node.node |
| 507 | ); |
| 508 | } |
| 509 | if node.expires_ms <= crate::ownership_store::now_ms() { |
| 510 | return Ok(None); |
| 511 | } |
| 512 | if node.addr.is_empty() { |
| 513 | bail!("node {peer} lease has no advertised address"); |
| 514 | } |
| 515 | Ok(Some(node)) |
| 516 | } |
| 517 | |
| 518 | pub(crate) async fn node_lease_ids(bucket: &Bucket) -> anyhow::Result<Vec<String>> { |
| 519 | let mut nodes = Vec::new(); |
| 520 | for object in bucket |
| 521 | .list("nodes/") |
| 522 | .await |
| 523 | .context("enumerate node leases")? |
| 524 | { |
| 525 | let Some(node) = object |
| 526 | .location |
| 527 | .as_ref() |
| 528 | .strip_prefix("nodes/") |
| 529 | .and_then(|key| key.strip_suffix(".json")) |
| 530 | else { |
| 531 | continue; |
| 532 | }; |
| 533 | if !node.is_empty() { |
| 534 | nodes.push(node.to_string()); |
| 535 | } |
| 536 | } |
| 537 | nodes.sort(); |
| 538 | nodes.dedup(); |
| 539 | Ok(nodes) |
| 540 | } |
| 541 | |
| 542 | pub(crate) fn resolve_storage_location( |
| 543 | bucket: &mut Option<String>, |
| 544 | endpoint: &mut Option<String>, |
| 545 | region: Option<&str>, |
| 546 | ) -> String { |
| 547 | let env = |name: &str| { |
| 548 | std::env::var(name) |
| 549 | .ok() |
| 550 | .filter(|value| !value.trim().is_empty()) |
| 551 | }; |
| 552 | if bucket.is_none() { |
| 553 | *bucket = crate::cli_options::bucket_from_environment(); |
| 554 | } |
| 555 | if endpoint.is_none() { |
| 556 | *endpoint = env("S3_ENDPOINT"); |
| 557 | } |
| 558 | region |
| 559 | .map(str::to_string) |
| 560 | .or_else(|| env("AWS_REGION")) |
| 561 | .or_else(|| env("AWS_DEFAULT_REGION")) |
| 562 | .unwrap_or_else(|| "us-east-1".to_string()) |
| 563 | } |
| 564 | |
| 565 | #[cfg(all(test, celld_internal_tests))] |
| 566 | mod internal_tests { |
| 567 | include!(env!("CELLD_INTERNAL_FLEET_TESTS")); |
| 568 | } |
| 569 | |
| 570 | pub async fn run_deploy(arguments: Vec<String>) -> anyhow::Result<()> { |
| 571 | let Some(mut options) = deploy::options_from_arguments(arguments)? else { |
| 572 | deploy::print_help(); |
| 573 | return Ok(()); |
| 574 | }; |
| 575 | let region = resolve_storage_location( |
| 576 | &mut options.bucket, |
| 577 | &mut options.endpoint, |
| 578 | options.region.as_deref(), |
| 579 | ); |
| 580 | if !options.dry_run && options.bucket.is_none() { |
| 581 | bail!( |
| 582 | "celld deploy requires --bucket s3://NAME, gs://NAME or az://CONTAINER \ |
| 583 | (or CELLD_BUCKET)" |
| 584 | ); |
| 585 | } |
| 586 | let built = deploy::build(&options)?; |
| 587 | built.report(); |
| 588 | let mut out = Output::new(if options.json { |
| 589 | Format::Json |
| 590 | } else { |
| 591 | Format::Text |
| 592 | }); |
| 593 | if options.dry_run { |
| 594 | out.row(&Deployed { |
| 595 | worker: built.script_name.clone(), |
| 596 | version: built.version.clone(), |
| 597 | location: String::new(), |
| 598 | dry_run: true, |
| 599 | })?; |
| 600 | return out.finish(); |
| 601 | } |
| 602 | |
| 603 | let bucket = options.bucket.expect("validated deployment bucket"); |
| 604 | let store = bucket_client(&bucket, options.endpoint.as_deref(), ®ion)?; |
| 605 | validate_bucket(&store).await?; |
| 606 | crate::wake_format::ensure_ready(&store).await?; |
| 607 | let started = std::time::Instant::now(); |
| 608 | deploy::write(&store, &built).await?; |
| 609 | let location = format!( |
| 610 | "{}://{}/{}{}", |
| 611 | store.scheme(), |
| 612 | store.name, |
| 613 | store.prefix, |
| 614 | built.prefix |
| 615 | ); |
| 616 | note!( |
| 617 | "Uploaded {} ({:.2} sec)", |
| 618 | built.script_name, |
| 619 | started.elapsed().as_secs_f64() |
| 620 | ); |
| 621 | note!(" {location}"); |
| 622 | out.row(&Deployed { |
| 623 | worker: built.script_name.clone(), |
| 624 | version: built.version.clone(), |
| 625 | location, |
| 626 | dry_run: false, |
| 627 | })?; |
| 628 | note!("Nodes adopt this version at their next pointer poll, without a restart."); |
| 629 | out.finish() |
| 630 | } |
| 631 | |
| 632 | async fn get_string(bucket: &Bucket, key: &str) -> anyhow::Result<String> { |
| 633 | String::from_utf8(get_bytes(bucket, key).await?.into()) |
| 634 | .context("deployment module is not UTF-8") |
| 635 | } |
| 636 | |
| 637 | async fn get_bytes(bucket: &Bucket, key: &str) -> anyhow::Result<bytes::Bytes> { |
| 638 | let (bytes, _) = bucket.get(key).await?.with_context(|| { |
| 639 | format!( |
| 640 | "read {}://{}/{key}: no such key", |
| 641 | bucket.scheme(), |
| 642 | bucket.name |
| 643 | ) |
| 644 | })?; |
| 645 | Ok(bytes) |
| 646 | } |
| 647 | |
| 648 | /// The fleet-wide pointer: the bucket's only application commit point. |
| 649 | pub const CURRENT_POINTER_KEY: &str = "deploy/current.json"; |
| 650 | |
| 651 | pub async fn load_current_worker( |
| 652 | bucket: &Bucket, |
| 653 | node: String, |
| 654 | ) -> anyhow::Result<LoadedDeployment> { |
| 655 | load_worker_from_pointer(bucket, CURRENT_POINTER_KEY, node).await |
| 656 | } |
| 657 | |
| 658 | /// Block until the fleet-wide pointer exists, so a self-hosted node that |
| 659 | /// starts before its first `celld deploy` idles instead of exiting. |
| 660 | /// |
| 661 | /// The boot path reads `deploy/current.json` and treats "no such key" as |
| 662 | /// fatal, so a node started against an empty bucket exits and systemd |
| 663 | /// restarts it in a loop until a deployment appears. The pointer is the |
| 664 | /// authority, so the node waits for it and then serves it, with no |
| 665 | /// operator restart. A bucket or transport error still returns `Err`, so |
| 666 | /// a misconfigured bucket fails the boot rather than waiting forever. |
| 667 | pub async fn wait_for_deployment_pointer(bucket: &Bucket) -> anyhow::Result<()> { |
| 668 | let mut waited = false; |
| 669 | loop { |
| 670 | if bucket.get(CURRENT_POINTER_KEY).await?.is_some() { |
| 671 | if waited { |
| 672 | tracing::info!(event = "initial_deployment_found"); |
| 673 | } |
| 674 | return Ok(()); |
| 675 | } |
| 676 | if !waited { |
| 677 | waited = true; |
| 678 | tracing::info!( |
| 679 | event = "awaiting_initial_deployment", |
| 680 | "no deployment yet; run `celld deploy` and the node serves it \ |
| 681 | without a restart" |
| 682 | ); |
| 683 | } |
| 684 | tokio::time::sleep(std::time::Duration::from_secs(2)).await; |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | /// Read the fleet-wide pointer without loading what it names. The watcher |
| 689 | /// compares it with the serving generation before it loads anything. |
| 690 | pub async fn read_current_pointer(bucket: &Bucket) -> anyhow::Result<DeployPointer> { |
| 691 | serde_json::from_str(&get_string(bucket, CURRENT_POINTER_KEY).await?) |
| 692 | .with_context(|| format!("decode {CURRENT_POINTER_KEY}")) |
| 693 | } |
| 694 | |
| 695 | pub async fn load_named_worker( |
| 696 | bucket: &Bucket, |
| 697 | script: &str, |
| 698 | node: String, |
| 699 | ) -> anyhow::Result<LoadedDeployment> { |
| 700 | load_worker_from_pointer(bucket, &format!("deploy/{script}/current.json"), node).await |
| 701 | } |
| 702 | |
| 703 | pub async fn load_queue_consumer_attachment( |
| 704 | bucket: &Bucket, |
| 705 | queue: &str, |
| 706 | ) -> anyhow::Result<Option<crate::protocol::QueueConsumerDeployment>> { |
| 707 | let key = crate::protocol::queue_consumer_attachment_key(queue) |
| 708 | .with_context(|| format!("invalid queue name {queue:?} in deployment manifest"))?; |
| 709 | let Some((body, _)) = bucket.get(&key).await? else { |
| 710 | return Ok(None); |
| 711 | }; |
| 712 | let attachment: crate::protocol::QueueConsumerAttachment = serde_json::from_slice(&body) |
| 713 | .with_context(|| format!("decode queue consumer attachment {key}"))?; |
| 714 | crate::protocol::validate_queue_consumer_attachment(queue, &attachment)?; |
| 715 | Ok(attachment.consumer) |
| 716 | } |
| 717 | |
| 718 | pub async fn load_queue_consumer_worker( |
| 719 | bucket: &Bucket, |
| 720 | queue: &str, |
| 721 | consumer: &crate::protocol::QueueConsumerDeployment, |
| 722 | node: String, |
| 723 | ) -> anyhow::Result<LoadedDeployment> { |
| 724 | let pointer = DeployPointer { |
| 725 | script_name: Some(consumer.script_name.clone()), |
| 726 | version: consumer.version.clone(), |
| 727 | prefix: consumer.prefix.clone(), |
| 728 | rollout: Rollout { percent: 100 }, |
| 729 | }; |
| 730 | let pointer_key = format!("deploy/{}/current.json", consumer.script_name); |
| 731 | let loaded = load_worker_at_pointer(bucket, pointer, &pointer_key, node).await?; |
| 732 | anyhow::ensure!( |
| 733 | loaded |
| 734 | .options |
| 735 | .queue_consumers |
| 736 | .iter() |
| 737 | .any(|config| config.queue == queue), |
| 738 | "queue {queue:?} attachment resolved deployment {} of script {:?}, which does not consume that queue", |
| 739 | consumer.version, |
| 740 | consumer.script_name |
| 741 | ); |
| 742 | Ok(loaded) |
| 743 | } |
| 744 | |
| 745 | async fn load_worker_from_pointer( |
| 746 | bucket: &Bucket, |
| 747 | pointer_key: &str, |
| 748 | node: String, |
| 749 | ) -> anyhow::Result<LoadedDeployment> { |
| 750 | let pointer: DeployPointer = serde_json::from_str(&get_string(bucket, pointer_key).await?) |
| 751 | .with_context(|| format!("decode {pointer_key}"))?; |
| 752 | load_worker_at_pointer(bucket, pointer, pointer_key, node).await |
| 753 | } |
| 754 | |
| 755 | async fn load_worker_at_pointer( |
| 756 | bucket: &Bucket, |
| 757 | pointer: DeployPointer, |
| 758 | pointer_key: &str, |
| 759 | node: String, |
| 760 | ) -> anyhow::Result<LoadedDeployment> { |
| 761 | let manifest: Manifest = serde_json::from_str( |
| 762 | &get_string(bucket, &format!("{}/manifest.json", pointer.prefix)).await?, |
| 763 | ) |
| 764 | .context("decode deployment manifest")?; |
| 765 | anyhow::ensure!( |
| 766 | manifest.version == pointer.version, |
| 767 | "deployment pointer for version {:?} resolved manifest version {:?}", |
| 768 | pointer.version, |
| 769 | manifest.version |
| 770 | ); |
| 771 | if let Some(script_name) = &pointer.script_name { |
| 772 | anyhow::ensure!( |
| 773 | manifest.script_name == *script_name, |
| 774 | "deployment pointer for script {script_name:?} resolved script {:?}", |
| 775 | manifest.script_name |
| 776 | ); |
| 777 | } |
| 778 | crate::protocol::validate_required_features(&manifest.required_features)?; |
| 779 | crate::protocol::validate_queue_manifest(&manifest)?; |
| 780 | // Old managed uploads can contain AI metadata without a required-feature |
| 781 | // gate. Refuse it before loading code, rather than serve a missing binding. |
| 782 | anyhow::ensure!( |
| 783 | bindings(&manifest, "ai").next().is_none(), |
| 784 | "AI bindings are not supported; call the provider from application code" |
| 785 | ); |
| 786 | let prefix = &pointer.prefix; |
| 787 | let mut fetched = |
| 788 | futures_util::future::try_join_all(manifest.modules.iter().map(|module| async move { |
| 789 | let key = format!("{prefix}/{}", module.name); |
| 790 | let bytes = get_bytes(bucket, &key).await?; |
| 791 | module.verify(&bytes)?; |
| 792 | anyhow::Ok((module, bytes)) |
| 793 | })) |
| 794 | .await?; |
| 795 | let src = match manifest.main_module.as_deref() { |
| 796 | Some(main) => { |
| 797 | let position = fetched |
| 798 | .iter() |
| 799 | .position(|(module, _)| module.name == main) |
| 800 | .with_context(|| { |
| 801 | format!("main module {main:?} is absent from the manifest module list") |
| 802 | })?; |
| 803 | let (_, bytes) = fetched.remove(position); |
| 804 | String::from_utf8(bytes.into()).context("deployment main module is not UTF-8")? |
| 805 | } |
| 806 | None if manifest.assets.is_some() => { |
| 807 | // Ingress is handled by the immutable asset resolver. Keeping a |
| 808 | // synthetic Worker makes the runtime construction path uniform |
| 809 | // and is a fail-closed guard if an asset-only request escapes it. |
| 810 | "export default { fetch() { return new Response('Not found', { status: 404 }); } };" |
| 811 | .to_string() |
| 812 | } |
| 813 | None => bail!("deployment has neither a main module nor assets"), |
| 814 | }; |
| 815 | let mut modules = Vec::new(); |
| 816 | for (module, bytes) in fetched { |
| 817 | let entry = match module.kind { |
| 818 | Some(ModuleKind::Wasm) => (module.name.clone(), ModuleSource::Wasm(bytes)), |
| 819 | None => ( |
| 820 | format!("./{}", module.name), |
| 821 | ModuleSource::Text( |
| 822 | String::from_utf8(bytes.into()).context("deployment module is not UTF-8")?, |
| 823 | ), |
| 824 | ), |
| 825 | }; |
| 826 | modules.push(entry); |
| 827 | } |
| 828 | let do_bindings = bindings(&manifest, "durable_object_namespace") |
| 829 | .filter_map(|binding| { |
| 830 | Some(( |
| 831 | binding.get("name")?.as_str()?.to_string(), |
| 832 | binding.get("class_name")?.as_str()?.to_string(), |
| 833 | )) |
| 834 | }) |
| 835 | .collect(); |
| 836 | // (env name, bucket name). The bucket name is the key space the |
| 837 | // binding owns inside the fleet bucket; see [[r2]]. |
| 838 | let r2_bindings = bindings(&manifest, "r2_bucket") |
| 839 | .filter_map(|binding| { |
| 840 | Some(( |
| 841 | binding.get("name")?.as_str()?.to_string(), |
| 842 | binding.get("bucket_name")?.as_str()?.to_string(), |
| 843 | )) |
| 844 | }) |
| 845 | .collect(); |
| 846 | // (env name, stable database identity). A Cloudflare database_id survives |
| 847 | // Worker renames and lets several Workers share the resource. A celld-only |
| 848 | // config without one falls back to the database name. |
| 849 | let d1_bindings = bindings(&manifest, "d1") |
| 850 | .filter_map(|binding| { |
| 851 | Some(( |
| 852 | binding.get("name")?.as_str()?.to_string(), |
| 853 | binding |
| 854 | .get("database_id") |
| 855 | .or_else(|| binding.get("database_name"))? |
| 856 | .as_str()? |
| 857 | .to_string(), |
| 858 | )) |
| 859 | }) |
| 860 | .collect(); |
| 861 | // (env name, namespace identity). The identity is the config's `id` |
| 862 | // verbatim: upstream's `kv_namespaces` has no human-readable name field, so |
| 863 | // there is no second key to fall back to and none is invented. |
| 864 | let kv_bindings = bindings(&manifest, "kv") |
| 865 | .filter_map(|binding| { |
| 866 | Some(( |
| 867 | binding.get("name")?.as_str()?.to_string(), |
| 868 | binding.get("id")?.as_str()?.to_string(), |
| 869 | )) |
| 870 | }) |
| 871 | .collect(); |
| 872 | let queue_bindings = bindings(&manifest, "queue") |
| 873 | .filter_map(|binding| { |
| 874 | Some(crate::js::QueueBinding { |
| 875 | environment: binding.get("name")?.as_str()?.to_string(), |
| 876 | queue: binding.get("queue")?.as_str()?.to_string(), |
| 877 | delivery_delay: binding |
| 878 | .get("delivery_delay") |
| 879 | .and_then(serde_json::Value::as_u64) |
| 880 | .and_then(|value| u32::try_from(value).ok()) |
| 881 | .unwrap_or(0), |
| 882 | }) |
| 883 | }) |
| 884 | .collect(); |
| 885 | let workflow_bindings = bindings(&manifest, "workflow") |
| 886 | .filter_map(|binding| { |
| 887 | Some(crate::js::WorkflowBinding { |
| 888 | environment: binding.get("name")?.as_str()?.to_string(), |
| 889 | workflow: binding.get("workflow_name")?.as_str()?.to_string(), |
| 890 | class: binding.get("class_name")?.as_str()?.to_string(), |
| 891 | }) |
| 892 | }) |
| 893 | .collect(); |
| 894 | // The `worker_loaders` key of the deployed config. Every entry becomes a |
| 895 | // binding of its own, because each loader caches the Workers it loaded. |
| 896 | let loader_bindings = bindings(&manifest, "worker_loader") |
| 897 | .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string)) |
| 898 | .collect(); |
| 899 | let services = service_bindings(&manifest); |
| 900 | let vars = worker_vars(&manifest); |
| 901 | let compat = crate::worker_compat(&manifest.raw_metadata); |
| 902 | let assets = match &manifest.assets { |
| 903 | Some(reference) => Some( |
| 904 | crate::assets::AssetResolver::load( |
| 905 | bucket, |
| 906 | &pointer.prefix, |
| 907 | reference, |
| 908 | manifest.main_module.is_none(), |
| 909 | // The resolver can consult this pointer again later: a |
| 910 | // rolling restart serves new HTML from upgraded nodes while |
| 911 | // this process still holds the boot index, and the fallback |
| 912 | // is what keeps the new content-hashed assets servable |
| 913 | // everywhere (denoland/celld#161). |
| 914 | Some(crate::assets::FallbackSource { |
| 915 | pointer_key: pointer_key.to_string(), |
| 916 | boot_prefix: pointer.prefix.clone(), |
| 917 | }), |
| 918 | ) |
| 919 | .await?, |
| 920 | ), |
| 921 | None => None, |
| 922 | }; |
| 923 | let asset_binding = assets |
| 924 | .as_ref() |
| 925 | .and_then(crate::assets::AssetResolver::binding_name) |
| 926 | .map(str::to_string); |
| 927 | let script_name = manifest.script_name.clone(); |
| 928 | let version = manifest.version.clone(); |
| 929 | let prefix = pointer.prefix.clone(); |
| 930 | let crons = manifest.crons.clone(); |
| 931 | let containers = manifest.containers.clone(); |
| 932 | let fence_image = manifest.fence_image.clone(); |
| 933 | Ok(LoadedDeployment { |
| 934 | options: WorkerConfigOptions { |
| 935 | src, |
| 936 | script_name: script_name.clone(), |
| 937 | do_classes: manifest.do_classes, |
| 938 | bindings: do_bindings, |
| 939 | r2_bindings, |
| 940 | d1_bindings, |
| 941 | kv_bindings, |
| 942 | queue_bindings, |
| 943 | queue_consumers: manifest.queue_consumers, |
| 944 | workflow_bindings, |
| 945 | vars, |
| 946 | node, |
| 947 | modules, |
| 948 | compat, |
| 949 | }, |
| 950 | script_name, |
| 951 | version, |
| 952 | prefix, |
| 953 | asset_binding, |
| 954 | loader_bindings, |
| 955 | assets, |
| 956 | services, |
| 957 | crons, |
| 958 | containers, |
| 959 | fence_image, |
| 960 | }) |
| 961 | } |
| 962 | |
| 963 | pub struct LoadedDeployment { |
| 964 | pub options: WorkerConfigOptions, |
| 965 | pub script_name: String, |
| 966 | pub version: String, |
| 967 | pub prefix: String, |
| 968 | pub asset_binding: Option<String>, |
| 969 | /// `env` names of this script's Worker Loaders, from its |
| 970 | /// `worker_loaders` config. A script reaches no loader that it does not |
| 971 | /// declare, and each loader keeps a cache of its own loaded Workers. |
| 972 | pub loader_bindings: Vec<String>, |
| 973 | pub assets: Option<crate::assets::AssetResolver>, |
| 974 | pub services: Vec<(String, String, Option<String>)>, |
| 975 | /// `triggers.crons` from the manifest, driving the reserved cron cell. |
| 976 | pub crons: Vec<String>, |
| 977 | /// `containers` from the manifest: the classes whose cells supervise a |
| 978 | /// container. |
| 979 | pub containers: Vec<crate::container::ContainerSpec>, |
| 980 | /// See `Manifest::fence_image`. |
| 981 | pub fence_image: Option<String>, |
| 982 | } |
| 983 | |
| 984 | fn bindings<'a>( |
| 985 | manifest: &'a Manifest, |
| 986 | kind: &'a str, |
| 987 | ) -> impl Iterator<Item = &'a serde_json::Value> { |
| 988 | manifest |
| 989 | .raw_metadata |
| 990 | .get("bindings") |
| 991 | .and_then(serde_json::Value::as_array) |
| 992 | .into_iter() |
| 993 | .flatten() |
| 994 | .filter(move |binding| { |
| 995 | binding.get("type").and_then(serde_json::Value::as_str) == Some(kind) |
| 996 | }) |
| 997 | } |
| 998 | |
| 999 | fn service_bindings(manifest: &Manifest) -> Vec<(String, String, Option<String>)> { |
| 1000 | bindings(manifest, "service") |
| 1001 | .filter_map(|binding| { |
| 1002 | Some(( |
| 1003 | binding.get("name")?.as_str()?.to_string(), |
| 1004 | binding.get("service")?.as_str()?.to_string(), |
| 1005 | binding |
| 1006 | .get("entrypoint") |
| 1007 | .and_then(serde_json::Value::as_str) |
| 1008 | .map(str::to_string), |
| 1009 | )) |
| 1010 | }) |
| 1011 | .collect() |
| 1012 | } |
| 1013 | |
| 1014 | fn worker_vars(manifest: &Manifest) -> Vec<(String, String)> { |
| 1015 | bindings(manifest, "plain_text") |
| 1016 | .filter_map(|binding| { |
| 1017 | Some(( |
| 1018 | binding.get("name")?.as_str()?.to_string(), |
| 1019 | binding.get("text")?.as_str()?.to_string(), |
| 1020 | )) |
| 1021 | }) |
| 1022 | .collect() |
| 1023 | } |