| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! One application deployment as the running process holds it. |
| 4 | //! |
| 5 | //! A [`Generation`] is everything a node derives from a deployment: the |
| 6 | //! compiled Worker configurations, the isolate pools they run in, the |
| 7 | //! Durable Object class registry, the service-binding graph, the asset |
| 8 | //! resolvers, and the cron schedule. A node serves exactly one current |
| 9 | //! generation and reaches it through a snapshot, so a request that started |
| 10 | //! on one generation finishes on it even after the node adopts another. |
| 11 | //! |
| 12 | //! Boot and reload construct a generation through the same two functions, |
| 13 | //! [`DeploymentGraph::load`] and `Generation::build`. Nothing else reads a |
| 14 | //! deployment manifest into runtime state. A value a deployment implies |
| 15 | //! therefore has one place it can be computed, and a reload cannot miss what |
| 16 | //! a boot did, because there is no second path for it to miss. |
| 17 | |
| 18 | use std::collections::hash_map::Entry; |
| 19 | use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; |
| 20 | use std::sync::Arc; |
| 21 | |
| 22 | use anyhow::{anyhow, Context}; |
| 23 | |
| 24 | use crate::assets::AssetResolver; |
| 25 | use crate::bucket::Bucket; |
| 26 | use crate::fleet::{self, LoadedDeployment}; |
| 27 | use crate::js::{WorkerConfig, WorkerConfigOptions}; |
| 28 | |
| 29 | /// Which generation, within this process. Monotonic from one at boot; never |
| 30 | /// reused, never persisted, and never compared across nodes — the fleet-wide |
| 31 | /// identity of a deployment is its version string. |
| 32 | pub type GenerationId = u64; |
| 33 | |
| 34 | /// The generation a node boots on. Later generations count up from it. |
| 35 | pub const FIRST_GENERATION: GenerationId = 1; |
| 36 | |
| 37 | /// Ask the node to adopt the deployment `deploy/current.json` names now. |
| 38 | pub struct ReloadRequest { |
| 39 | /// Rebuild even when the pointer names the current deployment, so a |
| 40 | /// memoised failure is retried and fresh isolates replace the serving |
| 41 | /// ones. `POST /reload` sets it; a poll tick and a managed nudge do not. |
| 42 | pub force: bool, |
| 43 | /// Where to report the outcome. A poll tick has nobody to tell. |
| 44 | pub reply: Option<tokio::sync::oneshot::Sender<ReloadOutcome>>, |
| 45 | } |
| 46 | |
| 47 | /// What one adoption attempt concluded. |
| 48 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 49 | pub enum ReloadOutcome { |
| 50 | /// A new generation serves. Requests admitted from now on use it. |
| 51 | Adopted { |
| 52 | generation: GenerationId, |
| 53 | version: String, |
| 54 | prefix: String, |
| 55 | }, |
| 56 | /// The pointer names the deployment already serving and the request did |
| 57 | /// not force a rebuild. |
| 58 | Unchanged { |
| 59 | generation: GenerationId, |
| 60 | version: String, |
| 61 | }, |
| 62 | /// The deployment did not build. The current generation is untouched. |
| 63 | Failed { |
| 64 | version: String, |
| 65 | prefix: String, |
| 66 | error: String, |
| 67 | }, |
| 68 | } |
| 69 | |
| 70 | pub type ReloadSender = tokio::sync::mpsc::UnboundedSender<ReloadRequest>; |
| 71 | pub type ReloadReceiver = tokio::sync::mpsc::UnboundedReceiver<ReloadRequest>; |
| 72 | |
| 73 | pub fn reload_channel() -> (ReloadSender, ReloadReceiver) { |
| 74 | tokio::sync::mpsc::unbounded_channel() |
| 75 | } |
| 76 | |
| 77 | /// Ask for a poll now, without waiting for the outcome. A managed |
| 78 | /// `deployment_current` message and a successful apply both end here: the |
| 79 | /// pointer is the authority, and the nudge only shortens the wait for it. |
| 80 | pub fn nudge(reload: &ReloadSender) { |
| 81 | let _ = reload.send(ReloadRequest { |
| 82 | force: false, |
| 83 | reply: None, |
| 84 | }); |
| 85 | } |
| 86 | |
| 87 | /// How often a node re-reads the pointer without a nudge. For a standalone |
| 88 | /// node this is the deploy latency; for a managed node it is the backstop |
| 89 | /// behind the push. `CELLD_DEPLOY_POLL_S`, default 30. |
| 90 | pub fn poll_interval() -> std::time::Duration { |
| 91 | let seconds = crate::env_vars::positive_or("CELLD_DEPLOY_POLL_S", 30u64) |
| 92 | .expect("validated CELLD_DEPLOY_POLL_S"); |
| 93 | std::time::Duration::from_secs(seconds) |
| 94 | } |
| 95 | |
| 96 | /// How long a resident cell may keep running a superseded generation after |
| 97 | /// the node adopts a new one, before its swap is forced: its activity |
| 98 | /// cancelled and its regular WebSockets closed with 1012. Zero forces every |
| 99 | /// resident cell at the flip, which is what a Cloudflare deployment does. |
| 100 | /// `CELLD_DEPLOY_MAX_AGE_S`, default 60. |
| 101 | pub fn max_age() -> std::time::Duration { |
| 102 | // Not `positive_or`: zero is meaningful here. |
| 103 | let seconds = crate::env_vars::with_default("CELLD_DEPLOY_MAX_AGE_S", 60u64) |
| 104 | .expect("validated CELLD_DEPLOY_MAX_AGE_S"); |
| 105 | std::time::Duration::from_secs(seconds) |
| 106 | } |
| 107 | |
| 108 | /// The scripts one deployment reaches: the primary script plus every |
| 109 | /// service-binding target and queue consumer it declares, transitively. |
| 110 | /// |
| 111 | /// [`DeploymentGraph::load`] is the only bucket walk, so the boot path and |
| 112 | /// the reload path cannot resolve a deployment's dependencies differently. |
| 113 | pub struct DeploymentGraph { |
| 114 | pub primary: LoadedDeployment, |
| 115 | pub cohosted: Vec<LoadedDeployment>, |
| 116 | } |
| 117 | |
| 118 | impl DeploymentGraph { |
| 119 | /// One script and nothing else: the local-script mode a runtime test |
| 120 | /// starts from a file, which declares no services and has no bucket to |
| 121 | /// resolve them from. |
| 122 | pub fn single(primary: LoadedDeployment) -> Self { |
| 123 | Self { |
| 124 | primary, |
| 125 | cohosted: Vec::new(), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Resolve the fleet-wide pointer and every script it depends on. |
| 130 | /// |
| 131 | /// A service binding names a script, and that script's own pointer names |
| 132 | /// its deployment. A queue dependency names a queue, and the queue's |
| 133 | /// consumer attachment names an exact deployment. The walk refuses a |
| 134 | /// script that resolves twice and a queue attached to a deployment other |
| 135 | /// than the one already loaded, because either would give one script two |
| 136 | /// bodies in one process. |
| 137 | pub async fn load(bucket: &Bucket, node: String) -> anyhow::Result<Self> { |
| 138 | let primary = fleet::load_current_worker(bucket, node.clone()).await?; |
| 139 | let primary_script = primary.script_name.clone(); |
| 140 | let mut loaded_scripts = BTreeMap::from([(primary_script.clone(), primary.prefix.clone())]); |
| 141 | let mut loaded_consumers = |
| 142 | BTreeMap::from([(primary_script.clone(), consumed_queues(&primary.options))]); |
| 143 | let mut visited_queues = BTreeSet::new(); |
| 144 | let mut dependencies = dependencies_of(&primary); |
| 145 | let mut cohosted = Vec::new(); |
| 146 | while let Some(dependency) = dependencies.pop_front() { |
| 147 | let loaded = match dependency { |
| 148 | Dependency::Service(target) => { |
| 149 | if target == primary_script || loaded_scripts.contains_key(&target) { |
| 150 | continue; |
| 151 | } |
| 152 | let loaded = fleet::load_named_worker(bucket, &target, node.clone()) |
| 153 | .await |
| 154 | .with_context(|| format!("load service binding target {target}"))?; |
| 155 | if loaded.script_name != target { |
| 156 | anyhow::bail!( |
| 157 | "service pointer {target} resolved script {}", |
| 158 | loaded.script_name |
| 159 | ); |
| 160 | } |
| 161 | loaded |
| 162 | } |
| 163 | Dependency::Queue(queue) => { |
| 164 | if !visited_queues.insert(queue.clone()) { |
| 165 | continue; |
| 166 | } |
| 167 | let declared_by = loaded_consumers |
| 168 | .iter() |
| 169 | .find_map(|(script, queues)| queues.contains(&queue).then_some(script)); |
| 170 | let Some(consumer) = |
| 171 | fleet::load_queue_consumer_attachment(bucket, &queue).await? |
| 172 | else { |
| 173 | if let Some(script) = declared_by { |
| 174 | anyhow::bail!( |
| 175 | "script {script:?} consumes queue {queue:?}, but the queue has no active consumer attachment; re-run `celld deploy`" |
| 176 | ); |
| 177 | } |
| 178 | continue; |
| 179 | }; |
| 180 | if let Some(script) = declared_by { |
| 181 | anyhow::ensure!( |
| 182 | script == &consumer.script_name, |
| 183 | "queue {queue:?} is attached to script {:?}, but loaded script {script:?} also consumes it", |
| 184 | consumer.script_name |
| 185 | ); |
| 186 | } |
| 187 | if let Some(prefix) = loaded_scripts.get(&consumer.script_name) { |
| 188 | anyhow::ensure!( |
| 189 | prefix == &consumer.prefix, |
| 190 | "queue {queue:?} is attached to deployment {} of script {:?}, but deployment {prefix} is already loaded; re-run `celld deploy`", |
| 191 | consumer.version, |
| 192 | consumer.script_name |
| 193 | ); |
| 194 | anyhow::ensure!( |
| 195 | loaded_consumers |
| 196 | .get(&consumer.script_name) |
| 197 | .is_some_and(|queues| queues.contains(&queue)), |
| 198 | "queue {queue:?} is attached to script {:?}, but its loaded deployment does not consume that queue", |
| 199 | consumer.script_name |
| 200 | ); |
| 201 | continue; |
| 202 | } |
| 203 | fleet::load_queue_consumer_worker(bucket, &queue, &consumer, node.clone()) |
| 204 | .await |
| 205 | .with_context(|| format!("load consumer for queue {queue:?}"))? |
| 206 | } |
| 207 | }; |
| 208 | let target = loaded.script_name.clone(); |
| 209 | anyhow::ensure!( |
| 210 | loaded_scripts |
| 211 | .insert(target.clone(), loaded.prefix.clone()) |
| 212 | .is_none(), |
| 213 | "script {target:?} was loaded twice" |
| 214 | ); |
| 215 | loaded_consumers.insert(target.clone(), consumed_queues(&loaded.options)); |
| 216 | dependencies.extend(dependencies_of(&loaded)); |
| 217 | // A node runs the schedule of the deployment it was given and of |
| 218 | // no other. The reserved class is one key, so a second script's |
| 219 | // cron cell would resolve to the first script's config and run |
| 220 | // the wrong `scheduled` handler. Dropping the schedule is the |
| 221 | // safe half of that trade and this says so out loud, because a |
| 222 | // trigger that never fires and says nothing is the failure the |
| 223 | // whole feature is built to avoid. Deploy the script as a node's |
| 224 | // own deployment to run its crons. |
| 225 | if !loaded.crons.is_empty() { |
| 226 | tracing::warn!( |
| 227 | script = %target, |
| 228 | crons = %loaded.crons.join(", "), |
| 229 | "a service binding target declares cron triggers; a node fires only its own deployment's schedule, so these never run here" |
| 230 | ); |
| 231 | } |
| 232 | cohosted.push(loaded); |
| 233 | } |
| 234 | Ok(Self { primary, cohosted }) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | enum Dependency { |
| 239 | Service(String), |
| 240 | Queue(String), |
| 241 | } |
| 242 | |
| 243 | fn consumed_queues(options: &WorkerConfigOptions) -> BTreeSet<String> { |
| 244 | options |
| 245 | .queue_consumers |
| 246 | .iter() |
| 247 | .map(|consumer| consumer.queue.clone()) |
| 248 | .collect() |
| 249 | } |
| 250 | |
| 251 | fn dependencies_of(loaded: &LoadedDeployment) -> VecDeque<Dependency> { |
| 252 | let queues = loaded |
| 253 | .options |
| 254 | .queue_bindings |
| 255 | .iter() |
| 256 | .map(|binding| binding.queue.clone()) |
| 257 | .chain(loaded.options.queue_consumers.iter().flat_map(|consumer| { |
| 258 | std::iter::once(consumer.queue.clone()).chain(consumer.dead_letter_queue.clone()) |
| 259 | })) |
| 260 | .collect::<BTreeSet<_>>(); |
| 261 | loaded |
| 262 | .services |
| 263 | .iter() |
| 264 | .map(|(_, script, _)| Dependency::Service(script.clone())) |
| 265 | .chain(queues.into_iter().map(Dependency::Queue)) |
| 266 | .collect() |
| 267 | } |
| 268 | |
| 269 | /// Node-level inputs `Generation::build` needs beside the deployment itself. |
| 270 | pub struct GenerationOptions { |
| 271 | pub node: String, |
| 272 | pub region: String, |
| 273 | } |
| 274 | |
| 275 | /// A deployment, built and ready to serve. |
| 276 | /// |
| 277 | /// The fields are the four maps `RuntimeManager` once held for the life of |
| 278 | /// the process, plus the asset resolvers and the cron schedule that lived on |
| 279 | /// the application handle. They are private and reached through |
| 280 | /// `RuntimeManager`, which hands out this struct only as a snapshot. |
| 281 | pub struct Generation { |
| 282 | pub(crate) id: GenerationId, |
| 283 | pub(crate) version: String, |
| 284 | pub(crate) prefix: String, |
| 285 | pub(crate) script_name: String, |
| 286 | pub(crate) stateless: crate::runtime::StatelessRuntime, |
| 287 | pub(crate) services: HashMap<String, crate::runtime::StatelessRuntime>, |
| 288 | pub(crate) cell_configs: HashMap<String, Arc<WorkerConfig>>, |
| 289 | /// The isolates a Worker script's cells live in — the same `Pool` the |
| 290 | /// stateless path admits into, because an isolate is an isolate. Cells |
| 291 | /// of one script share them, so cells of one class share module scope |
| 292 | /// exactly when they are colocated, which is what Durable Objects do. |
| 293 | pub(crate) cell_isolates: HashMap<String, Arc<crate::pool::Pool>>, |
| 294 | pub(crate) default_do_class: Option<Arc<str>>, |
| 295 | pub(crate) assets: HashMap<String, AssetResolver>, |
| 296 | /// Every container class of every script in the graph. |
| 297 | pub(crate) containers: Vec<crate::container::ContainerSpec>, |
| 298 | /// See `Manifest::fence_image`; the first script's, they are all the |
| 299 | /// same image when one celld deployed them. |
| 300 | pub(crate) fence_image: Option<String>, |
| 301 | } |
| 302 | |
| 303 | impl Generation { |
| 304 | pub fn id(&self) -> GenerationId { |
| 305 | self.id |
| 306 | } |
| 307 | |
| 308 | pub fn version(&self) -> &str { |
| 309 | &self.version |
| 310 | } |
| 311 | |
| 312 | pub fn prefix(&self) -> &str { |
| 313 | &self.prefix |
| 314 | } |
| 315 | |
| 316 | /// The primary script: the one ingress serves and whose assets ingress |
| 317 | /// consults before running the Worker. |
| 318 | pub fn script_name(&self) -> &str { |
| 319 | &self.script_name |
| 320 | } |
| 321 | |
| 322 | /// The asset resolver of the named script, if that script deployed |
| 323 | /// assets. |
| 324 | pub fn assets(&self, script: &str) -> Option<&AssetResolver> { |
| 325 | self.assets.get(script) |
| 326 | } |
| 327 | |
| 328 | /// The primary script's asset resolver, which ingress consults. |
| 329 | pub fn ingress_assets(&self) -> Option<&AssetResolver> { |
| 330 | self.assets.get(&self.script_name) |
| 331 | } |
| 332 | |
| 333 | pub fn has_cell_classes(&self) -> bool { |
| 334 | !self.cell_configs.is_empty() |
| 335 | } |
| 336 | |
| 337 | /// The reserved cell carrying this deployment's cron schedule, or `None` |
| 338 | /// when the deployment declares no `triggers.crons`. Derived from the |
| 339 | /// registered class rather than plumbed separately, so it cannot |
| 340 | /// disagree with what `start_cell` will accept. |
| 341 | pub fn cron_cell(&self) -> Option<String> { |
| 342 | self.cell_configs |
| 343 | .get(celld_logic::cron::RESERVED_CLASS) |
| 344 | .map(|config| celld_logic::cron::reserved_cell(&config.script_name)) |
| 345 | } |
| 346 | |
| 347 | pub(crate) fn cell_config(&self, class: &str) -> Option<Arc<WorkerConfig>> { |
| 348 | self.cell_configs.get(class).cloned() |
| 349 | } |
| 350 | |
| 351 | /// The engine's reserved Durable Object classes this generation |
| 352 | /// registers: cron, queue, workflow, D1, KV. Their cells hold no |
| 353 | /// application state worth waiting for, so an adoption moves them at |
| 354 | /// once — and the cron cell must run the new schedule before the |
| 355 | /// adoption arms it. |
| 356 | /// |
| 357 | /// The cron class is named beside `deploy::is_reserved_class` rather |
| 358 | /// than added to it. That predicate also decides which classes refuse an |
| 359 | /// unauthenticated operator route, and the cron cell is not one of them, |
| 360 | /// so widening it to reach this list would widen that refusal too. |
| 361 | pub fn reserved_classes(&self) -> Vec<String> { |
| 362 | self.cell_configs |
| 363 | .keys() |
| 364 | .filter(|class| { |
| 365 | crate::deploy::is_reserved_class(class) |
| 366 | || class.as_str() == celld_logic::cron::RESERVED_CLASS |
| 367 | }) |
| 368 | .cloned() |
| 369 | .collect() |
| 370 | } |
| 371 | |
| 372 | pub(crate) fn cell_isolates(&self, script: &str) -> Option<Arc<crate::pool::Pool>> { |
| 373 | self.cell_isolates.get(script).cloned() |
| 374 | } |
| 375 | |
| 376 | pub(crate) fn service(&self, script: &str) -> Option<crate::runtime::StatelessRuntime> { |
| 377 | self.services.get(script).cloned() |
| 378 | } |
| 379 | |
| 380 | pub(crate) fn default_do_class(&self) -> Option<&str> { |
| 381 | self.default_do_class.as_deref() |
| 382 | } |
| 383 | |
| 384 | /// Stop every isolate of this generation from taking new work. Stateless |
| 385 | /// isolates free as their affiliations drop; cell isolates free as their |
| 386 | /// cells move to a newer generation. |
| 387 | pub(crate) fn retire(&self) { |
| 388 | for service in self.services.values() { |
| 389 | service.isolates.retire_all(); |
| 390 | } |
| 391 | for pool in self.cell_isolates.values() { |
| 392 | pool.retire_all(); |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | /// Whether every isolate of this generation has been freed, so the |
| 397 | /// generation itself can be dropped. |
| 398 | pub(crate) fn is_drained(&self) -> bool { |
| 399 | self.services |
| 400 | .values() |
| 401 | .all(|service| service.isolates.is_drained()) |
| 402 | && self.cell_isolates.values().all(|pool| pool.is_drained()) |
| 403 | } |
| 404 | |
| 405 | /// One maintenance pass over the cell pools: retire and free every empty |
| 406 | /// isolate. An empty cell heap carries no warm request capacity worth |
| 407 | /// preserving, unlike a stateless one. |
| 408 | pub(crate) fn reap_cell_pools(&self) { |
| 409 | for pool in self.cell_isolates.values() { |
| 410 | pool.reap_empty(); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /// The isolates this generation holds right now, for `/state`. |
| 415 | pub(crate) fn isolate_census(&self) -> IsolateCensus { |
| 416 | IsolateCensus { |
| 417 | stateless: self.stateless.isolates.census(), |
| 418 | services: self |
| 419 | .services |
| 420 | .iter() |
| 421 | .map(|(name, service)| (name.clone(), service.isolates.census())) |
| 422 | .collect(), |
| 423 | cells: self |
| 424 | .cell_isolates |
| 425 | .iter() |
| 426 | .map(|(script, pool)| (script.clone(), pool.census())) |
| 427 | .collect(), |
| 428 | } |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /// The isolates one generation holds, by the pool they belong to, as |
| 433 | /// `/state` reports them. |
| 434 | #[derive(Debug, serde::Serialize)] |
| 435 | pub struct IsolateCensus { |
| 436 | /// The pool that serves the primary script's stateless handlers. |
| 437 | pub stateless: crate::pool::PoolCensus, |
| 438 | /// The pools of the named services, by service name. |
| 439 | pub services: BTreeMap<String, crate::pool::PoolCensus>, |
| 440 | /// The pools the cells live in, by Worker script. |
| 441 | pub cells: BTreeMap<String, crate::pool::PoolCensus>, |
| 442 | } |
| 443 | |
| 444 | /// The generation an isolate was built for, installed as an isolate slot by |
| 445 | /// `Worker::load_config` so a call the isolate makes into the host — a |
| 446 | /// service binding, an assets binding, a queue dispatch — resolves against |
| 447 | /// the graph the caller was built with rather than whichever generation is |
| 448 | /// current when the call lands. |
| 449 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 450 | pub struct GenerationTag(pub GenerationId); |
| 451 | impl Generation { |
| 452 | /// Build a deployment into a generation that can serve. |
| 453 | /// |
| 454 | /// Every script in the graph is compiled and its primary pool warmed, so |
| 455 | /// a bundle that does not load, or declares a Durable Object class it |
| 456 | /// does not export, fails here — before the generation can take traffic |
| 457 | /// — rather than on the first request. The Durable Object classes of |
| 458 | /// every script form one flat registry, because `start_cell` resolves a |
| 459 | /// cell by the class its scope names and nothing else. |
| 460 | /// |
| 461 | /// Boot and reload both come through here. There is no other function |
| 462 | /// that turns a deployment into runtime state. |
| 463 | pub fn build( |
| 464 | id: GenerationId, |
| 465 | graph: DeploymentGraph, |
| 466 | options: GenerationOptions, |
| 467 | ) -> anyhow::Result<Self> { |
| 468 | let GenerationOptions { node, region } = options; |
| 469 | let DeploymentGraph { primary, cohosted } = graph; |
| 470 | crate::runtime::init_engine(); |
| 471 | |
| 472 | // A Queue class is shared by every co-hosted script, but its broker |
| 473 | // needs the consumer script rather than whichever script happened to |
| 474 | // register `__Queue` first. Resolve one deployment-wide catalog before |
| 475 | // constructing any WorkerConfig, then install the same catalog into |
| 476 | // every isolate that could host a queue cell. |
| 477 | let mut queue_catalog = BTreeMap::new(); |
| 478 | for (script, consumers) in |
| 479 | std::iter::once((&primary.script_name, &primary.options.queue_consumers)).chain( |
| 480 | cohosted |
| 481 | .iter() |
| 482 | .map(|target| (&target.script_name, &target.options.queue_consumers)), |
| 483 | ) |
| 484 | { |
| 485 | for consumer in consumers { |
| 486 | let registration = crate::js::QueueConsumerRegistration { |
| 487 | script: script.clone(), |
| 488 | config: consumer.clone(), |
| 489 | }; |
| 490 | if let Some(previous) = queue_catalog.insert(consumer.queue.clone(), registration) { |
| 491 | return Err(anyhow!( |
| 492 | "queue {:?} is consumed by both {} and {}", |
| 493 | consumer.queue, |
| 494 | previous.script, |
| 495 | script |
| 496 | )); |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | let queue_catalog = queue_catalog.into_values().collect::<Vec<_>>(); |
| 501 | |
| 502 | let node: Arc<str> = Arc::from(node); |
| 503 | let region: Arc<str> = Arc::from(region); |
| 504 | let primary_script = primary.script_name.clone(); |
| 505 | let version = primary.version.clone(); |
| 506 | let prefix = primary.prefix.clone(); |
| 507 | let mut all_containers = Vec::new(); |
| 508 | let mut fence_image = None; |
| 509 | // Only classes the user declared can be a bare-id default. Every |
| 510 | // runtime-supplied class rides in `do_classes` so that its namespace |
| 511 | // key is minted, and counting one here made adding any D1 binding flip |
| 512 | // a one-class project past the `len == 1` condition — every |
| 513 | // `/do/<bare-id>` request then failed with "requires exactly one |
| 514 | // configured Durable Object class" for a config that still declared |
| 515 | // exactly one. |
| 516 | // |
| 517 | // This asks `deploy::is_reserved_class` rather than naming one class, |
| 518 | // because the first version of this filter named `__D1Database` alone |
| 519 | // and `__Workflow` walked straight back into the same bug when it |
| 520 | // shipped. A fourth reserved class must not be able to do it a third |
| 521 | // time. |
| 522 | let user_classes: Vec<&String> = primary |
| 523 | .options |
| 524 | .do_classes |
| 525 | .iter() |
| 526 | .filter(|class| !crate::deploy::is_reserved_class(class)) |
| 527 | .collect(); |
| 528 | let default_do_class = |
| 529 | (user_classes.len() == 1).then(|| Arc::from(user_classes[0].as_str())); |
| 530 | // Two scripts exporting one class name is genuinely ambiguous and is |
| 531 | // refused — but a *reserved* class is not an export, and the two kinds |
| 532 | // behave differently: |
| 533 | // |
| 534 | // `__D1Database` is deliberately shared. Its namespace is fleet-wide so |
| 535 | // that several Workers can bind one database and a rename cannot rename |
| 536 | // it, so two scripts declaring `d1_databases` address the same cells on |
| 537 | // purpose. A D1 cell runs SQL and reads no user code, binding or var, |
| 538 | // so whichever config serves it is immaterial and the first wins. |
| 539 | // Refusing the second made the node exit instead of start. |
| 540 | // |
| 541 | // A workflow class is script-scoped (`deploy::workflow_class`), so two |
| 542 | // scripts produce two distinct names and never reach this branch. If |
| 543 | // one ever did, it would be a real collision and must still be refused. |
| 544 | let mut cell_configs: HashMap<String, Arc<WorkerConfig>> = HashMap::new(); |
| 545 | let mut service_pools = HashMap::new(); |
| 546 | let mut assets = HashMap::new(); |
| 547 | // Primary first: shared reserved classes retain the first script's |
| 548 | // config. Only this script owns ingress and the node's cron schedule; |
| 549 | // bindings and runtime construction follow the same path for all scripts. |
| 550 | for (index, deployment) in std::iter::once(primary).chain(cohosted).enumerate() { |
| 551 | let is_primary = index == 0; |
| 552 | let crate::fleet::LoadedDeployment { |
| 553 | options, |
| 554 | script_name: script, |
| 555 | asset_binding, |
| 556 | loader_bindings, |
| 557 | media_bindings, |
| 558 | version_metadata, |
| 559 | assets: resolver, |
| 560 | services, |
| 561 | crons, |
| 562 | containers, |
| 563 | fence_image: fence, |
| 564 | .. |
| 565 | } = deployment; |
| 566 | all_containers.extend(containers.iter().cloned()); |
| 567 | fence_image = fence_image.or(fence); |
| 568 | if let Some(resolver) = resolver { |
| 569 | assets.insert(script.clone(), resolver); |
| 570 | } |
| 571 | let classes = options.do_classes.clone(); |
| 572 | let config = Arc::new( |
| 573 | WorkerConfig::new(options) |
| 574 | .with_services(services) |
| 575 | .with_asset_binding(asset_binding) |
| 576 | .with_loaders(loader_bindings) |
| 577 | .with_media(media_bindings) |
| 578 | .with_version_metadata(version_metadata) |
| 579 | .with_queue_consumers(queue_catalog.clone()) |
| 580 | .with_crons(if is_primary { crons } else { Vec::new() }) |
| 581 | .with_containers(containers) |
| 582 | .with_generation(id), |
| 583 | ); |
| 584 | let pool = crate::runtime::StatelessRuntime::start( |
| 585 | config.clone(), |
| 586 | node.clone(), |
| 587 | region.clone(), |
| 588 | )?; |
| 589 | if service_pools.insert(script.clone(), pool).is_some() { |
| 590 | return Err(anyhow!("duplicate co-hosted Worker script {script}")); |
| 591 | } |
| 592 | for class in classes { |
| 593 | register_cell_class(&mut cell_configs, class, config.clone(), &|class| { |
| 594 | if is_primary { |
| 595 | anyhow!("duplicate Durable Object class {class}") |
| 596 | } else { |
| 597 | anyhow!( |
| 598 | "Durable Object class {class} is exported by more than one co-hosted script" |
| 599 | ) |
| 600 | } |
| 601 | })?; |
| 602 | } |
| 603 | // Cron is runtime-supplied, not a manifest class. Its alarm calls |
| 604 | // the primary script's scheduled handler with that script's bindings. |
| 605 | if !config.crons.is_empty() { |
| 606 | cell_configs.insert(celld_logic::cron::RESERVED_CLASS.to_string(), config); |
| 607 | } |
| 608 | } |
| 609 | let stateless = service_pools[&primary_script].clone(); |
| 610 | let cell_isolates: HashMap<String, Arc<crate::pool::Pool>> = cell_configs |
| 611 | .values() |
| 612 | .map(|config| { |
| 613 | ( |
| 614 | config.script_name.clone(), |
| 615 | crate::runtime::cell_pool(config.clone()), |
| 616 | ) |
| 617 | }) |
| 618 | .collect(); |
| 619 | Ok(Generation { |
| 620 | id, |
| 621 | version, |
| 622 | prefix, |
| 623 | script_name: primary_script, |
| 624 | stateless, |
| 625 | services: service_pools, |
| 626 | cell_configs, |
| 627 | cell_isolates, |
| 628 | default_do_class, |
| 629 | assets, |
| 630 | containers: all_containers, |
| 631 | fence_image, |
| 632 | }) |
| 633 | } |
| 634 | } |
| 635 | /// Claim one class name in a deployment's cell registry. |
| 636 | /// |
| 637 | /// A duplicate is an error for a user class, because `start_cell` resolves a |
| 638 | /// cell from the class its scope names and two exports of one name are |
| 639 | /// genuinely ambiguous. A duplicate of a *shared* reserved class is not: see |
| 640 | /// `deploy::is_shared_reserved_class`. The caller supplies the error so the |
| 641 | /// message can say whether the collision was inside one script or across two. |
| 642 | fn register_cell_class( |
| 643 | configs: &mut HashMap<String, Arc<WorkerConfig>>, |
| 644 | class: String, |
| 645 | config: Arc<WorkerConfig>, |
| 646 | duplicate: &dyn Fn(&str) -> anyhow::Error, |
| 647 | ) -> anyhow::Result<()> { |
| 648 | match configs.entry(class) { |
| 649 | Entry::Vacant(slot) => { |
| 650 | slot.insert(config); |
| 651 | Ok(()) |
| 652 | } |
| 653 | Entry::Occupied(slot) if crate::deploy::is_shared_reserved_class(slot.key()) => Ok(()), |
| 654 | Entry::Occupied(slot) => Err(duplicate(slot.key())), |
| 655 | } |
| 656 | } |