Diffinery

homeflare/celldpublic

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