| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Strict runtime environment parsing. |
| 4 | //! |
| 5 | //! An unset variable selects its caller's documented default. A supplied |
| 6 | //! variable must contain a valid value, so a typo cannot silently change the |
| 7 | //! configuration of a running node. |
| 8 | |
| 9 | use anyhow::{anyhow, bail}; |
| 10 | |
| 11 | pub const DEFAULT_SHUTDOWN_TOTAL_MS: u64 = 40_000; |
| 12 | |
| 13 | /// Shared by deployment assembly, managed deployment validation and serving |
| 14 | /// nodes. Operators must configure the same policy on all three paths. |
| 15 | pub fn max_asset_file_bytes() -> anyhow::Result<u64> { |
| 16 | // A manifest can contain thousands of entries. Cache the policy so each |
| 17 | // entry neither allocates an environment string nor observes a new limit. |
| 18 | // Keep parse failures fallible for library callers that skip startup validation. |
| 19 | static LIMIT: std::sync::OnceLock<Result<u64, String>> = std::sync::OnceLock::new(); |
| 20 | LIMIT |
| 21 | .get_or_init(|| { |
| 22 | positive_or("CELLD_MAX_ASSET_FILE_BYTES", 25 * 1024 * 1024) |
| 23 | .map_err(|error| error.to_string()) |
| 24 | }) |
| 25 | .as_ref() |
| 26 | .copied() |
| 27 | .map_err(|message| anyhow!("{message}")) |
| 28 | } |
| 29 | |
| 30 | /// One process stop budget and the internal waits derived from it. |
| 31 | /// The absolute deadline also bounds progress extensions, so neither wait |
| 32 | /// grants time beyond the supervisor-facing process budget. |
| 33 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 34 | pub struct ShutdownTiming { |
| 35 | pub total_ms: u64, |
| 36 | pub drain_token_wait_ms: u64, |
| 37 | pub drain_no_progress_ms: u64, |
| 38 | } |
| 39 | |
| 40 | impl ShutdownTiming { |
| 41 | fn from_total_ms(total_ms: u64) -> Self { |
| 42 | // Preserve the 30-second token wait and 25-second no-progress window |
| 43 | // at the default 40-second bound. Derive both when that bound changes: |
| 44 | // independent defaults made a shorter supervisor grace fail startup. |
| 45 | // Split the arithmetic so even the largest accepted u64 cannot wrap. |
| 46 | let drain_token_wait_ms = (total_ms / 4) * 3 + (total_ms % 4) * 3 / 4; |
| 47 | let drain_no_progress_ms = ((total_ms / 8) * 5 + (total_ms % 8) * 5 / 8).max(1); |
| 48 | Self { |
| 49 | total_ms, |
| 50 | drain_token_wait_ms, |
| 51 | drain_no_progress_ms, |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// A variable celld no longer reads, and the sentence that names what an |
| 57 | /// operator must write instead. |
| 58 | /// |
| 59 | /// The lists below enumerate the names celld knows, so a name that is not on |
| 60 | /// one of them is never looked at and never reported. That is correct for a |
| 61 | /// name celld never had, but wrong for one it removed: the operator set the |
| 62 | /// removed name on purpose, and the behaviour it bought is gone. A node whose |
| 63 | /// unit file still carries the name would boot clean, log nothing, and serve a |
| 64 | /// deployment that no longer has the binding, so the defect would surface as a |
| 65 | /// `TypeError` in a request handler on a node the operator believes they just |
| 66 | /// configured. Refusing the boot moves that failure to the moment the operator |
| 67 | /// can still read the unit file. |
| 68 | struct Removed { |
| 69 | name: &'static str, |
| 70 | /// What the operator must write in place of the line they delete. |
| 71 | replacement: &'static str, |
| 72 | /// Whether the removed reader ignored an empty value. Only a value that |
| 73 | /// once changed the node is stale, so this decides whether `NAME=` is a |
| 74 | /// line to delete or a line that never did anything. It is a property of |
| 75 | /// the reader that went away, so each entry must state it for itself: a |
| 76 | /// removed variable whose reader treated `NAME=` as meaningful sets |
| 77 | /// `false`, and an operator who templated it to an empty string then still |
| 78 | /// gets the refusal they need. |
| 79 | empty_was_inert: bool, |
| 80 | } |
| 81 | |
| 82 | const REMOVED: &[Removed] = &[ |
| 83 | Removed { |
| 84 | name: "CELLD_TEST_OTEL_SWEEP_MS", |
| 85 | replacement: "remove this setting; celld manages the telemetry retention cadence", |
| 86 | empty_was_inert: false, |
| 87 | }, |
| 88 | Removed { |
| 89 | name: "CELLD_OTEL_SINK", |
| 90 | replacement: "set CELLD_OTEL=1 for the fleet bucket or CELLD_OTEL=<collector URL> for OTLP", |
| 91 | empty_was_inert: false, |
| 92 | }, |
| 93 | Removed { |
| 94 | name: "CELLD_AI_BINDING", |
| 95 | replacement: "remove this setting; call the AI provider from application code", |
| 96 | empty_was_inert: false, |
| 97 | }, |
| 98 | Removed { |
| 99 | name: "CELLD_AI_URL", |
| 100 | replacement: "remove this setting; call the AI provider from application code", |
| 101 | empty_was_inert: false, |
| 102 | }, |
| 103 | Removed { |
| 104 | name: "CELLD_PACED_HANDOFF", |
| 105 | replacement: |
| 106 | "remove this setting; celld hands off ownership within CELLD_SHUTDOWN_TOTAL_MS", |
| 107 | empty_was_inert: false, |
| 108 | }, |
| 109 | Removed { |
| 110 | name: "CELLD_LOG_GROUP_COMMIT_MS", |
| 111 | replacement: "remove this setting; celld uses its built-in Queue batching policy", |
| 112 | empty_was_inert: false, |
| 113 | }, |
| 114 | Removed { |
| 115 | name: "CELLD_QUEUE_PRODUCER_GROUP_MS", |
| 116 | replacement: "remove this setting; celld uses its built-in Queue batching policy", |
| 117 | empty_was_inert: false, |
| 118 | }, |
| 119 | Removed { |
| 120 | name: "CELLD_LOG_BUNDLE", |
| 121 | replacement: "remove this setting; fleet durability uses bundled tiering", |
| 122 | empty_was_inert: false, |
| 123 | }, |
| 124 | Removed { |
| 125 | name: "CELLD_PRESENCE_SHADOW", |
| 126 | replacement: |
| 127 | "remove this setting; managed presence no longer compares a shadow lease report", |
| 128 | empty_was_inert: false, |
| 129 | }, |
| 130 | Removed { |
| 131 | name: "CELLD_STORAGE_PROBE", |
| 132 | replacement: "remove this setting; celld checks the storage contract before serving", |
| 133 | empty_was_inert: false, |
| 134 | }, |
| 135 | Removed { |
| 136 | name: "CELLD_EVICTIONS", |
| 137 | replacement: "remove this setting; celld uses its built-in scheduling limits", |
| 138 | empty_was_inert: false, |
| 139 | }, |
| 140 | Removed { |
| 141 | name: "CELLD_LOG_CAPTURE_WORKERS", |
| 142 | replacement: "remove this setting; celld uses its built-in scheduling limits", |
| 143 | empty_was_inert: false, |
| 144 | }, |
| 145 | Removed { |
| 146 | name: "CELLD_REBALANCE_BATCH_CELLS", |
| 147 | replacement: "remove this setting; celld uses its built-in scheduling limits", |
| 148 | empty_was_inert: false, |
| 149 | }, |
| 150 | Removed { |
| 151 | name: "CELLD_CLOUD_RESTART_ON_DEPLOY", |
| 152 | replacement: "remove this setting; managed deployments are adopted in place", |
| 153 | empty_was_inert: false, |
| 154 | }, |
| 155 | Removed { |
| 156 | name: "CELLD_OUTPUT_GATE", |
| 157 | replacement: "remove this setting; celld always waits for durability proof", |
| 158 | empty_was_inert: false, |
| 159 | }, |
| 160 | Removed { |
| 161 | name: "CELLD_DRAIN_TOKEN_WAIT_MS", |
| 162 | replacement: "set only CELLD_SHUTDOWN_TOTAL_MS; celld derives the drain-token wait", |
| 163 | // Zero disabled the token wait, and an empty value failed parsing. |
| 164 | empty_was_inert: false, |
| 165 | }, |
| 166 | Removed { |
| 167 | name: "CELLD_SHUTDOWN_DRAIN_MS", |
| 168 | replacement: |
| 169 | "set only CELLD_SHUTDOWN_TOTAL_MS; celld derives the handoff no-progress interval", |
| 170 | empty_was_inert: false, |
| 171 | }, |
| 172 | Removed { |
| 173 | name: "CELLD_MAX_LOADED_WORKERS", |
| 174 | replacement: "remove this setting; celld manages Dynamic Worker admission", |
| 175 | // Even an empty value failed in the old typed reader. Refuse it rather |
| 176 | // than silently changing the operator's configured admission policy. |
| 177 | empty_was_inert: false, |
| 178 | }, |
| 179 | Removed { |
| 180 | name: "CELLD_WORKER_LOADER", |
| 181 | replacement: "declare `worker_loaders` in the project config", |
| 182 | // The reader this replaced was |
| 183 | // `var("CELLD_WORKER_LOADER").ok().filter(|name| !name.is_empty())`, so |
| 184 | // an empty value never bound a loader. A deployment system that |
| 185 | // templates every known name to an empty string must not lose an |
| 186 | // upgrade on a node that never used the feature. |
| 187 | empty_was_inert: true, |
| 188 | }, |
| 189 | Removed { |
| 190 | name: "CELLD_VARS_FILE", |
| 191 | replacement: "set `vars` in the Wrangler config, or `.dev.vars` for `celld dev`", |
| 192 | // The former reader used the path verbatim, so `CELLD_VARS_FILE=` |
| 193 | // selected an empty path and failed instead of doing nothing. An |
| 194 | // operator must therefore delete the empty setting. |
| 195 | empty_was_inert: false, |
| 196 | }, |
| 197 | ]; |
| 198 | |
| 199 | /// The removed `CELLD_VAR_<NAME>` family. It is a prefix and not a name, so |
| 200 | /// the table above cannot hold it: celld never knew which names an operator |
| 201 | /// used. A node started with any of them would run with no override at all, |
| 202 | /// which reads inside a Worker as a missing secret with nothing in the log. |
| 203 | const REMOVED_PREFIX: (&str, &str) = ( |
| 204 | "CELLD_VAR_", |
| 205 | "set `vars` in the Wrangler config, or `.dev.vars` for `celld dev`", |
| 206 | ); |
| 207 | |
| 208 | /// Validate every typed production variable before the runtime starts. |
| 209 | /// |
| 210 | /// Some consumers cache a value or read it from a synchronous callback, so |
| 211 | /// they cannot return a configuration error at the point of use. This pass |
| 212 | /// makes those reads infallible without giving malformed values a default. |
| 213 | pub fn validate() -> anyhow::Result<()> { |
| 214 | // Each entry carries its own empty-value rule, because whether `NAME=` was |
| 215 | // inert is a property of the reader that went away and not of removal. |
| 216 | for removed in REMOVED { |
| 217 | let Some(value) = std::env::var_os(removed.name) else { |
| 218 | continue; |
| 219 | }; |
| 220 | if removed.empty_was_inert && value.is_empty() { |
| 221 | continue; |
| 222 | } |
| 223 | bail!("{} is removed; {}", removed.name, removed.replacement); |
| 224 | } |
| 225 | let (prefix, replacement) = REMOVED_PREFIX; |
| 226 | if let Some(name) = std::env::vars_os().find_map(|(name, _)| { |
| 227 | let name = name.to_string_lossy().into_owned(); |
| 228 | name.starts_with(prefix).then_some(name) |
| 229 | }) { |
| 230 | bail!("{name} is removed; {replacement}"); |
| 231 | } |
| 232 | |
| 233 | for name in [ |
| 234 | "CELLD_CLOUD", |
| 235 | "CELLD_LTX_COMPACTION", |
| 236 | "CELLD_LTX_PAGED", |
| 237 | "CELLD_TRUST_FORWARDED_HEADERS", |
| 238 | "CELLD_UNSAFE_PUBLIC_ADVERTISE", |
| 239 | ] { |
| 240 | flag(name, false)?; |
| 241 | } |
| 242 | |
| 243 | for name in [ |
| 244 | "CELLD_ACTIVATIONS", |
| 245 | "CELLD_DEPLOY_POLL_S", |
| 246 | "CELLD_FETCH_TIMEOUT_S", |
| 247 | "CELLD_HANDLER_BUDGET_S", |
| 248 | "CELLD_IDLE_EVICT_S", |
| 249 | "CELLD_LOG_PIPELINE", |
| 250 | "CELLD_LTX_COMPACTIONS", |
| 251 | "CELLD_LTX_COMPACTION_MIN_TXIDS", |
| 252 | "CELLD_LTX_DURABILITY_TIMEOUT_SECS", |
| 253 | "CELLD_MAX_CELL_REQUESTS", |
| 254 | "CELLD_MAX_ASSET_FILE_BYTES", |
| 255 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 256 | "CELLD_MAX_REQUEST_BODY_BYTES", |
| 257 | "CELLD_MAX_REQUESTS", |
| 258 | "CELLD_RECOVERY_RETRY_MS", |
| 259 | "CELLD_RECOVERY_RETRIES", |
| 260 | "CELLD_MAX_STATELESS_ISOLATES", |
| 261 | "CELLD_OPERATION_DEADLINE_MS", |
| 262 | "CELLD_PLACEMENT_WEIGHT", |
| 263 | "CELLD_RELEASES", |
| 264 | "CELLD_TOKIO_THREADS", |
| 265 | "CELLD_TTL_MS", |
| 266 | "CELLD_WAKER_TICK_MS", |
| 267 | ] { |
| 268 | positive::<u64>(name)?; |
| 269 | } |
| 270 | |
| 271 | for name in [ |
| 272 | "CELLD_ADMISSION_WAIT_MS", |
| 273 | "CELLD_ALARM_RESIDENT_MS", |
| 274 | "CELLD_ASSET_CACHE_BYTES", |
| 275 | "CELLD_CONTAINER_MEMORY_MB", |
| 276 | "CELLD_DEPLOY_MAX_AGE_S", |
| 277 | "CELLD_LOCAL_CACHE_MAX_BYTES", |
| 278 | "CELLD_LTX_TRUNCATE_PAGES", |
| 279 | "CELLD_LTX_RETENTION_SECS", |
| 280 | "CELLD_LOG_HEDGE_MS", |
| 281 | "CELLD_LOG_WINDOW", |
| 282 | "CELLD_LOG_WINDOW_BYTES", |
| 283 | "CELLD_MAX_RESIDENT_CELLS", |
| 284 | "CELLD_MAX_RSS_MB", |
| 285 | "CELLD_READY_FLEET_GATE_MS", |
| 286 | "CELLD_REBALANCE_INTERVAL_MS", |
| 287 | ] { |
| 288 | optional::<u64>(name)?; |
| 289 | } |
| 290 | |
| 291 | shutdown_timing()?; |
| 292 | |
| 293 | positive::<usize>("CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES")?; |
| 294 | |
| 295 | if let Some(value) = optional::<u64>("CELLD_PRESENCE_HEARTBEAT_MS")? { |
| 296 | if !(50..=30_000).contains(&value) { |
| 297 | bail!("CELLD_PRESENCE_HEARTBEAT_MS must be between 50 and 30000, not {value}"); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | if let Some(megabytes) = positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")? { |
| 302 | if megabytes.checked_mul(1024 * 1024).is_none() { |
| 303 | bail!("CELLD_V8_HEAP_LIMIT_MB is too large: {megabytes}"); |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | if let Some(value) = value("CELLD_LOG_TRANSPORT")? { |
| 308 | if !matches!(value.as_str(), "http" | "stream") { |
| 309 | bail!("CELLD_LOG_TRANSPORT must be http or stream, not {value:?}"); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | if let Some(value) = value("CELLD_PRESSURE_OWNERSHIP")? { |
| 314 | if !matches!(value.as_str(), "release" | "sticky") { |
| 315 | bail!("CELLD_PRESSURE_OWNERSHIP must be release or sticky, not {value:?}"); |
| 316 | } |
| 317 | } |
| 318 | if let Some(node) = value("CELLD_NODE")? { |
| 319 | crate::machine::validate_node_name(&node).map_err(|error| anyhow!("CELLD_NODE {error}"))?; |
| 320 | } |
| 321 | Ok(()) |
| 322 | } |
| 323 | |
| 324 | /// Resolve all shutdown timing from the operator's complete process bound. |
| 325 | /// Token acquisition consumes at most three quarters of that bound. The |
| 326 | /// no-progress interval is five eighths, with a one-millisecond minimum. |
| 327 | /// The process deadline still caps every shutdown phase and progress reset. |
| 328 | pub fn shutdown_timing() -> anyhow::Result<ShutdownTiming> { |
| 329 | let total_ms = positive("CELLD_SHUTDOWN_TOTAL_MS")?.unwrap_or(DEFAULT_SHUTDOWN_TOTAL_MS); |
| 330 | Ok(ShutdownTiming::from_total_ms(total_ms)) |
| 331 | } |
| 332 | |
| 333 | pub fn value(name: &str) -> anyhow::Result<Option<String>> { |
| 334 | match std::env::var(name) { |
| 335 | Ok(value) => Ok(Some(value)), |
| 336 | Err(std::env::VarError::NotPresent) => Ok(None), |
| 337 | Err(error) => Err(anyhow!("read {name}: {error}")), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | pub fn flag(name: &str, default: bool) -> anyhow::Result<bool> { |
| 342 | let value = value(name)?; |
| 343 | parse_flag(name, value.as_deref(), default) |
| 344 | } |
| 345 | |
| 346 | pub fn parse_flag(name: &str, value: Option<&str>, default: bool) -> anyhow::Result<bool> { |
| 347 | match value { |
| 348 | None => Ok(default), |
| 349 | Some("0") => Ok(false), |
| 350 | Some("1") => Ok(true), |
| 351 | Some(other) => bail!("{name} must be 0 or 1, not {other:?}"), |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | pub fn optional<T>(name: &str) -> anyhow::Result<Option<T>> |
| 356 | where |
| 357 | T: std::str::FromStr, |
| 358 | T::Err: std::fmt::Display, |
| 359 | { |
| 360 | parse_optional(name, value(name)?) |
| 361 | } |
| 362 | |
| 363 | pub fn parse_optional<T>(name: &str, value: Option<String>) -> anyhow::Result<Option<T>> |
| 364 | where |
| 365 | T: std::str::FromStr, |
| 366 | T::Err: std::fmt::Display, |
| 367 | { |
| 368 | value |
| 369 | .map(|value| { |
| 370 | value |
| 371 | .parse::<T>() |
| 372 | .map_err(|error| anyhow!("{name} has invalid value {value:?}: {error}")) |
| 373 | }) |
| 374 | .transpose() |
| 375 | } |
| 376 | |
| 377 | pub fn with_default<T>(name: &str, default: T) -> anyhow::Result<T> |
| 378 | where |
| 379 | T: std::str::FromStr, |
| 380 | T::Err: std::fmt::Display, |
| 381 | { |
| 382 | Ok(optional(name)?.unwrap_or(default)) |
| 383 | } |
| 384 | |
| 385 | pub fn positive<T>(name: &str) -> anyhow::Result<Option<T>> |
| 386 | where |
| 387 | T: std::str::FromStr + Default + PartialOrd + std::fmt::Display, |
| 388 | T::Err: std::fmt::Display, |
| 389 | { |
| 390 | parse_positive(name, value(name)?) |
| 391 | } |
| 392 | |
| 393 | pub fn parse_positive<T>(name: &str, value: Option<String>) -> anyhow::Result<Option<T>> |
| 394 | where |
| 395 | T: std::str::FromStr + Default + PartialOrd + std::fmt::Display, |
| 396 | T::Err: std::fmt::Display, |
| 397 | { |
| 398 | let Some(value) = parse_optional::<T>(name, value)? else { |
| 399 | return Ok(None); |
| 400 | }; |
| 401 | if value <= T::default() { |
| 402 | bail!("{name} must be greater than zero, not {value}"); |
| 403 | } |
| 404 | Ok(Some(value)) |
| 405 | } |
| 406 | |
| 407 | pub fn positive_or<T>(name: &str, default: T) -> anyhow::Result<T> |
| 408 | where |
| 409 | T: std::str::FromStr + Default + PartialOrd + std::fmt::Display, |
| 410 | T::Err: std::fmt::Display, |
| 411 | { |
| 412 | Ok(positive(name)?.unwrap_or(default)) |
| 413 | } |