systemprompt_sync/
crate_deploy.rs1use std::env;
2use std::io::Write;
3use std::path::PathBuf;
4use std::process::Command;
5
6use crate::api_client::SyncApiClient;
7use crate::error::{SyncError, SyncResult};
8use crate::{SyncConfig, SyncOperationResult};
9
10#[derive(Debug)]
11pub struct CrateDeployService {
12 config: SyncConfig,
13 api_client: SyncApiClient,
14}
15
16impl CrateDeployService {
17 pub const fn new(config: SyncConfig, api_client: SyncApiClient) -> Self {
18 Self { config, api_client }
19 }
20
21 pub async fn deploy(
22 &self,
23 skip_build: bool,
24 custom_tag: Option<String>,
25 ) -> SyncResult<SyncOperationResult> {
26 let project_root = Self::get_project_root()?;
27 let app_id = self.get_app_id().await?;
28
29 let tag = if let Some(t) = custom_tag {
30 t
31 } else {
32 let timestamp = chrono::Utc::now().timestamp();
33 let git_sha = Self::get_git_sha()?;
34 format!("deploy-{timestamp}-{git_sha}")
35 };
36
37 let image = format!("registry.fly.io/{app_id}:{tag}");
38
39 if !skip_build {
40 Self::build_release(&project_root)?;
41 }
42
43 Self::build_docker(&project_root, &image)?;
44
45 let token = self
46 .api_client
47 .get_registry_token(&self.config.tenant_id)
48 .await?;
49 Self::docker_login(&token.registry, &token.username, &token.token)?;
50 Self::docker_push(&image)?;
51
52 let response = self
53 .api_client
54 .deploy(&self.config.tenant_id, &image)
55 .await?;
56
57 Ok(
58 SyncOperationResult::success("crate_deploy", 1).with_details(serde_json::json!({
59 "image": image,
60 "status": response.status,
61 "app_url": response.app_url,
62 })),
63 )
64 }
65
66 fn get_project_root() -> SyncResult<PathBuf> {
67 let current = env::current_dir()?;
68 if current.join("infrastructure").exists() {
69 Ok(current)
70 } else {
71 Err(SyncError::NotProjectRoot)
72 }
73 }
74
75 async fn get_app_id(&self) -> SyncResult<String> {
76 self.api_client
77 .get_tenant_app_id(&self.config.tenant_id)
78 .await
79 }
80
81 fn get_git_sha() -> SyncResult<String> {
82 let output = Command::new("git")
83 .args(["rev-parse", "--short", "HEAD"])
84 .output()?;
85
86 String::from_utf8(output.stdout)
87 .map(|sha| sha.trim().to_string())
88 .map_err(|_| SyncError::GitShaUnavailable)
89 }
90
91 fn build_release(project_root: &PathBuf) -> SyncResult<()> {
92 Self::run_command(
93 "cargo",
94 &[
95 "build",
96 "--release",
97 "--manifest-path=core/Cargo.toml",
98 "--bin",
99 "systemprompt",
100 ],
101 project_root,
102 )
103 }
104
105 fn build_docker(project_root: &PathBuf, image: &str) -> SyncResult<()> {
106 Self::run_command(
107 "docker",
108 &[
109 "build",
110 "-f",
111 "infrastructure/docker/app.Dockerfile",
112 "-t",
113 image,
114 ".",
115 ],
116 project_root,
117 )
118 }
119
120 fn docker_login(registry: &str, username: &str, token: &str) -> SyncResult<()> {
121 let mut command = Command::new("docker");
122 command.args(["login", registry, "-u", username, "--password-stdin"]);
123 command.stdin(std::process::Stdio::piped());
124
125 let mut child = command.spawn()?;
126 if let Some(mut stdin) = child.stdin.take() {
127 stdin.write_all(token.as_bytes())?;
128 }
129
130 let status = child.wait()?;
131 if !status.success() {
132 return Err(SyncError::DockerLoginFailed);
133 }
134 Ok(())
135 }
136
137 fn docker_push(image: &str) -> SyncResult<()> {
138 Self::run_command("docker", &["push", image], &env::current_dir()?)
139 }
140
141 fn run_command(cmd: &str, args: &[&str], dir: &PathBuf) -> SyncResult<()> {
142 let status = Command::new(cmd).args(args).current_dir(dir).status()?;
143
144 if !status.success() {
145 return Err(SyncError::CommandFailed {
146 command: format!("{cmd} {}", args.join(" ")),
147 });
148 }
149 Ok(())
150 }
151}