Diffinery

homeflare/celldpublic

celld/crates/celld/ownership_store.rs
511 lines · 18.9 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3#![warn(clippy::disallowed_macros)]
4
5//! Bucket ownership effect adapter, over either conditional-write dialect.
6//!
7//! This module deliberately contains serialization, wall-clock sampling, SDK
8//! configuration and error classification only. Ownership decisions remain in
9//! `celld-logic`.
10
11use crate::bucket::Bucket;
12use anyhow::Context;
13use celld_logic::{
14 CapacityPeer, CasGuard, CasOutcome, LeaseCasOutcome, NodeLeaseRecord, OwnerRecord,
15};
16use futures_util::stream::{self, StreamExt};
17use serde::{Deserialize, Serialize};
18use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
19use std::sync::Arc;
20
21#[derive(Serialize)]
22struct OwnerWire<'a> {
23 node: &'a str,
24 epoch: u64,
25}
26
27#[derive(Deserialize)]
28struct OwnerWireOwned {
29 node: String,
30 epoch: u64,
31}
32
33#[derive(Clone, Deserialize, Serialize)]
34pub(crate) struct NodeLeaseWire {
35 pub(crate) node: String,
36 pub(crate) expires_ms: u64,
37 #[serde(default)]
38 pub(crate) addr: String,
39 #[serde(default)]
40 pub(crate) probe_public_key: String,
41 #[serde(default)]
42 pub(crate) peer_protocol: u16,
43 #[serde(default, rename = "ownership_index_generation")]
44 pub(crate) generation: String,
45 /// The folded node log: absent until the
46 /// session's first fleet open. Every writer of this record carries it
47 /// through unchanged except the log tier itself and recovery.
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub(crate) log: Option<NodeLogWire>,
50 #[serde(default)]
51 pub(crate) load: NodeLoadWire,
52}
53
54/// The folded log fields, exactly the old log/<session>.json body: the
55/// record moved into the lease, the shape did not change.
56#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
57pub(crate) struct NodeLogWire {
58 pub(crate) state: String,
59 pub(crate) epoch: u64,
60 pub(crate) ensemble: Vec<String>,
61 pub(crate) tiered: u64,
62 #[serde(default)]
63 pub(crate) active: bool,
64}
65
66pub(crate) fn log_state_from_wire(
67 log: &Option<NodeLogWire>,
68) -> Option<celld_logic::log_tier::LogState> {
69 match log.as_ref().map(|log| log.state.as_str()) {
70 Some("open") => Some(celld_logic::log_tier::LogState::Open),
71 Some("recovering") => Some(celld_logic::log_tier::LogState::Recovering),
72 Some("sealed") => Some(celld_logic::log_tier::LogState::Sealed),
73 _ => None,
74 }
75}
76
77#[derive(Clone, Default, Deserialize, Serialize)]
78pub struct NodeLoadWire {
79 pub sampled_ms: u64,
80 pub resident_cells: usize,
81 pub host_websockets: usize,
82 pub rss_bytes: u64,
83 /// What the pressure classifier reads, published next to `rss_bytes` so a
84 /// gap between the two is visible.
85 ///
86 /// `None` means the node did not report it, which a node before this field
87 /// existed does not. That is not the same as zero, and a consumer that
88 /// ranks nodes must not read a silent zero as the emptiest node in the
89 /// fleet for the length of a rolling upgrade.
90 #[serde(default)]
91 pub in_use_bytes: Option<u64>,
92 pub cpu_percent_x100: u64,
93 pub open_fds: u64,
94 pub fd_limit: u64,
95 pub pressured: bool,
96 pub shed_cells: u64,
97 /// Cold demand queued behind the activation ceiling. Zero in steady
98 /// state; positive only while a restore burst saturates the node, so a
99 /// rollout waits it out before it restarts the next node.
100 #[serde(default)]
101 pub restoring: u64,
102}
103
104/// A node record older than this is not worth reading. Three lease
105/// lifetimes, floored, so a fleet with a short TTL does not discard records
106/// a slow renewal would have refreshed.
107const CAPACITY_RECORD_RECENCY_FLOOR_MS: u64 = 60_000;
108
109fn capacity_record_is_recent(last_modified_secs: i64, now_ms: u64, lease_ttl_ms: u64) -> bool {
110 let window_ms = lease_ttl_ms
111 .saturating_mul(3)
112 .max(CAPACITY_RECORD_RECENCY_FLOOR_MS);
113 last_modified_secs >= (now_ms.saturating_sub(window_ms) / 1_000) as i64
114}
115
116pub fn now_ms() -> u64 {
117 crate::asyncrt::wall_ms().max(0) as u64
118}
119
120/// The production-compatible conditional object store used by ownership
121/// effects. A failed write is always reported to the core as ambiguous unless
122/// the store definitively returned HTTP 412.
123pub struct BucketOwnership {
124 bucket: Bucket,
125 lease_bucket: Bucket,
126 node: String,
127 probe_public_key: String,
128 live: Arc<LiveLoad>,
129 lease_ttl_ms: u64,
130 /// The full folded log object this node's OWN lease record carries,
131 /// tagged with a publish sequence.
132 /// Renewals snapshot (seq, object) ONCE when they serialize the wire
133 /// body, and the applied notification reports the seq of the body
134 /// that actually landed — never a re-read of this slot, which is what
135 /// made the first protocol unsound (cold review, B1): a confirmation
136 /// must carry the identity of the write it confirms.
137 own_log: std::sync::Mutex<(u64, Option<NodeLogWire>)>,
138 /// Every APPLIED write of our own lease record, as (etag, the publish
139 /// seq its body carried). A waiter that published seq S is satisfied
140 /// only by applied seq >= S; combined with the OwnLog write lock
141 /// (one publish outstanding at a time), >= S implies the applied body
142 /// IS the waiter's object.
143 applied: tokio::sync::watch::Sender<(String, u64)>,
144}
145
146/// What this node currently looks like, for peers deciding where to place a
147/// cell. The executor owns these numbers and publishes them on every lease
148/// renewal; nothing here decides anything locally.
149pub fn set_node_load(load: std::sync::Arc<LiveLoad>) {
150 crate::asyncrt::services().set_node_load(load);
151}
152
153/// Is this node over a resource ceiling and recovering? False when nothing
154/// publishes load (no bucket), which is also when there is no pressure
155/// sampler to say otherwise.
156pub fn node_is_shedding() -> bool {
157 crate::asyncrt::services()
158 .node_load()
159 .is_some_and(|load| load.pressured.load(std::sync::atomic::Ordering::Relaxed))
160}
161
162#[derive(Debug, Default)]
163pub struct LiveLoad {
164 pub resident_cells: AtomicUsize,
165 pub host_websockets: AtomicUsize,
166 pub cpu_percent_x100: AtomicU64,
167 pub pressured: AtomicBool,
168 /// Cells shed since this process started. Monotonic, and only ever read
169 /// by a human or a diagnostic -- placement uses the levels, not the rate.
170 pub shed_cells: AtomicU64,
171 /// Cold demand queued behind the activation ceiling, republished on every
172 /// lease renewal for a rollout to pace on.
173 pub restoring: AtomicU64,
174}
175
176impl BucketOwnership {
177 /// Creates an adapter with an isolated lease pool and the process key
178 /// advertised for challenge-bound direct probes.
179 pub fn new(
180 bucket: Bucket,
181 lease_bucket: Bucket,
182 node: String,
183 probe_public_key: String,
184 ) -> Self {
185 Self {
186 bucket,
187 lease_bucket,
188 node,
189 probe_public_key,
190 live: Arc::new(LiveLoad::default()),
191 lease_ttl_ms: 0,
192 own_log: std::sync::Mutex::new((0, None)),
193 applied: tokio::sync::watch::channel((String::new(), 0)).0,
194 }
195 }
196
197 /// The lease lifetime this fleet renews on, used to decide which node
198 /// records are still worth reading.
199 pub fn with_lease_ttl_ms(mut self, ttl_ms: u64) -> Self {
200 self.lease_ttl_ms = ttl_ms;
201 self
202 }
203
204 pub fn lease_ttl_ms(&self) -> u64 {
205 self.lease_ttl_ms
206 }
207
208 /// The store's own transport, shared with the log tier. A fresh client
209 /// costs tens of milliseconds of rustls setup at boot, and boot speed is
210 /// load-bearing: the clean-reload resume window is the predecessor's
211 /// remaining lease TTL, and two extra client constructions can consume
212 /// enough of a short lease to prevent a clean reload.
213 pub fn bucket_client(&self) -> Bucket {
214 self.bucket.clone()
215 }
216
217 /// The counters this node publishes to its peers.
218 pub fn live(&self) -> Arc<LiveLoad> {
219 self.live.clone()
220 }
221
222 /// The storage scheme this adapter coordinates through (`s3` or `gs`),
223 /// for the startup banner.
224 pub fn storage_scheme(&self) -> &'static str {
225 self.bucket.scheme()
226 }
227
228 /// Stable identity for this exact lease-writing process.
229 pub fn process_generation(&self) -> Option<&str> {
230 (!self.probe_public_key.is_empty()).then_some(self.probe_public_key.as_str())
231 }
232
233 pub async fn read_owner(&self, cell: &str) -> anyhow::Result<Option<OwnerRecord>> {
234 let key = format!("cells/{cell}/own.json");
235 let Some((owner, etag)) = load_json::<OwnerWireOwned>(&self.bucket, &key).await? else {
236 return Ok(None);
237 };
238 let record = OwnerRecord {
239 node: (!owner.node.is_empty()).then_some(owner.node),
240 epoch: owner.epoch,
241 etag,
242 };
243 Ok(Some(record))
244 }
245
246 pub async fn read_node_lease(&self, owner: &str) -> anyhow::Result<Option<NodeLeaseRecord>> {
247 load_node_lease(&self.bucket, owner).await
248 }
249
250 /// Read this process's authority record through the isolated lease pool.
251 pub async fn read_self_node_lease(
252 &self,
253 owner: &str,
254 ) -> anyhow::Result<Option<NodeLeaseRecord>> {
255 load_node_lease(&self.lease_bucket, owner).await
256 }
257
258 /// Enumerate the fleet membership records used for advisory placement.
259 /// The adapter owns pagination and bounded I/O concurrency; the core gets
260 /// every decoded observation and owns all filtering and selection policy.
261 pub async fn read_capacity_peers(&self) -> anyhow::Result<Vec<CapacityPeer>> {
262 const READ_CONCURRENCY: usize = 16;
263 let current_ms = now_ms();
264 let mut nodes = Vec::new();
265 for object in self.bucket.list("nodes/").await? {
266 // A record nothing has rewritten in several lease lifetimes
267 // belongs to a node that is not coming back. Skipping it here
268 // is the difference between reading the live fleet and
269 // reading every node that has ever run: the listing is what
270 // the placement decision costs, and it is paid on every
271 // unowned cell.
272 if !capacity_record_is_recent(
273 object.last_modified.timestamp(),
274 current_ms,
275 self.lease_ttl_ms,
276 ) {
277 continue;
278 }
279 let Some(node) = object
280 .location
281 .as_ref()
282 .strip_prefix("nodes/")
283 .and_then(|key| key.strip_suffix(".json"))
284 else {
285 continue;
286 };
287 if !node.is_empty() {
288 nodes.push(node.to_string());
289 }
290 }
291 nodes.sort();
292 nodes.dedup();
293
294 let mut reads = stream::iter(nodes.into_iter().map(|node| async move {
295 let key = format!("nodes/{node}.json");
296 Ok::<_, anyhow::Error>(load_json::<NodeLeaseWire>(&self.bucket, &key).await?.map(
297 |(lease, _)| CapacityPeer {
298 node: lease.node,
299 addr: lease.addr,
300 expires_ms: lease.expires_ms,
301 peer_protocol: lease.peer_protocol,
302 sampled_ms: lease.load.sampled_ms,
303 resident_cells: lease.load.resident_cells,
304 host_websockets: lease.load.host_websockets,
305 rss_bytes: lease.load.rss_bytes,
306 in_use_bytes: lease.load.in_use_bytes,
307 pressured: lease.load.pressured,
308 },
309 ))
310 }))
311 .buffer_unordered(READ_CONCURRENCY);
312 let mut peers = Vec::new();
313 while let Some(peer) = reads.next().await {
314 if let Some(peer) = peer? {
315 peers.push(peer);
316 }
317 }
318 Ok(peers)
319 }
320
321 /// Publish a cell as unowned, keeping its epoch.
322 ///
323 /// Read-then-conditional-write, because the release is only safe against
324 /// the exact record this node wrote: a takeover in the meantime means the
325 /// cell is someone else's now, and blanking it would strip a live owner's
326 /// claim. Rejection is an ordinary outcome, not an error -- the record
327 /// keeps naming whoever it names, and nothing was lost.
328 pub async fn release_owner(&self, cell: &str, epoch: u64) -> anyhow::Result<CasOutcome> {
329 let Some(current) = self.read_owner(cell).await? else {
330 return Ok(CasOutcome::Rejected);
331 };
332 if current.node.as_deref() != Some(self.node.as_str()) || current.epoch != epoch {
333 return Ok(CasOutcome::Rejected);
334 }
335 let key = format!("cells/{cell}/own.json");
336 let body = serde_json::to_vec(&OwnerWire { node: "", epoch })?;
337 match self.bucket.put_cas(&key, body, Some(&current.etag)).await? {
338 Some(_) => Ok(CasOutcome::Applied),
339 None => Ok(CasOutcome::Rejected),
340 }
341 }
342
343 pub async fn cas_owner(
344 &self,
345 cell: &str,
346 guard: CasGuard,
347 epoch: u64,
348 ) -> anyhow::Result<CasOutcome> {
349 let key = format!("cells/{cell}/own.json");
350 let body = serde_json::to_vec(&OwnerWire {
351 node: &self.node,
352 epoch,
353 })?;
354 let etag = match &guard {
355 CasGuard::Absent => None,
356 CasGuard::Match(etag) => Some(etag.as_str()),
357 };
358 match self.bucket.put_cas(&key, body, etag).await? {
359 Some(_) => Ok(CasOutcome::Applied),
360 None => Ok(CasOutcome::Rejected),
361 }
362 }
363
364 pub async fn cas_node_lease(
365 &self,
366 guard: CasGuard,
367 record: &NodeLeaseRecord,
368 stamped: &mut Option<celld_logic::log_tier::LogState>,
369 ) -> anyhow::Result<LeaseCasOutcome> {
370 if self.probe_public_key.is_empty() {
371 return Err(anyhow::anyhow!(
372 "refusing to publish a node lease without a signed-probe key"
373 ));
374 }
375 let key = format!("nodes/{}.json", self.node);
376 // Snapshot the folded log ONCE, before serialization: the applied
377 // notification below reports THIS seq — the identity of the body
378 // that landed — never a re-read of the slot (cold review, B1).
379 let (log_seq, log) = self.own_log.lock().unwrap().clone();
380 // Report the stamp through the out-parameter, synchronously,
381 // before the first await: a caller that times this future out
382 // still learns what the possibly-landed body carried (second
383 // cold review, finding 3).
384 *stamped = log_state_from_wire(&log);
385 let body = serde_json::to_vec(&NodeLeaseWire {
386 node: record.node.clone(),
387 expires_ms: record.expires_ms,
388 addr: record.addr.clone(),
389 probe_public_key: self.probe_public_key.clone(),
390 peer_protocol: record.peer_protocol,
391 generation: record.generation.clone(),
392 load: process_load(&self.live),
393 // The CORE's lease writes carry the folded log through
394 // UNCHANGED: the full object lives in own_log, written only by
395 // the log tier's own core-mediated updates.
396 log,
397 })?;
398 let etag = match &guard {
399 CasGuard::Absent => None,
400 CasGuard::Match(etag) => Some(etag.as_str()),
401 };
402 match self.lease_bucket.put_cas(&key, body, etag).await? {
403 Some(etag) => {
404 let _ = self.applied.send((etag.clone(), log_seq));
405 Ok(LeaseCasOutcome::Applied { etag })
406 }
407 None => Ok(LeaseCasOutcome::Rejected),
408 }
409 }
410}
411
412impl BucketOwnership {
413 /// Replace the folded log object the next lease write carries and
414 /// return its publish seq. The caller nudges a renewal and awaits
415 /// `applied_log` reaching that seq; the store never initiates writes.
416 pub(crate) fn set_own_log(&self, log: Option<NodeLogWire>) -> u64 {
417 let mut slot = self.own_log.lock().unwrap();
418 slot.0 += 1;
419 slot.1 = log;
420 slot.0
421 }
422
423 pub(crate) fn own_log(&self) -> Option<NodeLogWire> {
424 self.own_log.lock().unwrap().1.clone()
425 }
426
427 pub(crate) fn applied_log(&self) -> tokio::sync::watch::Receiver<(String, u64)> {
428 self.applied.subscribe()
429 }
430}
431
432pub(crate) async fn load_node_lease(
433 bucket: &Bucket,
434 owner: &str,
435) -> anyhow::Result<Option<NodeLeaseRecord>> {
436 let key = format!("nodes/{owner}.json");
437 Ok(load_json::<NodeLeaseWire>(bucket, &key)
438 .await?
439 .map(|(lease, etag)| NodeLeaseRecord {
440 log_state: log_state_from_wire(&lease.log),
441 node: lease.node,
442 addr: lease.addr,
443 expires_ms: lease.expires_ms,
444 peer_protocol: lease.peer_protocol,
445 generation: lease.generation,
446 etag,
447 }))
448}
449
450async fn load_json<T: for<'de> Deserialize<'de>>(
451 bucket: &Bucket,
452 key: &str,
453) -> anyhow::Result<Option<(T, String)>> {
454 let Some((bytes, etag)) = bucket.get(key).await? else {
455 return Ok(None);
456 };
457 let value = serde_json::from_slice(&bytes)
458 .with_context(|| format!("decode {}://{}/{key}", bucket.scheme(), bucket.name))?;
459 Ok(Some((value, etag)))
460}
461
462#[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage.
463fn process_load(live: &LiveLoad) -> NodeLoadWire {
464 // One sample for both numbers. Reading the resident set size here and the
465 // in-use figure from a value the actor wrote on its own timer would publish
466 // a pair from two instants, and before the first sample it would publish a
467 // real resident set size beside an in-use figure of zero -- which reads as
468 // total allocator retention.
469 let memory = crate::memory::sample();
470 // A 1-byte floor is the sentinel a platform without /proc leaves behind.
471 // Both numbers take it, so the in-use figure can never read as zero beside
472 // a real resident set size.
473 let rss_bytes = memory.rss_bytes.max(1);
474 let in_use_bytes = memory.in_use_bytes.max(1).min(rss_bytes);
475
476 #[cfg(target_os = "linux")]
477 let open_fds = std::fs::read_dir("/proc/self/fd")
478 .map(|entries| entries.count() as u64)
479 .unwrap_or_default();
480 #[cfg(not(target_os = "linux"))]
481 let open_fds = 0;
482
483 #[cfg(unix)]
484 let fd_limit = {
485 let mut limit = libc::rlimit {
486 rlim_cur: 0,
487 rlim_max: 0,
488 };
489 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 {
490 limit.rlim_cur
491 } else {
492 0
493 }
494 };
495 #[cfg(not(unix))]
496 let fd_limit = 0;
497
498 NodeLoadWire {
499 sampled_ms: now_ms(),
500 rss_bytes,
501 in_use_bytes: Some(in_use_bytes),
502 open_fds,
503 fd_limit,
504 cpu_percent_x100: live.cpu_percent_x100.load(Ordering::Relaxed),
505 resident_cells: live.resident_cells.load(Ordering::Relaxed),
506 host_websockets: live.host_websockets.load(Ordering::Relaxed),
507 pressured: live.pressured.load(Ordering::Relaxed),
508 shed_cells: live.shed_cells.load(Ordering::Relaxed),
509 restoring: live.restoring.load(Ordering::Relaxed),
510 }
511}