| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Durable types on the bucket contract between deployment tools and celld. |
| 4 | //! These objects are the interface; nothing else is exchanged. |
| 5 | use anyhow::Context; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use sha2::Digest; |
| 8 | use sha2::Sha256; |
| 9 | use std::collections::BTreeMap; |
| 10 | |
| 11 | /// `deploy/<script>/<version>/manifest.json` — the normalized thing celld reads |
| 12 | /// to know what to run. The script name is deployment identity, not a fleet |
| 13 | /// selector: one fleet has one current application. |
| 14 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 15 | pub struct Manifest { |
| 16 | #[serde(default = "legacy_manifest_schema_version")] |
| 17 | pub schema_version: u32, |
| 18 | pub version: String, |
| 19 | pub script_name: String, |
| 20 | /// Absent for Wrangler asset-only deployments. |
| 21 | pub main_module: Option<String>, |
| 22 | /// Durable Object classes exported by the worker. |
| 23 | pub do_classes: Vec<String>, |
| 24 | /// Subset of `do_classes` that are SQLite-backed (from migrations). |
| 25 | pub sqlite_classes: Vec<String>, |
| 26 | pub modules: Vec<ModuleRef>, |
| 27 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 28 | pub assets: Option<AssetManifestRef>, |
| 29 | /// Cron trigger expressions from the config's `triggers.crons`. They are |
| 30 | /// deployment state rather than cell state: the reserved cron cell reads |
| 31 | /// them from the manifest it is running under, so changing a schedule |
| 32 | /// needs no migration of an already-armed alarm. |
| 33 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 34 | pub crons: Vec<String>, |
| 35 | /// Push consumers attached to this Worker deployment. Producer bindings |
| 36 | /// remain in `raw_metadata.bindings`, because they become values in `env`; |
| 37 | /// consumers drive the broker and have no environment binding. |
| 38 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 39 | pub queue_consumers: Vec<QueueConsumerConfig>, |
| 40 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 41 | pub required_features: Vec<String>, |
| 42 | /// wrangler's raw metadata, retained verbatim for anything we don't yet model. |
| 43 | pub raw_metadata: serde_json::Value, |
| 44 | } |
| 45 | |
| 46 | fn legacy_manifest_schema_version() -> u32 { |
| 47 | 1 |
| 48 | } |
| 49 | |
| 50 | /// Manifest `required_features` values this build can load. A manifest |
| 51 | /// requiring anything else must be rejected up front: `ModuleRef` tolerates |
| 52 | /// unknown fields, so an older node would otherwise deserialize the manifest |
| 53 | /// partially and fail (or misbehave) at worker load instead. |
| 54 | pub const SUPPORTED_DEPLOYMENT_FEATURES: &[&str] = &[ |
| 55 | FEATURE_ASSETS_V1, |
| 56 | FEATURE_CRON_V1, |
| 57 | FEATURE_D1_V1, |
| 58 | FEATURE_KV_V1, |
| 59 | FEATURE_QUEUES_V1, |
| 60 | FEATURE_SQLITE_VEC_V1, |
| 61 | FEATURE_R2_V1, |
| 62 | FEATURE_WASM_V1, |
| 63 | FEATURE_WORKFLOWS_V1, |
| 64 | ]; |
| 65 | |
| 66 | pub const FEATURE_ASSETS_V1: &str = "assets-v1"; |
| 67 | /// A deployment with D1 databases. Required because a build without the |
| 68 | /// reserved `__D1Database` class would load the manifest and then fail every |
| 69 | /// `env.DB` call at request time, on a node the developer is not watching — |
| 70 | /// the gate moves that failure to the deploy. |
| 71 | pub const FEATURE_D1_V1: &str = "d1-v1"; |
| 72 | /// A deployment with cron triggers. Required because a build without the |
| 73 | /// reserved cron cell would load the manifest, ignore `crons`, and silently |
| 74 | /// never fire — the quiet failure the gate exists to prevent. |
| 75 | pub const FEATURE_CRON_V1: &str = "cron-v1"; |
| 76 | /// A deployment with `r2_buckets` bindings. Required because a build without |
| 77 | /// the R2 binding would load the manifest and then throw on every method the |
| 78 | /// application calls, at request time, on a node the developer is not |
| 79 | /// watching — the gate moves that failure to the deploy. |
| 80 | pub const FEATURE_R2_V1: &str = "r2-v1"; |
| 81 | pub const FEATURE_SQLITE_VEC_V1: &str = "sqlite-vec-v1"; |
| 82 | pub const FEATURE_WASM_V1: &str = "wasm-v1"; |
| 83 | /// A deployment with `workflows` bindings. Required because a build without |
| 84 | /// the reserved workflow cell would load the manifest, build an `env` missing |
| 85 | /// the binding, and fail only when the application first calls `create()` — |
| 86 | /// in production, with an error that blames the application. |
| 87 | pub const FEATURE_WORKFLOWS_V1: &str = "workflows-v1"; |
| 88 | |
| 89 | /// A deployment with `kv_namespaces` bindings. Gated for the same reason |
| 90 | /// workflows are, and not for D1's reason: a build without KV would load the |
| 91 | /// manifest, build an `env` with no `KV` on it, and fail only when the |
| 92 | /// application first reads a key. D1's absence fails loudly at load instead, |
| 93 | /// because its reserved class is in `do_classes` and the loader refuses a |
| 94 | /// class it does not know. |
| 95 | pub const FEATURE_KV_V1: &str = "kv-v1"; |
| 96 | |
| 97 | /// A deployment with a Queue producer or consumer. A node without the broker |
| 98 | /// would otherwise omit a producer binding or silently stop consuming. |
| 99 | pub const FEATURE_QUEUES_V1: &str = "queues-v1"; |
| 100 | |
| 101 | pub const QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION: u32 = 1; |
| 102 | |
| 103 | /// `deploy/queues/<queue>/consumer.json` — the one deployment allowed to |
| 104 | /// consume a fleet-global queue. The record keeps an exact deployment |
| 105 | /// reference, because the script's named pointer can move independently |
| 106 | /// between the attachment read and the Worker load. |
| 107 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 108 | pub struct QueueConsumerAttachment { |
| 109 | pub schema_version: u32, |
| 110 | pub queue: String, |
| 111 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 112 | pub consumer: Option<QueueConsumerDeployment>, |
| 113 | } |
| 114 | |
| 115 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 116 | pub struct QueueConsumerDeployment { |
| 117 | pub script_name: String, |
| 118 | pub version: String, |
| 119 | pub prefix: String, |
| 120 | } |
| 121 | |
| 122 | pub fn queue_consumer_attachment_key(queue: &str) -> Option<String> { |
| 123 | celld_logic::cell::valid_cell_scope(queue) |
| 124 | .then(|| format!("deploy/queues/{queue}/consumer.json")) |
| 125 | } |
| 126 | |
| 127 | pub fn validate_queue_consumer_attachment( |
| 128 | expected_queue: &str, |
| 129 | attachment: &QueueConsumerAttachment, |
| 130 | ) -> anyhow::Result<()> { |
| 131 | anyhow::ensure!( |
| 132 | attachment.schema_version == QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION, |
| 133 | "queue consumer attachment for {expected_queue:?} has unsupported schema version {}", |
| 134 | attachment.schema_version |
| 135 | ); |
| 136 | anyhow::ensure!( |
| 137 | attachment.queue == expected_queue, |
| 138 | "queue consumer attachment for {expected_queue:?} names queue {:?}", |
| 139 | attachment.queue |
| 140 | ); |
| 141 | if let Some(consumer) = &attachment.consumer { |
| 142 | anyhow::ensure!( |
| 143 | !consumer.script_name.is_empty() |
| 144 | && !consumer.version.is_empty() |
| 145 | && consumer.prefix |
| 146 | == format!("deploy/{}/{}", consumer.script_name, consumer.version), |
| 147 | "queue consumer attachment for {expected_queue:?} has an invalid deployment reference" |
| 148 | ); |
| 149 | } |
| 150 | Ok(()) |
| 151 | } |
| 152 | |
| 153 | /// The normalized push-consumer settings stored in a deployment manifest. |
| 154 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 155 | pub struct QueueConsumerConfig { |
| 156 | pub queue: String, |
| 157 | pub max_batch_size: u16, |
| 158 | pub max_batch_timeout: u16, |
| 159 | pub max_retries: u16, |
| 160 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 161 | pub dead_letter_queue: Option<String>, |
| 162 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 163 | pub max_concurrency: Option<u16>, |
| 164 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 165 | pub retry_delay: Option<u32>, |
| 166 | } |
| 167 | |
| 168 | /// Validate every Queue value before a deployment becomes runtime state. |
| 169 | /// |
| 170 | /// A native deploy validates its source configuration before it writes a |
| 171 | /// manifest. A managed deploy has a separate TypeScript producer, so the node |
| 172 | /// repeats the authoritative checks from `celld-logic` when it loads either |
| 173 | /// manifest. This prevents a malformed producer from becoming a missing |
| 174 | /// binding and prevents an invalid consumer policy from reaching the broker. |
| 175 | #[doc(hidden)] |
| 176 | pub fn validate_queue_manifest(manifest: &Manifest) -> anyhow::Result<()> { |
| 177 | let queue_bindings = manifest |
| 178 | .raw_metadata |
| 179 | .get("bindings") |
| 180 | .and_then(serde_json::Value::as_array) |
| 181 | .into_iter() |
| 182 | .flatten() |
| 183 | .filter(|binding| binding.get("type").and_then(serde_json::Value::as_str) == Some("queue")) |
| 184 | .collect::<Vec<_>>(); |
| 185 | if queue_bindings.is_empty() && manifest.queue_consumers.is_empty() { |
| 186 | return Ok(()); |
| 187 | } |
| 188 | |
| 189 | anyhow::ensure!( |
| 190 | manifest |
| 191 | .required_features |
| 192 | .iter() |
| 193 | .any(|feature| feature == FEATURE_QUEUES_V1), |
| 194 | "Queue deployment does not require {FEATURE_QUEUES_V1}" |
| 195 | ); |
| 196 | anyhow::ensure!( |
| 197 | manifest |
| 198 | .do_classes |
| 199 | .iter() |
| 200 | .any(|class| class == celld_logic::queue::RESERVED_CLASS) |
| 201 | && manifest |
| 202 | .sqlite_classes |
| 203 | .iter() |
| 204 | .any(|class| class == celld_logic::queue::RESERVED_CLASS), |
| 205 | "Queue deployment does not install the reserved SQLite Queue class" |
| 206 | ); |
| 207 | |
| 208 | for binding in queue_bindings { |
| 209 | let environment = binding |
| 210 | .get("name") |
| 211 | .and_then(serde_json::Value::as_str) |
| 212 | .filter(|name| valid_binding_name(name)) |
| 213 | .context("Queue binding has an invalid environment name")?; |
| 214 | let queue = binding |
| 215 | .get("queue") |
| 216 | .and_then(serde_json::Value::as_str) |
| 217 | .filter(|queue| celld_logic::cell::valid_cell_scope(queue)) |
| 218 | .with_context(|| format!("Queue binding {environment:?} has an invalid queue name"))?; |
| 219 | let delivery_delay_seconds = match binding.get("delivery_delay") { |
| 220 | None => 0, |
| 221 | Some(value) => value |
| 222 | .as_u64() |
| 223 | .and_then(|value| u32::try_from(value).ok()) |
| 224 | .with_context(|| { |
| 225 | format!("Queue binding {environment:?} has an invalid delivery_delay") |
| 226 | })?, |
| 227 | }; |
| 228 | celld_logic::queue::validate_config(&celld_logic::queue::QueueConfig { |
| 229 | max_batch_size: celld_logic::queue::DEFAULT_MAX_BATCH_SIZE, |
| 230 | max_batch_timeout_seconds: celld_logic::queue::DEFAULT_MAX_BATCH_TIMEOUT_SECONDS, |
| 231 | max_retries: celld_logic::queue::DEFAULT_MAX_RETRIES, |
| 232 | max_concurrency: None, |
| 233 | delivery_delay_seconds, |
| 234 | retry_delay_seconds: None, |
| 235 | }) |
| 236 | .map_err(anyhow::Error::new) |
| 237 | .with_context(|| format!("Queue binding {environment:?} for {queue:?} is invalid"))?; |
| 238 | } |
| 239 | |
| 240 | anyhow::ensure!( |
| 241 | manifest.queue_consumers.is_empty() || manifest.main_module.is_some(), |
| 242 | "Queue consumer deployment has no Worker module" |
| 243 | ); |
| 244 | let mut consumed = std::collections::BTreeSet::new(); |
| 245 | for consumer in &manifest.queue_consumers { |
| 246 | anyhow::ensure!( |
| 247 | celld_logic::cell::valid_cell_scope(&consumer.queue), |
| 248 | "Queue consumer has an invalid queue name {:?}", |
| 249 | consumer.queue |
| 250 | ); |
| 251 | anyhow::ensure!( |
| 252 | consumed.insert(&consumer.queue), |
| 253 | "Queue consumer deployment repeats queue {:?}", |
| 254 | consumer.queue |
| 255 | ); |
| 256 | if let Some(dead_letter_queue) = &consumer.dead_letter_queue { |
| 257 | anyhow::ensure!( |
| 258 | celld_logic::cell::valid_cell_scope(dead_letter_queue) |
| 259 | && dead_letter_queue != &consumer.queue, |
| 260 | "Queue consumer for {:?} has an invalid dead-letter queue {:?}", |
| 261 | consumer.queue, |
| 262 | dead_letter_queue |
| 263 | ); |
| 264 | } |
| 265 | celld_logic::queue::validate_config(&celld_logic::queue::QueueConfig { |
| 266 | max_batch_size: consumer.max_batch_size, |
| 267 | max_batch_timeout_seconds: consumer.max_batch_timeout, |
| 268 | max_retries: consumer.max_retries, |
| 269 | max_concurrency: consumer.max_concurrency, |
| 270 | delivery_delay_seconds: 0, |
| 271 | retry_delay_seconds: consumer.retry_delay, |
| 272 | }) |
| 273 | .map_err(anyhow::Error::new) |
| 274 | .with_context(|| format!("Queue consumer for {:?} is invalid", consumer.queue))?; |
| 275 | } |
| 276 | Ok(()) |
| 277 | } |
| 278 | |
| 279 | fn valid_binding_name(name: &str) -> bool { |
| 280 | name.len() <= 128 |
| 281 | && name |
| 282 | .chars() |
| 283 | .next() |
| 284 | .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic()) |
| 285 | && name |
| 286 | .chars() |
| 287 | .skip(1) |
| 288 | .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric()) |
| 289 | } |
| 290 | |
| 291 | /// Reject a manifest requiring any feature this build does not support. Both |
| 292 | /// load paths (control-plane deployments and fleet pointer loads) must apply |
| 293 | /// the same gate, so it lives here beside the feature list. |
| 294 | pub fn validate_required_features(required: &[String]) -> anyhow::Result<()> { |
| 295 | for feature in required { |
| 296 | if !SUPPORTED_DEPLOYMENT_FEATURES.contains(&feature.as_str()) { |
| 297 | anyhow::bail!( |
| 298 | "deployment requires feature {feature:?} this celld build does not support; upgrade celld" |
| 299 | ); |
| 300 | } |
| 301 | } |
| 302 | Ok(()) |
| 303 | } |
| 304 | |
| 305 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 306 | pub struct ModuleRef { |
| 307 | pub name: String, |
| 308 | pub bytes: usize, |
| 309 | /// content hash of this module's bytes (hex, truncated) |
| 310 | pub sha256: String, |
| 311 | /// Absent means UTF-8 source: the main module is ESM, siblings become |
| 312 | /// text modules. `wasm` bytes become a module whose default export is a |
| 313 | /// compiled `WebAssembly.Module` (Wrangler's `CompiledWasm` rule). |
| 314 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 315 | pub kind: Option<ModuleKind>, |
| 316 | } |
| 317 | |
| 318 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 319 | #[serde(rename_all = "lowercase")] |
| 320 | pub enum ModuleKind { |
| 321 | Wasm, |
| 322 | } |
| 323 | |
| 324 | /// Reference from a deploy manifest to its immutable, canonical asset index. |
| 325 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 326 | pub struct AssetManifestRef { |
| 327 | pub index: String, |
| 328 | pub sha256: String, |
| 329 | pub file_count: u32, |
| 330 | pub total_bytes: u64, |
| 331 | } |
| 332 | |
| 333 | /// `deploy/<script>/<version>/assets.json`. |
| 334 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] |
| 335 | pub struct AssetIndex { |
| 336 | pub schema_version: u32, |
| 337 | pub entries: BTreeMap<String, AssetEntry>, |
| 338 | pub config: AssetConfig, |
| 339 | } |
| 340 | |
| 341 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 342 | pub struct AssetEntry { |
| 343 | /// Full SHA-256 of the exact response body, lowercase hexadecimal. |
| 344 | pub sha256: String, |
| 345 | pub bytes: u64, |
| 346 | /// `None` means omit Content-Type, matching Wrangler's `application/null`. |
| 347 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 348 | pub content_type: Option<String>, |
| 349 | } |
| 350 | |
| 351 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 352 | pub struct AssetConfig { |
| 353 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 354 | pub binding: Option<String>, |
| 355 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 356 | pub html_handling: Option<String>, |
| 357 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 358 | pub not_found_handling: Option<String>, |
| 359 | #[serde(default)] |
| 360 | pub run_worker_first: RunWorkerFirst, |
| 361 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 362 | pub headers: Option<String>, |
| 363 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 364 | pub redirects: Option<String>, |
| 365 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 366 | pub compatibility_date: Option<String>, |
| 367 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 368 | pub compatibility_flags: Vec<String>, |
| 369 | } |
| 370 | |
| 371 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 372 | #[serde(untagged)] |
| 373 | pub enum RunWorkerFirst { |
| 374 | Bool(bool), |
| 375 | Routes(Vec<String>), |
| 376 | } |
| 377 | |
| 378 | impl Default for RunWorkerFirst { |
| 379 | fn default() -> Self { |
| 380 | Self::Bool(false) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | /// A fleet-wide immutable asset body key. The digest is validated before this |
| 385 | /// is called by the receiver and again by the applying node. |
| 386 | pub fn asset_blob_key(sha256: &str) -> Option<String> { |
| 387 | if sha256.len() != 64 |
| 388 | || !sha256 |
| 389 | .bytes() |
| 390 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 391 | { |
| 392 | return None; |
| 393 | } |
| 394 | Some(format!( |
| 395 | "deploy-blobs/assets/sha256/{}/{}", |
| 396 | &sha256[..2], |
| 397 | sha256 |
| 398 | )) |
| 399 | } |
| 400 | |
| 401 | /// `deploy/current.json` — the fleet-wide pointer a node reads on startup. |
| 402 | /// Changing this is a deploy; nodes converge to it. |
| 403 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 404 | pub struct DeployPointer { |
| 405 | /// Present on fleet-wide pointers. Older named pointers omit it. |
| 406 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 407 | pub script_name: Option<String>, |
| 408 | pub version: String, |
| 409 | pub prefix: String, |
| 410 | pub rollout: Rollout, |
| 411 | } |
| 412 | |
| 413 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 414 | pub struct Rollout { |
| 415 | pub percent: u8, |
| 416 | } |
| 417 | |
| 418 | /// Deployment identity: sorted module contents plus the serialized metadata, |
| 419 | /// never the raw upload framing (which is not deterministic). Every sender |
| 420 | /// must agree on this or identical code deploys as two versions depending on |
| 421 | /// the path used. |
| 422 | /// |
| 423 | /// `metadata_json` is the exact byte serialization the sender stores as |
| 424 | /// `Manifest::raw_metadata`; callers pass the same bytes to both. |
| 425 | /// Cron trigger expressions are deliberately NOT an input. A version names |
| 426 | /// the code and its bindings; a schedule is configuration layered on top, |
| 427 | /// which is also how Cloudflare models it — schedules are their own resource, |
| 428 | /// set by their own API call after the script upload. Hashing them would make |
| 429 | /// the native and managed paths disagree about what a version is. |
| 430 | pub fn deployment_version( |
| 431 | modules: &[(String, Vec<u8>)], |
| 432 | metadata_json: &[u8], |
| 433 | asset_index: Option<&[u8]>, |
| 434 | ) -> String { |
| 435 | let mut sorted = modules.iter().collect::<Vec<_>>(); |
| 436 | sorted.sort_by(|left, right| left.0.cmp(&right.0)); |
| 437 | let mut hasher = Sha256::new(); |
| 438 | for (name, bytes) in sorted { |
| 439 | hasher.update(name.as_bytes()); |
| 440 | hasher.update([0]); |
| 441 | hasher.update(bytes); |
| 442 | } |
| 443 | hasher.update(metadata_json); |
| 444 | if let Some(index) = asset_index { |
| 445 | hasher.update([0]); |
| 446 | hasher.update(b"assets.json"); |
| 447 | hasher.update([0]); |
| 448 | hasher.update(index); |
| 449 | } |
| 450 | format!("{:x}", hasher.finalize())[..16].to_string() |
| 451 | } |