1use std::collections::HashMap;
2use std::sync::Arc;
3
4use rootcx_types::{AppManifest, InstalledApp, OsStatus, SchemaVerification};
5use serde_json::Value as JsonValue;
6
7#[cfg(feature = "tauri")]
8pub mod oidc;
9
10#[derive(Debug, thiserror::Error)]
11pub enum ClientError {
12 #[error("HTTP request failed: {0}")]
13 Http(#[from] reqwest::Error),
14
15 #[error("API error ({status}): {message}")]
16 Api { status: u16, message: String },
17}
18
19#[derive(Clone)]
20pub struct RuntimeClient {
21 base_url: String,
22 client: reqwest::Client,
23 token: Arc<std::sync::RwLock<Option<String>>>,
24}
25
26impl RuntimeClient {
27 pub fn new(base_url: &str) -> Self {
28 Self {
29 base_url: base_url.trim_end_matches('/').to_string(),
30 client: reqwest::Client::new(),
31 token: Arc::new(std::sync::RwLock::new(None)),
32 }
33 }
34
35 fn api(&self, path: &str) -> String {
36 format!("{}/api/v1{path}", self.base_url)
37 }
38
39 fn authed(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
40 if let Some(ref t) = *self.token.read().unwrap() { req.bearer_auth(t) } else { req }
41 }
42
43 pub fn set_token(&self, token: Option<String>) {
44 *self.token.write().unwrap() = token;
45 }
46
47 pub fn base_url(&self) -> &str {
48 &self.base_url
49 }
50
51 pub fn token(&self) -> Option<String> {
52 self.token.read().unwrap().clone()
53 }
54
55 pub async fn is_available(&self) -> bool {
56 self.client.get(format!("{}/health", self.base_url)).send().await.is_ok()
57 }
58
59 pub async fn status(&self) -> Result<OsStatus, ClientError> {
60 let resp = self.authed(self.client.get(self.api("/status"))).send().await?;
61 check_response(resp).await?.json().await.map_err(Into::into)
62 }
63
64 pub async fn install_app(&self, manifest: &AppManifest) -> Result<String, ClientError> {
65 let resp = self.authed(self.client.post(self.api("/apps"))).json(manifest).send().await?;
66 extract_message(resp).await
67 }
68
69 pub async fn list_apps(&self) -> Result<Vec<InstalledApp>, ClientError> {
70 let resp = self.authed(self.client.get(self.api("/apps"))).send().await?;
71 check_response(resp).await?.json().await.map_err(Into::into)
72 }
73
74 pub async fn uninstall_app(&self, app_id: &str) -> Result<(), ClientError> {
75 let resp = self.authed(self.client.delete(self.api(&format!("/apps/{app_id}")))).send().await?;
76 check_response(resp).await?;
77 Ok(())
78 }
79
80 pub async fn list_records(&self, app_id: &str, entity: &str) -> Result<Vec<JsonValue>, ClientError> {
81 let resp = self.authed(self.client.get(self.api(&format!("/apps/{app_id}/collections/{entity}")))).send().await?;
82 check_response(resp).await?.json().await.map_err(Into::into)
83 }
84
85 pub async fn create_record(&self, app_id: &str, entity: &str, data: &JsonValue) -> Result<JsonValue, ClientError> {
86 let resp = self
87 .authed(self.client.post(self.api(&format!("/apps/{app_id}/collections/{entity}"))))
88 .json(data)
89 .send()
90 .await?;
91 check_response(resp).await?.json().await.map_err(Into::into)
92 }
93
94 pub async fn bulk_create_records(&self, app_id: &str, entity: &str, data: &[JsonValue]) -> Result<Vec<JsonValue>, ClientError> {
95 let resp = self
96 .authed(self.client.post(self.api(&format!("/apps/{app_id}/collections/{entity}/bulk"))))
97 .json(&data)
98 .send()
99 .await?;
100 check_response(resp).await?.json().await.map_err(Into::into)
101 }
102
103 pub async fn get_record(&self, app_id: &str, entity: &str, id: &str) -> Result<JsonValue, ClientError> {
104 let resp = self
105 .authed(self.client.get(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
106 .send()
107 .await?;
108 check_response(resp).await?.json().await.map_err(Into::into)
109 }
110
111 pub async fn update_record(
112 &self,
113 app_id: &str,
114 entity: &str,
115 id: &str,
116 data: &JsonValue,
117 ) -> Result<JsonValue, ClientError> {
118 let resp = self
119 .authed(self.client.patch(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
120 .json(data)
121 .send()
122 .await?;
123 check_response(resp).await?.json().await.map_err(Into::into)
124 }
125
126 pub async fn delete_record(&self, app_id: &str, entity: &str, id: &str) -> Result<(), ClientError> {
127 let resp = self
128 .authed(self.client.delete(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
129 .send()
130 .await?;
131 check_response(resp).await?;
132 Ok(())
133 }
134
135 pub async fn verify_schema(&self, manifest: &AppManifest) -> Result<SchemaVerification, ClientError> {
136 let resp = self.authed(self.client.post(self.api("/apps/schema/verify"))).json(manifest).send().await?;
137 check_response(resp).await?.json().await.map_err(Into::into)
138 }
139
140 pub async fn deploy_app(&self, app_id: &str, archive: Vec<u8>) -> Result<String, ClientError> {
141 self.upload_archive(&format!("/apps/{app_id}/deploy"), archive).await
142 }
143
144 pub async fn deploy_frontend(&self, app_id: &str, archive: Vec<u8>) -> Result<String, ClientError> {
145 self.upload_archive(&format!("/apps/{app_id}/frontend"), archive).await
146 }
147
148 async fn upload_archive(&self, path: &str, archive: Vec<u8>) -> Result<String, ClientError> {
149 let part = reqwest::multipart::Part::bytes(archive)
150 .mime_str("application/gzip")
151 .map_err(ClientError::Http)?;
152 let form = reqwest::multipart::Form::new().part("archive", part);
153 let resp = self.authed(self.client.post(self.api(path))).multipart(form).send().await?;
154 extract_message(resp).await
155 }
156
157 pub async fn start_worker(&self, app_id: &str) -> Result<String, ClientError> {
158 self.worker_action(app_id, "start").await
159 }
160
161 pub async fn stop_worker(&self, app_id: &str) -> Result<String, ClientError> {
162 self.worker_action(app_id, "stop").await
163 }
164
165 pub async fn worker_status(&self, app_id: &str) -> Result<String, ClientError> {
166 let resp = self.authed(self.client.get(self.api(&format!("/apps/{app_id}/worker/status")))).send().await?;
167 let body: JsonValue = check_response(resp).await?.json().await?;
168 Ok(body["status"].as_str().unwrap_or("unknown").to_string())
169 }
170
171 pub async fn list_integrations(&self) -> Result<Vec<JsonValue>, ClientError> {
172 let resp = self.authed(self.client.get(self.api("/integrations"))).send().await?;
173 check_response(resp).await?.json().await.map_err(Into::into)
174 }
175
176 pub async fn get_forge_config(&self) -> Result<JsonValue, ClientError> {
177 let resp = self.authed(self.client.get(self.api("/config/ai/forge"))).send().await?;
178 check_response(resp).await?.json().await.map_err(Into::into)
179 }
180
181 pub async fn get_platform_env(&self) -> Result<HashMap<String, String>, ClientError> {
182 let resp = self.authed(self.client.get(self.api("/platform/secrets/env"))).send().await?;
183 let body: HashMap<String, String> = check_response(resp).await?.json().await?;
184 Ok(body)
185 }
186
187 pub async fn list_platform_secrets(&self) -> Result<Vec<String>, ClientError> {
188 let resp = self.authed(self.client.get(self.api("/platform/secrets"))).send().await?;
189 check_response(resp).await?.json().await.map_err(Into::into)
190 }
191
192 pub async fn set_platform_secret(&self, key: &str, value: &str) -> Result<(), ClientError> {
193 let body = serde_json::json!({ "key": key, "value": value });
194 let resp = self.authed(self.client.post(self.api("/platform/secrets"))).json(&body).send().await?;
195 check_response(resp).await?;
196 Ok(())
197 }
198
199 pub async fn delete_platform_secret(&self, key: &str) -> Result<(), ClientError> {
200 let resp = self.authed(self.client.delete(self.api(&format!("/platform/secrets/{key}")))).send().await?;
201 check_response(resp).await?;
202 Ok(())
203 }
204
205 async fn worker_action(&self, app_id: &str, action: &str) -> Result<String, ClientError> {
206 let resp = self
207 .authed(self.client.post(self.api(&format!("/apps/{app_id}/worker/{action}"))))
208 .send()
209 .await?;
210 extract_message(resp).await
211 }
212}
213
214async fn extract_message(resp: reqwest::Response) -> Result<String, ClientError> {
215 let body: JsonValue = check_response(resp).await?.json().await?;
216 Ok(body["message"].as_str().unwrap_or("ok").to_string())
217}
218
219async fn check_response(resp: reqwest::Response) -> Result<reqwest::Response, ClientError> {
220 if resp.status().is_success() {
221 return Ok(resp);
222 }
223 let status = resp.status().as_u16();
224 let body: JsonValue = resp.json().await.unwrap_or_default();
225 let message = body["error"].as_str().unwrap_or("unknown error").to_string();
226 Err(ClientError::Api { status, message })
227}