| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! S3-compatible ownership effect adapter. |
| 4 | //! |
| 5 | //! This module deliberately contains serialization, wall-clock sampling, SDK |
| 6 | //! configuration and error classification only. Ownership decisions remain in |
| 7 | //! `celld-logic`. |
| 8 | |
| 9 | use crate::bucket::Bucket; |
| 10 | use anyhow::Context; |
| 11 | use celld_logic::{ |
| 12 | CapacityPeer, CasGuard, CasOutcome, LeaseCasOutcome, NodeLeaseRecord, OwnerRecord, |
| 13 | }; |
| 14 | use futures_util::stream::{self, StreamExt}; |
| 15 | use serde::{Deserialize, Serialize}; |
| 16 | use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; |
| 17 | use std::sync::Arc; |
| 18 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 19 | |
| 20 | #[derive(Serialize)] |
| 21 | struct OwnerWire<'a> { |
| 22 | node: &'a str, |
| 23 | epoch: u64, |
| 24 | } |
| 25 | |
| 26 | #[derive(Deserialize)] |
| 27 | struct OwnerWireOwned { |
| 28 | node: String, |
| 29 | epoch: u64, |
| 30 | } |
| 31 | |
| 32 | #[derive(Deserialize, Serialize)] |
| 33 | struct NodeLeaseWire { |
| 34 | node: String, |
| 35 | expires_ms: u64, |
| 36 | #[serde(default)] |
| 37 | addr: String, |
| 38 | #[serde(default)] |
| 39 | probe_public_key: String, |
| 40 | #[serde(default)] |
| 41 | peer_protocol: u16, |
| 42 | #[serde(default, rename = "ownership_index_generation")] |
| 43 | generation: String, |
| 44 | #[serde(default)] |
| 45 | load: NodeLoadWire, |
| 46 | } |
| 47 | |
| 48 | #[derive(Clone, Default, Deserialize, Serialize)] |
| 49 | pub struct NodeLoadWire { |
| 50 | pub sampled_ms: u64, |
| 51 | pub resident_cells: usize, |
| 52 | pub host_websockets: usize, |
| 53 | pub rss_bytes: u64, |
| 54 | pub cpu_percent_x100: u64, |
| 55 | pub open_fds: u64, |
| 56 | pub fd_limit: u64, |
| 57 | pub pressured: bool, |
| 58 | pub shed_cells: u64, |
| 59 | } |
| 60 | |
| 61 | /// A node record older than this is not worth reading. Three lease |
| 62 | /// lifetimes, floored, so a fleet with a short TTL does not discard records |
| 63 | /// a slow renewal would have refreshed. |
| 64 | const CAPACITY_RECORD_RECENCY_FLOOR_MS: u64 = 60_000; |
| 65 | |
| 66 | fn capacity_record_is_recent(last_modified_secs: i64, now_ms: u64, lease_ttl_ms: u64) -> bool { |
| 67 | let window_ms = lease_ttl_ms |
| 68 | .saturating_mul(3) |
| 69 | .max(CAPACITY_RECORD_RECENCY_FLOOR_MS); |
| 70 | last_modified_secs >= (now_ms.saturating_sub(window_ms) / 1_000) as i64 |
| 71 | } |
| 72 | |
| 73 | pub fn now_ms() -> u64 { |
| 74 | SystemTime::now() |
| 75 | .duration_since(UNIX_EPOCH) |
| 76 | .unwrap_or_default() |
| 77 | .as_millis() as u64 |
| 78 | } |
| 79 | |
| 80 | /// The production-compatible conditional object store used by ownership |
| 81 | /// effects. A failed write is always reported to the core as ambiguous unless |
| 82 | /// S3 definitively returned HTTP 412. |
| 83 | pub struct S3Ownership { |
| 84 | bucket: Bucket, |
| 85 | lease_bucket: Bucket, |
| 86 | node: String, |
| 87 | probe_public_key: String, |
| 88 | live: Arc<LiveLoad>, |
| 89 | lease_ttl_ms: u64, |
| 90 | } |
| 91 | |
| 92 | /// What this node currently looks like, for peers deciding where to place a |
| 93 | /// cell. The executor owns these numbers and publishes them on every lease |
| 94 | /// renewal; nothing here decides anything locally. |
| 95 | #[derive(Debug, Default)] |
| 96 | pub struct LiveLoad { |
| 97 | pub resident_cells: AtomicUsize, |
| 98 | pub host_websockets: AtomicUsize, |
| 99 | pub cpu_percent_x100: AtomicU64, |
| 100 | pub pressured: AtomicBool, |
| 101 | /// Cells shed since this process started. Monotonic, and only ever read |
| 102 | /// by a human or a diagnostic -- placement uses the levels, not the rate. |
| 103 | pub shed_cells: AtomicU64, |
| 104 | } |
| 105 | |
| 106 | impl S3Ownership { |
| 107 | pub fn new(bucket: Bucket, node: String) -> Self { |
| 108 | Self { |
| 109 | lease_bucket: bucket.clone(), |
| 110 | bucket, |
| 111 | node, |
| 112 | probe_public_key: String::new(), |
| 113 | live: Arc::new(LiveLoad::default()), |
| 114 | lease_ttl_ms: 0, |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Configure the per-process key advertised for challenge-bound direct |
| 119 | /// probes. Read-only ownership adapters deliberately use [`Self::new`] |
| 120 | /// and cannot accidentally publish a lease. |
| 121 | pub fn with_probe_public_key( |
| 122 | bucket: Bucket, |
| 123 | lease_bucket: Bucket, |
| 124 | node: String, |
| 125 | probe_public_key: String, |
| 126 | ) -> Self { |
| 127 | Self { |
| 128 | bucket, |
| 129 | lease_bucket, |
| 130 | node, |
| 131 | probe_public_key, |
| 132 | live: Arc::new(LiveLoad::default()), |
| 133 | lease_ttl_ms: 0, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | pub async fn from_environment(bucket: String, node: String) -> anyhow::Result<Self> { |
| 138 | let endpoint = std::env::var("S3_ENDPOINT").ok(); |
| 139 | let region = std::env::var("AWS_REGION") |
| 140 | .ok() |
| 141 | .or_else(|| std::env::var("AWS_DEFAULT_REGION").ok()) |
| 142 | .unwrap_or_else(|| "us-east-1".into()); |
| 143 | Ok(Self::new( |
| 144 | Bucket::open(&bucket, endpoint.as_deref(), ®ion, None, None)?, |
| 145 | node, |
| 146 | )) |
| 147 | } |
| 148 | |
| 149 | /// The lease lifetime this fleet renews on, used to decide which node |
| 150 | /// records are still worth reading. |
| 151 | pub fn with_lease_ttl_ms(mut self, ttl_ms: u64) -> Self { |
| 152 | self.lease_ttl_ms = ttl_ms; |
| 153 | self |
| 154 | } |
| 155 | |
| 156 | /// The counters this node publishes to its peers. |
| 157 | pub fn live(&self) -> Arc<LiveLoad> { |
| 158 | self.live.clone() |
| 159 | } |
| 160 | |
| 161 | /// Stable identity for this exact lease-writing process. |
| 162 | pub fn process_generation(&self) -> Option<&str> { |
| 163 | (!self.probe_public_key.is_empty()).then_some(self.probe_public_key.as_str()) |
| 164 | } |
| 165 | |
| 166 | pub async fn read_owner(&self, cell: &str) -> anyhow::Result<Option<OwnerRecord>> { |
| 167 | let key = format!("cells/{cell}/own.json"); |
| 168 | let Some((owner, etag)) = self.read_json::<OwnerWireOwned>(&key).await? else { |
| 169 | return Ok(None); |
| 170 | }; |
| 171 | Ok(Some(OwnerRecord { |
| 172 | node: (!owner.node.is_empty()).then_some(owner.node), |
| 173 | epoch: owner.epoch, |
| 174 | etag, |
| 175 | })) |
| 176 | } |
| 177 | |
| 178 | pub async fn read_node_lease(&self, owner: &str) -> anyhow::Result<Option<NodeLeaseRecord>> { |
| 179 | self.read_node_lease_with(&self.bucket, owner).await |
| 180 | } |
| 181 | |
| 182 | /// Read this process's authority record through the isolated lease pool. |
| 183 | pub async fn read_self_node_lease( |
| 184 | &self, |
| 185 | owner: &str, |
| 186 | ) -> anyhow::Result<Option<NodeLeaseRecord>> { |
| 187 | self.read_node_lease_with(&self.lease_bucket, owner).await |
| 188 | } |
| 189 | |
| 190 | async fn read_node_lease_with( |
| 191 | &self, |
| 192 | bucket: &Bucket, |
| 193 | owner: &str, |
| 194 | ) -> anyhow::Result<Option<NodeLeaseRecord>> { |
| 195 | let key = format!("nodes/{owner}.json"); |
| 196 | Ok(self |
| 197 | .read_json_with::<NodeLeaseWire>(bucket, &key) |
| 198 | .await? |
| 199 | .map(|(lease, etag)| NodeLeaseRecord { |
| 200 | node: lease.node, |
| 201 | addr: lease.addr, |
| 202 | expires_ms: lease.expires_ms, |
| 203 | peer_protocol: lease.peer_protocol, |
| 204 | generation: lease.generation, |
| 205 | etag, |
| 206 | })) |
| 207 | } |
| 208 | |
| 209 | /// Enumerate the fleet membership records used for advisory placement. |
| 210 | /// The adapter owns pagination and bounded I/O concurrency; the core gets |
| 211 | /// every decoded observation and owns all filtering and selection policy. |
| 212 | pub async fn read_capacity_peers(&self) -> anyhow::Result<Vec<CapacityPeer>> { |
| 213 | const READ_CONCURRENCY: usize = 16; |
| 214 | let current_ms = now_ms(); |
| 215 | let mut nodes = Vec::new(); |
| 216 | for object in self.bucket.list("nodes/").await? { |
| 217 | // A record nothing has rewritten in several lease lifetimes |
| 218 | // belongs to a node that is not coming back. Skipping it here |
| 219 | // is the difference between reading the live fleet and |
| 220 | // reading every node that has ever run: the listing is what |
| 221 | // the placement decision costs, and it is paid on every |
| 222 | // unowned cell. |
| 223 | if !capacity_record_is_recent( |
| 224 | object.last_modified.timestamp(), |
| 225 | current_ms, |
| 226 | self.lease_ttl_ms, |
| 227 | ) { |
| 228 | continue; |
| 229 | } |
| 230 | let Some(node) = object |
| 231 | .location |
| 232 | .as_ref() |
| 233 | .strip_prefix("nodes/") |
| 234 | .and_then(|key| key.strip_suffix(".json")) |
| 235 | else { |
| 236 | continue; |
| 237 | }; |
| 238 | if !node.is_empty() { |
| 239 | nodes.push(node.to_string()); |
| 240 | } |
| 241 | } |
| 242 | nodes.sort(); |
| 243 | nodes.dedup(); |
| 244 | |
| 245 | let mut reads = stream::iter(nodes.into_iter().map(|node| async move { |
| 246 | let key = format!("nodes/{node}.json"); |
| 247 | Ok::<_, anyhow::Error>(self.read_json::<NodeLeaseWire>(&key).await?.map( |
| 248 | |(lease, _)| CapacityPeer { |
| 249 | node: lease.node, |
| 250 | addr: lease.addr, |
| 251 | expires_ms: lease.expires_ms, |
| 252 | peer_protocol: lease.peer_protocol, |
| 253 | sampled_ms: lease.load.sampled_ms, |
| 254 | resident_cells: lease.load.resident_cells, |
| 255 | host_websockets: lease.load.host_websockets, |
| 256 | rss_bytes: lease.load.rss_bytes, |
| 257 | pressured: lease.load.pressured, |
| 258 | }, |
| 259 | )) |
| 260 | })) |
| 261 | .buffer_unordered(READ_CONCURRENCY); |
| 262 | let mut peers = Vec::new(); |
| 263 | while let Some(peer) = reads.next().await { |
| 264 | if let Some(peer) = peer? { |
| 265 | peers.push(peer); |
| 266 | } |
| 267 | } |
| 268 | Ok(peers) |
| 269 | } |
| 270 | |
| 271 | /// Publish a cell as unowned, keeping its epoch. |
| 272 | /// |
| 273 | /// Read-then-conditional-write, because the release is only safe against |
| 274 | /// the exact record this node wrote: a takeover in the meantime means the |
| 275 | /// cell is someone else's now, and blanking it would strip a live owner's |
| 276 | /// claim. Rejection is an ordinary outcome, not an error -- the record |
| 277 | /// keeps naming whoever it names, and nothing was lost. |
| 278 | pub async fn release_owner(&self, cell: &str, epoch: u64) -> anyhow::Result<CasOutcome> { |
| 279 | let Some(current) = self.read_owner(cell).await? else { |
| 280 | return Ok(CasOutcome::Rejected); |
| 281 | }; |
| 282 | if current.node.as_deref() != Some(self.node.as_str()) || current.epoch != epoch { |
| 283 | return Ok(CasOutcome::Rejected); |
| 284 | } |
| 285 | let key = format!("cells/{cell}/own.json"); |
| 286 | let body = serde_json::to_vec(&OwnerWire { node: "", epoch })?; |
| 287 | match self.bucket.put_cas(&key, body, Some(¤t.etag)).await? { |
| 288 | Some(_) => Ok(CasOutcome::Applied), |
| 289 | None => Ok(CasOutcome::Rejected), |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | pub async fn cas_owner( |
| 294 | &self, |
| 295 | cell: &str, |
| 296 | guard: CasGuard, |
| 297 | epoch: u64, |
| 298 | ) -> anyhow::Result<CasOutcome> { |
| 299 | let key = format!("cells/{cell}/own.json"); |
| 300 | let body = serde_json::to_vec(&OwnerWire { |
| 301 | node: &self.node, |
| 302 | epoch, |
| 303 | })?; |
| 304 | let etag = match &guard { |
| 305 | CasGuard::Absent => None, |
| 306 | CasGuard::Match(etag) => Some(etag.as_str()), |
| 307 | }; |
| 308 | match self.bucket.put_cas(&key, body, etag).await? { |
| 309 | Some(_) => Ok(CasOutcome::Applied), |
| 310 | None => Ok(CasOutcome::Rejected), |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | pub async fn cas_node_lease( |
| 315 | &self, |
| 316 | guard: CasGuard, |
| 317 | record: &NodeLeaseRecord, |
| 318 | ) -> anyhow::Result<LeaseCasOutcome> { |
| 319 | if self.probe_public_key.is_empty() { |
| 320 | return Err(anyhow::anyhow!( |
| 321 | "refusing to publish a node lease without a signed-probe key" |
| 322 | )); |
| 323 | } |
| 324 | let key = format!("nodes/{}.json", self.node); |
| 325 | let body = serde_json::to_vec(&NodeLeaseWire { |
| 326 | node: record.node.clone(), |
| 327 | expires_ms: record.expires_ms, |
| 328 | addr: record.addr.clone(), |
| 329 | probe_public_key: self.probe_public_key.clone(), |
| 330 | peer_protocol: record.peer_protocol, |
| 331 | generation: record.generation.clone(), |
| 332 | load: process_load(&self.live), |
| 333 | })?; |
| 334 | let etag = match &guard { |
| 335 | CasGuard::Absent => None, |
| 336 | CasGuard::Match(etag) => Some(etag.as_str()), |
| 337 | }; |
| 338 | match self.lease_bucket.put_cas(&key, body, etag).await? { |
| 339 | Some(etag) => Ok(LeaseCasOutcome::Applied { etag }), |
| 340 | None => Ok(LeaseCasOutcome::Rejected), |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | async fn read_json<T: for<'de> Deserialize<'de>>( |
| 345 | &self, |
| 346 | key: &str, |
| 347 | ) -> anyhow::Result<Option<(T, String)>> { |
| 348 | self.read_json_with(&self.bucket, key).await |
| 349 | } |
| 350 | |
| 351 | async fn read_json_with<T: for<'de> Deserialize<'de>>( |
| 352 | &self, |
| 353 | bucket: &Bucket, |
| 354 | key: &str, |
| 355 | ) -> anyhow::Result<Option<(T, String)>> { |
| 356 | let Some((bytes, etag)) = bucket.get(key).await? else { |
| 357 | return Ok(None); |
| 358 | }; |
| 359 | let value = serde_json::from_slice(&bytes) |
| 360 | .with_context(|| format!("decode s3://{}/{key}", bucket.name))?; |
| 361 | Ok(Some((value, etag))) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | fn process_load(live: &LiveLoad) -> NodeLoadWire { |
| 366 | #[cfg(target_os = "linux")] |
| 367 | let rss_bytes = std::fs::read_to_string("/proc/self/statm") |
| 368 | .ok() |
| 369 | .and_then(|statm| statm.split_whitespace().nth(1)?.parse::<u64>().ok()) |
| 370 | .map(|pages| pages.saturating_mul(4_096)) |
| 371 | .unwrap_or(1); |
| 372 | #[cfg(not(target_os = "linux"))] |
| 373 | let rss_bytes = 1; |
| 374 | |
| 375 | #[cfg(target_os = "linux")] |
| 376 | let open_fds = std::fs::read_dir("/proc/self/fd") |
| 377 | .map(|entries| entries.count() as u64) |
| 378 | .unwrap_or_default(); |
| 379 | #[cfg(not(target_os = "linux"))] |
| 380 | let open_fds = 0; |
| 381 | |
| 382 | #[cfg(unix)] |
| 383 | let fd_limit = { |
| 384 | let mut limit = libc::rlimit { |
| 385 | rlim_cur: 0, |
| 386 | rlim_max: 0, |
| 387 | }; |
| 388 | if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 { |
| 389 | limit.rlim_cur |
| 390 | } else { |
| 391 | 0 |
| 392 | } |
| 393 | }; |
| 394 | #[cfg(not(unix))] |
| 395 | let fd_limit = 0; |
| 396 | |
| 397 | NodeLoadWire { |
| 398 | sampled_ms: now_ms(), |
| 399 | rss_bytes, |
| 400 | open_fds, |
| 401 | fd_limit, |
| 402 | cpu_percent_x100: live.cpu_percent_x100.load(Ordering::Relaxed), |
| 403 | resident_cells: live.resident_cells.load(Ordering::Relaxed), |
| 404 | host_websockets: live.host_websockets.load(Ordering::Relaxed), |
| 405 | pressured: live.pressured.load(Ordering::Relaxed), |
| 406 | shed_cells: live.shed_cells.load(Ordering::Relaxed), |
| 407 | } |
| 408 | } |