Diffinery

homeflare/celldpublic

celld/crates/celld/generation.rs
420 lines · 17.2 KBRaw History
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
18use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
19use std::sync::Arc;
20
21use anyhow::Context;
22
23use crate::assets::AssetResolver;
24use crate::bucket::Bucket;
25use crate::fleet::{self, LoadedDeployment};
26use crate::js::{WorkerConfig, WorkerConfigOptions};
27
28/// Which generation, within this process. Monotonic from one at boot; never
29/// reused, never persisted, and never compared across nodes — the fleet-wide
30/// identity of a deployment is its version string.
31pub type GenerationId = u64;
32
33/// The generation a node boots on. Later generations count up from it.
34pub const FIRST_GENERATION: GenerationId = 1;
35
36/// Ask the node to adopt the deployment `deploy/current.json` names now.
37pub struct ReloadRequest {
38 /// Rebuild even when the pointer names the current deployment, so the
39 /// manifest and `CELLD_VARS_FILE` are read again. `POST /reload` sets it;
40 /// a poll tick and a managed nudge do not.
41 pub force: bool,
42 /// Where to report the outcome. A poll tick has nobody to tell.
43 pub reply: Option<tokio::sync::oneshot::Sender<ReloadOutcome>>,
44}
45
46/// What one adoption attempt concluded.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum ReloadOutcome {
49 /// A new generation serves. Requests admitted from now on use it.
50 Adopted {
51 generation: GenerationId,
52 version: String,
53 prefix: String,
54 },
55 /// The pointer names the deployment already serving and the request did
56 /// not force a rebuild.
57 Unchanged {
58 generation: GenerationId,
59 version: String,
60 },
61 /// The deployment did not build. The current generation is untouched.
62 Failed {
63 version: String,
64 prefix: String,
65 error: String,
66 },
67}
68
69pub type ReloadSender = tokio::sync::mpsc::UnboundedSender<ReloadRequest>;
70pub type ReloadReceiver = tokio::sync::mpsc::UnboundedReceiver<ReloadRequest>;
71
72pub fn reload_channel() -> (ReloadSender, ReloadReceiver) {
73 tokio::sync::mpsc::unbounded_channel()
74}
75
76/// Ask for a poll now, without waiting for the outcome. A managed
77/// `deployment_current` message and a successful apply both end here: the
78/// pointer is the authority, and the nudge only shortens the wait for it.
79pub fn nudge(reload: &ReloadSender) {
80 let _ = reload.send(ReloadRequest {
81 force: false,
82 reply: None,
83 });
84}
85
86/// How often a node re-reads the pointer without a nudge. For a standalone
87/// node this is the deploy latency; for a managed node it is the backstop
88/// behind the push. `CELLD_DEPLOY_POLL_S`, default 30.
89pub fn poll_interval() -> std::time::Duration {
90 let seconds = crate::env_vars::positive_or("CELLD_DEPLOY_POLL_S", 30u64)
91 .expect("validated CELLD_DEPLOY_POLL_S");
92 std::time::Duration::from_secs(seconds)
93}
94
95/// How long a resident cell may keep running a superseded generation after
96/// the node adopts a new one, before its swap is forced: its activity
97/// cancelled and its regular WebSockets closed with 1012. Zero forces every
98/// resident cell at the flip, which is what a Cloudflare deployment does.
99/// `CELLD_DEPLOY_MAX_AGE_S`, default 60.
100pub fn max_age() -> std::time::Duration {
101 // Not `positive_or`: zero is meaningful here.
102 let seconds = crate::env_vars::with_default("CELLD_DEPLOY_MAX_AGE_S", 60u64)
103 .expect("validated CELLD_DEPLOY_MAX_AGE_S");
104 std::time::Duration::from_secs(seconds)
105}
106
107/// The scripts one deployment reaches: the primary script plus every
108/// service-binding target and queue consumer it declares, transitively.
109///
110/// [`DeploymentGraph::load`] is the only bucket walk, so the boot path and
111/// the reload path cannot resolve a deployment's dependencies differently.
112pub struct DeploymentGraph {
113 pub primary: LoadedDeployment,
114 pub cohosted: Vec<LoadedDeployment>,
115}
116
117impl DeploymentGraph {
118 /// One script and nothing else: the local-script mode a runtime test
119 /// starts from a file, which declares no services and has no bucket to
120 /// resolve them from.
121 pub fn single(primary: LoadedDeployment) -> Self {
122 Self {
123 primary,
124 cohosted: Vec::new(),
125 }
126 }
127
128 /// Resolve the fleet-wide pointer and every script it depends on.
129 ///
130 /// A service binding names a script, and that script's own pointer names
131 /// its deployment. A queue dependency names a queue, and the queue's
132 /// consumer attachment names an exact deployment. The walk refuses a
133 /// script that resolves twice and a queue attached to a deployment other
134 /// than the one already loaded, because either would give one script two
135 /// bodies in one process.
136 pub async fn load(bucket: &Bucket, node: String) -> anyhow::Result<Self> {
137 let primary = fleet::load_current_worker(bucket, node.clone()).await?;
138 let primary_script = primary.script_name.clone();
139 let mut loaded_scripts = BTreeMap::from([(primary_script.clone(), primary.prefix.clone())]);
140 let mut loaded_consumers =
141 BTreeMap::from([(primary_script.clone(), consumed_queues(&primary.options))]);
142 let mut visited_queues = BTreeSet::new();
143 let mut dependencies = dependencies_of(&primary);
144 let mut cohosted = Vec::new();
145 while let Some(dependency) = dependencies.pop_front() {
146 let loaded = match dependency {
147 Dependency::Service(target) => {
148 if target == primary_script || loaded_scripts.contains_key(&target) {
149 continue;
150 }
151 let loaded = fleet::load_named_worker(bucket, &target, node.clone())
152 .await
153 .with_context(|| format!("load service binding target {target}"))?;
154 if loaded.script_name != target {
155 anyhow::bail!(
156 "service pointer {target} resolved script {}",
157 loaded.script_name
158 );
159 }
160 loaded
161 }
162 Dependency::Queue(queue) => {
163 if !visited_queues.insert(queue.clone()) {
164 continue;
165 }
166 let declared_by = loaded_consumers
167 .iter()
168 .find_map(|(script, queues)| queues.contains(&queue).then_some(script));
169 let Some(consumer) =
170 fleet::load_queue_consumer_attachment(bucket, &queue).await?
171 else {
172 if let Some(script) = declared_by {
173 anyhow::bail!(
174 "script {script:?} consumes queue {queue:?}, but the queue has no active consumer attachment; re-run `celld deploy`"
175 );
176 }
177 continue;
178 };
179 if let Some(script) = declared_by {
180 anyhow::ensure!(
181 script == &consumer.script_name,
182 "queue {queue:?} is attached to script {:?}, but loaded script {script:?} also consumes it",
183 consumer.script_name
184 );
185 }
186 if let Some(prefix) = loaded_scripts.get(&consumer.script_name) {
187 anyhow::ensure!(
188 prefix == &consumer.prefix,
189 "queue {queue:?} is attached to deployment {} of script {:?}, but deployment {prefix} is already loaded; re-run `celld deploy`",
190 consumer.version,
191 consumer.script_name
192 );
193 anyhow::ensure!(
194 loaded_consumers
195 .get(&consumer.script_name)
196 .is_some_and(|queues| queues.contains(&queue)),
197 "queue {queue:?} is attached to script {:?}, but its loaded deployment does not consume that queue",
198 consumer.script_name
199 );
200 continue;
201 }
202 fleet::load_queue_consumer_worker(bucket, &queue, &consumer, node.clone())
203 .await
204 .with_context(|| format!("load consumer for queue {queue:?}"))?
205 }
206 };
207 let target = loaded.script_name.clone();
208 anyhow::ensure!(
209 loaded_scripts
210 .insert(target.clone(), loaded.prefix.clone())
211 .is_none(),
212 "script {target:?} was loaded twice"
213 );
214 loaded_consumers.insert(target.clone(), consumed_queues(&loaded.options));
215 dependencies.extend(dependencies_of(&loaded));
216 // A node runs the schedule of the deployment it was given and of
217 // no other. The reserved class is one key, so a second script's
218 // cron cell would resolve to the first script's config and run
219 // the wrong `scheduled` handler. Dropping the schedule is the
220 // safe half of that trade and this says so out loud, because a
221 // trigger that never fires and says nothing is the failure the
222 // whole feature is built to avoid. Deploy the script as a node's
223 // own deployment to run its crons.
224 if !loaded.crons.is_empty() {
225 tracing::warn!(
226 script = %target,
227 crons = %loaded.crons.join(", "),
228 "a service binding target declares cron triggers; a node fires only its own deployment's schedule, so these never run here"
229 );
230 }
231 cohosted.push(loaded);
232 }
233 Ok(Self { primary, cohosted })
234 }
235}
236
237enum Dependency {
238 Service(String),
239 Queue(String),
240}
241
242fn consumed_queues(options: &WorkerConfigOptions) -> BTreeSet<String> {
243 options
244 .queue_consumers
245 .iter()
246 .map(|consumer| consumer.queue.clone())
247 .collect()
248}
249
250fn dependencies_of(loaded: &LoadedDeployment) -> VecDeque<Dependency> {
251 let queues = loaded
252 .options
253 .queue_bindings
254 .iter()
255 .map(|binding| binding.queue.clone())
256 .chain(loaded.options.queue_consumers.iter().flat_map(|consumer| {
257 std::iter::once(consumer.queue.clone()).chain(consumer.dead_letter_queue.clone())
258 }))
259 .collect::<BTreeSet<_>>();
260 loaded
261 .services
262 .iter()
263 .map(|(_, script, _)| Dependency::Service(script.clone()))
264 .chain(queues.into_iter().map(Dependency::Queue))
265 .collect()
266}
267
268/// Node-level inputs `Generation::build` needs beside the deployment itself.
269pub struct GenerationOptions {
270 pub loader_binding: Option<String>,
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.
281pub 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 /// `triggers.crons` of the primary script, so an adoption can tell
297 /// whether the schedule changed without re-reading the manifest.
298 #[allow(dead_code)]
299 pub(crate) crons: Vec<String>,
300}
301
302impl Generation {
303 pub fn id(&self) -> GenerationId {
304 self.id
305 }
306
307 pub fn version(&self) -> &str {
308 &self.version
309 }
310
311 pub fn prefix(&self) -> &str {
312 &self.prefix
313 }
314
315 /// The primary script: the one ingress serves and whose assets ingress
316 /// consults before running the Worker.
317 pub fn script_name(&self) -> &str {
318 &self.script_name
319 }
320
321 /// The asset resolver of the named script, if that script deployed
322 /// assets.
323 pub fn assets(&self, script: &str) -> Option<&AssetResolver> {
324 self.assets.get(script)
325 }
326
327 /// The primary script's asset resolver, which ingress consults.
328 pub fn ingress_assets(&self) -> Option<&AssetResolver> {
329 self.assets.get(&self.script_name)
330 }
331
332 pub fn has_cell_classes(&self) -> bool {
333 !self.cell_configs.is_empty()
334 }
335
336 /// The reserved cell carrying this deployment's cron schedule, or `None`
337 /// when the deployment declares no `triggers.crons`. Derived from the
338 /// registered class rather than plumbed separately, so it cannot
339 /// disagree with what `start_cell` will accept.
340 pub fn cron_cell(&self) -> Option<String> {
341 self.cell_configs
342 .get(celld_logic::cron::RESERVED_CLASS)
343 .map(|config| celld_logic::cron::reserved_cell(&config.script_name))
344 }
345
346 pub(crate) fn cell_config(&self, class: &str) -> Option<Arc<WorkerConfig>> {
347 self.cell_configs.get(class).cloned()
348 }
349
350 /// The engine's reserved Durable Object classes this generation
351 /// registers: cron, queue, workflow, D1, KV. Their cells hold no
352 /// application state worth waiting for, so an adoption moves them at
353 /// once — and the cron cell must run the new schedule before the
354 /// adoption arms it.
355 ///
356 /// The cron class is named beside `deploy::is_reserved_class` rather
357 /// than added to it. That predicate also decides which classes refuse an
358 /// unauthenticated operator route, and the cron cell is not one of them,
359 /// so widening it to reach this list would widen that refusal too.
360 pub fn reserved_classes(&self) -> Vec<String> {
361 self.cell_configs
362 .keys()
363 .filter(|class| {
364 crate::deploy::is_reserved_class(class)
365 || class.as_str() == celld_logic::cron::RESERVED_CLASS
366 })
367 .cloned()
368 .collect()
369 }
370
371 pub(crate) fn cell_isolates(&self, script: &str) -> Option<Arc<crate::pool::Pool>> {
372 self.cell_isolates.get(script).cloned()
373 }
374
375 pub(crate) fn service(&self, script: &str) -> Option<crate::runtime::StatelessRuntime> {
376 self.services.get(script).cloned()
377 }
378
379 pub(crate) fn default_do_class(&self) -> Option<&str> {
380 self.default_do_class.as_deref()
381 }
382
383 /// Stop every isolate of this generation from taking new work. Stateless
384 /// isolates free as their affiliations drop; cell isolates free as their
385 /// cells move to a newer generation.
386 pub(crate) fn retire(&self) {
387 for service in self.services.values() {
388 service.isolates.retire_all();
389 }
390 for pool in self.cell_isolates.values() {
391 pool.retire_all();
392 }
393 }
394
395 /// Whether every isolate of this generation has been freed, so the
396 /// generation itself can be dropped.
397 pub(crate) fn is_drained(&self) -> bool {
398 self.services
399 .values()
400 .all(|service| service.isolates.is_drained())
401 && self.cell_isolates.values().all(|pool| pool.is_drained())
402 }
403
404 /// One maintenance pass over the cell pools: retire and free every empty
405 /// isolate. An empty cell heap carries no warm request capacity worth
406 /// preserving, unlike a stateless one.
407 pub(crate) fn reap_cell_pools(&self) {
408 for pool in self.cell_isolates.values() {
409 pool.reap_empty();
410 }
411 }
412}
413
414/// The generation an isolate was built for, installed as an isolate slot by
415/// `Worker::load_config` so a call the isolate makes into the host — a
416/// service binding, an assets binding, a queue dispatch — resolves against
417/// the graph the caller was built with rather than whichever generation is
418/// current when the call lands.
419#[derive(Clone, Copy, Debug, PartialEq, Eq)]
420pub struct GenerationTag(pub GenerationId);