Diffinery

homeflare/celldpublic

celld/crates/celld/cell_runtime.rs
310 lines · 11.1 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! What a node's cell runtime holds whichever engine runs the cells: the
4//! generations it resolves calls against, the data directory, replication,
5//! wake discovery and facet streams. Each engine's `RuntimeManager` wraps one
6//! and adds what only its engine knows: cells, isolates, requests.
7
8use std::path::Path;
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use anyhow::anyhow;
13use anyhow::Context;
14
15use crate::asyncrt;
16use crate::engine_api::AlarmObserver;
17use crate::generation::Generation;
18use crate::generation::GenerationId;
19use crate::ltx_replication::Replication;
20use crate::wake::WakeFlusher;
21
22/// The generations a node can resolve a call against: the one it serves and
23/// the superseded ones whose isolates are still draining.
24///
25/// One value under one lock, because installing the new generation and
26/// keeping the previous one resolvable are the same instant. Held apart,
27/// the window between them resolved an in-flight call from the previous
28/// generation against the new deployment graph.
29pub(crate) struct Generations {
30 pub(crate) current: Arc<Generation>,
31 pub(crate) draining: Vec<Arc<Generation>>,
32}
33
34#[derive(Clone)]
35pub struct CellRuntime {
36 /// The generations a call can resolve against. A reader takes one
37 /// snapshot and never holds the lock across an await.
38 pub(crate) generations: Arc<std::sync::RwLock<Generations>>,
39 pub(crate) data_dir: Arc<PathBuf>,
40 pub(crate) replication: Option<Replication>,
41 pub(crate) wake: Option<Arc<WakeFlusher>>,
42 pub(crate) alarm_observer: AlarmObserver,
43 /// The facet streams of each resident root object.
44 pub(crate) facets: crate::facet_streams::FacetStreams,
45 pub(crate) node: Arc<str>,
46 pub(crate) region: Arc<str>,
47}
48
49impl CellRuntime {
50 pub(crate) fn new(
51 generation: Arc<Generation>,
52 data_dir: PathBuf,
53 replication: Option<Replication>,
54 wake: Option<Arc<WakeFlusher>>,
55 alarm_observer: AlarmObserver,
56 node: String,
57 region: String,
58 ) -> anyhow::Result<Self> {
59 require_cell_scope_capacity(&data_dir)?;
60 Ok(Self {
61 generations: Arc::new(std::sync::RwLock::new(Generations {
62 current: generation,
63 draining: Vec::new(),
64 })),
65 data_dir: Arc::new(data_dir),
66 replication,
67 wake,
68 alarm_observer,
69 facets: Default::default(),
70 node: Arc::from(node),
71 region: Arc::from(region),
72 })
73 }
74
75 /// The generation this node serves now.
76 ///
77 /// A caller that makes more than one decision from it takes the snapshot
78 /// once and uses it throughout: the current generation can change between
79 /// two reads, and a request must see one deployment graph, not two.
80 pub fn generation(&self) -> Arc<Generation> {
81 self.generations
82 .read()
83 .expect("generation lock poisoned")
84 .current
85 .clone()
86 }
87
88 /// The generation an isolate was built for: the current one when the id
89 /// matches, otherwise a superseded generation still draining. Zero — the
90 /// tag of an isolate built outside any generation — and an id whose
91 /// generation has finished draining both resolve to the current one.
92 pub fn generation_by_id(&self, id: GenerationId) -> Arc<Generation> {
93 // One lock over both halves: read separately, a caller from the
94 // previous generation could observe the new one as current before
95 // the previous one was resolvable, find neither, and fall through to
96 // the new graph -- the cross-generation call this exists to prevent.
97 let generations = self.generations.read().expect("generation lock poisoned");
98 if id == 0 || generations.current.id == id {
99 return generations.current.clone();
100 }
101 generations
102 .draining
103 .iter()
104 .find(|generation| generation.id == id)
105 .cloned()
106 .unwrap_or_else(|| generations.current.clone())
107 }
108
109 /// The id the next generation takes: one past the newest this node has
110 /// built, draining generations included, so an id is never reused while
111 /// an isolate still carries it.
112 pub fn next_generation_id(&self) -> GenerationId {
113 let generations = self.generations.read().expect("generation lock poisoned");
114 let draining = generations
115 .draining
116 .iter()
117 .map(|generation| generation.id)
118 .max()
119 .unwrap_or(0);
120 generations.current.id.max(draining) + 1
121 }
122
123 /// The generations still draining, for `/state`. Each one holds its
124 /// isolates until the last cell in them moves, so the caller reads the
125 /// census from the generation and not only its version.
126 pub fn draining_generations(&self) -> Vec<Arc<Generation>> {
127 self.generations
128 .read()
129 .expect("generation lock poisoned")
130 .draining
131 .clone()
132 }
133
134 /// Resolve a client-supplied cell id to a scope.
135 ///
136 /// The id arrives from the network, and the scope it becomes is used as a
137 /// path component and as an object-store key, so the charset gate runs
138 /// first. Without it a scope carries its own path segments and `db_path`
139 /// walks out of the data directory through them.
140 ///
141 /// The fleet-wide storage gate runs a second time on the composed scope. A
142 /// bare id takes a class prefix, so the scope that reaches storage is the
143 /// value that must fit.
144 pub fn cell_scope(&self, id: &str) -> anyhow::Result<String> {
145 if !celld_logic::cell::valid_cell_scope(id) {
146 return Err(anyhow!("cell id is not a well-formed scope"));
147 }
148 if id.contains(':') {
149 return Ok(id.to_string());
150 }
151 let generation = self.generation();
152 let class = generation.default_do_class().ok_or_else(|| {
153 anyhow!("a bare cell id requires exactly one configured Durable Object class")
154 })?;
155 let scope = format!("{class}:{id}");
156 if !celld_logic::cell::valid_cell_scope(&scope) {
157 return Err(anyhow!("cell id is not a well-formed scope"));
158 }
159 Ok(scope)
160 }
161
162 pub fn replication(&self) -> Option<Replication> {
163 self.replication.clone()
164 }
165
166 /// Read the filesystem inventory after the core has replaced the exact
167 /// clean predecessor lease generation.
168 pub fn local_reload_cells(&self) -> anyhow::Result<Vec<celld_logic::LocalCell>> {
169 let replication = self
170 .replication
171 .as_ref()
172 .context("local reload requires replication")?;
173 Ok(replication.local_cells())
174 }
175
176 pub fn replication_status(&self) -> std::io::Result<Option<std::process::ExitStatus>> {
177 match &self.replication {
178 Some(replication) => replication.process_status(),
179 None => Ok(None),
180 }
181 }
182
183 pub async fn ensure_durable(
184 &self,
185 cell: &str,
186 epoch: u64,
187 revocable: bool,
188 ) -> anyhow::Result<()> {
189 let Some(replication) = &self.replication else {
190 return Ok(());
191 };
192 for facet in self.facets.resident(cell, epoch) {
193 replication.ensure_durable(&facet, epoch, revocable).await?;
194 }
195 replication.ensure_durable(cell, epoch, revocable).await
196 }
197
198 /// The output-gate durability wait (see `Replication::await_durable`).
199 /// Returns the proved durable position and its proof source; with no
200 /// replicator every position is trivially durable, and the fleet source
201 /// keeps the gate read-free exactly like the old immediate release.
202 pub async fn await_durable(
203 &self,
204 cell: &str,
205 epoch: u64,
206 position: u64,
207 ) -> anyhow::Result<(u64, celld_logic::ProofSource)> {
208 match &self.replication {
209 Some(replication) => replication.await_durable(cell, epoch, position).await,
210 None => Ok((position, celld_logic::ProofSource::Fleet)),
211 }
212 }
213
214 /// Activate a facet's stream and answer its database file.
215 pub async fn open_facet(
216 &self,
217 root: &str,
218 epoch: u64,
219 names: &[String],
220 ) -> anyhow::Result<(PathBuf, bool)> {
221 self.facets
222 .open(
223 self.replication.as_ref(),
224 |cell, epoch| self.db_path(cell, epoch),
225 root,
226 epoch,
227 names,
228 )
229 .await
230 }
231
232 /// Delete a facet's stream and every stream below it.
233 pub async fn delete_facet(
234 &self,
235 root: &str,
236 epoch: u64,
237 names: &[String],
238 ) -> anyhow::Result<()> {
239 self.facets
240 .delete(
241 self.replication.as_ref(),
242 |cell| self.data_dir.join(cell),
243 root,
244 epoch,
245 names,
246 )
247 .await
248 }
249
250 /// Prove every committed write of a facet's stream durable.
251 pub async fn prove_facet(&self, stream: &str, epoch: u64) -> anyhow::Result<()> {
252 self.await_durable(stream, epoch, 0).await.map(|_| ())
253 }
254
255 pub(crate) fn db_path(&self, cell: &str, epoch: u64) -> PathBuf {
256 // A runtime without replication has no remote epoch namespace, so it
257 // keeps its only SQLite family at the existing e1 path across logical
258 // ownership epochs. The stable path survives a restart, needs no
259 // multi-file SQLite family move, and remains compatible with older
260 // releases.
261 let epoch = if self.replication.is_some() { epoch } else { 1 };
262 self.data_dir
263 .join(cell)
264 .join("ltx")
265 .join(format!("e{epoch}"))
266 .join("db.sqlite")
267 }
268
269 pub fn alarm_covered(&self, cell: &str, alarm: celld_logic::wake::AlarmSnapshot) -> bool {
270 match (alarm.at_ms(), &self.wake) {
271 (None, _) => true,
272 (Some(_), Some(wake)) if self.replication.is_some() => wake.covered(cell, alarm),
273 (Some(_), None) => false,
274 (Some(_), Some(_)) => false,
275 }
276 }
277
278 pub fn node(&self) -> &str {
279 &self.node
280 }
281
282 pub fn region(&self) -> &str {
283 &self.region
284 }
285}
286
287fn require_cell_scope_capacity(data_dir: &Path) -> anyhow::Result<()> {
288 asyncrt::fs()
289 .create_dir_all(data_dir)
290 .with_context(|| format!("create data directory {}", data_dir.display()))?;
291 let reported = asyncrt::filesystem_name_max(data_dir)
292 .with_context(|| format!("read NAME_MAX for {}", data_dir.display()))?
293 .with_context(|| {
294 format!(
295 "the filesystem does not report NAME_MAX for {}",
296 data_dir.display()
297 )
298 })?;
299 let name_max = usize::try_from(reported).context("NAME_MAX does not fit usize")?;
300 require_cell_scope_name_max(name_max)
301}
302
303pub(crate) fn require_cell_scope_name_max(name_max: usize) -> anyhow::Result<()> {
304 anyhow::ensure!(
305 name_max >= celld_logic::cell::MAX_CELL_SCOPE,
306 "the data filesystem supports {name_max}-byte names, but celld requires {}",
307 celld_logic::cell::MAX_CELL_SCOPE
308 );
309 Ok(())
310}