Diffinery

homeflare/celldpublic

celld/crates/celld/control_plane.rs
2841 lines · 102.7 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Managed control-plane sessions execute outside the Actor execution domain.
4#![allow(clippy::disallowed_methods, clippy::disallowed_types)]
5
6use crate::bucket::Bucket;
7use crate::note;
8use crate::protocol::{asset_blob_key, AssetIndex, DeployPointer, Manifest};
9use anyhow::{anyhow, Context};
10use celld_logic::PresenceSnapshot;
11use fastwebsockets::{Frame, OpCode};
12use hyper::header::HeaderMap;
13use rand::RngCore;
14use rusqlite::{types::ValueRef, Connection, OpenFlags, OptionalExtension};
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17use std::fs::File;
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::pin::Pin;
21use std::sync::{Arc, Mutex, OnceLock};
22use std::time::{Duration, Instant};
23use tracing::{info, warn};
24
25const DEFAULT_CONTROL_URL: &str = "https://celld.dev";
26const DEFAULT_ENVIRONMENT: &str = "prod";
27const MAX_PRESENCE_CELLS: usize = 50;
28const MAX_PRESENCE_CELL_ID_BYTES: usize = 200;
29const MAX_EXPLORER_CELL_PAGE: usize = 100;
30const MAX_EXPLORER_TABLES: usize = 100;
31const MAX_EXPLORER_COLUMNS: usize = 32;
32const MAX_EXPLORER_ROWS: usize = 25;
33const MAX_EXPLORER_VALUE_BYTES: usize = 2 * 1024;
34const MAX_EXPLORER_RESPONSE_BYTES: usize = 96 * 1024;
35const MAX_MANAGED_MODULES: usize = 64;
36const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024;
37
38#[cfg(unix)]
39fn restart_with_rotated_credentials() -> ! {
40 use std::os::unix::process::CommandExt;
41 use std::process::Command;
42
43 let executable = match std::env::current_exe() {
44 Ok(executable) => executable,
45 Err(error) => {
46 warn!(
47 event = "control_plane_restart_exec_failed",
48 trigger = "credential_rotation",
49 %error,
50 "could not locate celld for process reload; exiting for an external supervisor"
51 );
52 std::process::exit(75);
53 }
54 };
55 let signer = match crate::peer_probe::reexec_signer_secret() {
56 Ok(signer) => signer,
57 Err(error) => {
58 warn!(
59 event = "control_plane_restart_exec_failed",
60 trigger = "credential_rotation",
61 %error,
62 "could not preserve process probe identity; exiting for an external supervisor"
63 );
64 std::process::exit(75);
65 }
66 };
67 let mut command = Command::new(executable);
68 command
69 .args(std::env::args_os().skip(1))
70 .env(crate::peer_probe::REEXEC_SIGNER_ENV, signer);
71 if let Some(node) = REEXEC_NODE_SESSION_ID.get() {
72 command.env("CELLD_NODE", node);
73 }
74 let error = command.exec();
75 warn!(
76 event = "control_plane_restart_exec_failed",
77 trigger = "credential_rotation",
78 %error,
79 "could not re-exec celld for process reload; exiting for an external supervisor"
80 );
81 std::process::exit(75);
82}
83
84#[cfg(not(unix))]
85fn restart_with_rotated_credentials() -> ! {
86 std::process::exit(75);
87}
88
89static REEXEC_NODE_SESSION_ID: OnceLock<String> = OnceLock::new();
90
91pub fn install_reexec_node_session_id(node: &str) -> anyhow::Result<()> {
92 REEXEC_NODE_SESSION_ID
93 .set(node.to_string())
94 .map_err(|_| anyhow!("re-exec node-session identity is already installed"))
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum ManagedRuntimeState {
99 Connected,
100 ControlPlaneUnavailable,
101 BucketUnavailable,
102 CredentialRevoked,
103 /// The bucket answers, and the credential works, but the store does not
104 /// support a required conditional write or ranged read. Distinct from
105 /// `BucketUnavailable`, which a retry can clear: this one never does.
106 StorageContractViolated,
107}
108
109impl ManagedRuntimeState {
110 fn as_str(self) -> &'static str {
111 match self {
112 Self::Connected => "connected",
113 Self::ControlPlaneUnavailable => "control_plane_unavailable",
114 Self::BucketUnavailable => "bucket_unavailable",
115 Self::CredentialRevoked => "credential_revoked",
116 Self::StorageContractViolated => "storage_contract_violated",
117 }
118 }
119}
120
121static MANAGED_RUNTIME_STATE: OnceLock<Mutex<Option<ManagedRuntimeState>>> = OnceLock::new();
122
123pub fn report_managed_runtime_state(state: ManagedRuntimeState) {
124 let mut current = MANAGED_RUNTIME_STATE
125 .get_or_init(|| Mutex::new(None))
126 .lock()
127 .unwrap();
128 if *current == Some(state) {
129 return;
130 }
131 *current = Some(state);
132 drop(current);
133 let managed_state = state.as_str();
134 match state {
135 ManagedRuntimeState::Connected => info!(
136 event = "managed_runtime_state",
137 managed_state, "Managed Control Plane connected"
138 ),
139 ManagedRuntimeState::ControlPlaneUnavailable => info!(
140 event = "managed_runtime_state",
141 managed_state, "Managed Control Plane unavailable; bucket-backed serving continues"
142 ),
143 ManagedRuntimeState::BucketUnavailable => warn!(
144 event = "managed_runtime_state",
145 managed_state, "fleet bucket unavailable; serving cannot start"
146 ),
147 // Name the remedy: this condition can be cleared by a restart or an
148 // explicit credential refresh.
149 ManagedRuntimeState::CredentialRevoked => warn!(
150 event = "managed_runtime_state",
151 managed_state,
152 "managed storage credential was rejected; restart celld to fetch a \
153 fresh one, or run `celld credentials refresh` if a rotation is pending"
154 ),
155 // No remedy on this node: the store lacks a required operation, so a
156 // restart repeats the refusal. The operator needs a compatible store.
157 ManagedRuntimeState::StorageContractViolated => warn!(
158 event = "managed_runtime_state",
159 managed_state,
160 "the fleet bucket does not support a storage operation celld requires, \
161 so serving cannot start; move the fleet to a compatible store"
162 ),
163 }
164}
165
166#[derive(Debug)]
167struct ManagedControlCredentialRevoked;
168
169impl std::fmt::Display for ManagedControlCredentialRevoked {
170 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 formatter.write_str(
172 "Managed Control Plane credential was rejected or revoked.\n\
173 Restart celld to fetch a fresh credential. If that does not help, \
174 run `celld credentials refresh`, and `celld diagnose` to check \
175 bucket access.",
176 )
177 }
178}
179
180impl std::error::Error for ManagedControlCredentialRevoked {}
181
182#[derive(Clone, Debug, PartialEq, Eq)]
183struct ConnectOptions {
184 control_url: String,
185 environment: String,
186 force: bool,
187 byo_storage: Option<ByoStorageConfig>,
188}
189
190#[derive(Clone, Deserialize, Serialize)]
191struct CloudConfig {
192 #[serde(default = "installation_schema_version")]
193 version: u32,
194 #[serde(alias = "instance_id")]
195 installation_id: String,
196 #[serde(alias = "instance_token")]
197 installation_token: Option<String>,
198 #[serde(default = "initial_credential_version")]
199 credential_version: u64,
200 fleet_id: Option<String>,
201 environment_id: Option<String>,
202 control_url: String,
203 environment: String,
204 #[serde(default)]
205 storage: Option<ManagedStorageConfig>,
206 #[serde(default)]
207 byo_storage: Option<ByoStorageConfig>,
208 #[serde(default)]
209 credential_handoff_id: Option<String>,
210 #[serde(default)]
211 previous_credential: Option<PreviousCredential>,
212 #[serde(default)]
213 pending_claim: Option<PendingClaim>,
214}
215
216#[derive(Clone, Deserialize, Serialize)]
217struct PreviousCredential {
218 installation_token: String,
219 credential_version: u64,
220 storage: ManagedStorageConfig,
221}
222
223#[derive(Clone, Deserialize, Serialize)]
224struct PendingClaim {
225 verification_uri_complete: String,
226 expires_at_ms: u64,
227}
228
229#[derive(Clone, Deserialize, Serialize)]
230pub struct ManagedStorageConfig {
231 pub bucket: String,
232 pub endpoint: String,
233 pub region: String,
234 pub access_key_id: String,
235 pub secret_access_key: String,
236 #[serde(default)]
237 pub session_token: Option<String>,
238}
239
240#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
241pub struct ByoStorageConfig {
242 pub bucket: String,
243 #[serde(default)]
244 pub endpoint: Option<String>,
245 pub region: String,
246}
247
248#[derive(Clone)]
249pub enum InstallationStorageConfig {
250 Managed(ManagedStorageConfig),
251 Byo(ByoStorageConfig),
252}
253
254#[derive(Serialize)]
255struct CreateClaimRequest<'a> {
256 instance_id: &'a str,
257 instance_name: &'a str,
258 environment: &'a str,
259 version: &'static str,
260 platform: String,
261 storage_origin: &'static str,
262 #[serde(skip_serializing_if = "Option::is_none")]
263 bucket: Option<&'a str>,
264 #[serde(skip_serializing_if = "Option::is_none")]
265 endpoint: Option<&'a str>,
266 #[serde(skip_serializing_if = "Option::is_none")]
267 region: Option<&'a str>,
268}
269
270#[derive(Deserialize)]
271struct CreateClaimResponse {
272 device_code: String,
273 verification_uri_complete: String,
274 expires_in: u64,
275 interval: u64,
276}
277
278#[derive(Serialize)]
279struct PollClaimRequest<'a> {
280 device_code: &'a str,
281}
282
283#[derive(Deserialize)]
284struct PollClaimResponse {
285 status: String,
286 #[serde(default = "managed_storage_origin")]
287 storage_origin: String,
288 credential_handoff_id: Option<String>,
289 credential_version: Option<u64>,
290 instance_token: Option<String>,
291 fleet_id: Option<String>,
292 environment_id: Option<String>,
293 bucket: Option<String>,
294 endpoint: Option<String>,
295 region: Option<String>,
296 access_key_id: Option<String>,
297 secret_access_key: Option<String>,
298 session_token: Option<String>,
299 interval: Option<u64>,
300}
301
302#[derive(Deserialize)]
303struct CredentialRotationResponse {
304 status: String,
305 credential_handoff_id: String,
306 credential_version: u64,
307 instance_token: String,
308 bucket: String,
309 endpoint: String,
310 region: String,
311 access_key_id: String,
312 secret_access_key: String,
313 session_token: Option<String>,
314}
315
316#[derive(Deserialize)]
317struct AgentCommandEnvelope {
318 command: AgentCommand,
319}
320
321#[derive(Deserialize)]
322struct AgentCommand {
323 id: String,
324 #[serde(rename = "type")]
325 kind: String,
326 deployment: AgentDeployment,
327}
328
329#[derive(Deserialize)]
330#[doc(hidden)]
331pub struct AgentDeployment {
332 pub script_name: String,
333 pub version: String,
334 pub manifest: Manifest,
335 pub pointer: DeployPointer,
336 pub modules: Vec<AgentModule>,
337 #[serde(default)]
338 pub assets: Option<AgentAssets>,
339}
340
341#[derive(Deserialize)]
342#[doc(hidden)]
343pub struct AgentModule {
344 pub name: String,
345 pub sha256: String,
346 pub download_url: String,
347}
348
349#[derive(Deserialize)]
350pub struct AgentAssets {
351 pub index_download_url: String,
352 pub blob_download_base_url: String,
353 pub sha256: String,
354 pub file_count: u32,
355 pub total_bytes: u64,
356}
357
358#[derive(Serialize)]
359struct CompleteCommandRequest<'a> {
360 success: bool,
361 error: Option<&'a str>,
362}
363
364struct AppliedDeployment {
365 id: String,
366 script_name: String,
367}
368
369pub async fn handle_connect_command(
370 arguments: impl IntoIterator<Item = String>,
371) -> anyhow::Result<()> {
372 let mut options = options_from_env()?;
373 let mut args = arguments.into_iter();
374 while let Some(argument) = args.next() {
375 match argument.as_str() {
376 "--env" => {
377 options.environment = args.next().context("--env requires a value")?;
378 }
379 "--control-url" => {
380 options.control_url = args.next().context("--control-url requires a value")?;
381 }
382 "--force" => options.force = true,
383 "--help" | "-h" => {
384 if let Some(argument) = args.next() {
385 return Err(anyhow!(
386 "unexpected argument after connect --help: {argument}"
387 ));
388 }
389 print_connect_help();
390 return Ok(());
391 }
392 _ => return Err(anyhow!("unknown connect option: {argument}")),
393 }
394 }
395 validate_environment(&options.environment)?;
396 connect(options, true).await
397}
398
399/// `celld token` — print the fleet's deploy token and the exact commands to
400/// use it.
401///
402/// Wrangler expects deployment credentials in environment variables, so this
403/// command exposes the connected fleet's short-lived token in a shell-friendly
404/// form.
405pub async fn handle_token_command(
406 arguments: impl IntoIterator<Item = String>,
407) -> anyhow::Result<()> {
408 let arguments = arguments.into_iter().collect::<Vec<_>>();
409 if matches!(arguments.as_slice(), [a] if a == "--help" || a == "-h") {
410 // Help is prose an operator redirects on purpose, so it is stdout.
411 return crate::cli_output::Output::new(crate::cli_output::Format::Text).help(
412 "Print this fleet's deploy token, and how to deploy with it.\n\n\
413 USAGE:\n celld token [--format shell]\n\n\
414 OPTIONS:\n --format shell Print only shell exports, suitable for `eval`.\n",
415 );
416 }
417 let shell_only = match arguments.as_slice() {
418 [] => false,
419 [format, value] if format == "--format" && value == "shell" => true,
420 _ => {
421 return Err(anyhow!(
422 "expected `celld token` or `celld token --format shell`; \
423 run `celld token --help` for usage"
424 ))
425 }
426 };
427 let path = config_path()?;
428 let contents = std::fs::read_to_string(&path).with_context(|| {
429 format!(
430 "read {}. This celld installation is not enrolled yet — run `celld` \
431 and approve the link it prints.",
432 path.display()
433 )
434 })?;
435 let config: CloudConfig =
436 serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
437 let token = config.installation_token.as_deref().context(
438 "this celld installation is not enrolled in the Managed Control Plane — \
439 run `celld` and approve the link it prints",
440 )?;
441 let client = reqwest::Client::new();
442 let response = client
443 .post(format!("{}/api/agent/deploy-token", config.control_url))
444 .bearer_auth(token)
445 .send()
446 .await
447 .context("request a deploy token")?;
448 if !response.status().is_success() {
449 let status = response.status();
450 let body = response.text().await.unwrap_or_default();
451 return Err(anyhow!(
452 "could not get a deploy token ({status}): {body}\n\
453 If this installation was disconnected, run `celld` to re-enrol."
454 ));
455 }
456 #[derive(serde::Deserialize)]
457 struct DeployTokenResponse {
458 token: String,
459 account_id: String,
460 api_base_url: String,
461 }
462 let issued: DeployTokenResponse = response.json().await.context("decode deploy token")?;
463 let exports = render_deploy_token(&issued.token, &issued.account_id, &issued.api_base_url);
464 if !shell_only {
465 // Say what to do next, not merely what happened -- on stderr, so
466 // that `eval "$(celld token)"` sees only the exports.
467 note!("Deploy token for this fleet:\n\n {}\n", issued.token);
468 note!("Deploy your app with these exports, then `npx wrangler@4 deploy`:\n");
469 }
470 crate::cli_output::Output::new(crate::cli_output::Format::Text).bytes(exports.as_bytes())
471}
472
473fn render_deploy_token(token: &str, account_id: &str, api_base_url: &str) -> String {
474 format!(
475 "export CLOUDFLARE_API_TOKEN={}\n\
476 export CLOUDFLARE_ACCOUNT_ID={}\n\
477 export CLOUDFLARE_API_BASE_URL={}\n",
478 shell_quote(token),
479 shell_quote(account_id),
480 shell_quote(api_base_url),
481 )
482}
483
484fn shell_quote(value: &str) -> String {
485 format!("'{}'", value.replace('\'', "'\"'\"'"))
486}
487
488pub async fn handle_credentials_command(
489 arguments: impl IntoIterator<Item = String>,
490) -> anyhow::Result<()> {
491 let arguments = arguments.into_iter().collect::<Vec<_>>();
492 if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") {
493 print_credentials_help();
494 return Ok(());
495 }
496 if !matches!(arguments.as_slice(), [command] if command == "refresh") {
497 return Err(anyhow!(
498 "expected `celld credentials refresh`; run `celld credentials --help` for usage"
499 ));
500 }
501 refresh_credentials().await
502}
503
504pub async fn handle_disconnect_command(
505 arguments: impl IntoIterator<Item = String>,
506) -> anyhow::Result<()> {
507 let arguments = arguments.into_iter().collect::<Vec<_>>();
508 if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") {
509 print_disconnect_help();
510 return Ok(());
511 }
512 if !matches!(arguments.as_slice(), [confirmation] if confirmation == "--yes") {
513 return Err(anyhow!(
514 "disconnect revokes every process sharing this installation; rerun `celld disconnect --yes` to confirm"
515 ));
516 }
517 let path = config_path()?;
518 let client = reqwest::Client::builder()
519 .timeout(Duration::from_secs(15))
520 .build()?;
521 let archive = disconnect_at_path(path, &client).await?;
522 note!(
523 "Disconnected this installation from the Managed Control Plane.\nArchived its revoked local record at {}.",
524 archive.display()
525 );
526 Ok(())
527}
528
529async fn disconnect_at_path(path: PathBuf, client: &reqwest::Client) -> anyhow::Result<PathBuf> {
530 let _lock = acquire_enrollment_lock(&path).await?;
531 let contents =
532 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
533 let config: CloudConfig =
534 serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
535 let token = config
536 .installation_token
537 .as_deref()
538 .context("this celld installation is not enrolled in the Managed Control Plane")?;
539 let response = client
540 .post(format!(
541 "{}/api/agent/credentials/revoke",
542 config.control_url
543 ))
544 .bearer_auth(token)
545 .json(&serde_json::json!({ "installation_id": config.installation_id }))
546 .send()
547 .await
548 .context("revoke managed installation")?;
549 if !response.status().is_success() {
550 return Err(anyhow!(
551 "managed installation revocation returned {}",
552 response.status()
553 ));
554 }
555
556 // Keep a recoverable, permission-preserving record rather than deleting
557 // secrets in place. The provider credential is already revoked, and bare
558 // `celld` will create a fresh installation record on its next start.
559 let file_name = path
560 .file_name()
561 .and_then(|value| value.to_str())
562 .context("managed installation path has no UTF-8 file name")?;
563 let archive = path.with_file_name(format!("{file_name}.disconnected-{}", current_time_ms()));
564 std::fs::rename(&path, &archive).with_context(|| {
565 format!(
566 "archive revoked installation record as {}",
567 archive.display()
568 )
569 })?;
570 Ok(archive)
571}
572
573async fn refresh_credentials() -> anyhow::Result<()> {
574 let path = config_path()?;
575 let client = reqwest::Client::builder()
576 .timeout(Duration::from_secs(15))
577 .build()?;
578 refresh_credentials_at_path(path, &client).await
579}
580
581async fn refresh_credentials_at_path(
582 path: PathBuf,
583 client: &reqwest::Client,
584) -> anyhow::Result<()> {
585 let _lock = acquire_enrollment_lock(&path).await?;
586 let contents =
587 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
588 let mut config: CloudConfig =
589 serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
590 let token = config
591 .installation_token
592 .as_deref()
593 .context("this celld installation is not enrolled in the Managed Control Plane")?;
594 let current_storage = config
595 .storage
596 .as_ref()
597 .context("managed installation record has no storage credentials")?;
598
599 if let Some(handoff_id) = config.credential_handoff_id.clone() {
600 acknowledge_credential_handoff(client, &config, &handoff_id)
601 .await
602 .context("finish previously saved credential refresh")?;
603 config.credential_handoff_id = None;
604 config.previous_credential = None;
605 save_config(&path, &config)?;
606 note!(
607 "Managed credential refresh completed (version {}).",
608 config.credential_version
609 );
610 return Ok(());
611 }
612
613 let response = client
614 .post(format!("{}/api/agent/credentials/next", config.control_url))
615 .bearer_auth(token)
616 .json(&serde_json::json!({}))
617 .send()
618 .await
619 .context("request staged managed credential")?;
620 if response.status() == reqwest::StatusCode::NO_CONTENT {
621 note!("No managed credential rotation is pending.");
622 return Ok(());
623 }
624 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
625 return Err(anyhow!(
626 "this installation credential is revoked; enroll a new installation"
627 ));
628 }
629 if !response.status().is_success() {
630 return Err(anyhow!(
631 "credential refresh endpoint returned {}",
632 response.status()
633 ));
634 }
635 let replacement: CredentialRotationResponse = response
636 .json()
637 .await
638 .context("decode staged managed credential")?;
639 validate_credential_rotation(&replacement, &config, current_storage)?;
640
641 config.previous_credential = Some(PreviousCredential {
642 installation_token: token.to_string(),
643 credential_version: config.credential_version,
644 storage: current_storage.clone(),
645 });
646 config.installation_token = Some(replacement.instance_token);
647 config.credential_version = replacement.credential_version;
648 config.storage = Some(ManagedStorageConfig {
649 bucket: replacement.bucket,
650 endpoint: replacement.endpoint,
651 region: replacement.region,
652 access_key_id: replacement.access_key_id,
653 secret_access_key: replacement.secret_access_key,
654 session_token: replacement.session_token,
655 });
656 config.credential_handoff_id = Some(replacement.credential_handoff_id.clone());
657
658 // The replacement is persisted before acknowledgement. If this process is
659 // killed after the rename, the marker makes the acknowledgement retryable.
660 // The managed control plane keeps both token hashes valid until this
661 // acknowledgement succeeds.
662 save_config(&path, &config)?;
663 acknowledge_credential_handoff(client, &config, &replacement.credential_handoff_id)
664 .await
665 .context(
666 "replacement credential is saved, but acknowledgement is pending; rerun `celld credentials refresh`",
667 )?;
668 config.credential_handoff_id = None;
669 config.previous_credential = None;
670 save_config(&path, &config)?;
671 note!(
672 "Managed credential refresh completed (version {}).",
673 config.credential_version
674 );
675 Ok(())
676}
677
678fn validate_credential_rotation(
679 replacement: &CredentialRotationResponse,
680 config: &CloudConfig,
681 current: &ManagedStorageConfig,
682) -> anyhow::Result<()> {
683 if replacement.status != "rotation_pending" {
684 return Err(anyhow!(
685 "unexpected credential refresh status: {}",
686 replacement.status
687 ));
688 }
689 if replacement.credential_version != config.credential_version.saturating_add(1) {
690 return Err(anyhow!(
691 "credential refresh version is not the next installation version"
692 ));
693 }
694 if replacement.bucket != current.bucket
695 || replacement.endpoint != current.endpoint
696 || replacement.region != current.region
697 {
698 return Err(anyhow!(
699 "credential refresh attempted to change the installation storage target"
700 ));
701 }
702 for (name, value) in [
703 (
704 "credential handoff",
705 replacement.credential_handoff_id.as_str(),
706 ),
707 ("installation token", replacement.instance_token.as_str()),
708 ("storage access key", replacement.access_key_id.as_str()),
709 ("storage secret key", replacement.secret_access_key.as_str()),
710 ] {
711 if value.is_empty() || value.len() > 500 {
712 return Err(anyhow!("credential refresh returned an invalid {name}"));
713 }
714 }
715 Ok(())
716}
717
718pub async fn connect_on_startup_with_storage(
719 byo_storage: Option<ByoStorageConfig>,
720) -> anyhow::Result<()> {
721 let mut options = options_from_env()?;
722 options.byo_storage = byo_storage;
723 validate_environment(&options.environment)?;
724 connect(options, true).await
725}
726
727pub fn installation_storage() -> anyhow::Result<InstallationStorageConfig> {
728 installation_storage_with_version().map(|(storage, _)| storage)
729}
730
731pub fn installation_storage_with_version() -> anyhow::Result<(InstallationStorageConfig, u64)> {
732 let config = connected_config()?.context("managed installation is not connected")?;
733 let credential_version = config.credential_version;
734 let storage = match (config.storage, config.byo_storage) {
735 (Some(storage), None) => InstallationStorageConfig::Managed(storage),
736 (None, Some(storage)) => InstallationStorageConfig::Byo(storage),
737 (None, None) => {
738 return Err(anyhow!("managed installation record has no storage target"));
739 }
740 (Some(_), Some(_)) => {
741 return Err(anyhow!(
742 "managed installation record contains conflicting storage targets"
743 ));
744 }
745 };
746 Ok((storage, credential_version))
747}
748
749pub type PresenceSnapshotFuture = Pin<Box<dyn Future<Output = Option<PresenceSnapshot>> + Send>>;
750pub type PresenceSnapshotSource = Arc<dyn Fn() -> PresenceSnapshotFuture + Send + Sync>;
751
752/// Production WebSocket transport around a read-only projection supplied by
753/// celld-logic. The control-plane adapter cannot mutate lifecycle state or
754/// maintain its own resident inventory.
755pub struct PresenceRuntime {
756 pub s3: Bucket,
757 pub replication: Option<crate::runtime::Replication>,
758 pub node_session_id: String,
759 pub advertise: String,
760 pub listen: String,
761 /// Credential version used to construct S3, lease, replication, explorer,
762 /// and deployment adapters. This intentionally comes from the same config
763 /// snapshot as those credentials, not from a later presence-agent read.
764 pub credential_version: u64,
765 pub snapshot: PresenceSnapshotSource,
766 /// The pointer watcher a deployment notification nudges.
767 pub reload: crate::generation::ReloadSender,
768}
769
770pub fn start_presence_agent(runtime: PresenceRuntime) -> bool {
771 let config = match connected_config() {
772 Ok(Some(config)) => config,
773 Ok(None) => return false,
774 Err(error) => {
775 warn!(event = "control_plane_presence_configuration_error", %error);
776 return false;
777 }
778 };
779 let hostname = machine_hostname();
780 tokio::spawn(async move {
781 let mut consecutive_failures = 0_u32;
782 loop {
783 let started = Instant::now();
784 let result = crate::asyncrt::select! {
785 result = presence_session(&config, &runtime, &hostname) => result,
786 credential_version = wait_for_credential_rotation(runtime.credential_version) => {
787 restart_for_credential_rotation(runtime.credential_version, credential_version);
788 }
789 };
790 if started.elapsed() >= Duration::from_secs(30) {
791 consecutive_failures = 0;
792 }
793 match result {
794 Ok(()) => {}
795 Err(error) if consecutive_failures == 0 => {
796 report_managed_runtime_state(
797 if error.is::<ManagedControlCredentialRevoked>() {
798 ManagedRuntimeState::CredentialRevoked
799 } else {
800 ManagedRuntimeState::ControlPlaneUnavailable
801 },
802 );
803 info!(
804 event = "control_plane_presence_unavailable",
805 %error,
806 "Managed Control Plane presence unavailable; bucket-backed serving continues"
807 );
808 }
809 Err(_) => {}
810 }
811 consecutive_failures = consecutive_failures.saturating_add(1);
812 let exponent = consecutive_failures.saturating_sub(1).min(5);
813 let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60);
814 let jitter_ms = (rand::random::<u16>() as u64) % 1000;
815 crate::asyncrt::select! {
816 _ = tokio::time::sleep(Duration::from_millis(seconds * 1000 + jitter_ms)) => {}
817 credential_version = wait_for_credential_rotation(runtime.credential_version) => {
818 restart_for_credential_rotation(runtime.credential_version, credential_version);
819 }
820 }
821 }
822 });
823 true
824}
825
826fn restart_for_credential_rotation(previous_version: u64, credential_version: u64) -> ! {
827 info!(
828 event = "control_plane_restart_for_credentials",
829 previous_credential_version = previous_version,
830 credential_version,
831 "managed credential changed; restarting celld to rebuild every credentialed adapter"
832 );
833 restart_with_rotated_credentials()
834}
835
836/// Watch the durable installation record for the lifetime of the advisory
837/// presence agent. `celld credentials refresh` persists the replacement before
838/// acknowledging its handoff; seeing that version is therefore enough to
839/// rebuild the complete adapter graph. Replacing only one S3 client here would
840/// leave the lease pool, replication, explorer, or deploy agent on revoked
841/// credentials.
842async fn wait_for_credential_rotation(current_version: u64) -> u64 {
843 let mut tick = tokio::time::interval(Duration::from_secs(1));
844 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
845 let mut unavailable = false;
846 loop {
847 tick.tick().await;
848 match connected_config() {
849 Ok(Some(config)) => {
850 if unavailable {
851 info!(
852 event = "control_plane_credential_watch_recovered",
853 "managed installation record is readable again"
854 );
855 unavailable = false;
856 }
857 if config.credential_version != current_version {
858 return config.credential_version;
859 }
860 }
861 Ok(None) => {
862 if !unavailable {
863 warn!(
864 event = "control_plane_credential_watch_unavailable",
865 reason = "installation_not_connected",
866 "cannot observe managed credential rotation"
867 );
868 unavailable = true;
869 }
870 }
871 Err(error) => {
872 if !unavailable {
873 warn!(
874 event = "control_plane_credential_watch_unavailable",
875 reason = "installation_read_failed",
876 %error,
877 "cannot observe managed credential rotation"
878 );
879 unavailable = true;
880 }
881 }
882 }
883 }
884}
885
886async fn presence_session(
887 config: &CloudConfig,
888 runtime: &PresenceRuntime,
889 hostname: &str,
890) -> anyhow::Result<()> {
891 let (url, headers) = presence_request(
892 config,
893 &runtime.node_session_id,
894 &runtime.advertise,
895 &runtime.listen,
896 hostname,
897 )?;
898 let socket = match crate::ws_client::connect(&url, headers).await {
899 Ok(connection) => connection.socket,
900 Err(crate::ws_client::Error::Declined(declined))
901 if matches!(declined.status.as_u16(), 401 | 403) =>
902 {
903 return Err(ManagedControlCredentialRevoked.into());
904 }
905 Err(error) => {
906 return Err(anyhow!("{error}")).context("connect Managed Control Plane presence");
907 }
908 };
909 report_managed_runtime_state(ManagedRuntimeState::Connected);
910 info!(
911 event = "control_plane_presence_connected",
912 node_session_id = %runtime.node_session_id,
913 advertise = %runtime.advertise,
914 "node session connected to the Managed Control Plane"
915 );
916 let heartbeat_period = Duration::from_millis(
917 crate::env_vars::with_default("CELLD_PRESENCE_HEARTBEAT_MS", 30_000)
918 .expect("validated CELLD_PRESENCE_HEARTBEAT_MS"),
919 );
920 pump_presence(
921 socket,
922 heartbeat_period,
923 move || async move {
924 let snapshot = (runtime.snapshot)()
925 .await
926 .context("celld core stopped before presence snapshot")?;
927 let mut cells = snapshot
928 .cells
929 .iter()
930 .filter(|cell| {
931 !cell.id.is_empty()
932 && cell.id.len() <= MAX_PRESENCE_CELL_ID_BYTES
933 && !cell.id.chars().any(char::is_control)
934 })
935 .map(|cell| {
936 serde_json::json!({
937 "id": cell.id,
938 "epoch": cell.epoch,
939 })
940 })
941 .collect::<Vec<_>>();
942 let cells_truncated =
943 cells.len() < snapshot.cells.len() || cells.len() > MAX_PRESENCE_CELLS;
944 cells.truncate(MAX_PRESENCE_CELLS);
945 let message = serde_json::json!({
946 "serving": snapshot.serving,
947 "owned_cells": snapshot.owned_cells(),
948 "cells": cells,
949 "cells_truncated": cells_truncated,
950 "activity": {
951 "acquired": snapshot.activity.acquired,
952 "proxied": snapshot.activity.proxied,
953 "expired_owner_leases": snapshot.activity.expired_owner_leases,
954 "restored": snapshot.activity.restored,
955 "advanced_epochs": snapshot.activity.advanced_epochs,
956 "handed_off": snapshot.activity.handed_off,
957 "handoff_failed": snapshot.activity.handoff_failed,
958 },
959 });
960 Ok(message.to_string())
961 },
962 move |text| async move {
963 let message = serde_json::from_str::<serde_json::Value>(&text).ok();
964 let message_type = message
965 .as_ref()
966 .and_then(|value| value.get("type"))
967 .and_then(|value| value.as_str())
968 .map(str::to_string);
969 match message_type.as_deref() {
970 Some("explorer_request") => {
971 let response =
972 handle_explorer_request(message.as_ref().unwrap(), runtime).await;
973 return Ok(Some(response.to_string()));
974 }
975 Some("deployment") => {
976 let client = reqwest::Client::builder()
977 .timeout(Duration::from_secs(30))
978 .build()?;
979 if poll_and_apply(&client, config, &runtime.s3)
980 .await?
981 .is_some()
982 {
983 crate::generation::nudge(&runtime.reload);
984 }
985 }
986 Some("deployment_current") => crate::generation::nudge(&runtime.reload),
987 _ => {}
988 }
989 Ok(None)
990 },
991 )
992 .await
993}
994
995/// Run a presence session until the heartbeat or the socket stops it.
996///
997/// The read is never cancelled. `fastwebsockets::read_frame` consumes header
998/// bytes from its buffer and then awaits for the payload, holding what it parsed
999/// in local variables, so dropping that future keeps the buffer advanced and
1000/// loses the header. The next read then treats a payload byte as a frame header
1001/// and the stream never realigns. An earlier version of this session read the
1002/// socket in the same select as the heartbeat timer, so every tick dropped a read
1003/// in progress. Cancelling a read mid-payload fails against that shape.
1004///
1005/// One async block therefore owns each direction, and the socket is split so
1006/// that the heartbeat can write while the reader reads. The select at the end
1007/// drops the direction that did not finish, which is safe because the session is
1008/// over and the caller reconnects with a new socket.
1009///
1010/// The two directions are not independent. Both write to the one socket, so they
1011/// share the writer behind a mutex, and `write_frame` is awaited while that mutex
1012/// is held. A control plane that stops reading therefore blocks the heartbeat and
1013/// the automatic replies of the reader alike. The cancelling `select!` had the
1014/// same head-of-line property, so this is not a regression, but the split shape
1015/// must not be read as two isolated pipes.
1016///
1017/// `heartbeat` returns the message for one tick. `text` handles one text message
1018/// and returns an optional reply. Ping and Close keep the automatic reply of the
1019/// reader, so only Text reaches `text`.
1020#[doc(hidden)]
1021pub async fn pump_presence<S, H, HFut, T, TFut>(
1022 socket: fastwebsockets::WebSocket<S>,
1023 heartbeat_period: Duration,
1024 mut heartbeat: H,
1025 mut text: T,
1026) -> anyhow::Result<()>
1027where
1028 S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
1029 H: FnMut() -> HFut,
1030 HFut: Future<Output = anyhow::Result<String>>,
1031 T: FnMut(String) -> TFut,
1032 TFut: Future<Output = anyhow::Result<Option<String>>>,
1033{
1034 use fastwebsockets::{FragmentCollectorRead, Payload};
1035
1036 let (reader, writer) = socket.split(tokio::io::split);
1037 let mut reader = FragmentCollectorRead::new(reader);
1038 let writer = Arc::new(tokio::sync::Mutex::new(writer));
1039
1040 let mut ticker = tokio::time::interval(heartbeat_period);
1041 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1042
1043 let beat_writer = writer.clone();
1044 let beat = async {
1045 loop {
1046 ticker.tick().await;
1047 let message = heartbeat().await?;
1048 beat_writer
1049 .lock()
1050 .await
1051 .write_frame(Frame::text(message.into_bytes().into()))
1052 .await?;
1053 }
1054 };
1055
1056 let obligated_writer = writer.clone();
1057 let mut obligated = move |frame: Frame<'_>| {
1058 let writer = obligated_writer.clone();
1059 // The reply borrows the reader's buffer, and the write outlives the
1060 // callback, so the payload is copied out. The reader builds a pong or a
1061 // close echo unmasked, exactly as the unsplit collector did.
1062 let reply = Frame::new(
1063 frame.fin,
1064 frame.opcode,
1065 None,
1066 Payload::Owned(frame.payload.to_vec()),
1067 );
1068 async move { writer.lock().await.write_frame(reply).await }
1069 };
1070 let read = async {
1071 loop {
1072 let frame = reader
1073 .read_frame(&mut obligated)
1074 .await
1075 .map_err(|error| anyhow!("{error}"))
1076 .context("read Managed Control Plane presence")?;
1077 match frame.opcode {
1078 OpCode::Text => {
1079 let message = String::from_utf8_lossy(&frame.payload).into_owned();
1080 if let Some(reply) = text(message).await? {
1081 writer
1082 .lock()
1083 .await
1084 .write_frame(Frame::text(reply.into_bytes().into()))
1085 .await?;
1086 }
1087 }
1088 OpCode::Close => return Err(anyhow!("Managed Control Plane closed presence")),
1089 _ => {}
1090 }
1091 }
1092 };
1093
1094 let mut beat = std::pin::pin!(beat);
1095 let mut read = std::pin::pin!(read);
1096 crate::asyncrt::select! {
1097 result = &mut beat => result,
1098 result = &mut read => result,
1099 }
1100}
1101
1102/// How long a read-only exploration can spend in object storage.
1103///
1104/// A person waits for this answer in the Managed Control Plane, and the
1105/// presence read loop runs the handler inline, so an exploration that never
1106/// finishes holds every later presence message behind it. The bounded replica
1107/// retry policy already keeps an ordinary failure well under this, therefore
1108/// reaching this deadline means the store stopped answering rather than
1109/// answering with an error.
1110const EXPLORER_STORAGE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
1111
1112async fn handle_explorer_request(
1113 message: &serde_json::Value,
1114 runtime: &PresenceRuntime,
1115) -> serde_json::Value {
1116 let request_id = message
1117 .get("request_id")
1118 .and_then(|value| value.as_str())
1119 .filter(|value| {
1120 !value.is_empty()
1121 && value.len() <= 64
1122 && value
1123 .bytes()
1124 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
1125 })
1126 .unwrap_or("");
1127 let operation = message.get("operation").and_then(|value| value.as_str());
1128 let result = match operation {
1129 Some("list_cells") => {
1130 let cursor = match message.get("cursor") {
1131 None | Some(serde_json::Value::Null) => None,
1132 Some(serde_json::Value::String(cursor)) if cursor.len() <= 2_048 => {
1133 Some(cursor.as_str())
1134 }
1135 _ => return explorer_error(request_id, "invalid_request"),
1136 };
1137 match tokio::time::timeout(
1138 EXPLORER_STORAGE_DEADLINE,
1139 list_durable_cells(&runtime.s3, cursor),
1140 )
1141 .await
1142 {
1143 Ok(result) => result,
1144 Err(_) => {
1145 warn!(
1146 event = "control_plane_explorer_deadline",
1147 request_id,
1148 operation = "list_cells",
1149 "read-only exploration passed its storage deadline"
1150 );
1151 return explorer_error(request_id, "inspection_timed_out");
1152 }
1153 }
1154 }
1155 Some("inspect_cell") => {
1156 let Some(cell) = message
1157 .get("cell_id")
1158 .and_then(|value| value.as_str())
1159 // The engine's storage fence, the same one the listing
1160 // applies. An inbound id is spliced into a bucket key, so
1161 // the charset that decides what a node could have written
1162 // also decides what this can ask for.
1163 .filter(|cell| celld_logic::cell::valid_cell_scope(cell))
1164 else {
1165 return explorer_error(request_id, "invalid_request");
1166 };
1167 let table = match message.get("table") {
1168 None | Some(serde_json::Value::Null) => None,
1169 Some(serde_json::Value::String(table))
1170 if !table.is_empty() && table.len() <= 200 =>
1171 {
1172 Some(table.clone())
1173 }
1174 _ => return explorer_error(request_id, "invalid_request"),
1175 };
1176 let Some(replication) = runtime.replication.clone() else {
1177 return explorer_error(request_id, "snapshot_not_found");
1178 };
1179 let Some(snapshot) = (runtime.snapshot)().await else {
1180 return explorer_error(request_id, "node_transport_unavailable");
1181 };
1182 let active_epoch = snapshot
1183 .cells
1184 .iter()
1185 .find(|candidate| candidate.id == cell)
1186 .map(|candidate| candidate.epoch);
1187 if let Some(epoch) = active_epoch {
1188 let cell = cell.to_string();
1189 match tokio::task::spawn_blocking(move || {
1190 let Some(snapshot) = replication.snapshot_active(&cell, epoch)? else {
1191 return Ok(None);
1192 };
1193 inspect_snapshot(snapshot, &cell, table.as_deref(), "active").map(Some)
1194 })
1195 .await
1196 {
1197 Ok(Ok(Some(result))) => Ok(result),
1198 Ok(Ok(None)) => {
1199 return explorer_error(request_id, "active_snapshot_unavailable");
1200 }
1201 Ok(Err(error)) => Err(error.context("inspect active cell snapshot")),
1202 Err(error) => Err(anyhow!("active inspection task failed: {error}")),
1203 }
1204 } else {
1205 let restored = match tokio::time::timeout(
1206 EXPLORER_STORAGE_DEADLINE,
1207 replication.restore_snapshot(cell),
1208 )
1209 .await
1210 {
1211 Ok(result) => result,
1212 Err(_) => {
1213 warn!(
1214 event = "control_plane_explorer_deadline",
1215 request_id,
1216 operation = "inspect_cell",
1217 cell,
1218 "read-only exploration passed its storage deadline"
1219 );
1220 return explorer_error(request_id, "inspection_timed_out");
1221 }
1222 };
1223 match restored {
1224 Ok(Some(snapshot)) => {
1225 let cell = cell.to_string();
1226 match tokio::task::spawn_blocking(move || {
1227 inspect_snapshot(snapshot, &cell, table.as_deref(), "replicated")
1228 })
1229 .await
1230 {
1231 Ok(result) => result,
1232 Err(error) => Err(anyhow!("inspection task failed: {error}")),
1233 }
1234 }
1235 Ok(None) => return explorer_error(request_id, "snapshot_not_found"),
1236 Err(error) => Err(error.context("restore replicated snapshot")),
1237 }
1238 }
1239 }
1240 _ => return explorer_error(request_id, "invalid_request"),
1241 };
1242 match result {
1243 Ok(result) => serde_json::json!({
1244 "type": "explorer_response",
1245 "request_id": request_id,
1246 "ok": true,
1247 "result": result,
1248 }),
1249 Err(error) => {
1250 let stable_error = if error
1251 .chain()
1252 .any(|cause| cause.to_string() == "table_not_found")
1253 {
1254 "table_not_found"
1255 } else if error
1256 .chain()
1257 .any(|cause| cause.to_string() == "table_not_previewable")
1258 {
1259 "table_not_previewable"
1260 } else {
1261 "inspection_failed"
1262 };
1263 warn!(
1264 event = "control_plane_explorer_request_failed",
1265 request_id,
1266 %error,
1267 "read-only cell inspection failed"
1268 );
1269 explorer_error(request_id, stable_error)
1270 }
1271 }
1272}
1273
1274fn explorer_error(request_id: &str, error: &str) -> serde_json::Value {
1275 serde_json::json!({
1276 "type": "explorer_response",
1277 "request_id": request_id,
1278 "ok": false,
1279 "error": error,
1280 })
1281}
1282
1283async fn list_durable_cells(
1284 bucket: &Bucket,
1285 cursor: Option<&str>,
1286) -> anyhow::Result<serde_json::Value> {
1287 // Paging is client-side over the full delimiter listing, bounded by the
1288 // fleet's cell count. `Bucket::common_prefixes_page` would bound the
1289 // request too, but the explorer's cursor is a sorted position and the
1290 // store lists in key order, which are not the same sequence.
1291 let mut cells = bucket
1292 .common_prefixes("cells/")
1293 .await?
1294 .into_iter()
1295 .filter_map(|prefix| prefix.strip_prefix("cells/").map(str::to_string))
1296 // The same fence `celld cell list` applies: the engine's storage
1297 // charset decides what a celld node could have written. A second
1298 // opinion here would show foreign bucket content as a cell in one
1299 // surface and hide it in the other.
1300 .filter(|cell| celld_logic::cell::valid_cell_scope(cell))
1301 .collect::<Vec<_>>();
1302 cells.sort();
1303 if let Some(cursor) = cursor {
1304 cells.retain(|cell| cell.as_str() > cursor);
1305 }
1306 let mut next_cursor = None;
1307 if cells.len() > MAX_EXPLORER_CELL_PAGE {
1308 cells.truncate(MAX_EXPLORER_CELL_PAGE);
1309 next_cursor = cells.last().cloned();
1310 }
1311 Ok(serde_json::json!({
1312 "cells": cells,
1313 "next_cursor": next_cursor,
1314 }))
1315}
1316
1317fn inspect_snapshot(
1318 snapshot: crate::replication::RestoredSnapshot,
1319 cell: &str,
1320 selected_table: Option<&str>,
1321 source: &str,
1322) -> anyhow::Result<serde_json::Value> {
1323 let connection = Connection::open_with_flags(
1324 snapshot.path(),
1325 OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
1326 )?;
1327 let mut schema = connection.prepare(
1328 "SELECT name, type, sql
1329 FROM sqlite_schema
1330 WHERE type IN ('table', 'view')
1331 AND name NOT LIKE 'sqlite_%'
1332 ORDER BY name
1333 LIMIT ?1",
1334 )?;
1335 let mut rows = schema.query([i64::try_from(MAX_EXPLORER_TABLES + 1)?])?;
1336 let mut tables = Vec::new();
1337 let mut schema_bytes = 0_usize;
1338 let mut tables_truncated = false;
1339 while let Some(row) = rows.next()? {
1340 if tables.len() >= MAX_EXPLORER_TABLES {
1341 tables_truncated = true;
1342 break;
1343 }
1344 let name: String = row.get(0)?;
1345 let kind: String = row.get(1)?;
1346 let sql: Option<String> = row.get(2)?;
1347 let entry = serde_json::json!({
1348 "name": name,
1349 "kind": kind,
1350 "sql": sql.map(|sql| truncate_utf8(&sql, 4 * 1024).0),
1351 });
1352 let entry_bytes = serde_json::to_vec(&entry)?.len();
1353 if schema_bytes + entry_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 {
1354 tables_truncated = true;
1355 break;
1356 }
1357 schema_bytes += entry_bytes;
1358 tables.push(entry);
1359 }
1360 drop(rows);
1361 drop(schema);
1362 let preview = match selected_table {
1363 Some(table) => Some(preview_table(&connection, table)?),
1364 None => None,
1365 };
1366 Ok(serde_json::json!({
1367 "cell_id": cell,
1368 "epoch": snapshot.epoch,
1369 "source": source,
1370 "tables": tables,
1371 "tables_truncated": tables_truncated,
1372 "preview": preview,
1373 }))
1374}
1375
1376fn preview_table(connection: &Connection, table: &str) -> anyhow::Result<serde_json::Value> {
1377 let kind = connection
1378 .query_row(
1379 "SELECT type FROM sqlite_schema WHERE name = ?1 AND type IN ('table', 'view')",
1380 [table],
1381 |row| row.get::<_, String>(0),
1382 )
1383 .optional()?
1384 .context("table_not_found")?;
1385 if kind != "table" {
1386 anyhow::bail!("table_not_previewable");
1387 }
1388 let quoted = table.replace('"', "\"\"");
1389 let mut statement = connection.prepare(&format!(
1390 "SELECT * FROM \"{quoted}\" LIMIT {}",
1391 MAX_EXPLORER_ROWS + 1,
1392 ))?;
1393 let columns = statement
1394 .column_names()
1395 .iter()
1396 .take(MAX_EXPLORER_COLUMNS)
1397 .map(|name| truncate_utf8(name, 200).0)
1398 .collect::<Vec<_>>();
1399 let column_count = columns.len();
1400 let all_column_count = statement.column_count();
1401 let mut query = statement.query([])?;
1402 let mut rows = Vec::new();
1403 let mut response_bytes = 0_usize;
1404 let mut truncated = all_column_count > MAX_EXPLORER_COLUMNS;
1405 while let Some(row) = query.next()? {
1406 if rows.len() >= MAX_EXPLORER_ROWS {
1407 truncated = true;
1408 break;
1409 }
1410 let mut values = Vec::with_capacity(column_count);
1411 for index in 0..column_count {
1412 values.push(explorer_value(row.get_ref(index)?));
1413 }
1414 let row_bytes = serde_json::to_vec(&values)?.len();
1415 if response_bytes + row_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 {
1416 truncated = true;
1417 break;
1418 }
1419 response_bytes += row_bytes;
1420 rows.push(values);
1421 }
1422 Ok(serde_json::json!({
1423 "table": table,
1424 "columns": columns,
1425 "rows": rows,
1426 "truncated": truncated,
1427 }))
1428}
1429
1430fn explorer_value(value: ValueRef<'_>) -> serde_json::Value {
1431 match value {
1432 ValueRef::Null => serde_json::json!({ "type": "null", "value": null }),
1433 ValueRef::Integer(value) => {
1434 serde_json::json!({ "type": "integer", "value": value.to_string() })
1435 }
1436 ValueRef::Real(value) => {
1437 serde_json::json!({ "type": "real", "value": value.to_string() })
1438 }
1439 ValueRef::Text(value) => {
1440 let text = String::from_utf8_lossy(value);
1441 let (text, truncated) = truncate_utf8(&text, MAX_EXPLORER_VALUE_BYTES);
1442 serde_json::json!({
1443 "type": "text",
1444 "value": text,
1445 "bytes": value.len(),
1446 "truncated": truncated,
1447 })
1448 }
1449 ValueRef::Blob(value) => {
1450 let shown = &value[..value.len().min(MAX_EXPLORER_VALUE_BYTES)];
1451 serde_json::json!({
1452 "type": "blob",
1453 "value": hex(shown),
1454 "bytes": value.len(),
1455 "truncated": shown.len() < value.len(),
1456 })
1457 }
1458 }
1459}
1460
1461fn truncate_utf8(value: &str, max_bytes: usize) -> (String, bool) {
1462 if value.len() <= max_bytes {
1463 return (value.to_string(), false);
1464 }
1465 let mut end = max_bytes;
1466 while !value.is_char_boundary(end) {
1467 end -= 1;
1468 }
1469 (value[..end].to_string(), true)
1470}
1471
1472fn hex(value: &[u8]) -> String {
1473 const DIGITS: &[u8; 16] = b"0123456789abcdef";
1474 let mut encoded = String::with_capacity(value.len() * 2);
1475 for byte in value {
1476 encoded.push(DIGITS[(byte >> 4) as usize] as char);
1477 encoded.push(DIGITS[(byte & 0x0f) as usize] as char);
1478 }
1479 encoded
1480}
1481
1482fn presence_request(
1483 config: &CloudConfig,
1484 node_session_id: &str,
1485 advertise: &str,
1486 listen: &str,
1487 hostname: &str,
1488) -> anyhow::Result<(String, HeaderMap)> {
1489 use hyper::header::{HeaderName, HeaderValue, AUTHORIZATION};
1490
1491 let token = config
1492 .installation_token
1493 .as_deref()
1494 .context("managed installation has no token")?;
1495 let mut url = url::Url::parse(&config.control_url)?;
1496 url.set_scheme(if url.scheme() == "https" { "wss" } else { "ws" })
1497 .map_err(|_| anyhow!("invalid Managed Control Plane WebSocket scheme"))?;
1498 url.set_path("/api/agent/presence");
1499 url.query_pairs_mut()
1500 .append_pair("node_session_id", node_session_id)
1501 .append_pair("advertise", advertise)
1502 .append_pair("listen", listen);
1503 let mut headers = HeaderMap::new();
1504 headers.insert(
1505 AUTHORIZATION,
1506 HeaderValue::from_str(&format!("Bearer {token}"))?,
1507 );
1508 headers.insert(
1509 HeaderName::from_static("x-cells-version"),
1510 HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
1511 );
1512 // Deployment features come from the shared list so the advertised
1513 // capabilities can never drift from what apply_deployment accepts.
1514 let capabilities = crate::protocol::SUPPORTED_DEPLOYMENT_FEATURES
1515 .iter()
1516 .copied()
1517 .chain(["sqlite-explorer-v1", "sqlite-explorer-v2"])
1518 .collect::<Vec<_>>()
1519 .join(",");
1520 headers.insert(
1521 HeaderName::from_static("x-cells-capabilities"),
1522 HeaderValue::from_str(&capabilities)?,
1523 );
1524 headers.insert(
1525 HeaderName::from_static("x-cells-hostname"),
1526 HeaderValue::from_str(hostname)?,
1527 );
1528 headers.insert(
1529 HeaderName::from_static("x-cells-os"),
1530 HeaderValue::from_static(std::env::consts::OS),
1531 );
1532 headers.insert(
1533 HeaderName::from_static("x-cells-arch"),
1534 HeaderValue::from_static(std::env::consts::ARCH),
1535 );
1536 Ok((url.into(), headers))
1537}
1538
1539pub fn start_deploy_agent(bucket: Bucket, reload: crate::generation::ReloadSender) -> bool {
1540 let config = match connected_config() {
1541 Ok(Some(config)) => config,
1542 Ok(None) => return false,
1543 Err(error) => {
1544 warn!(event = "control_plane_agent_configuration_error", %error);
1545 return false;
1546 }
1547 };
1548 tokio::spawn(async move {
1549 let client = match reqwest::Client::builder()
1550 .timeout(Duration::from_secs(30))
1551 .build()
1552 {
1553 Ok(client) => client,
1554 Err(error) => {
1555 warn!(event = "control_plane_agent_client_error", %error);
1556 return;
1557 }
1558 };
1559 let mut consecutive_failures = 0_u32;
1560 loop {
1561 let mut delay = Duration::from_secs(60);
1562 match poll_and_apply(&client, &config, &bucket).await {
1563 Ok(Some(applied)) => {
1564 if consecutive_failures > 0 {
1565 info!(
1566 event = "control_plane_agent_reconnected",
1567 failures = consecutive_failures,
1568 "Managed Control Plane connection restored"
1569 );
1570 }
1571 consecutive_failures = 0;
1572 info!(
1573 event = "control_plane_deployment_applied",
1574 deployment_id = %applied.id,
1575 script_name = %applied.script_name,
1576 "deployment applied to the fleet bucket; adopting it"
1577 );
1578 crate::generation::nudge(&reload);
1579 }
1580 Ok(None) => {
1581 if consecutive_failures > 0 {
1582 info!(
1583 event = "control_plane_agent_reconnected",
1584 failures = consecutive_failures,
1585 "Managed Control Plane connection restored"
1586 );
1587 }
1588 consecutive_failures = 0;
1589 }
1590 Err(error) => {
1591 if error.is::<ManagedControlCredentialRevoked>() {
1592 report_managed_runtime_state(ManagedRuntimeState::CredentialRevoked);
1593 }
1594 consecutive_failures = consecutive_failures.saturating_add(1);
1595 if consecutive_failures == 1 {
1596 info!(
1597 event = "control_plane_agent_unavailable",
1598 %error,
1599 "Managed Control Plane unavailable; bucket-backed serving continues"
1600 );
1601 }
1602 let exponent = consecutive_failures.saturating_sub(1).min(5);
1603 let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60);
1604 let jitter_ms = (rand::random::<u16>() as u64) % 1000;
1605 delay = Duration::from_millis(seconds * 1000 + jitter_ms);
1606 }
1607 }
1608 tokio::time::sleep(delay).await;
1609 }
1610 });
1611 true
1612}
1613
1614pub async fn wait_for_initial_deployment(bucket: &Bucket) -> anyhow::Result<()> {
1615 let config = connected_config()?.context("managed installation is not connected")?;
1616 let client = reqwest::Client::builder()
1617 .timeout(Duration::from_secs(30))
1618 .build()?;
1619 note!("Waiting for the first Managed Control Plane deployment...");
1620 note!(
1621 "Deploy from {}/control; this process will start automatically.",
1622 config.control_url.trim_end_matches('/')
1623 );
1624 loop {
1625 if deployment_exists(bucket).await? {
1626 return Ok(());
1627 }
1628 if poll_and_apply(&client, &config, bucket).await?.is_some() {
1629 return Ok(());
1630 }
1631 tokio::time::sleep(Duration::from_secs(2)).await;
1632 }
1633}
1634
1635async fn deployment_exists(bucket: &Bucket) -> anyhow::Result<bool> {
1636 let objects = bucket
1637 .list("deploy/")
1638 .await
1639 .context("discover managed deployment")?;
1640 Ok(objects
1641 .iter()
1642 .map(|object| object.location.as_ref())
1643 .any(|key| {
1644 key == "deploy/current.json"
1645 || key
1646 .strip_prefix("deploy/")
1647 .is_some_and(is_named_current_pointer)
1648 }))
1649}
1650
1651fn is_named_current_pointer(key: &str) -> bool {
1652 let mut parts = key.split('/');
1653 matches!(
1654 (parts.next(), parts.next(), parts.next()),
1655 (Some(_), Some("current.json"), None)
1656 )
1657}
1658
1659fn connected_config() -> anyhow::Result<Option<CloudConfig>> {
1660 let path = config_path()?;
1661 if !path.exists() {
1662 return Ok(None);
1663 }
1664 let contents =
1665 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1666 let config: CloudConfig =
1667 serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
1668 if config.installation_token.is_some() {
1669 Ok(Some(config))
1670 } else {
1671 Ok(None)
1672 }
1673}
1674
1675async fn poll_and_apply(
1676 client: &reqwest::Client,
1677 config: &CloudConfig,
1678 bucket: &Bucket,
1679) -> anyhow::Result<Option<AppliedDeployment>> {
1680 let token = config
1681 .installation_token
1682 .as_deref()
1683 .context("cloud config has no instance token")?;
1684 let response = client
1685 .post(format!("{}/api/agent/commands/next", config.control_url))
1686 .bearer_auth(token)
1687 .json(&serde_json::json!({}))
1688 .send()
1689 .await
1690 .context("poll deployment command")?;
1691 if response.status() == reqwest::StatusCode::NO_CONTENT {
1692 return Ok(None);
1693 }
1694 if matches!(response.status().as_u16(), 401 | 403) {
1695 return Err(ManagedControlCredentialRevoked.into());
1696 }
1697 if !response.status().is_success() {
1698 let status = response.status();
1699 let body = response.text().await.unwrap_or_default();
1700 return Err(anyhow!("deployment poll returned {status}: {body}"));
1701 }
1702 let envelope: AgentCommandEnvelope =
1703 response.json().await.context("decode deployment command")?;
1704 let command = envelope.command;
1705 if command.kind != "deploy" {
1706 return Err(anyhow!(
1707 "unsupported control-plane command: {}",
1708 command.kind
1709 ));
1710 }
1711
1712 let result = apply_deployment(client, token, bucket, &command.deployment).await;
1713 let failure = result.as_ref().err().map(|error| format!("{error:#}"));
1714 let completion = client
1715 .post(format!(
1716 "{}/api/agent/commands/{}/complete",
1717 config.control_url, command.id
1718 ))
1719 .bearer_auth(token)
1720 .json(&CompleteCommandRequest {
1721 success: result.is_ok(),
1722 error: failure.as_deref(),
1723 })
1724 .send()
1725 .await
1726 .context("report deployment completion")?;
1727 if !completion.status().is_success() {
1728 let status = completion.status();
1729 let body = completion.text().await.unwrap_or_default();
1730 return Err(anyhow!("deployment completion returned {status}: {body}"));
1731 }
1732 result?;
1733 Ok(Some(AppliedDeployment {
1734 id: command.id,
1735 script_name: command.deployment.script_name,
1736 }))
1737}
1738
1739#[doc(hidden)]
1740pub async fn apply_deployment(
1741 client: &reqwest::Client,
1742 token: &str,
1743 bucket: &Bucket,
1744 deployment: &AgentDeployment,
1745) -> anyhow::Result<()> {
1746 if deployment.pointer.version != deployment.version
1747 || deployment.manifest.version != deployment.version
1748 || deployment.manifest.script_name != deployment.script_name
1749 {
1750 return Err(anyhow!("control-plane deployment metadata is inconsistent"));
1751 }
1752 validate_managed_module_envelope(deployment)?;
1753 validate_managed_class_migrations(&deployment.manifest)?;
1754 crate::protocol::validate_required_features(&deployment.manifest.required_features)?;
1755 crate::protocol::validate_queue_manifest(&deployment.manifest)?;
1756 // Read the current owner before writing this deployment's immutable
1757 // objects. A competing Queue consumer must refuse the deployment without
1758 // leaving a prefix that looks publishable.
1759 let queue_attachments =
1760 crate::deploy::prepare_queue_attachments(bucket, &deployment.manifest).await?;
1761
1762 let mut asset_files = 0_u32;
1763 let mut asset_bytes = 0_u64;
1764 let mut asset_blobs = 0_usize;
1765 if let Some(reference) = &deployment.manifest.assets {
1766 let assets = deployment
1767 .assets
1768 .as_ref()
1769 .context("asset manifest has no control-plane transport")?;
1770 if reference.index != "assets.json"
1771 || reference.sha256 != assets.sha256
1772 || reference.file_count != assets.file_count
1773 || reference.total_bytes != assets.total_bytes
1774 {
1775 return Err(anyhow!("control-plane asset metadata is inconsistent"));
1776 }
1777 let response = client
1778 .get(&assets.index_download_url)
1779 .bearer_auth(token)
1780 .send()
1781 .await
1782 .context("download asset index")?;
1783 if !response.status().is_success() {
1784 return Err(anyhow!(
1785 "asset index download returned {}",
1786 response.status()
1787 ));
1788 }
1789 let index_bytes = response.bytes().await?;
1790 let index_hash = format!("{:x}", Sha256::digest(&index_bytes));
1791 if index_hash != assets.sha256 {
1792 return Err(anyhow!("asset index checksum mismatch"));
1793 }
1794 let index: AssetIndex =
1795 serde_json::from_slice(&index_bytes).context("decode asset index")?;
1796 if index.schema_version != 1
1797 || index.entries.len() != assets.file_count as usize
1798 || index.entries.values().map(|entry| entry.bytes).sum::<u64>() != assets.total_bytes
1799 {
1800 return Err(anyhow!("asset index counts do not match deployment"));
1801 }
1802
1803 let mut unique = std::collections::BTreeMap::<String, u64>::new();
1804 for (path, entry) in &index.entries {
1805 validate_asset_index_entry(path, &entry.sha256, entry.bytes)?;
1806 if let Some(previous) = unique.insert(entry.sha256.clone(), entry.bytes) {
1807 if previous != entry.bytes {
1808 return Err(anyhow!(
1809 "asset digest has conflicting sizes: {}",
1810 entry.sha256
1811 ));
1812 }
1813 }
1814 }
1815 for (sha256, bytes) in &unique {
1816 let key =
1817 asset_blob_key(sha256).ok_or_else(|| anyhow!("invalid asset digest: {sha256}"))?;
1818 if let Ok(Some((size, meta))) = bucket.head_with_meta(&key, "sha256").await {
1819 if size == *bytes && meta.as_deref() == Some(sha256.as_str()) {
1820 continue;
1821 }
1822 tracing::warn!(
1823 event = "asset_blob_repair_required",
1824 %sha256,
1825 "asset blob exists with an invalid size or checksum metadata"
1826 );
1827 }
1828
1829 let response = client
1830 .get(format!(
1831 "{}/{}",
1832 assets.blob_download_base_url.trim_end_matches('/'),
1833 sha256
1834 ))
1835 .bearer_auth(token)
1836 .send()
1837 .await
1838 .with_context(|| format!("download asset blob {sha256}"))?;
1839 if !response.status().is_success() {
1840 return Err(anyhow!(
1841 "asset blob {sha256} download returned {}",
1842 response.status()
1843 ));
1844 }
1845 let body = response.bytes().await?;
1846 if body.len() as u64 != *bytes {
1847 return Err(anyhow!("asset blob {sha256} size mismatch"));
1848 }
1849 let hash = format!("{:x}", Sha256::digest(&body));
1850 if hash != *sha256 {
1851 return Err(anyhow!("asset blob {sha256} checksum mismatch"));
1852 }
1853 bucket
1854 .put_with_meta(&key, body.to_vec(), &[("sha256", sha256)])
1855 .await?;
1856 }
1857 bucket
1858 .put(
1859 &format!("{}/assets.json", deployment.pointer.prefix),
1860 index_bytes.to_vec(),
1861 )
1862 .await?;
1863 asset_files = assets.file_count;
1864 asset_bytes = assets.total_bytes;
1865 asset_blobs = unique.len();
1866 } else if deployment.assets.is_some() {
1867 return Err(anyhow!(
1868 "control-plane sent asset transport for a manifest without assets"
1869 ));
1870 }
1871
1872 for module in &deployment.modules {
1873 let response = client
1874 .get(&module.download_url)
1875 .bearer_auth(token)
1876 .send()
1877 .await
1878 .with_context(|| format!("download module {}", module.name))?;
1879 if !response.status().is_success() {
1880 return Err(anyhow!(
1881 "module {} download returned {}",
1882 module.name,
1883 response.status()
1884 ));
1885 }
1886 let bytes = response.bytes().await?;
1887 let expected_bytes = deployment
1888 .manifest
1889 .modules
1890 .iter()
1891 .find(|reference| reference.name == module.name)
1892 .expect("managed module envelope validated above")
1893 .bytes;
1894 if bytes.len() != expected_bytes {
1895 return Err(anyhow!("module {} size mismatch", module.name));
1896 }
1897 let hash = format!("{:x}", Sha256::digest(&bytes));
1898 if hash != module.sha256 {
1899 return Err(anyhow!("module {} checksum mismatch", module.name));
1900 }
1901 bucket
1902 .put(
1903 &format!("{}/{}", deployment.pointer.prefix, module.name),
1904 bytes.to_vec(),
1905 )
1906 .await?;
1907 }
1908 bucket
1909 .put(
1910 &format!("{}/manifest.json", deployment.pointer.prefix),
1911 serde_json::to_vec_pretty(&deployment.manifest)?,
1912 )
1913 .await?;
1914 // A producer can run in a different script, so the manifest is not a
1915 // discoverable consumer index. Publish the same fleet-wide attachment as
1916 // `celld deploy`, after its exact deployment prefix is complete.
1917 crate::deploy::publish_queue_attachments(
1918 bucket,
1919 &deployment.manifest,
1920 &deployment.pointer.prefix,
1921 queue_attachments,
1922 )
1923 .await?;
1924 bucket
1925 .put(
1926 &format!("deploy/{}/current.json", deployment.script_name),
1927 serde_json::to_vec_pretty(&deployment.pointer)?,
1928 )
1929 .await?;
1930 // This fleet-wide pointer is the sole application selector. The named
1931 // pointer above remains only for resolving service-binding components and
1932 // for migrating buckets written by older celld releases.
1933 bucket
1934 .put(
1935 "deploy/current.json",
1936 serde_json::to_vec_pretty(&deployment.pointer)?,
1937 )
1938 .await?;
1939 info!(
1940 event = "control_plane_deployment_applied",
1941 script_name = %deployment.script_name,
1942 version = %deployment.version,
1943 modules = deployment.modules.len(),
1944 asset_files,
1945 asset_bytes,
1946 asset_blobs,
1947 bucket = %bucket.name,
1948 "deployment artifacts written to fleet bucket"
1949 );
1950 Ok(())
1951}
1952
1953fn validate_managed_module_envelope(deployment: &AgentDeployment) -> anyhow::Result<()> {
1954 let expected_prefix = format!("deploy/{}/{}", deployment.script_name, deployment.version);
1955 if deployment.pointer.script_name.as_deref() != Some(deployment.script_name.as_str())
1956 || deployment.pointer.prefix != expected_prefix
1957 || deployment.pointer.rollout.percent != 100
1958 {
1959 return Err(anyhow!(
1960 "control-plane deployment pointer is inconsistent with its identity"
1961 ));
1962 }
1963 let expected_schema = if deployment.manifest.assets.is_some() {
1964 2
1965 } else {
1966 1
1967 };
1968 if deployment.manifest.schema_version != expected_schema {
1969 return Err(anyhow!(
1970 "control-plane manifest schema does not match its features"
1971 ));
1972 }
1973 if deployment.manifest.modules.len() > MAX_MANAGED_MODULES
1974 || deployment.modules.len() > MAX_MANAGED_MODULES
1975 {
1976 return Err(anyhow!("control-plane deployment has too many modules"));
1977 }
1978
1979 let mut manifest_modules = std::collections::BTreeMap::new();
1980 let mut total_bytes = 0_usize;
1981 for module in &deployment.manifest.modules {
1982 if !valid_managed_module_name(&module.name)
1983 || !(valid_lower_hex(&module.sha256, 16) || valid_lower_hex(&module.sha256, 64))
1984 {
1985 return Err(anyhow!(
1986 "control-plane manifest has an invalid module reference: {:?}",
1987 module.name
1988 ));
1989 }
1990 total_bytes = total_bytes
1991 .checked_add(module.bytes)
1992 .filter(|bytes| *bytes <= MAX_MANAGED_MODULE_BYTES)
1993 .ok_or_else(|| anyhow!("control-plane deployment modules are too large"))?;
1994 if manifest_modules
1995 .insert(module.name.as_str(), module)
1996 .is_some()
1997 {
1998 return Err(anyhow!(
1999 "control-plane manifest repeats module {:?}",
2000 module.name
2001 ));
2002 }
2003 }
2004 match deployment.manifest.main_module.as_deref() {
2005 Some(main) if !manifest_modules.contains_key(main) => {
2006 return Err(anyhow!(
2007 "control-plane manifest main module is not in its module list"
2008 ));
2009 }
2010 None if deployment.manifest.assets.is_none() => {
2011 return Err(anyhow!(
2012 "control-plane manifest has neither a main module nor assets"
2013 ));
2014 }
2015 _ => {}
2016 }
2017
2018 let mut transport_modules = std::collections::BTreeMap::new();
2019 for module in &deployment.modules {
2020 if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 64) {
2021 return Err(anyhow!(
2022 "control-plane transport has an invalid module reference: {:?}",
2023 module.name
2024 ));
2025 }
2026 if transport_modules
2027 .insert(module.name.as_str(), module)
2028 .is_some()
2029 {
2030 return Err(anyhow!(
2031 "control-plane transport repeats module {:?}",
2032 module.name
2033 ));
2034 }
2035 }
2036 if manifest_modules.keys().ne(transport_modules.keys()) {
2037 return Err(anyhow!(
2038 "control-plane transport modules do not match the manifest"
2039 ));
2040 }
2041 for (name, manifest) in manifest_modules {
2042 let transport = transport_modules
2043 .get(name)
2044 .expect("module name sets compared above");
2045 if !transport.sha256.starts_with(&manifest.sha256) {
2046 return Err(anyhow!(
2047 "control-plane transport checksum does not match manifest module {name:?}"
2048 ));
2049 }
2050 }
2051 Ok(())
2052}
2053
2054fn valid_managed_module_name(name: &str) -> bool {
2055 !name.is_empty()
2056 && name.len() <= 240
2057 && !name.starts_with('/')
2058 && !name.contains('\\')
2059 && name
2060 .split('/')
2061 .all(|segment| !segment.is_empty() && segment != "." && segment != "..")
2062}
2063
2064fn valid_lower_hex(value: &str, length: usize) -> bool {
2065 value.len() == length
2066 && value
2067 .bytes()
2068 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2069}
2070
2071fn validate_managed_class_migrations(manifest: &Manifest) -> anyhow::Result<()> {
2072 let do_classes = manifest
2073 .do_classes
2074 .iter()
2075 .map(|class| {
2076 if class.is_empty() {
2077 Err(anyhow!(
2078 "managed manifest has an empty Durable Object class"
2079 ))
2080 } else {
2081 Ok(class.as_str())
2082 }
2083 })
2084 .collect::<anyhow::Result<std::collections::BTreeSet<_>>>()?;
2085 let mut declared_sqlite = std::collections::BTreeSet::new();
2086 for class in &manifest.sqlite_classes {
2087 if class.is_empty() {
2088 return Err(anyhow!("managed manifest has an empty SQLite class"));
2089 }
2090 if !do_classes.contains(class.as_str()) {
2091 return Err(anyhow!(
2092 "managed manifest SQLite class {class:?} is not a Durable Object class"
2093 ));
2094 }
2095 if !declared_sqlite.insert(class.as_str()) {
2096 return Err(anyhow!(
2097 "managed manifest declares SQLite class {class:?} more than once"
2098 ));
2099 }
2100 }
2101
2102 let metadata = manifest
2103 .raw_metadata
2104 .as_object()
2105 .context("managed manifest raw_metadata must be an object")?;
2106 let Some(migrations) = metadata.get("migrations") else {
2107 if declared_sqlite.is_empty() {
2108 return Ok(());
2109 }
2110 return Err(anyhow!(
2111 "managed manifest SQLite classes do not match its migration metadata"
2112 ));
2113 };
2114 let migrations = migrations
2115 .as_object()
2116 .context("managed manifest migrations must be an object")?;
2117 let unsupported = migrations
2118 .keys()
2119 .filter(|key| !matches!(key.as_str(), "old_tag" | "new_tag" | "steps"))
2120 .cloned()
2121 .collect::<Vec<_>>();
2122 if !unsupported.is_empty() {
2123 return Err(anyhow!(
2124 "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment",
2125 unsupported.join(", ")
2126 ));
2127 }
2128 for tag in ["old_tag", "new_tag"] {
2129 if let Some(value) = migrations.get(tag) {
2130 if !value.is_null() && value.as_str().is_none_or(str::is_empty) {
2131 return Err(anyhow!(
2132 "managed manifest migrations.{tag} must be null or a non-empty string"
2133 ));
2134 }
2135 }
2136 }
2137 let steps = migrations
2138 .get("steps")
2139 .and_then(serde_json::Value::as_array)
2140 .context("managed manifest migrations.steps must be an array")?;
2141 let mut migrated_sqlite = std::collections::BTreeSet::new();
2142 for (index, step) in steps.iter().enumerate() {
2143 let step = step.as_object().with_context(|| {
2144 format!("managed manifest migrations.steps[{index}] must be an object")
2145 })?;
2146 let unsupported = step
2147 .keys()
2148 .filter(|key| key.as_str() != "new_sqlite_classes")
2149 .cloned()
2150 .collect::<Vec<_>>();
2151 if !unsupported.is_empty() {
2152 return Err(anyhow!(
2153 "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment",
2154 unsupported.join(", ")
2155 ));
2156 }
2157 let classes = step
2158 .get("new_sqlite_classes")
2159 .and_then(serde_json::Value::as_array)
2160 .with_context(|| {
2161 format!(
2162 "managed manifest migrations.steps[{index}].new_sqlite_classes must be an array"
2163 )
2164 })?;
2165 for (class_index, class) in classes.iter().enumerate() {
2166 let class = class.as_str().filter(|class| !class.is_empty()).with_context(|| {
2167 format!(
2168 "managed manifest migrations.steps[{index}].new_sqlite_classes[{class_index}] must be a non-empty string"
2169 )
2170 })?;
2171 if !migrated_sqlite.insert(class) {
2172 return Err(anyhow!(
2173 "managed migration introduces SQLite class {class:?} more than once"
2174 ));
2175 }
2176 }
2177 }
2178 if migrated_sqlite != declared_sqlite {
2179 return Err(anyhow!(
2180 "managed manifest SQLite classes do not match its migration metadata"
2181 ));
2182 }
2183 Ok(())
2184}
2185
2186fn validate_asset_index_entry(path: &str, sha256: &str, bytes: u64) -> anyhow::Result<()> {
2187 if !path.starts_with('/')
2188 || path.len() > 1024
2189 || path.contains('\\')
2190 || path.contains('\0')
2191 || path
2192 .split('/')
2193 .skip(1)
2194 .any(|segment| segment.is_empty() || segment == "." || segment == "..")
2195 {
2196 return Err(anyhow!("invalid asset path in index: {path:?}"));
2197 }
2198 if asset_blob_key(sha256).is_none() {
2199 return Err(anyhow!("invalid asset digest in index: {sha256:?}"));
2200 }
2201 crate::assets::validate_asset_file_size(path, bytes, crate::env_vars::max_asset_file_bytes()?)
2202}
2203
2204async fn connect(options: ConnectOptions, wait: bool) -> anyhow::Result<()> {
2205 let path = config_path()?;
2206 connect_at_path(path, options, wait).await
2207}
2208
2209async fn connect_at_path(path: PathBuf, options: ConnectOptions, wait: bool) -> anyhow::Result<()> {
2210 let _lock = match try_acquire_enrollment_lock(&path).await? {
2211 Some(lock) => lock,
2212 None => wait_for_shared_enrollment(&path).await?,
2213 };
2214 let mut config = load_or_create_config(&path, &options)?;
2215 let enrollment_byo = match (
2216 config.storage.as_ref(),
2217 config.byo_storage.as_ref(),
2218 options.byo_storage.as_ref(),
2219 ) {
2220 (Some(_), None, Some(_)) => {
2221 return Err(anyhow!(
2222 "this installation is enrolled with managed storage; disconnect before changing storage origin"
2223 ));
2224 }
2225 (None, Some(current), Some(requested)) if current != requested => {
2226 return Err(anyhow!(
2227 "the requested BYO bucket does not match this installation enrollment"
2228 ));
2229 }
2230 (None, Some(current), _) => Some(current.clone()),
2231 (None, None, requested) => requested.cloned(),
2232 (Some(_), None, None) => None,
2233 _ => {
2234 return Err(anyhow!(
2235 "managed installation record contains an invalid storage target"
2236 ));
2237 }
2238 };
2239 if config.installation_token.is_some()
2240 && (config.storage.is_some() || config.byo_storage.is_some())
2241 && !options.force
2242 {
2243 validate_requested_storage(&config, options.byo_storage.as_ref())?;
2244 retry_credential_handoff_ack(path.clone(), config.clone());
2245 info!(
2246 event = "control_plane_already_connected",
2247 installation_id = %config.installation_id,
2248 environment = %config.environment,
2249 control_url = %config.control_url,
2250 "celld is already connected to the Managed Control Plane"
2251 );
2252 return Ok(());
2253 }
2254
2255 config.control_url = normalized_control_url(&options.control_url)?;
2256 config.environment = options.environment.clone();
2257 config.installation_token = None;
2258 config.fleet_id = None;
2259 config.environment_id = None;
2260 config.credential_handoff_id = None;
2261 config.pending_claim = None;
2262 config.storage = None;
2263 config.byo_storage = enrollment_byo;
2264 save_config(&path, &config)?;
2265
2266 let client = reqwest::Client::builder()
2267 .timeout(Duration::from_secs(if wait { 15 } else { 3 }))
2268 .build()?;
2269 let claim_url = format!("{}/api/instances/claims", config.control_url);
2270 let instance_name = instance_name();
2271 let response = client
2272 .post(claim_url)
2273 .json(&CreateClaimRequest {
2274 instance_id: &config.installation_id,
2275 instance_name: &instance_name,
2276 environment: &config.environment,
2277 version: env!("CARGO_PKG_VERSION"),
2278 platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
2279 storage_origin: if config.byo_storage.is_some() {
2280 "byo"
2281 } else {
2282 "managed_r2"
2283 },
2284 bucket: config
2285 .byo_storage
2286 .as_ref()
2287 .map(|storage| storage.bucket.as_str()),
2288 endpoint: config
2289 .byo_storage
2290 .as_ref()
2291 .and_then(|storage| storage.endpoint.as_deref()),
2292 region: config
2293 .byo_storage
2294 .as_ref()
2295 .map(|storage| storage.region.as_str()),
2296 })
2297 .send()
2298 .await
2299 .context("request activation link")?;
2300 if !response.status().is_success() {
2301 let status = response.status();
2302 let body = response.text().await.unwrap_or_default();
2303 return Err(anyhow!("activation endpoint returned {status}: {body}"));
2304 }
2305 let claim: CreateClaimResponse = response.json().await.context("decode activation link")?;
2306 config.pending_claim = Some(PendingClaim {
2307 verification_uri_complete: claim.verification_uri_complete.clone(),
2308 expires_at_ms: current_time_ms().saturating_add(claim.expires_in.saturating_mul(1000)),
2309 });
2310 save_config(&path, &config)?;
2311
2312 info!(
2313 event = "control_plane_claim_pending",
2314 installation_id = %config.installation_id,
2315 environment = %config.environment,
2316 verification_url = %claim.verification_uri_complete,
2317 expires_in_seconds = claim.expires_in,
2318 "authenticate to connect this celld instance"
2319 );
2320 note!(
2321 "\nConnect this celld instance to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n",
2322 claim.verification_uri_complete,
2323 config.environment
2324 );
2325
2326 if wait {
2327 wait_for_approval(client, path, config, claim).await
2328 } else {
2329 tokio::spawn(async move {
2330 if let Err(error) = wait_for_approval(client, path, config, claim).await {
2331 warn!(event = "control_plane_claim_failed", %error);
2332 }
2333 });
2334 Ok(())
2335 }
2336}
2337
2338async fn wait_for_approval(
2339 client: reqwest::Client,
2340 path: PathBuf,
2341 mut config: CloudConfig,
2342 claim: CreateClaimResponse,
2343) -> anyhow::Result<()> {
2344 let deadline = Instant::now() + Duration::from_secs(claim.expires_in);
2345 let poll_url = format!("{}/api/instances/claims/token", config.control_url);
2346 let mut interval = claim.interval.max(1);
2347 while Instant::now() < deadline {
2348 tokio::time::sleep(Duration::from_secs(interval)).await;
2349 let response = client
2350 .post(&poll_url)
2351 .json(&PollClaimRequest {
2352 device_code: &claim.device_code,
2353 })
2354 .send()
2355 .await
2356 .context("poll activation")?;
2357 if response.status() == reqwest::StatusCode::GONE {
2358 return Err(anyhow!("activation link expired"));
2359 }
2360 if !response.status().is_success() {
2361 let status = response.status();
2362 let body = response.text().await.unwrap_or_default();
2363 return Err(anyhow!("activation poll returned {status}: {body}"));
2364 }
2365 let result: PollClaimResponse =
2366 response.json().await.context("decode activation status")?;
2367 if result.status == "pending" {
2368 interval = result.interval.unwrap_or(interval).max(1);
2369 continue;
2370 }
2371 if result.status != "connected" {
2372 return Err(anyhow!("unexpected activation status: {}", result.status));
2373 }
2374 config.installation_token = Some(
2375 result
2376 .instance_token
2377 .context("activation response omitted instance token")?,
2378 );
2379 config.credential_version = result.credential_version.unwrap_or(1);
2380 config.fleet_id = Some(
2381 result
2382 .fleet_id
2383 .context("activation response omitted fleet")?,
2384 );
2385 config.environment_id = Some(
2386 result
2387 .environment_id
2388 .context("activation response omitted environment")?,
2389 );
2390 let bucket = result
2391 .bucket
2392 .context("activation response omitted bucket")?;
2393 let region = result
2394 .region
2395 .context("activation response omitted bucket region")?;
2396 match result.storage_origin.as_str() {
2397 "managed_r2" => {
2398 if config.byo_storage.is_some() {
2399 return Err(anyhow!(
2400 "activation changed the requested BYO bucket to managed storage"
2401 ));
2402 }
2403 config.storage = Some(ManagedStorageConfig {
2404 bucket,
2405 endpoint: result
2406 .endpoint
2407 .context("activation response omitted bucket endpoint")?,
2408 region,
2409 access_key_id: result
2410 .access_key_id
2411 .context("activation response omitted storage access key")?,
2412 secret_access_key: result
2413 .secret_access_key
2414 .context("activation response omitted storage secret key")?,
2415 session_token: result.session_token,
2416 });
2417 config.credential_handoff_id = Some(
2418 result
2419 .credential_handoff_id
2420 .context("activation response omitted credential handoff")?,
2421 );
2422 }
2423 "byo" => {
2424 let storage = ByoStorageConfig {
2425 bucket,
2426 endpoint: result.endpoint,
2427 region,
2428 };
2429 if config.byo_storage.as_ref() != Some(&storage) {
2430 return Err(anyhow!(
2431 "activation returned a different BYO storage target"
2432 ));
2433 }
2434 if result.credential_handoff_id.is_some()
2435 || result.access_key_id.is_some()
2436 || result.secret_access_key.is_some()
2437 || result.session_token.is_some()
2438 {
2439 return Err(anyhow!(
2440 "activation returned managed credentials for a BYO bucket"
2441 ));
2442 }
2443 config.storage = None;
2444 config.byo_storage = Some(storage);
2445 config.credential_handoff_id = None;
2446 }
2447 origin => {
2448 return Err(anyhow!(
2449 "activation returned unknown storage origin: {origin}"
2450 ))
2451 }
2452 }
2453 config.pending_claim = None;
2454 save_config(&path, &config)?;
2455 if let Some(handoff_id) = config.credential_handoff_id.clone() {
2456 match acknowledge_credential_handoff(&client, &config, &handoff_id).await {
2457 Ok(()) => {
2458 config.credential_handoff_id = None;
2459 save_config(&path, &config)?;
2460 }
2461 Err(error) => {
2462 info!(
2463 event = "control_plane_credential_ack_deferred",
2464 %error,
2465 "managed credential is saved; delivery acknowledgement will retry in the background"
2466 );
2467 retry_credential_handoff_ack(path.clone(), config.clone());
2468 }
2469 }
2470 }
2471 info!(
2472 event = "control_plane_connected",
2473 installation_id = %config.installation_id,
2474 fleet_id = %config.fleet_id.as_deref().unwrap_or_default(),
2475 environment_id = %config.environment_id.as_deref().unwrap_or_default(),
2476 environment = %config.environment,
2477 "celld connected to the Managed Control Plane"
2478 );
2479 note!(
2480 "Connected to the Managed Control Plane ({}).\n\
2481 Keep celld running. In your app directory, run `celld token`, apply the \
2482 exports it prints, then run `npx wrangler@4 deploy`.",
2483 config.environment
2484 );
2485 return Ok(());
2486 }
2487 // Make expiry visible so an unattended process cannot keep displaying a
2488 // dead approval URL.
2489 note!(
2490 "\nThe activation link expired before it was approved.\n\
2491 Restart celld to get a new one.\n"
2492 );
2493 Err(anyhow!(
2494 "activation link expired before approval; restart celld for a new link"
2495 ))
2496}
2497
2498fn options_from_env() -> anyhow::Result<ConnectOptions> {
2499 Ok(ConnectOptions {
2500 control_url: std::env::var("CELLD_CONTROL_URL")
2501 .unwrap_or_else(|_| DEFAULT_CONTROL_URL.to_string()),
2502 environment: std::env::var("CELLD_ENV").unwrap_or_else(|_| DEFAULT_ENVIRONMENT.to_string()),
2503 force: false,
2504 byo_storage: None,
2505 })
2506}
2507
2508fn config_path() -> anyhow::Result<PathBuf> {
2509 let base = if let Some(path) = std::env::var_os("CELLD_CONFIG_DIR") {
2510 PathBuf::from(path)
2511 } else if let Some(path) = std::env::var_os("XDG_CONFIG_HOME") {
2512 PathBuf::from(path).join("celld")
2513 } else if let Some(path) = std::env::var_os("HOME") {
2514 PathBuf::from(path).join(".config").join("celld")
2515 } else {
2516 std::env::current_dir()?.join(".celld")
2517 };
2518 Ok(base.join("cloud.json"))
2519}
2520
2521fn load_or_create_config(path: &Path, options: &ConnectOptions) -> anyhow::Result<CloudConfig> {
2522 if path.exists() {
2523 let contents =
2524 std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2525 return serde_json::from_str(&contents)
2526 .with_context(|| format!("decode {}", path.display()));
2527 }
2528 let config = CloudConfig {
2529 version: installation_schema_version(),
2530 installation_id: random_instance_id(),
2531 installation_token: None,
2532 credential_version: initial_credential_version(),
2533 fleet_id: None,
2534 environment_id: None,
2535 control_url: normalized_control_url(&options.control_url)?,
2536 environment: options.environment.clone(),
2537 storage: None,
2538 byo_storage: None,
2539 credential_handoff_id: None,
2540 previous_credential: None,
2541 pending_claim: None,
2542 };
2543 save_config(path, &config)?;
2544 Ok(config)
2545}
2546
2547fn retry_credential_handoff_ack(path: PathBuf, config: CloudConfig) {
2548 let Some(handoff_id) = config.credential_handoff_id.clone() else {
2549 return;
2550 };
2551 tokio::spawn(async move {
2552 let client = match reqwest::Client::builder()
2553 .timeout(Duration::from_secs(5))
2554 .build()
2555 {
2556 Ok(client) => client,
2557 Err(_) => return,
2558 };
2559 if acknowledge_credential_handoff(&client, &config, &handoff_id)
2560 .await
2561 .is_err()
2562 {
2563 return;
2564 }
2565 let Ok(_lock) = acquire_enrollment_lock(&path).await else {
2566 return;
2567 };
2568 let Ok(contents) = std::fs::read_to_string(&path) else {
2569 return;
2570 };
2571 let Ok(mut current) = serde_json::from_str::<CloudConfig>(&contents) else {
2572 return;
2573 };
2574 if current.credential_handoff_id.as_deref() != Some(&handoff_id) {
2575 return;
2576 }
2577 current.credential_handoff_id = None;
2578 current.previous_credential = None;
2579 if let Err(error) = save_config(&path, &current) {
2580 warn!(
2581 event = "control_plane_credential_ack_save_failed",
2582 %error,
2583 "credential delivery was acknowledged but the local marker could not be cleared"
2584 );
2585 }
2586 });
2587}
2588
2589async fn acknowledge_credential_handoff(
2590 client: &reqwest::Client,
2591 config: &CloudConfig,
2592 handoff_id: &str,
2593) -> anyhow::Result<()> {
2594 let token = config
2595 .installation_token
2596 .as_deref()
2597 .context("managed installation has no token")?;
2598 let response = client
2599 .post(format!("{}/api/agent/credentials/ack", config.control_url))
2600 .bearer_auth(token)
2601 .json(&serde_json::json!({ "handoff_id": handoff_id }))
2602 .send()
2603 .await
2604 .context("acknowledge managed credential delivery")?;
2605 if !response.status().is_success() {
2606 return Err(anyhow!(
2607 "credential acknowledgement returned {}",
2608 response.status()
2609 ));
2610 }
2611 Ok(())
2612}
2613
2614fn save_config(path: &Path, config: &CloudConfig) -> anyhow::Result<()> {
2615 let parent = path
2616 .parent()
2617 .context("cloud config has no parent directory")?;
2618 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
2619 let temporary = path.with_extension("json.tmp");
2620 std::fs::write(&temporary, serde_json::to_vec_pretty(config)?)
2621 .with_context(|| format!("write {}", temporary.display()))?;
2622 restrict_permissions(&temporary)?;
2623 std::fs::rename(&temporary, path).with_context(|| format!("replace {}", path.display()))?;
2624 Ok(())
2625}
2626
2627#[cfg(unix)]
2628fn restrict_permissions(path: &Path) -> anyhow::Result<()> {
2629 use std::os::unix::fs::PermissionsExt;
2630 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
2631 Ok(())
2632}
2633
2634#[cfg(not(unix))]
2635fn restrict_permissions(_path: &Path) -> anyhow::Result<()> {
2636 Ok(())
2637}
2638
2639fn random_instance_id() -> String {
2640 let mut bytes = [0_u8; 16];
2641 rand::rngs::OsRng.fill_bytes(&mut bytes);
2642 let suffix = bytes
2643 .iter()
2644 .map(|byte| format!("{byte:02x}"))
2645 .collect::<String>();
2646 format!("inst_{suffix}")
2647}
2648
2649fn installation_schema_version() -> u32 {
2650 1
2651}
2652
2653fn initial_credential_version() -> u64 {
2654 1
2655}
2656
2657fn managed_storage_origin() -> String {
2658 "managed_r2".to_string()
2659}
2660
2661fn validate_requested_storage(
2662 config: &CloudConfig,
2663 requested: Option<&ByoStorageConfig>,
2664) -> anyhow::Result<()> {
2665 match (config.storage.as_ref(), config.byo_storage.as_ref(), requested) {
2666 (Some(_), None, None) | (None, Some(_), None) => Ok(()),
2667 (Some(_), None, Some(_)) => Err(anyhow!(
2668 "this installation is enrolled with managed storage; disconnect before changing storage origin"
2669 )),
2670 (None, Some(current), Some(requested)) if current == requested => Ok(()),
2671 (None, Some(_), Some(_)) => Err(anyhow!(
2672 "the requested BYO bucket does not match this installation enrollment"
2673 )),
2674 _ => Err(anyhow!(
2675 "managed installation record contains an invalid storage target"
2676 )),
2677 }
2678}
2679
2680struct EnrollmentLock {
2681 _file: File,
2682}
2683
2684async fn try_acquire_enrollment_lock(config: &Path) -> anyhow::Result<Option<EnrollmentLock>> {
2685 let (file, lock_path) = open_enrollment_lock(config).await?;
2686 tokio::task::spawn_blocking(move || match file.try_lock() {
2687 Ok(()) => Ok(Some(EnrollmentLock { _file: file })),
2688 Err(std::fs::TryLockError::WouldBlock) => Ok(None),
2689 Err(std::fs::TryLockError::Error(error)) => {
2690 Err(error).with_context(|| format!("lock {}", lock_path.display()))
2691 }
2692 })
2693 .await
2694 .context("join enrollment try-lock task")?
2695}
2696
2697async fn acquire_enrollment_lock(config: &Path) -> anyhow::Result<EnrollmentLock> {
2698 let (file, lock_path) = open_enrollment_lock(config).await?;
2699 tokio::task::spawn_blocking(move || {
2700 file.lock()
2701 .with_context(|| format!("lock {}", lock_path.display()))?;
2702 Ok(EnrollmentLock { _file: file })
2703 })
2704 .await
2705 .context("join enrollment lock task")?
2706}
2707
2708async fn open_enrollment_lock(config: &Path) -> anyhow::Result<(File, PathBuf)> {
2709 let lock_path = config.with_extension("lock");
2710 let parent = lock_path
2711 .parent()
2712 .context("managed installation lock has no parent directory")?
2713 .to_path_buf();
2714 tokio::task::spawn_blocking(move || {
2715 std::fs::create_dir_all(&parent).with_context(|| format!("create {}", parent.display()))?;
2716 let file = File::options()
2717 .read(true)
2718 .write(true)
2719 .create(true)
2720 .truncate(false)
2721 .open(&lock_path)
2722 .with_context(|| format!("open {}", lock_path.display()))?;
2723 Ok((file, lock_path))
2724 })
2725 .await
2726 .context("join enrollment lock open task")?
2727}
2728
2729async fn wait_for_shared_enrollment(path: &Path) -> anyhow::Result<EnrollmentLock> {
2730 loop {
2731 if let Ok(contents) = std::fs::read_to_string(path) {
2732 if let Ok(config) = serde_json::from_str::<CloudConfig>(&contents) {
2733 if config.installation_token.is_some()
2734 && (config.storage.is_some() || config.byo_storage.is_some())
2735 {
2736 return acquire_enrollment_lock(path).await;
2737 }
2738 if let Some(pending) = config.pending_claim {
2739 if pending.expires_at_ms > current_time_ms() {
2740 note!(
2741 "\nConnect this celld installation to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n",
2742 pending.verification_uri_complete, config.environment
2743 );
2744 return acquire_enrollment_lock(path).await;
2745 }
2746 }
2747 }
2748 }
2749 if let Some(lock) = try_acquire_enrollment_lock(path).await? {
2750 return Ok(lock);
2751 }
2752 tokio::time::sleep(Duration::from_millis(100)).await;
2753 }
2754}
2755
2756fn current_time_ms() -> u64 {
2757 std::time::SystemTime::now()
2758 .duration_since(std::time::UNIX_EPOCH)
2759 .unwrap_or_default()
2760 .as_millis() as u64
2761}
2762
2763fn normalized_control_url(value: &str) -> anyhow::Result<String> {
2764 let value = value.trim_end_matches('/');
2765 let url = url::Url::parse(value).context("invalid control plane URL")?;
2766 if url.scheme() != "https"
2767 && !(url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1")))
2768 {
2769 return Err(anyhow!("control plane URL must use HTTPS"));
2770 }
2771 if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
2772 return Err(anyhow!(
2773 "control plane URL must not contain a path, query, or fragment"
2774 ));
2775 }
2776 Ok(value.to_string())
2777}
2778
2779fn validate_environment(value: &str) -> anyhow::Result<()> {
2780 if value.is_empty() || value.len() > 32 {
2781 return Err(anyhow!("environment must be 1–32 characters"));
2782 }
2783 let mut characters = value.chars();
2784 if !characters
2785 .next()
2786 .is_some_and(|character| character.is_ascii_lowercase())
2787 || !characters.all(|character| {
2788 character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
2789 })
2790 {
2791 return Err(anyhow!(
2792 "environment must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens"
2793 ));
2794 }
2795 Ok(())
2796}
2797
2798fn instance_name() -> String {
2799 std::env::var("CELLD_INSTANCE_NAME").unwrap_or_else(|_| machine_hostname())
2800}
2801
2802fn machine_hostname() -> String {
2803 std::env::var("HOSTNAME")
2804 .or_else(|_| std::env::var("COMPUTERNAME"))
2805 .ok()
2806 .or_else(|| {
2807 std::process::Command::new("hostname")
2808 .output()
2809 .ok()
2810 .filter(|output| output.status.success())
2811 .and_then(|output| String::from_utf8(output.stdout).ok())
2812 })
2813 .map(|value| value.trim().to_string())
2814 .filter(|value| {
2815 !value.is_empty()
2816 && value.len() <= 100
2817 && value.is_ascii()
2818 && !value.chars().any(char::is_control)
2819 })
2820 .unwrap_or_else(|| "celld".to_string())
2821}
2822
2823// The presence session read the socket in the same select! as the heartbeat
2824// timer, so every tick dropped a read in progress. The fault is invisible from
2825// outside: the session reconnects and only the messages in the window are gone,
2826// so frame-level observation is required.
2827
2828fn print_connect_help() {
2829 let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text)
2830 .help("Connect this celld installation to the Managed Control Plane.\n\nUSAGE:\n celld connect [--env prod] [--control-url https://celld.dev] [--force]");
2831}
2832
2833fn print_credentials_help() {
2834 let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text)
2835 .help("Refresh a staged Managed Control Plane credential.\n\nUSAGE:\n celld credentials refresh\n\nRunning celld processes sharing this installation automatically reload after the replacement is saved. Unix processes re-exec; other platforms exit 75 for their supervisor.");
2836}
2837
2838fn print_disconnect_help() {
2839 let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text)
2840 .help("Revoke and disconnect this Managed Control Plane installation.\n\nUSAGE:\n celld disconnect --yes\n\nStop every celld process sharing this installation first. Other installations in the fleet are unaffected.");
2841}