Diffinery

homeflare/celldpublic

celld/crates/celld/deploy.rs
2243 lines · 86.6 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Deployment is an operator control-plane path outside the Actor execution
4// domain.
5#![allow(clippy::disallowed_methods)]
6// Deploy narrates progress; every line of it is for a person.
7
8//! `celld deploy` — build a Wrangler project and write it to the fleet bucket.
9//!
10//! Bundling is esbuild's job; this module does config, identity, and durable
11//! bucket publication. Nothing here shells out to wrangler or speaks a
12//! Cloudflare-shaped API. Config keys are an allowlist: anything we do not
13//! model is refused, never silently dropped.
14use crate::bucket::Bucket;
15use crate::note;
16use crate::protocol::{
17 asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest,
18 ModuleKind, ModuleRef, QueueConsumerAttachment, QueueConsumerConfig, QueueConsumerDeployment,
19 Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CRON_V1, FEATURE_D1_V1, FEATURE_KV_V1,
20 FEATURE_QUEUES_V1, FEATURE_R2_V1, FEATURE_SQLITE_VEC_V1, FEATURE_WASM_V1, FEATURE_WORKFLOWS_V1,
21 QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION,
22};
23use anyhow::{anyhow, bail, Context};
24use flate2::write::GzEncoder;
25use flate2::Compression;
26use futures_util::{stream, StreamExt, TryStreamExt};
27use serde_json::{json, Map, Value};
28use sha2::Digest;
29use sha2::Sha256;
30use std::collections::{BTreeMap, BTreeSet};
31use std::io::Write;
32use std::path::{Path, PathBuf};
33use std::process::Command;
34use std::time::{Duration, Instant};
35
36/// Config keys we understand. Anything else is an error: refusing is
37/// compat-safe, guessing produces confusing activation failures later.
38const SUPPORTED_KEYS: &[&str] = &[
39 "$schema",
40 "name",
41 "main",
42 "compatibility_date",
43 "compatibility_flags",
44 "durable_objects",
45 "migrations",
46 "assets",
47 "services",
48 "triggers",
49 "vars",
50 "d1_databases",
51 "kv_namespaces",
52 "queues",
53 "workflows",
54 "r2_buckets",
55 "no_bundle",
56];
57
58/// The Durable Object class every D1 database runs as. It is supplied by the
59/// runtime, not by the worker, so a config naming it in `durable_objects` or
60/// `migrations` is refused: the harness registers this class in every isolate,
61/// and a user binding onto it would silently reach a D1 database cell instead
62/// of the user's class. A bare module export of this name is not refused —
63/// the loader skips it rather than let it shadow the built-in.
64pub const D1_CLASS: &str = "__D1Database";
65
66/// The Durable Object class every workflow instance runs as. Like `D1_CLASS`,
67/// it is supplied by the runtime and refused as a user class name.
68pub const WORKFLOW_CLASS: &str = "__Workflow";
69
70/// The Durable Object class every KV namespace runs as.
71///
72/// Fleet-wide, like `D1_CLASS` and unlike `workflow_class`: a namespace is a
73/// resource several Workers bind, so two scripts naming one namespace mean to
74/// reach one set of cells.
75pub const KV_CLASS: &str = celld_logic::kv::RESERVED_CLASS;
76
77/// The Durable Object class every Queue broker runs as.
78pub const QUEUE_CLASS: &str = celld_logic::queue::RESERVED_CLASS;
79
80/// Every runtime-supplied Durable Object class.
81pub const RESERVED_CLASSES: &[&str] = &[D1_CLASS, WORKFLOW_CLASS, KV_CLASS, QUEUE_CLASS];
82
83/// The Durable Object class a script's workflow instances run as.
84///
85/// Script-scoped, because a workflow instance already is. Its namespace key is
86/// `cells:v1:<len>:<script>:__Workflow`, so two co-hosted scripts address
87/// different cells — but both used to register the *same* class name, and a
88/// deployment's class registry is one flat map, so the second script collided
89/// with the first and the node refused to start at all. The name now says what
90/// the namespace key always said.
91///
92/// D1 deliberately does not get this treatment. Its namespace is fleet-wide so
93/// that several Workers can bind one database and a Worker rename cannot rename
94/// it, which means a D1 cell genuinely is shared and one entry is correct.
95///
96/// `.` is the separator for three reasons, and all three are constraints
97/// rather than taste. A JavaScript class name cannot contain one, so no user
98/// export can collide. It is not `:`, which is what the cell-scope parser
99/// splits a class from an id on. And it is inside
100/// `celld_logic::cell::valid_cell_scope`'s charset, which is a security fence
101/// on a name that becomes a path component and an object-store key — `@` is
102/// not, and a scope carrying one is refused before it reaches storage. Cron
103/// picked `.` for the first of those reasons already.
104pub fn workflow_class(script_name: &str) -> String {
105 format!("{WORKFLOW_CLASS}.{script_name}")
106}
107
108/// Whether a reserved class names cells that several scripts share on purpose.
109///
110/// Only D1. Its namespace key is fleet-wide precisely so that a database
111/// outlives the name of any one Worker that binds it, so two scripts declaring
112/// `d1_databases` mean to reach the same cells, and one registry entry serving
113/// both is correct rather than merely tolerated. A workflow class carries its
114/// script, so it is never shared and a collision there is a real one.
115pub fn is_shared_reserved_class(class: &str) -> bool {
116 class == D1_CLASS || class == KV_CLASS || class == QUEUE_CLASS
117}
118
119/// Whether a class name is a script-scoped workflow class.
120///
121/// One reading of the shape, because three call sites wanted it and three
122/// copies of `strip_prefix(WORKFLOW_CLASS)` is how the separator comes to mean
123/// two things.
124pub fn is_workflow_class(class: &str) -> bool {
125 class
126 .strip_prefix(WORKFLOW_CLASS)
127 .is_some_and(|rest| rest.starts_with('.'))
128}
129
130pub fn is_reserved_class(class: &str) -> bool {
131 RESERVED_CLASSES.contains(&class) || is_workflow_class(class)
132}
133
134/// The reserved class a cell scope names, or `None` for an ordinary Durable
135/// Object.
136///
137/// A scope is `<class>:<instance>` and the instance may itself contain a `:`,
138/// so the class is everything before the first one — the same split
139/// `Runtime::start_cell` makes when it resolves a cell to its Worker config.
140pub fn reserved_class_of(scope: &str) -> Option<&str> {
141 let (class, _) = scope.split_once(':')?;
142 is_reserved_class(class).then_some(class)
143}
144
145/// Whether a cell scope names any runtime-supplied class.
146///
147/// This is what the unauthenticated `/do/` route refuses, and it is deliberately
148/// one question rather than one question per class. `/do/` used to ask
149/// one predicate per class, so every reserved class added a
150/// third, a fourth, and a place to forget one — and a forgotten refusal is not
151/// a missing feature, it is an unauthenticated route onto a cell whose whole
152/// surface is an operator protocol. Adding a class to `RESERVED_CLASSES` now
153/// closes that door with no new code.
154pub fn is_reserved_scope(scope: &str) -> bool {
155 reserved_class_of(scope).is_some()
156}
157
158/// What to tell an operator who reached a reserved class on the wrong route.
159///
160/// A hint, never a gate. The refusal is `is_reserved_scope`, which cannot be
161/// forgotten; this only decides how helpful the message is, so a class with no
162/// entry here is still refused and simply gets the general answer.
163pub fn operator_hint(class: &str) -> &'static str {
164 if class == D1_CLASS {
165 "use `celld d1`"
166 } else if class == KV_CLASS {
167 "use `celld kv`"
168 } else if class == QUEUE_CLASS {
169 "use `celld queue`"
170 } else if is_workflow_class(class) {
171 "use the workflow binding"
172 } else {
173 "reach it through its binding"
174 }
175}
176
177const MAX_ASSET_FILES: usize = 20_000;
178const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024;
179const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024;
180const MAX_ASSET_DIRECTIVE_BYTES: u64 = 100 * 1024;
181const ASSET_UPLOAD_CONCURRENCY: usize = 16;
182
183pub struct Options {
184 pub config: Option<PathBuf>,
185 pub bucket: Option<String>,
186 pub endpoint: Option<String>,
187 pub region: Option<String>,
188 pub dry_run: bool,
189 pub json: bool,
190}
191
192pub fn print_help() {
193 let text = "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\
194USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]\n\n\
195PROJECT is a directory or a Wrangler config; it defaults to the working\n\
196directory, where celld looks for wrangler.jsonc or wrangler.json.\n\n\
197OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://|az://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket, az://\n an Azure Blob Storage container with its account in\n AZURE_STORAGE_ACCOUNT_NAME; celld then rejects\n --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n --json Print the deployment as one JSON object\n -h, --help Show this help\n\n\
198Credentials come from the standard AWS credential chain, from Google\n\
199Application Default Credentials for a gs:// bucket, or from an Azure storage\n\
200account key, managed identity, or workload identity for an az:// bucket.\n\n\
201Worker projects require `esbuild` on PATH; asset-only projects do not. Static\n\
202assets, service bindings, and string vars are supported. Routes are not; use\n\
203Wrangler for route configuration.\n\
204A running node polls the deployment pointer and adopts the new version in\n\
205place; nothing restarts."
206 ;
207 let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text).help(text);
208}
209
210pub fn options_from_arguments(
211 arguments: impl IntoIterator<Item = String>,
212) -> anyhow::Result<Option<Options>> {
213 let mut options = Options {
214 config: None,
215 bucket: None,
216 endpoint: None,
217 region: None,
218 dry_run: false,
219 json: false,
220 };
221 let mut arguments = arguments.into_iter();
222 while let Some(argument) = arguments.next() {
223 match argument.as_str() {
224 "--help" | "-h" => return Ok(None),
225 "--dry-run" => options.dry_run = true,
226 "--json" => options.json = true,
227 "--config" => {
228 options.config = Some(PathBuf::from(
229 arguments.next().context("--config requires a value")?,
230 ));
231 }
232 "--bucket" => {
233 let value = arguments.next().context("--bucket requires a value")?;
234 options.bucket = Some(value.trim_start_matches("s3://").to_string());
235 }
236 "--endpoint" => {
237 options.endpoint = Some(arguments.next().context("--endpoint requires a value")?);
238 }
239 "--region" => {
240 options.region = Some(arguments.next().context("--region requires a value")?);
241 }
242 other if other.starts_with('-') => {
243 bail!("unknown argument for `celld deploy`: {other}")
244 }
245 other if options.config.is_none() => options.config = Some(PathBuf::from(other)),
246 other => bail!("`celld deploy` takes one project path, and already has one: {other}"),
247 }
248 }
249 Ok(Some(options))
250}
251
252/// What a config resolves to once the allowlist has been applied.
253struct Project {
254 script_name: String,
255 /// `no_bundle: true` uploads the entry file as written instead of running
256 /// esbuild. A Vite build has already bundled the Worker, and bundling it
257 /// twice is what breaks that output.
258 no_bundle: bool,
259 /// Entry relative to the project root. esbuild stamps this path into the
260 /// bundle, so it must not depend on the working directory celld was
261 /// invoked from — identical source would otherwise hash two ways.
262 entry: Option<String>,
263 assets: Option<ProjectAssets>,
264 metadata: Value,
265 do_classes: Vec<String>,
266 sqlite_classes: Vec<String>,
267 crons: Vec<String>,
268 has_workflows: bool,
269 has_kv: bool,
270 queue_consumers: Vec<QueueConsumerConfig>,
271 has_queues: bool,
272 has_r2: bool,
273}
274
275struct ProjectAssets {
276 directory: PathBuf,
277 config: AssetConfig,
278 raw_metadata: Value,
279}
280
281pub struct BuiltAssets {
282 pub index: Vec<u8>,
283 pub blobs: BTreeMap<String, Vec<u8>>,
284 pub file_count: u32,
285 pub total_bytes: u64,
286}
287
288/// The built deployment, before anything is written.
289pub struct Built {
290 pub script_name: String,
291 pub version: String,
292 pub prefix: String,
293 pub manifest: Manifest,
294 pub modules: Vec<(String, Vec<u8>)>,
295 pub assets: Option<BuiltAssets>,
296 pub bundled_in: Duration,
297}
298
299impl Built {
300 pub fn bytes(&self) -> usize {
301 self.modules.iter().map(|(_, body)| body.len()).sum()
302 }
303
304 /// What the deployment weighs, the bindings it will have, and nothing we
305 /// cannot stand behind: no URL, because celld routes nothing, and no
306 /// startup time, because deploying does not start an isolate.
307 pub fn report(&self) {
308 note!(" celld {}", env!("CARGO_PKG_VERSION"));
309 note!("{}", "─".repeat(47));
310 note!(
311 "Total Upload: {} / gzip: {}",
312 kib(self.bytes()),
313 kib(gzipped(&self.modules)),
314 );
315 if let Some(assets) = &self.assets {
316 note!(
317 "Static Assets: {} files / {} ({} unique bodies)",
318 assets.file_count,
319 kib(assets.total_bytes as usize),
320 assets.blobs.len(),
321 );
322 }
323 let bindings = self.bindings();
324 if bindings.is_empty() {
325 note!("Your Worker has no bindings.");
326 } else {
327 let width = bindings
328 .iter()
329 .map(|(binding, _)| binding.len())
330 .chain(std::iter::once("Binding".len()))
331 .max()
332 .unwrap_or_default()
333 + 6;
334 note!("Your Worker has access to the following bindings:");
335 note!("{:width$}Resource", "Binding");
336 for (binding, resource) in bindings {
337 note!("{binding:width$}{resource}");
338 }
339 }
340 note!(
341 "Bundled {} ({})",
342 self.script_name,
343 seconds(self.bundled_in)
344 );
345 }
346
347 /// `env.NAME (Class)` against the resource it resolves to, the way
348 /// Wrangler renders it.
349 fn bindings(&self) -> Vec<(String, String)> {
350 self.manifest
351 .raw_metadata
352 .get("bindings")
353 .and_then(Value::as_array)
354 .map(Vec::as_slice)
355 .unwrap_or_default()
356 .iter()
357 .filter_map(|binding| {
358 let name = binding.get("name").and_then(Value::as_str)?;
359 match binding.get("type").and_then(Value::as_str) {
360 Some("assets") => {
361 Some((format!("env.{name} (Assets)"), "Static Assets".to_string()))
362 }
363 Some("durable_object_namespace") => {
364 let class = binding.get("class_name").and_then(Value::as_str)?;
365 let sqlite = self.manifest.sqlite_classes.iter().any(|c| c == class);
366 Some((
367 format!("env.{name} ({class})"),
368 match sqlite {
369 true => "Durable Object (SQLite)".to_string(),
370 false => "Durable Object".to_string(),
371 },
372 ))
373 }
374 Some("service") => {
375 let service = binding.get("service").and_then(Value::as_str)?;
376 let target = binding
377 .get("entrypoint")
378 .and_then(Value::as_str)
379 .map_or_else(
380 || service.to_string(),
381 |entrypoint| format!("{service}#{entrypoint}"),
382 );
383 Some((format!("env.{name} (Service)"), target))
384 }
385 Some("d1") => {
386 let database = binding.get("database_name").and_then(Value::as_str)?;
387 Some((format!("env.{name} (D1)"), database.to_string()))
388 }
389 Some("workflow") => {
390 let workflow = binding.get("workflow_name").and_then(Value::as_str)?;
391 Some((format!("env.{name} (Workflow)"), workflow.to_string()))
392 }
393 Some("kv") => {
394 let id = binding.get("id").and_then(Value::as_str)?;
395 Some((format!("env.{name} (KV)"), id.to_string()))
396 }
397 Some("queue") => {
398 let queue = binding.get("queue").and_then(Value::as_str)?;
399 Some((format!("env.{name} (Queue)"), queue.to_string()))
400 }
401 Some("r2_bucket") => {
402 let bucket = binding.get("bucket_name").and_then(Value::as_str)?;
403 Some((format!("env.{name} (R2)"), bucket.to_string()))
404 }
405 Some("plain_text") => Some((
406 format!("env.{name} (Text)"),
407 "Environment Variable".to_string(),
408 )),
409 _ => None,
410 }
411 })
412 .collect()
413 }
414}
415
416fn kib(bytes: usize) -> String {
417 format!("{:.2} KiB", bytes as f64 / 1024.0)
418}
419
420fn seconds(elapsed: Duration) -> String {
421 format!("{:.2} sec", elapsed.as_secs_f64())
422}
423
424fn gzipped(modules: &[(String, Vec<u8>)]) -> usize {
425 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
426 for (_, body) in modules {
427 encoder.write_all(body).ok();
428 }
429 encoder.finish().map(|out| out.len()).unwrap_or_default()
430}
431
432pub fn build(options: &Options) -> anyhow::Result<Built> {
433 let config_path = resolve_config(options.config.clone())?;
434 let root = config_path
435 .parent()
436 .filter(|path| !path.as_os_str().is_empty())
437 .map(Path::to_path_buf)
438 .unwrap_or_else(|| PathBuf::from("."));
439 let project = read_project(&config_path, &root)?;
440 let started = Instant::now();
441 let built_assets = project.assets.as_ref().map(build_assets).transpose()?;
442 let bundle = project
443 .entry
444 .as_deref()
445 .map(|entry| {
446 if project.no_bundle {
447 // Already bundled by the caller's toolchain. Read it as it is;
448 // running esbuild over a Vite build is what corrupts it. A
449 // pre-bundled entry carries no sibling wasm: esbuild's copy
450 // loader is what would have produced them.
451 let path = root.join(entry);
452 std::fs::read(&path)
453 .with_context(|| format!("read entry point {}", path.display()))
454 .map(|bundle| BundleOutput {
455 bundle,
456 wasm: Vec::new(),
457 })
458 } else {
459 run_esbuild(&root, entry)
460 }
461 })
462 .transpose()?;
463 let bundled_in = started.elapsed();
464
465 // esbuild emits one JS module plus a copy of every wasm file the bundle
466 // imports; the copies ship as sibling modules.
467 let module_name = "index.js".to_string();
468 let (mut modules, wasm_modules) = match bundle {
469 Some(output) => (vec![(module_name.clone(), output.bundle)], output.wasm),
470 None => (Vec::new(), Vec::new()),
471 };
472 let wasm_names: BTreeSet<String> = wasm_modules.iter().map(|(name, _)| name.clone()).collect();
473 modules.extend(wasm_modules);
474 // Identity is over the exact metadata bytes the manifest retains, so the
475 // serialization happens once and is reused for both.
476 let metadata_json = serde_json::to_vec(&project.metadata)?;
477 let version = crate::protocol::deployment_version(
478 &modules,
479 &metadata_json,
480 built_assets.as_ref().map(|assets| assets.index.as_slice()),
481 );
482 let prefix = format!("deploy/{}/{}", project.script_name, version);
483 let asset_reference = built_assets.as_ref().map(|assets| AssetManifestRef {
484 index: "assets.json".to_string(),
485 sha256: format!("{:x}", Sha256::digest(&assets.index)),
486 file_count: assets.file_count,
487 total_bytes: assets.total_bytes,
488 });
489 let sqlite_vec = project
490 .metadata
491 .get("compatibility_flags")
492 .and_then(Value::as_array)
493 .is_some_and(|flags| flags.iter().any(|flag| flag.as_str() == Some("sqlite_vec")));
494 let uses_d1 = project.do_classes.iter().any(|class| class == D1_CLASS);
495 let manifest = Manifest {
496 schema_version: if asset_reference.is_some() { 2 } else { 1 },
497 version: version.clone(),
498 script_name: project.script_name.clone(),
499 main_module: project.entry.as_ref().map(|_| module_name.clone()),
500 do_classes: project.do_classes,
501 sqlite_classes: project.sqlite_classes,
502 modules: modules
503 .iter()
504 .map(|(name, bytes)| ModuleRef {
505 name: name.clone(),
506 bytes: bytes.len(),
507 sha256: format!("{:x}", Sha256::digest(bytes))[..16].to_string(),
508 kind: wasm_names.contains(name).then_some(ModuleKind::Wasm),
509 })
510 .collect(),
511 assets: asset_reference,
512 crons: project.crons.clone(),
513 queue_consumers: project.queue_consumers,
514 // Each capability the manifest depends on is named here, so a node
515 // that predates it rejects the deployment up front instead of
516 // partially deserializing the manifest and failing at worker load.
517 required_features: {
518 let mut features = Vec::new();
519 if built_assets.is_some() {
520 features.push(FEATURE_ASSETS_V1.to_string());
521 }
522 if !project.crons.is_empty() {
523 features.push(FEATURE_CRON_V1.to_string());
524 }
525 if uses_d1 {
526 features.push(FEATURE_D1_V1.to_string());
527 }
528 if project.has_workflows {
529 features.push(FEATURE_WORKFLOWS_V1.to_string());
530 }
531 if project.has_kv {
532 features.push(FEATURE_KV_V1.to_string());
533 }
534 if project.has_queues {
535 features.push(FEATURE_QUEUES_V1.to_string());
536 }
537 if project.has_r2 {
538 features.push(FEATURE_R2_V1.to_string());
539 }
540 if sqlite_vec {
541 features.push(FEATURE_SQLITE_VEC_V1.to_string());
542 }
543 if !wasm_names.is_empty() {
544 features.push(FEATURE_WASM_V1.to_string());
545 }
546 features
547 },
548 raw_metadata: project.metadata,
549 };
550 Ok(Built {
551 script_name: project.script_name,
552 version,
553 prefix,
554 manifest,
555 modules,
556 assets: built_assets,
557 bundled_in,
558 })
559}
560
561pub async fn write(bucket: &Bucket, built: &Built) -> anyhow::Result<()> {
562 // Read every attachment before uploading immutable deployment objects.
563 // A competing consumer is a deploy refusal, so it must not leave a new
564 // version in the bucket that an operator can mistake for a published one.
565 let queue_attachments = prepare_queue_attachments(bucket, &built.manifest).await?;
566
567 // Asset bodies are fleet-wide and content-addressed. Finish every body
568 // before publishing the deployment-local index or manifest so a reader
569 // can never observe a pointer whose assets are incomplete.
570 if let Some(assets) = &built.assets {
571 stream::iter(&assets.blobs)
572 .map(|(sha256, body)| ensure_asset_blob(bucket, sha256, body))
573 .buffer_unordered(ASSET_UPLOAD_CONCURRENCY)
574 .try_collect::<Vec<_>>()
575 .await?;
576 }
577 for (name, bytes) in &built.modules {
578 bucket
579 .put(&format!("{}/{name}", built.prefix), bytes.clone())
580 .await?;
581 }
582 if let Some(assets) = &built.assets {
583 bucket
584 .put(
585 &format!("{}/assets.json", built.prefix),
586 assets.index.clone(),
587 )
588 .await?;
589 }
590 bucket
591 .put(
592 &format!("{}/manifest.json", built.prefix),
593 serde_json::to_vec_pretty(&built.manifest)?,
594 )
595 .await?;
596
597 // An attachment names this exact immutable prefix. Publish it only after
598 // the prefix is complete, so a node can never resolve a consumer to a
599 // half-uploaded deployment. The named and fleet pointers can move later
600 // without tearing this queue-to-consumer relationship.
601 publish_queue_attachments(bucket, &built.manifest, &built.prefix, queue_attachments).await?;
602
603 let pointer = DeployPointer {
604 script_name: Some(built.script_name.clone()),
605 version: built.version.clone(),
606 prefix: built.prefix.clone(),
607 rollout: Rollout { percent: 100 },
608 };
609 let encoded = serde_json::to_vec_pretty(&pointer)?;
610 // The named pointer resolves service-binding components; the fleet-wide
611 // one is the sole application selector, so it moves last. A concurrent
612 // deploy must produce a loser, not a lost write.
613 put_pointer(
614 bucket,
615 &format!("deploy/{}/current.json", built.script_name),
616 encoded.clone(),
617 )
618 .await?;
619 put_pointer(bucket, "deploy/current.json", encoded).await?;
620 Ok(())
621}
622
623pub(crate) struct QueueAttachmentState {
624 queue: String,
625 key: String,
626 current: Option<QueueConsumerAttachment>,
627 token: Option<String>,
628 desired: bool,
629}
630
631pub(crate) async fn prepare_queue_attachments(
632 bucket: &Bucket,
633 manifest: &Manifest,
634) -> anyhow::Result<Vec<QueueAttachmentState>> {
635 let desired = manifest
636 .queue_consumers
637 .iter()
638 .map(|consumer| consumer.queue.clone())
639 .collect::<BTreeSet<_>>();
640 let previous = current_queue_consumers(bucket, &manifest.script_name).await?;
641 let queues = desired.union(&previous).cloned().collect::<Vec<_>>();
642 let mut states = Vec::with_capacity(queues.len());
643
644 for queue in queues {
645 let key = crate::protocol::queue_consumer_attachment_key(&queue)
646 .expect("deploy validated the queue name");
647 let (current, token) = match bucket.get(&key).await? {
648 Some((body, token)) => {
649 let attachment: QueueConsumerAttachment = serde_json::from_slice(&body)
650 .with_context(|| format!("decode queue consumer attachment {key}"))?;
651 crate::protocol::validate_queue_consumer_attachment(&queue, &attachment)?;
652 (Some(attachment), Some(token))
653 }
654 None => (None, None),
655 };
656 let is_desired = desired.contains(&queue);
657 if is_desired {
658 if let Some(owner) = current
659 .as_ref()
660 .and_then(|attachment| attachment.consumer.as_ref())
661 .filter(|consumer| consumer.script_name != manifest.script_name)
662 {
663 bail!(
664 "queue {:?} already has consumer script {:?}; remove that consumer before deploying {}",
665 queue,
666 owner.script_name,
667 manifest.script_name
668 );
669 }
670 }
671 states.push(QueueAttachmentState {
672 queue,
673 key,
674 current,
675 token,
676 desired: is_desired,
677 });
678 }
679 Ok(states)
680}
681
682async fn current_queue_consumers(
683 bucket: &Bucket,
684 script_name: &str,
685) -> anyhow::Result<BTreeSet<String>> {
686 let pointer_key = format!("deploy/{script_name}/current.json");
687 let Some((pointer_body, _)) = bucket.get(&pointer_key).await? else {
688 return Ok(BTreeSet::new());
689 };
690 let pointer: DeployPointer =
691 serde_json::from_slice(&pointer_body).with_context(|| format!("decode {pointer_key}"))?;
692 anyhow::ensure!(
693 pointer.script_name.as_deref() == Some(script_name),
694 "named deployment pointer {pointer_key} does not identify script {script_name:?}"
695 );
696 let manifest_key = format!("{}/manifest.json", pointer.prefix);
697 let (manifest_body, _) = bucket
698 .get(&manifest_key)
699 .await?
700 .with_context(|| format!("read {manifest_key}"))?;
701 let manifest: Manifest =
702 serde_json::from_slice(&manifest_body).with_context(|| format!("decode {manifest_key}"))?;
703 anyhow::ensure!(
704 manifest.script_name == script_name,
705 "named deployment pointer {pointer_key} resolved script {:?}",
706 manifest.script_name
707 );
708 Ok(manifest
709 .queue_consumers
710 .into_iter()
711 .map(|consumer| consumer.queue)
712 .collect())
713}
714
715pub(crate) async fn publish_queue_attachments(
716 bucket: &Bucket,
717 manifest: &Manifest,
718 prefix: &str,
719 states: Vec<QueueAttachmentState>,
720) -> anyhow::Result<()> {
721 let consumer = QueueConsumerDeployment {
722 script_name: manifest.script_name.clone(),
723 version: manifest.version.clone(),
724 prefix: prefix.to_string(),
725 };
726 for state in states {
727 let next_consumer = if state.desired {
728 Some(consumer.clone())
729 } else if state
730 .current
731 .as_ref()
732 .and_then(|attachment| attachment.consumer.as_ref())
733 .is_some_and(|owner| owner.script_name == manifest.script_name)
734 {
735 None
736 } else {
737 continue;
738 };
739 let next = QueueConsumerAttachment {
740 schema_version: QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION,
741 queue: state.queue,
742 consumer: next_consumer,
743 };
744 if state.current.as_ref() == Some(&next) {
745 continue;
746 }
747 let body = serde_json::to_vec_pretty(&next)?;
748 match bucket
749 .put_cas(&state.key, body, state.token.as_deref())
750 .await
751 {
752 Ok(Some(_)) => {}
753 Ok(None) => {
754 bail!(
755 "queue consumer attachment {} lost a race; another deploy may have landed first; re-run `celld deploy`",
756 state.key
757 )
758 }
759 Err(error) => {
760 return Err(error.context(
761 "a queue consumer attachment write may have committed; re-run `celld deploy`",
762 ));
763 }
764 }
765 }
766 Ok(())
767}
768
769async fn ensure_asset_blob(bucket: &Bucket, sha256: &str, body: &[u8]) -> anyhow::Result<()> {
770 let key = asset_blob_key(sha256).expect("built asset digest is valid");
771 if let Ok(Some((size, meta))) = bucket.head_with_meta(&key, "sha256").await {
772 if size == body.len() as u64 && meta.as_deref() == Some(sha256) {
773 return Ok(());
774 }
775 }
776 bucket
777 .put_with_meta(&key, body.to_vec(), &[("sha256", sha256)])
778 .await
779}
780
781/// Compare-and-swap on a pointer: create it if absent, otherwise replace
782/// exactly the value we read.
783async fn put_pointer(bucket: &Bucket, key: &str, body: Vec<u8>) -> anyhow::Result<()> {
784 let etag = bucket.head(key).await.ok().flatten().map(|(_, etag)| etag);
785 match bucket.put_cas(key, body, etag.as_deref()).await {
786 Ok(Some(_)) => Ok(()),
787 Ok(None) => Err(anyhow!(
788 "write {}://{}/{key} lost a race\n\
789 Another deploy may have landed first; re-run `celld deploy`.",
790 bucket.scheme(),
791 bucket.name
792 )),
793 Err(error) => {
794 Err(error.context("Another deploy may have landed first; re-run `celld deploy`."))
795 }
796 }
797}
798
799/// What `celld d1` needs out of a project: the declared databases, so a name
800/// the project never declared fails here instead of creating an empty one.
801pub struct D1Project {
802 /// One entry per declaration, in config order.
803 pub databases: Vec<D1Declaration>,
804}
805
806pub struct D1Declaration {
807 pub database_name: String,
808 /// Cloudflare's stable resource ID when present, otherwise the database
809 /// name for a celld-only project.
810 pub database_identity: String,
811 /// Wrangler scopes `migrations_dir` to the binding, so this is per
812 /// database and never shared. A single shared directory would apply one
813 /// database's migrations to another.
814 pub migrations_dir: PathBuf,
815 /// The bookkeeping table, per binding as on wrangler
816 /// (`migrations_table`). Hard-coding `d1_migrations` here made celld
817 /// read an empty table on a project that had renamed it, and every
818 /// already-applied migration re-ran.
819 pub migrations_table: String,
820}
821
822/// Read a project's D1 declarations. This reads the same config `build` reads,
823/// but it does not bundle: `celld d1` acts on a database that is already
824/// deployed, and a project that fails to build must still be migratable.
825pub fn read_d1_project(given: Option<PathBuf>) -> anyhow::Result<D1Project> {
826 let path = resolve_config(given)?;
827 let root = path.parent().unwrap_or(Path::new(".")).to_path_buf();
828 let source =
829 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
830 let config: Value = serde_json::from_str(&strip_jsonc(&source))
831 .with_context(|| format!("parse {}", path.display()))?;
832 let object = config
833 .as_object()
834 .ok_or_else(|| anyhow!("{} is not a JSON object", path.display()))?;
835 object
836 .get("name")
837 .and_then(Value::as_str)
838 .ok_or_else(|| anyhow!("{} has no `name`", path.display()))?;
839 let mut databases = Vec::new();
840 if let Some(Value::Array(entries)) = object.get("d1_databases") {
841 for entry in entries {
842 let Some(name) = entry.get("database_name").and_then(Value::as_str) else {
843 continue;
844 };
845 // Wrangler discovers migrations through more knobs than the two
846 // celld reads. An unread knob must be a refusal, not a silent
847 // default: honoring half of a project's migration config applies
848 // the wrong files in the wrong order.
849 if entry.get("migrations_pattern").is_some() {
850 bail!(
851 "d1 database {name:?} sets `migrations_pattern`, which celld \
852 does not support; celld reads `*.sql` from `migrations_dir`"
853 );
854 }
855 let migrations_table = match entry.get("migrations_table") {
856 None => "d1_migrations".to_string(),
857 Some(Value::String(table)) => table.clone(),
858 Some(_) => bail!("d1 database {name:?} has a non-string `migrations_table`"),
859 };
860 // The table name is joined into SQL as an identifier, both here
861 // and in the cell, so anything but a plain identifier is refused
862 // before it can reach either.
863 let mut characters = migrations_table.chars();
864 let plain = characters
865 .next()
866 .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
867 && characters.all(|c| c.is_ascii_alphanumeric() || c == '_');
868 if !plain {
869 bail!(
870 "d1 database {name:?} has a `migrations_table` that is not a \
871 plain identifier: {migrations_table:?}"
872 );
873 }
874 let database_identity = match entry.get("database_id") {
875 None => name.to_string(),
876 Some(Value::String(identity)) if !identity.is_empty() => identity.clone(),
877 Some(_) => bail!("d1 database {name:?} has an invalid `database_id`"),
878 };
879 databases.push(D1Declaration {
880 database_name: name.to_string(),
881 database_identity,
882 migrations_dir: entry
883 .get("migrations_dir")
884 .and_then(Value::as_str)
885 .map_or_else(|| root.join("migrations"), |dir| root.join(dir)),
886 migrations_table,
887 });
888 }
889 }
890 let mut unique = Vec::<D1Declaration>::new();
891 for declaration in databases {
892 if let Some(previous) = unique
893 .iter()
894 .find(|candidate| candidate.database_name == declaration.database_name)
895 {
896 if previous.database_identity != declaration.database_identity
897 || previous.migrations_dir != declaration.migrations_dir
898 || previous.migrations_table != declaration.migrations_table
899 {
900 bail!(
901 "d1 database {:?} has ambiguous aliases with different database_id, \
902 migrations_dir, or migrations_table values",
903 declaration.database_name
904 );
905 }
906 continue;
907 }
908 if let Some(previous) = unique
909 .iter()
910 .find(|candidate| candidate.database_identity == declaration.database_identity)
911 {
912 if previous.migrations_dir != declaration.migrations_dir
913 || previous.migrations_table != declaration.migrations_table
914 {
915 bail!(
916 "d1 database identity {:?} has ambiguous aliases {:?} and {:?} with \
917 different migrations_dir or migrations_table values",
918 declaration.database_identity,
919 previous.database_name,
920 declaration.database_name
921 );
922 }
923 }
924 unique.push(declaration);
925 }
926 Ok(D1Project { databases: unique })
927}
928
929/// A path may name the config itself or the directory holding it; with no
930/// path at all, the working directory.
931pub(crate) fn resolve_config(given: Option<PathBuf>) -> anyhow::Result<PathBuf> {
932 let directory = match given {
933 Some(path) if path.is_dir() => path,
934 Some(path) if path.exists() => return Ok(path),
935 Some(path) => bail!(
936 "no Wrangler config or project directory at {}",
937 path.display()
938 ),
939 None => PathBuf::from("."),
940 };
941 for candidate in ["wrangler.jsonc", "wrangler.json"] {
942 let path = directory.join(candidate);
943 if path.exists() {
944 return Ok(path);
945 }
946 }
947 if directory.join("wrangler.toml").exists() {
948 bail!("wrangler.toml is not supported; convert it to wrangler.jsonc");
949 }
950 bail!(
951 "no wrangler.jsonc or wrangler.json in {}",
952 directory.display()
953 )
954}
955
956fn read_project(path: &Path, root: &Path) -> anyhow::Result<Project> {
957 let source =
958 std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
959 let config: Value = serde_json::from_str(&strip_jsonc(&source))
960 .with_context(|| format!("parse {}", path.display()))?;
961 let object = config
962 .as_object()
963 .ok_or_else(|| anyhow!("{} is not a JSON object", path.display()))?;
964
965 let unsupported = object
966 .keys()
967 .filter(|key| !SUPPORTED_KEYS.contains(&key.as_str()))
968 .cloned()
969 .collect::<Vec<_>>();
970 if !unsupported.is_empty() {
971 bail!(
972 "`celld deploy` does not support these config keys: {}.\n\
973 Deploy this project with Wrangler instead, or remove them.",
974 unsupported.join(", ")
975 );
976 }
977
978 let script_name = object
979 .get("name")
980 .and_then(Value::as_str)
981 .ok_or_else(|| anyhow!("config has no `name`"))?
982 .to_string();
983 let main = object
984 .get("main")
985 .map(|value| {
986 value
987 .as_str()
988 .ok_or_else(|| anyhow!("config `main` must be a string"))
989 .and_then(|value| project_relative_path(value, "main"))
990 })
991 .transpose()?;
992 if let Some(main) = &main {
993 let entry = root.join(main);
994 let metadata = std::fs::symlink_metadata(&entry)
995 .with_context(|| format!("inspect entry point {}", entry.display()))?;
996 if !metadata.file_type().is_file() {
997 bail!("entry point {} is not a regular file", entry.display());
998 }
999 }
1000 let no_bundle = match object.get("no_bundle") {
1001 None => false,
1002 Some(Value::Bool(value)) => *value,
1003 Some(_) => bail!("config `no_bundle` must be a boolean"),
1004 };
1005 if no_bundle && main.is_none() {
1006 bail!("config sets `no_bundle` without `main`");
1007 }
1008 let assets = object
1009 .get("assets")
1010 .map(|value| read_asset_project(value, root, object))
1011 .transpose()?;
1012 if main.is_none() && assets.is_none() {
1013 bail!("config has neither `main` nor `assets`");
1014 }
1015 if main.is_none()
1016 && assets.as_ref().is_some_and(|assets| {
1017 matches!(
1018 &assets.config.run_worker_first,
1019 RunWorkerFirst::Bool(true) | RunWorkerFirst::Routes(_)
1020 )
1021 })
1022 {
1023 bail!("an asset-only project cannot set `assets.run_worker_first`");
1024 }
1025
1026 let mut sqlite_classes = read_sqlite_classes(object)?;
1027 if let Some(class) = sqlite_classes.iter().find(|class| is_reserved_class(class)) {
1028 bail!("`{class}` is a runtime class; remove it from `migrations`");
1029 }
1030 let crons = read_crons(object)?;
1031 if !crons.is_empty() && main.is_none() {
1032 bail!("config sets `triggers.crons` without `main`; a cron trigger needs a `scheduled` handler to call");
1033 }
1034
1035 // Wrangler-shaped upload metadata, so a manifest written here and one
1036 // written by the control plane describe a deployment the same way.
1037 let mut bindings = Vec::new();
1038 let mut do_classes = Vec::new();
1039 for binding in object
1040 .get("durable_objects")
1041 .and_then(|value| value.get("bindings"))
1042 .and_then(Value::as_array)
1043 .map(Vec::as_slice)
1044 .unwrap_or_default()
1045 {
1046 let name = binding
1047 .get("name")
1048 .and_then(Value::as_str)
1049 .ok_or_else(|| anyhow!("durable object binding has no `name`"))?;
1050 let class_name = binding
1051 .get("class_name")
1052 .and_then(Value::as_str)
1053 .ok_or_else(|| anyhow!("durable object binding {name} has no `class_name`"))?;
1054 do_classes.push(class_name.to_string());
1055 bindings.push(json!({
1056 "type": "durable_object_namespace",
1057 "name": name,
1058 "class_name": class_name,
1059 }));
1060 }
1061 let services = match object.get("services") {
1062 None => &[][..],
1063 Some(Value::Array(services)) => services.as_slice(),
1064 Some(_) => bail!("config `services` must be an array"),
1065 };
1066 let mut service_count = 0_usize;
1067 for service in services {
1068 let binding = service
1069 .get("binding")
1070 .and_then(Value::as_str)
1071 .ok_or_else(|| anyhow!("service binding has no `binding`"))?;
1072 if !valid_binding(binding) {
1073 bail!("invalid service binding name: {binding:?}");
1074 }
1075 let target = service
1076 .get("service")
1077 .and_then(Value::as_str)
1078 .ok_or_else(|| anyhow!("service binding {binding} has no `service`"))?;
1079 let entrypoint = service
1080 .get("entrypoint")
1081 .map(|value| {
1082 value.as_str().ok_or_else(|| {
1083 anyhow!("service binding {binding} `entrypoint` must be a string")
1084 })
1085 })
1086 .transpose()?;
1087 let mut encoded = json!({
1088 "type": "service",
1089 "name": binding,
1090 "service": target,
1091 });
1092 if let Some(entrypoint) = entrypoint {
1093 encoded["entrypoint"] = json!(entrypoint);
1094 }
1095 bindings.push(encoded);
1096 service_count += 1;
1097 }
1098 let d1_databases = match object.get("d1_databases") {
1099 None => &[][..],
1100 Some(Value::Array(databases)) => databases.as_slice(),
1101 Some(_) => bail!("config `d1_databases` must be an array"),
1102 };
1103 // The reserved class must be refused whether or not the project declares
1104 // any `d1_databases`: the harness registers its own `__D1Database` class
1105 // in every isolate, so a durable_objects binding naming it would silently
1106 // resolve to the D1 database cell instead of the user's class.
1107 if let Some(class) = do_classes.iter().find(|class| is_reserved_class(class)) {
1108 bail!("`{class}` is a runtime class; rename the Durable Object class");
1109 }
1110 for database in d1_databases {
1111 let binding = database
1112 .get("binding")
1113 .and_then(Value::as_str)
1114 .ok_or_else(|| anyhow!("d1 database has no `binding`"))?;
1115 if !valid_binding(binding) {
1116 bail!("invalid d1 binding name: {binding:?}");
1117 }
1118 let database_name = database
1119 .get("database_name")
1120 .and_then(Value::as_str)
1121 .ok_or_else(|| {
1122 anyhow!("d1 binding {binding} has no `database_name`; celld uses the name to select the database from the CLI")
1123 })?;
1124 if database_name.is_empty() {
1125 bail!("d1 binding {binding} has an empty `database_name`");
1126 }
1127 let mut encoded = json!({
1128 "type": "d1",
1129 "name": binding,
1130 "database_name": database_name,
1131 });
1132 if let Some(database_id) = database.get("database_id") {
1133 let database_id = database_id
1134 .as_str()
1135 .filter(|database_id| !database_id.is_empty())
1136 .ok_or_else(|| anyhow!("d1 binding {binding} has an invalid `database_id`"))?;
1137 encoded["database_id"] = json!(database_id);
1138 }
1139 bindings.push(encoded);
1140 }
1141 if !d1_databases.is_empty() {
1142 // A D1 database is a cell of a runtime-supplied class. Declaring it
1143 // here is what registers its namespace key and marks it SQLite-backed;
1144 // it is never a worker export, so it stays out of `ctx.exports`.
1145 do_classes.push(D1_CLASS.to_string());
1146 sqlite_classes.push(D1_CLASS.to_string());
1147 }
1148 let kv_namespaces = match object.get("kv_namespaces") {
1149 None => &[][..],
1150 Some(Value::Array(namespaces)) => namespaces.as_slice(),
1151 Some(_) => bail!("config `kv_namespaces` must be an array"),
1152 };
1153 let mut kv_ids = BTreeSet::new();
1154 for namespace in kv_namespaces {
1155 // Every key celld does not model stops the deploy, per the loud-gap
1156 // rule. `preview_id` is the exception and is accepted below: it selects
1157 // a different namespace under `wrangler dev`, which celld does not run,
1158 // so ignoring it costs a developer nothing at deploy time.
1159 let unsupported = namespace
1160 .as_object()
1161 .map(|object| {
1162 object
1163 .keys()
1164 .filter(|key| !matches!(key.as_str(), "binding" | "id" | "preview_id"))
1165 .cloned()
1166 .collect::<Vec<_>>()
1167 })
1168 .unwrap_or_default();
1169 if let Some(key) = unsupported.first() {
1170 bail!(
1171 "kv namespace declares `{key}`, which celld does not model; \
1172 celld models `binding`, `id`, and `preview_id`"
1173 );
1174 }
1175 let binding = namespace
1176 .get("binding")
1177 .and_then(Value::as_str)
1178 .ok_or_else(|| anyhow!("kv namespace has no `binding`"))?;
1179 if !valid_binding(binding) {
1180 bail!("invalid kv binding name: {binding:?}");
1181 }
1182 // `id` is the namespace identity, verbatim, and celld invents no
1183 // `namespace_name` key beside it. Upstream's `kv_namespaces` carries no
1184 // human-readable name at all -- only `binding`, `id` and `preview_id` --
1185 // and celld's accepted configuration is a strict subset of Wrangler's:
1186 // a key celld accepts and Wrangler diagnoses would make the file
1187 // unportable, which is the one property the deploy story rests on. A
1188 // project ported from Cloudflare therefore keeps its hex id and works;
1189 // a project that was never there writes a readable string.
1190 let id = namespace.get("id").and_then(Value::as_str).ok_or_else(|| {
1191 anyhow!(
1192 "kv binding {binding} has no `id`; celld uses the id as the \
1193 namespace identity, so any stable string serves"
1194 )
1195 })?;
1196 if id.is_empty() {
1197 bail!("kv binding {binding} has an empty `id`");
1198 }
1199 // The id becomes a cell name and therefore a path component and an
1200 // object-store key, so it answers to the same charset fence every cell
1201 // scope does rather than to a looser one invented here.
1202 if !celld_logic::cell::valid_cell_scope(id) {
1203 bail!(
1204 "kv binding {binding} has an `id` that cannot name a cell: {id:?}; \
1205 use ASCII letters, digits, and `_ - . : $`"
1206 );
1207 }
1208 if !kv_ids.insert(id.to_string()) {
1209 bail!("duplicate kv namespace id: {id:?}");
1210 }
1211 bindings.push(json!({
1212 "type": "kv",
1213 "name": binding,
1214 "id": id,
1215 }));
1216 }
1217 if !kv_namespaces.is_empty() {
1218 // A KV namespace is a cell of a runtime-supplied class, declared here
1219 // so its namespace key is minted and its cells are SQLite-backed. Like
1220 // D1's, it is never a worker export and stays out of `ctx.exports`.
1221 do_classes.push(KV_CLASS.to_string());
1222 sqlite_classes.push(KV_CLASS.to_string());
1223 }
1224 let queues = match object.get("queues") {
1225 None => None,
1226 Some(Value::Object(queues)) => Some(queues),
1227 Some(_) => bail!("config `queues` must be an object"),
1228 };
1229 if let Some(key) = queues
1230 .into_iter()
1231 .flat_map(|queues| queues.keys())
1232 .find(|key| !matches!(key.as_str(), "producers" | "consumers"))
1233 {
1234 bail!("config `queues` declares `{key}`, which celld does not model");
1235 }
1236 let queue_producers = match queues.and_then(|queues| queues.get("producers")) {
1237 None => &[][..],
1238 Some(Value::Array(producers)) => producers.as_slice(),
1239 Some(_) => bail!("config `queues.producers` must be an array"),
1240 };
1241 for producer in queue_producers {
1242 reject_queue_keys(
1243 producer,
1244 &["binding", "queue", "delivery_delay"],
1245 "producer",
1246 )?;
1247 let binding = producer
1248 .get("binding")
1249 .and_then(Value::as_str)
1250 .ok_or_else(|| anyhow!("queue producer has no `binding`"))?;
1251 if !valid_binding(binding) {
1252 bail!("invalid queue binding name: {binding:?}");
1253 }
1254 let queue = queue_name(producer, "producer")?;
1255 let delivery_delay = optional_queue_u32(producer, "delivery_delay")?.unwrap_or(0);
1256 if delivery_delay > celld_logic::queue::MAX_DELAY_SECONDS {
1257 bail!("queue producer delivery_delay must be between 0 and 86400 seconds");
1258 }
1259 let mut encoded = json!({
1260 "type": "queue",
1261 "name": binding,
1262 "queue": queue,
1263 });
1264 if producer.get("delivery_delay").is_some() {
1265 encoded["delivery_delay"] = json!(delivery_delay);
1266 }
1267 bindings.push(encoded);
1268 }
1269 let queue_consumers_raw = match queues.and_then(|queues| queues.get("consumers")) {
1270 None => &[][..],
1271 Some(Value::Array(consumers)) => consumers.as_slice(),
1272 Some(_) => bail!("config `queues.consumers` must be an array"),
1273 };
1274 let mut queue_consumers = Vec::new();
1275 let mut consumed_queues = BTreeSet::new();
1276 for consumer in queue_consumers_raw {
1277 if consumer.get("script_name").is_some() {
1278 bail!("queue consumer declares `script_name`; celld attaches it to the current script");
1279 }
1280 reject_queue_keys(
1281 consumer,
1282 &[
1283 "queue",
1284 "max_batch_size",
1285 "max_batch_timeout",
1286 "max_retries",
1287 "dead_letter_queue",
1288 "max_concurrency",
1289 "retry_delay",
1290 ],
1291 "consumer",
1292 )?;
1293 let queue = queue_name(consumer, "consumer")?.to_string();
1294 if !consumed_queues.insert(queue.clone()) {
1295 bail!("duplicate queue consumer: {queue:?}");
1296 }
1297 let dead_letter_queue = consumer
1298 .get("dead_letter_queue")
1299 .map(|value| {
1300 let name = value
1301 .as_str()
1302 .ok_or_else(|| anyhow!("queue consumer dead_letter_queue must be a string"))?;
1303 validate_queue_name(name, "dead-letter queue")?;
1304 anyhow::ensure!(
1305 name != queue,
1306 "a queue cannot use itself as its dead-letter queue"
1307 );
1308 Ok::<_, anyhow::Error>(name.to_string())
1309 })
1310 .transpose()?;
1311 let config = QueueConsumerConfig {
1312 queue,
1313 max_batch_size: optional_queue_u16(consumer, "max_batch_size")?
1314 .unwrap_or(celld_logic::queue::DEFAULT_MAX_BATCH_SIZE),
1315 max_batch_timeout: optional_queue_u16(consumer, "max_batch_timeout")?
1316 .unwrap_or(celld_logic::queue::DEFAULT_MAX_BATCH_TIMEOUT_SECONDS),
1317 max_retries: optional_queue_u16(consumer, "max_retries")?
1318 .unwrap_or(celld_logic::queue::DEFAULT_MAX_RETRIES),
1319 dead_letter_queue,
1320 max_concurrency: optional_queue_u16(consumer, "max_concurrency")?,
1321 retry_delay: optional_queue_u32(consumer, "retry_delay")?,
1322 };
1323 celld_logic::queue::validate_config(&celld_logic::queue::QueueConfig {
1324 max_batch_size: config.max_batch_size,
1325 max_batch_timeout_seconds: config.max_batch_timeout,
1326 max_retries: config.max_retries,
1327 max_concurrency: config.max_concurrency,
1328 delivery_delay_seconds: 0,
1329 retry_delay_seconds: config.retry_delay,
1330 })
1331 .map_err(anyhow::Error::new)?;
1332 queue_consumers.push(config);
1333 }
1334 if !queue_producers.is_empty() || !queue_consumers.is_empty() {
1335 if !queue_consumers.is_empty() && main.is_none() {
1336 bail!("config declares a queue consumer without `main`; a consumer needs a Worker module with a queue handler");
1337 }
1338 do_classes.push(QUEUE_CLASS.to_string());
1339 sqlite_classes.push(QUEUE_CLASS.to_string());
1340 }
1341 let workflows = match object.get("workflows") {
1342 None => &[][..],
1343 Some(Value::Array(workflows)) => workflows.as_slice(),
1344 Some(_) => bail!("config `workflows` must be an array"),
1345 };
1346 let mut workflow_names = BTreeSet::new();
1347 for workflow in workflows {
1348 // Any key celld does not model stops the deploy, per the loud-gap
1349 // rule: an unread knob (`schedules` is the notable one) must be a
1350 // refusal, never a workflow that silently lacks the behavior it
1351 // declares.
1352 let unsupported = workflow
1353 .as_object()
1354 .map(|object| {
1355 object
1356 .keys()
1357 .filter(|key| {
1358 !matches!(
1359 key.as_str(),
1360 "name" | "binding" | "class_name" | "script_name"
1361 )
1362 })
1363 .cloned()
1364 .collect::<Vec<_>>()
1365 })
1366 .unwrap_or_default();
1367 if !unsupported.is_empty() {
1368 bail!(
1369 "`celld deploy` does not support these workflow keys: {}.\n\
1370 celld models `name`, `binding`, `class_name`, and `script_name`; \
1371 remove the rest (`schedules` included).",
1372 unsupported.join(", ")
1373 );
1374 }
1375 let binding = workflow
1376 .get("binding")
1377 .and_then(Value::as_str)
1378 .ok_or_else(|| anyhow!("workflow has no `binding`"))?;
1379 if !valid_binding(binding) {
1380 bail!("invalid workflow binding name: {binding:?}");
1381 }
1382 let workflow_name = workflow
1383 .get("name")
1384 .and_then(Value::as_str)
1385 .ok_or_else(|| anyhow!("workflow binding {binding} has no `name`"))?;
1386 if !valid_resource_name(workflow_name) {
1387 bail!(
1388 "invalid workflow name {workflow_name:?}: use letters, digits, `-` and `_` \
1389 (not starting with `-`), at most 64 characters"
1390 );
1391 }
1392 if !workflow_names.insert(workflow_name.to_string()) {
1393 bail!("duplicate workflow name: {workflow_name:?}");
1394 }
1395 let class_name = workflow
1396 .get("class_name")
1397 .and_then(Value::as_str)
1398 .filter(|class| !class.is_empty())
1399 .ok_or_else(|| anyhow!("workflow binding {binding} has no `class_name`"))?;
1400 if is_reserved_class(class_name) {
1401 bail!(
1402 "workflow {workflow_name:?} names the reserved class {class_name:?} as its \
1403 `class_name`; export a WorkflowEntrypoint subclass of your own"
1404 );
1405 }
1406 if let Some(script) = workflow.get("script_name").and_then(Value::as_str) {
1407 if script != script_name {
1408 bail!(
1409 "workflow {workflow_name:?} sets `script_name` {script:?}; celld runs a \
1410 workflow only in the script that declares it"
1411 );
1412 }
1413 }
1414 bindings.push(json!({
1415 "type": "workflow",
1416 "name": binding,
1417 "workflow_name": workflow_name,
1418 "class_name": class_name,
1419 }));
1420 }
1421 if !workflows.is_empty() {
1422 if main.is_none() {
1423 bail!("config declares `workflows` without `main`; a workflow needs a Worker module to export its class");
1424 }
1425 do_classes.push(workflow_class(&script_name));
1426 sqlite_classes.push(workflow_class(&script_name));
1427 }
1428 let r2_buckets = match object.get("r2_buckets") {
1429 None => &[][..],
1430 Some(Value::Array(buckets)) => buckets.as_slice(),
1431 Some(_) => bail!("config `r2_buckets` must be an array"),
1432 };
1433 let mut r2_binding_names = BTreeSet::new();
1434 let mut r2_bucket_names = BTreeSet::new();
1435 for bucket in r2_buckets {
1436 let binding = bucket
1437 .get("binding")
1438 .and_then(Value::as_str)
1439 .ok_or_else(|| anyhow!("r2 bucket has no `binding`"))?;
1440 if !valid_binding(binding) {
1441 bail!("invalid r2 binding name: {binding:?}");
1442 }
1443 if !r2_binding_names.insert(binding.to_string()) {
1444 bail!("duplicate r2 binding name: {binding:?}");
1445 }
1446 let bucket_name = bucket
1447 .get("bucket_name")
1448 .and_then(Value::as_str)
1449 .ok_or_else(|| {
1450 anyhow!("r2 binding {binding} has no `bucket_name`; celld uses the name to place the bucket's keys in the fleet bucket")
1451 })?;
1452 if !valid_resource_name(bucket_name) {
1453 bail!(
1454 "invalid r2 bucket name {bucket_name:?}: use letters, digits, `-` and `_` \
1455 (not starting with `-`), at most 64 characters"
1456 );
1457 }
1458 if !r2_bucket_names.insert(bucket_name.to_string()) {
1459 bail!("two r2 bindings name the same bucket: {bucket_name:?}");
1460 }
1461 // Cloudflare scopes a jurisdiction to an account's R2; celld has
1462 // neither, and silently ignoring it would put the keys somewhere
1463 // the operator did not ask for.
1464 if bucket.get("jurisdiction").is_some() {
1465 bail!("r2 binding {binding} sets `jurisdiction`, which celld does not have");
1466 }
1467 bindings.push(json!({
1468 "type": "r2_bucket",
1469 "name": binding,
1470 "bucket_name": bucket_name,
1471 }));
1472 }
1473 let vars = match object.get("vars") {
1474 None => None,
1475 Some(Value::Object(vars)) => Some(vars),
1476 Some(_) => bail!("config `vars` must be an object"),
1477 };
1478 let mut var_count = 0_usize;
1479 for (name, value) in vars.into_iter().flatten() {
1480 if !valid_binding(name) {
1481 bail!("invalid var binding name: {name:?}");
1482 }
1483 let value = value
1484 .as_str()
1485 .ok_or_else(|| anyhow!("var binding {name} must be a string"))?;
1486 bindings.push(json!({
1487 "type": "plain_text",
1488 "name": name,
1489 "text": value,
1490 }));
1491 var_count += 1;
1492 }
1493 if main.is_none()
1494 && (!do_classes.is_empty()
1495 || !sqlite_classes.is_empty()
1496 || service_count > 0
1497 || var_count > 0
1498 || !r2_binding_names.is_empty())
1499 {
1500 bail!("an asset-only project cannot declare Worker bindings");
1501 }
1502 if let Some(binding) = assets
1503 .as_ref()
1504 .and_then(|assets| assets.config.binding.as_ref())
1505 {
1506 bindings.push(json!({
1507 "type": "assets",
1508 "name": binding,
1509 }));
1510 }
1511 // build_env installs every binding into one JavaScript object. Validate
1512 // that structural invariant once here, after every binding source has
1513 // contributed, so a new binding kind cannot silently shadow an old one.
1514 let mut binding_names = BTreeMap::new();
1515 for binding in &bindings {
1516 let name = binding.get("name").and_then(Value::as_str).unwrap_or("");
1517 let kind = binding.get("type").and_then(Value::as_str).unwrap_or("");
1518 if let Some(previous) = binding_names.insert(name, kind) {
1519 bail!(
1520 "binding name {name:?} is declared by both a {previous} and a {kind} \
1521 binding; every name in `env` must be unique"
1522 );
1523 }
1524 }
1525 let mut metadata = Map::new();
1526 if main.is_some() {
1527 metadata.insert("main_module".into(), json!("index.js"));
1528 }
1529 if let Some(assets) = &assets {
1530 metadata.insert("assets".into(), assets.raw_metadata.clone());
1531 }
1532 if let Some(date) = object.get("compatibility_date") {
1533 metadata.insert("compatibility_date".into(), date.clone());
1534 }
1535 if let Some(flags) = object.get("compatibility_flags") {
1536 metadata.insert("compatibility_flags".into(), flags.clone());
1537 }
1538 metadata.insert("bindings".into(), Value::Array(bindings));
1539 if !queue_consumers.is_empty() {
1540 // Include consumer policy in deployment identity. The typed manifest
1541 // field below is the runtime contract; this copy keeps a settings-only
1542 // deploy from reusing the previous code-and-bindings version.
1543 metadata.insert("queue_consumers".into(), json!(queue_consumers));
1544 }
1545 if !sqlite_classes.is_empty() {
1546 metadata.insert(
1547 "migrations".into(),
1548 json!({ "new_sqlite_classes": sqlite_classes }),
1549 );
1550 }
1551
1552 Ok(Project {
1553 script_name,
1554 no_bundle,
1555 entry: main,
1556 assets,
1557 metadata: Value::Object(metadata),
1558 do_classes,
1559 sqlite_classes,
1560 crons,
1561 has_workflows: !workflows.is_empty(),
1562 has_kv: !kv_namespaces.is_empty(),
1563 has_queues: !queue_producers.is_empty() || !queue_consumers.is_empty(),
1564 queue_consumers,
1565 has_r2: !r2_buckets.is_empty(),
1566 })
1567}
1568
1569fn reject_queue_keys(value: &Value, accepted: &[&str], kind: &str) -> anyhow::Result<()> {
1570 let object = value
1571 .as_object()
1572 .ok_or_else(|| anyhow!("queue {kind} must be an object"))?;
1573 if let Some(key) = object.keys().find(|key| !accepted.contains(&key.as_str())) {
1574 bail!("queue {kind} declares `{key}`, which celld does not model");
1575 }
1576 Ok(())
1577}
1578
1579fn queue_name<'a>(value: &'a Value, kind: &str) -> anyhow::Result<&'a str> {
1580 let name = value
1581 .get("queue")
1582 .and_then(Value::as_str)
1583 .ok_or_else(|| anyhow!("queue {kind} has no `queue` name"))?;
1584 validate_queue_name(name, kind)?;
1585 Ok(name)
1586}
1587
1588fn validate_queue_name(name: &str, kind: &str) -> anyhow::Result<()> {
1589 anyhow::ensure!(!name.is_empty(), "queue {kind} has an empty queue name");
1590 anyhow::ensure!(
1591 celld_logic::cell::valid_cell_scope(name),
1592 "queue {kind} has a name that cannot name a cell: {name:?}; use ASCII letters, digits, and `_ - . : $`"
1593 );
1594 Ok(())
1595}
1596
1597fn optional_queue_u64(value: &Value, field: &str) -> anyhow::Result<Option<u64>> {
1598 value
1599 .get(field)
1600 .map(|value| {
1601 value
1602 .as_u64()
1603 .ok_or_else(|| anyhow!("queue {field} must be a non-negative integer"))
1604 })
1605 .transpose()
1606}
1607
1608fn optional_queue_u16(value: &Value, field: &str) -> anyhow::Result<Option<u16>> {
1609 optional_queue_u64(value, field)?
1610 .map(|value| {
1611 u16::try_from(value).map_err(|_| anyhow!("queue {field} is too large: {value}"))
1612 })
1613 .transpose()
1614}
1615
1616fn optional_queue_u32(value: &Value, field: &str) -> anyhow::Result<Option<u32>> {
1617 optional_queue_u64(value, field)?
1618 .map(|value| {
1619 u32::try_from(value).map_err(|_| anyhow!("queue {field} is too large: {value}"))
1620 })
1621 .transpose()
1622}
1623
1624/// The upstream workflow-name rule (`^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`, at most 64
1625/// characters). Instance ids follow the same rule; the harness validates those
1626/// because they arrive at run time, not at deploy. An R2 `bucket_name` takes
1627/// the same rule for a second reason: the name becomes a key prefix inside the
1628/// fleet bucket, and this rule is what keeps it a single path segment, so a
1629/// binding cannot address the fleet's own deployment, cell, or lease keys.
1630fn valid_resource_name(name: &str) -> bool {
1631 name.len() <= 64
1632 && name
1633 .chars()
1634 .next()
1635 .is_some_and(|first| first == '_' || first.is_ascii_alphanumeric())
1636 && name
1637 .chars()
1638 .skip(1)
1639 .all(|value| value == '_' || value == '-' || value.is_ascii_alphanumeric())
1640}
1641
1642/// `triggers.crons`, validated here so a malformed expression stops the deploy
1643/// the developer is watching instead of an activation an hour later. Wrangler
1644/// accepts `triggers` with other keys we do not model; only `crons` is read.
1645fn read_crons(project: &Map<String, Value>) -> anyhow::Result<Vec<String>> {
1646 let Some(value) = project.get("triggers") else {
1647 return Ok(Vec::new());
1648 };
1649 let triggers = value
1650 .as_object()
1651 .ok_or_else(|| anyhow!("config `triggers` must be an object"))?;
1652 let Some(value) = triggers.get("crons") else {
1653 return Ok(Vec::new());
1654 };
1655 let entries = value
1656 .as_array()
1657 .ok_or_else(|| anyhow!("config `triggers.crons` must be an array of strings"))?;
1658 let mut crons = Vec::new();
1659 for entry in entries {
1660 let expression = entry
1661 .as_str()
1662 .ok_or_else(|| anyhow!("config `triggers.crons` must be an array of strings"))?;
1663 celld_logic::cron::parse(expression).map_err(|error| anyhow!("{error}"))?;
1664 crons.push(expression.trim().to_string());
1665 }
1666 Ok(crons)
1667}
1668
1669fn read_sqlite_classes(project: &Map<String, Value>) -> anyhow::Result<Vec<String>> {
1670 let Some(value) = project.get("migrations") else {
1671 return Ok(Vec::new());
1672 };
1673 let migrations = value
1674 .as_array()
1675 .ok_or_else(|| anyhow!("config `migrations` must be an array"))?;
1676 let mut tags = BTreeSet::new();
1677 let mut classes = BTreeSet::new();
1678 let mut result = Vec::new();
1679 for (index, migration) in migrations.iter().enumerate() {
1680 let migration = migration
1681 .as_object()
1682 .ok_or_else(|| anyhow!("config `migrations[{index}]` must be an object"))?;
1683 let unsupported = migration
1684 .keys()
1685 .filter(|key| !matches!(key.as_str(), "tag" | "new_sqlite_classes"))
1686 .cloned()
1687 .collect::<Vec<_>>();
1688 if !unsupported.is_empty() {
1689 bail!(
1690 "`celld deploy` does not support these migration keys: {}.\n\
1691 Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment.",
1692 unsupported.join(", ")
1693 );
1694 }
1695 let tag = migration
1696 .get("tag")
1697 .and_then(Value::as_str)
1698 .filter(|tag| !tag.is_empty())
1699 .ok_or_else(|| {
1700 anyhow!("config `migrations[{index}].tag` must be a non-empty string")
1701 })?;
1702 if !tags.insert(tag.to_string()) {
1703 bail!("config has duplicate migration tag {tag:?}");
1704 }
1705 let Some(value) = migration.get("new_sqlite_classes") else {
1706 continue;
1707 };
1708 let new_classes = value.as_array().ok_or_else(|| {
1709 anyhow!("config `migrations[{index}].new_sqlite_classes` must be an array")
1710 })?;
1711 for (class_index, class) in new_classes.iter().enumerate() {
1712 let class = class.as_str().filter(|class| !class.is_empty()).ok_or_else(|| {
1713 anyhow!(
1714 "config `migrations[{index}].new_sqlite_classes[{class_index}]` must be a non-empty string"
1715 )
1716 })?;
1717 if !classes.insert(class.to_string()) {
1718 bail!("SQLite class {class:?} is introduced by more than one migration");
1719 }
1720 result.push(class.to_string());
1721 }
1722 }
1723 Ok(result)
1724}
1725
1726fn read_asset_project(
1727 value: &Value,
1728 root: &Path,
1729 project: &Map<String, Value>,
1730) -> anyhow::Result<ProjectAssets> {
1731 let object = value
1732 .as_object()
1733 .ok_or_else(|| anyhow!("config `assets` must be an object"))?;
1734 let supported = [
1735 "directory",
1736 "binding",
1737 "html_handling",
1738 "not_found_handling",
1739 "run_worker_first",
1740 ];
1741 let unsupported = object
1742 .keys()
1743 .filter(|key| !supported.contains(&key.as_str()))
1744 .cloned()
1745 .collect::<Vec<_>>();
1746 if !unsupported.is_empty() {
1747 bail!(
1748 "`celld deploy` does not support these assets keys: {}",
1749 unsupported.join(", ")
1750 );
1751 }
1752 let directory = object
1753 .get("directory")
1754 .and_then(Value::as_str)
1755 .ok_or_else(|| anyhow!("config `assets.directory` must be a string"))?;
1756 let directory = project_relative_path(directory, "assets.directory")?;
1757 let directory = root.join(directory);
1758 let metadata = std::fs::symlink_metadata(&directory)
1759 .with_context(|| format!("inspect asset directory {}", directory.display()))?;
1760 if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
1761 bail!(
1762 "asset directory {} is not a regular directory",
1763 directory.display()
1764 );
1765 }
1766
1767 let binding = object
1768 .get("binding")
1769 .map(|value| {
1770 value
1771 .as_str()
1772 .ok_or_else(|| anyhow!("config `assets.binding` must be a string"))
1773 .and_then(|binding| {
1774 if valid_binding(binding) {
1775 Ok(binding.to_string())
1776 } else {
1777 bail!("invalid asset binding name: {binding:?}")
1778 }
1779 })
1780 })
1781 .transpose()?;
1782 let html_handling = optional_asset_mode(
1783 object,
1784 "html_handling",
1785 "auto-trailing-slash",
1786 &[
1787 "auto-trailing-slash",
1788 "force-trailing-slash",
1789 "drop-trailing-slash",
1790 "none",
1791 ],
1792 )?;
1793 let not_found_handling = optional_asset_mode(
1794 object,
1795 "not_found_handling",
1796 "none",
1797 &["none", "single-page-application", "404-page"],
1798 )?;
1799 let run_worker_first = object
1800 .get("run_worker_first")
1801 .map(|value| {
1802 serde_json::from_value::<RunWorkerFirst>(value.clone())
1803 .context("config `assets.run_worker_first` must be a boolean or route list")
1804 })
1805 .transpose()?
1806 .unwrap_or_default();
1807 validate_worker_first(&run_worker_first)?;
1808
1809 let headers = read_asset_directive(&directory, "_headers")?;
1810 let redirects = read_asset_directive(&directory, "_redirects")?;
1811 let compatibility_date = project
1812 .get("compatibility_date")
1813 .map(|value| {
1814 value
1815 .as_str()
1816 .map(str::to_string)
1817 .ok_or_else(|| anyhow!("config `compatibility_date` must be a string"))
1818 })
1819 .transpose()?;
1820 let compatibility_flags = project
1821 .get("compatibility_flags")
1822 .map(|value| {
1823 value
1824 .as_array()
1825 .ok_or_else(|| anyhow!("config `compatibility_flags` must be an array"))?
1826 .iter()
1827 .map(|flag| {
1828 flag.as_str()
1829 .map(str::to_string)
1830 .ok_or_else(|| anyhow!("compatibility flags must be strings"))
1831 })
1832 .collect::<anyhow::Result<Vec<_>>>()
1833 })
1834 .transpose()?
1835 .unwrap_or_default();
1836
1837 // Retain the Wrangler-shaped upload metadata as well as the normalized
1838 // index config. Defaults and compatibility settings belong in the index;
1839 // upload metadata includes only the values Wrangler would send.
1840 let mut upload_config = Map::new();
1841 for key in ["html_handling", "not_found_handling", "run_worker_first"] {
1842 if let Some(value) = object.get(key) {
1843 upload_config.insert(key.to_string(), value.clone());
1844 }
1845 }
1846 if let Some(headers) = &headers {
1847 upload_config.insert("_headers".to_string(), Value::String(headers.clone()));
1848 }
1849 if let Some(redirects) = &redirects {
1850 upload_config.insert("_redirects".to_string(), Value::String(redirects.clone()));
1851 }
1852
1853 Ok(ProjectAssets {
1854 directory,
1855 config: AssetConfig {
1856 binding,
1857 html_handling: Some(html_handling),
1858 not_found_handling: Some(not_found_handling),
1859 run_worker_first,
1860 headers,
1861 redirects,
1862 compatibility_date,
1863 compatibility_flags,
1864 },
1865 raw_metadata: json!({ "config": Value::Object(upload_config) }),
1866 })
1867}
1868
1869fn project_relative_path(value: &str, key: &str) -> anyhow::Result<String> {
1870 let value = value.strip_prefix("./").unwrap_or(value);
1871 let path = Path::new(value);
1872 if value.is_empty()
1873 || path
1874 .components()
1875 .any(|component| !matches!(component, std::path::Component::Normal(_)))
1876 {
1877 bail!("config `{key}` must be a path inside the project");
1878 }
1879 Ok(value.to_string())
1880}
1881
1882fn optional_asset_mode(
1883 object: &Map<String, Value>,
1884 key: &str,
1885 default: &str,
1886 supported: &[&str],
1887) -> anyhow::Result<String> {
1888 let value = match object.get(key) {
1889 Some(value) => value
1890 .as_str()
1891 .ok_or_else(|| anyhow!("config `assets.{key}` must be a string"))?,
1892 None => default,
1893 };
1894 if !supported.contains(&value) {
1895 bail!("unsupported assets.{key} value: {value:?}");
1896 }
1897 Ok(value.to_string())
1898}
1899
1900fn valid_binding(binding: &str) -> bool {
1901 binding.len() <= 128
1902 && binding
1903 .chars()
1904 .next()
1905 .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic())
1906 && binding
1907 .chars()
1908 .skip(1)
1909 .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric())
1910}
1911
1912fn validate_worker_first(value: &RunWorkerFirst) -> anyhow::Result<()> {
1913 let RunWorkerFirst::Routes(routes) = value else {
1914 return Ok(());
1915 };
1916 if routes.is_empty() || routes.len() > 100 {
1917 bail!("asset worker-first routes must contain between 1 and 100 rules");
1918 }
1919 let mut positive = false;
1920 let mut seen = std::collections::HashSet::new();
1921 for route in routes {
1922 if route.len() <= 1
1923 || route.len() > 100
1924 || route.contains(['\\', '\0'])
1925 || (!route.starts_with('/') && !route.starts_with("!/"))
1926 || !seen.insert(route)
1927 {
1928 bail!("invalid asset worker-first route: {route:?}");
1929 }
1930 positive |= route.starts_with('/');
1931 }
1932 if !positive {
1933 bail!("asset worker-first routes require a positive rule");
1934 }
1935 Ok(())
1936}
1937
1938fn read_asset_directive(directory: &Path, name: &str) -> anyhow::Result<Option<String>> {
1939 let path = directory.join(name);
1940 let metadata = match std::fs::symlink_metadata(&path) {
1941 Ok(metadata) => metadata,
1942 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1943 Err(error) => return Err(error).with_context(|| format!("inspect {}", path.display())),
1944 };
1945 if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
1946 bail!("asset directive {} is not a regular file", path.display());
1947 }
1948 if metadata.len() > MAX_ASSET_DIRECTIVE_BYTES {
1949 bail!("asset directive {} exceeds 100 KiB", path.display());
1950 }
1951 let contents =
1952 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1953 if contents.len() as u64 > MAX_ASSET_DIRECTIVE_BYTES {
1954 bail!("asset directive {} exceeds 100 KiB", path.display());
1955 }
1956 Ok(Some(contents))
1957}
1958
1959fn build_assets(project: &ProjectAssets) -> anyhow::Result<BuiltAssets> {
1960 let mut files = Vec::new();
1961 collect_asset_files(&project.directory, "", &mut files)?;
1962 files.sort_by(|left, right| left.0.cmp(&right.0));
1963 if files.len() > MAX_ASSET_FILES {
1964 bail!("asset directory exceeds the {MAX_ASSET_FILES}-file limit");
1965 }
1966
1967 let mut entries = BTreeMap::new();
1968 let mut blobs = BTreeMap::new();
1969 let mut total_bytes = 0_u64;
1970 for (relative, path) in files {
1971 let metadata =
1972 std::fs::metadata(&path).with_context(|| format!("inspect {}", path.display()))?;
1973 if metadata.len() > MAX_ASSET_FILE_BYTES {
1974 bail!("asset /{relative} exceeds the 25 MiB file limit");
1975 }
1976 total_bytes = total_bytes
1977 .checked_add(metadata.len())
1978 .context("asset byte count overflow")?;
1979 if total_bytes > MAX_ASSET_BYTES {
1980 bail!("asset directory exceeds the 1 GiB deployment limit");
1981 }
1982 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
1983 if body.len() as u64 != metadata.len() {
1984 bail!("asset changed while being read: {}", path.display());
1985 }
1986 let sha256 = format!("{:x}", Sha256::digest(&body));
1987 blobs.entry(sha256.clone()).or_insert(body);
1988 entries.insert(
1989 format!("/{relative}"),
1990 AssetEntry {
1991 sha256,
1992 bytes: metadata.len(),
1993 content_type: asset_content_type(&path).map(str::to_string),
1994 },
1995 );
1996 }
1997 let file_count = u32::try_from(entries.len()).context("asset file count overflow")?;
1998 let index = serde_json::to_vec(&AssetIndex {
1999 schema_version: 1,
2000 entries,
2001 config: project.config.clone(),
2002 })?;
2003 Ok(BuiltAssets {
2004 index,
2005 blobs,
2006 file_count,
2007 total_bytes,
2008 })
2009}
2010
2011fn collect_asset_files(
2012 directory: &Path,
2013 relative: &str,
2014 files: &mut Vec<(String, PathBuf)>,
2015) -> anyhow::Result<()> {
2016 let mut entries = std::fs::read_dir(directory)
2017 .with_context(|| format!("read asset directory {}", directory.display()))?
2018 .collect::<Result<Vec<_>, _>>()?;
2019 entries.sort_by_key(std::fs::DirEntry::file_name);
2020 for entry in entries {
2021 let name = entry.file_name().into_string().map_err(|_| {
2022 anyhow!(
2023 "asset path contains a non-UTF-8 name under {}",
2024 directory.display()
2025 )
2026 })?;
2027 if relative.is_empty() && name == ".assetsignore" {
2028 bail!(
2029 "{} is not supported by `celld deploy`; remove it or deploy with Wrangler",
2030 entry.path().display()
2031 );
2032 }
2033 if relative.is_empty() && (name == "_worker.js" || name.starts_with("_worker.js/")) {
2034 bail!(
2035 "refusing to publish reserved Worker source as an asset: {}",
2036 entry.path().display()
2037 );
2038 }
2039 if relative.is_empty() && matches!(name.as_str(), "_headers" | "_redirects") {
2040 continue;
2041 }
2042 if name.contains(['\\', '\0']) {
2043 bail!("invalid asset path component: {name:?}");
2044 }
2045 let child_relative = if relative.is_empty() {
2046 name
2047 } else {
2048 format!("{relative}/{name}")
2049 };
2050 if child_relative.len() + 1 > 1024 {
2051 bail!("asset path exceeds 1024 bytes: /{child_relative}");
2052 }
2053 let file_type = entry
2054 .file_type()
2055 .with_context(|| format!("inspect asset {}", entry.path().display()))?;
2056 if file_type.is_symlink() {
2057 bail!(
2058 "asset tree contains a symbolic link: {}",
2059 entry.path().display()
2060 );
2061 } else if file_type.is_dir() {
2062 collect_asset_files(&entry.path(), &child_relative, files)?;
2063 } else if file_type.is_file() {
2064 files.push((child_relative, entry.path()));
2065 } else {
2066 bail!(
2067 "asset tree contains a special file: {}",
2068 entry.path().display()
2069 );
2070 }
2071 }
2072 Ok(())
2073}
2074
2075fn asset_content_type(path: &Path) -> Option<&'static str> {
2076 let extension = path.extension()?.to_str()?.to_ascii_lowercase();
2077 Some(match extension.as_str() {
2078 "html" | "htm" => "text/html; charset=utf-8",
2079 "css" => "text/css; charset=utf-8",
2080 "js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
2081 "json" | "map" => "application/json; charset=utf-8",
2082 "txt" => "text/plain; charset=utf-8",
2083 "xml" => "application/xml; charset=utf-8",
2084 "svg" => "image/svg+xml",
2085 "webmanifest" => "application/manifest+json; charset=utf-8",
2086 "wasm" => "application/wasm",
2087 "png" => "image/png",
2088 "jpg" | "jpeg" => "image/jpeg",
2089 "gif" => "image/gif",
2090 "webp" => "image/webp",
2091 "avif" => "image/avif",
2092 "ico" => "image/x-icon",
2093 "pdf" => "application/pdf",
2094 "woff" => "font/woff",
2095 "woff2" => "font/woff2",
2096 "ttf" => "font/ttf",
2097 "otf" => "font/otf",
2098 "mp3" => "audio/mpeg",
2099 "wav" => "audio/wav",
2100 "ogg" => "audio/ogg",
2101 "mp4" => "video/mp4",
2102 "webm" => "video/webm",
2103 "zip" => "application/zip",
2104 "gz" => "application/gzip",
2105 "br" => "application/octet-stream",
2106 _ => return None,
2107 })
2108}
2109
2110/// esbuild's outputs: the bundled entry module, and the wasm files its
2111/// imports were resolved to (each under the name the rewritten import uses).
2112struct BundleOutput {
2113 bundle: Vec<u8>,
2114 wasm: Vec<(String, Vec<u8>)>,
2115}
2116
2117fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<BundleOutput> {
2118 // node: builtins stay external. Wrangler polyfills them with unenv; celld
2119 // implements the workerd `nodejs_compat` subset itself, so the runtime
2120 // provides them.
2121 let binary = std::env::var("CELLD_ESBUILD").unwrap_or_else(|_| "esbuild".to_string());
2122 let outdir = tempfile::tempdir().context("create esbuild output directory")?;
2123 let output = Command::new(&binary)
2124 .current_dir(root)
2125 .arg(entry)
2126 .arg("--bundle")
2127 .arg("--format=esm")
2128 .arg("--platform=browser")
2129 .arg("--target=es2024")
2130 .arg("--conditions=workerd,worker,browser")
2131 .arg("--external:node:*")
2132 .arg("--external:cloudflare:*")
2133 .args(
2134 crate::js::BARE_NODE_BUILTINS
2135 .iter()
2136 .map(|specifier| format!("--external:{specifier}")),
2137 )
2138 // Wasm becomes a sibling module (Wrangler's CompiledWasm rule). The
2139 // `copy` loader makes esbuild resolve each wasm import like any other
2140 // import (importer-relative, node_modules, deduplicated) and rewrite
2141 // the specifier to the copied file, so the bundle and the emitted
2142 // files agree on names; the runtime serves each file as a compiled
2143 // WebAssembly.Module default export.
2144 .arg("--loader:.wasm=copy")
2145 .arg(format!("--outdir={}", outdir.path().display()))
2146 .arg("--entry-names=index")
2147 .output()
2148 .map_err(|error| {
2149 if error.kind() == std::io::ErrorKind::NotFound {
2150 anyhow!(
2151 "esbuild not found ({binary}).\n\
2152 `celld deploy` bundles with esbuild; install it and retry,\n\
2153 or set CELLD_ESBUILD to its path."
2154 )
2155 } else {
2156 anyhow!("run esbuild: {error}")
2157 }
2158 })?;
2159 if !output.status.success() {
2160 bail!(
2161 "esbuild failed:\n{}",
2162 String::from_utf8_lossy(&output.stderr).trim()
2163 );
2164 }
2165 let bundle =
2166 std::fs::read(outdir.path().join("index.js")).context("read esbuild output bundle")?;
2167 // The copied wasm files land beside the bundle; each becomes its own
2168 // deployed module under the name the rewritten imports use.
2169 let mut wasm = Vec::new();
2170 for dirent in std::fs::read_dir(outdir.path()).context("read esbuild output directory")? {
2171 let path = dirent?.path();
2172 if path.extension().and_then(|extension| extension.to_str()) == Some("wasm") {
2173 let name = path
2174 .file_name()
2175 .expect("read_dir entries have a file name")
2176 .to_string_lossy()
2177 .into_owned();
2178 let bytes = std::fs::read(&path)
2179 .with_context(|| format!("read wasm module {}", path.display()))?;
2180 wasm.push((name, bytes));
2181 }
2182 }
2183 // read_dir order is platform-defined; the deployment version hashes the
2184 // module list, so keep it stable.
2185 wasm.sort();
2186 Ok(BundleOutput { bundle, wasm })
2187}
2188
2189/// Minimal JSONC support: line and block comments, and trailing commas.
2190/// String contents are preserved verbatim.
2191fn strip_jsonc(source: &str) -> String {
2192 let mut out = String::with_capacity(source.len());
2193 let mut chars = source.chars().peekable();
2194 let mut in_string = false;
2195 let mut escaped = false;
2196 while let Some(c) = chars.next() {
2197 if in_string {
2198 out.push(c);
2199 if escaped {
2200 escaped = false;
2201 } else if c == '\\' {
2202 escaped = true;
2203 } else if c == '"' {
2204 in_string = false;
2205 }
2206 continue;
2207 }
2208 match c {
2209 '"' => {
2210 in_string = true;
2211 out.push(c);
2212 }
2213 '/' if chars.peek() == Some(&'/') => {
2214 for c in chars.by_ref() {
2215 if c == '\n' {
2216 out.push('\n');
2217 break;
2218 }
2219 }
2220 }
2221 '/' if chars.peek() == Some(&'*') => {
2222 chars.next();
2223 let mut previous = '\0';
2224 for c in chars.by_ref() {
2225 if previous == '*' && c == '/' {
2226 break;
2227 }
2228 previous = c;
2229 }
2230 }
2231 '}' | ']' => {
2232 // The comma this closes is trailing; drop it, keep the layout.
2233 let trimmed = out.trim_end().len();
2234 if out[..trimmed].ends_with(',') {
2235 out.remove(trimmed - 1);
2236 }
2237 out.push(c);
2238 }
2239 _ => out.push(c),
2240 }
2241 }
2242 out
2243}