Skip to main content

rootcx_client/
lib.rs

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 token(&self) -> Option<String> {
48        self.token.read().unwrap().clone()
49    }
50
51    pub async fn is_available(&self) -> bool {
52        self.client.get(format!("{}/health", self.base_url)).send().await.is_ok()
53    }
54
55    pub async fn status(&self) -> Result<OsStatus, ClientError> {
56        let resp = self.authed(self.client.get(self.api("/status"))).send().await?;
57        check_response(resp).await?.json().await.map_err(Into::into)
58    }
59
60    pub async fn install_app(&self, manifest: &AppManifest) -> Result<String, ClientError> {
61        let resp = self.authed(self.client.post(self.api("/apps"))).json(manifest).send().await?;
62        extract_message(resp).await
63    }
64
65    pub async fn list_apps(&self) -> Result<Vec<InstalledApp>, ClientError> {
66        let resp = self.authed(self.client.get(self.api("/apps"))).send().await?;
67        check_response(resp).await?.json().await.map_err(Into::into)
68    }
69
70    pub async fn uninstall_app(&self, app_id: &str) -> Result<(), ClientError> {
71        let resp = self.authed(self.client.delete(self.api(&format!("/apps/{app_id}")))).send().await?;
72        check_response(resp).await?;
73        Ok(())
74    }
75
76    pub async fn list_records(&self, app_id: &str, entity: &str) -> Result<Vec<JsonValue>, ClientError> {
77        let resp = self.authed(self.client.get(self.api(&format!("/apps/{app_id}/collections/{entity}")))).send().await?;
78        check_response(resp).await?.json().await.map_err(Into::into)
79    }
80
81    pub async fn create_record(&self, app_id: &str, entity: &str, data: &JsonValue) -> Result<JsonValue, ClientError> {
82        let resp = self
83            .authed(self.client.post(self.api(&format!("/apps/{app_id}/collections/{entity}"))))
84            .json(data)
85            .send()
86            .await?;
87        check_response(resp).await?.json().await.map_err(Into::into)
88    }
89
90    pub async fn bulk_create_records(&self, app_id: &str, entity: &str, data: &[JsonValue]) -> Result<Vec<JsonValue>, ClientError> {
91        let resp = self
92            .authed(self.client.post(self.api(&format!("/apps/{app_id}/collections/{entity}/bulk"))))
93            .json(&data)
94            .send()
95            .await?;
96        check_response(resp).await?.json().await.map_err(Into::into)
97    }
98
99    pub async fn get_record(&self, app_id: &str, entity: &str, id: &str) -> Result<JsonValue, ClientError> {
100        let resp = self
101            .authed(self.client.get(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
102            .send()
103            .await?;
104        check_response(resp).await?.json().await.map_err(Into::into)
105    }
106
107    pub async fn update_record(
108        &self,
109        app_id: &str,
110        entity: &str,
111        id: &str,
112        data: &JsonValue,
113    ) -> Result<JsonValue, ClientError> {
114        let resp = self
115            .authed(self.client.patch(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
116            .json(data)
117            .send()
118            .await?;
119        check_response(resp).await?.json().await.map_err(Into::into)
120    }
121
122    pub async fn delete_record(&self, app_id: &str, entity: &str, id: &str) -> Result<(), ClientError> {
123        let resp = self
124            .authed(self.client.delete(self.api(&format!("/apps/{app_id}/collections/{entity}/{id}"))))
125            .send()
126            .await?;
127        check_response(resp).await?;
128        Ok(())
129    }
130
131    pub async fn verify_schema(&self, manifest: &AppManifest) -> Result<SchemaVerification, ClientError> {
132        let resp = self.authed(self.client.post(self.api("/apps/schema/verify"))).json(manifest).send().await?;
133        check_response(resp).await?.json().await.map_err(Into::into)
134    }
135
136    pub async fn deploy_app(&self, app_id: &str, archive: Vec<u8>) -> Result<String, ClientError> {
137        self.upload_archive(&format!("/apps/{app_id}/deploy"), archive).await
138    }
139
140    pub async fn deploy_frontend(&self, app_id: &str, archive: Vec<u8>) -> Result<String, ClientError> {
141        self.upload_archive(&format!("/apps/{app_id}/frontend"), archive).await
142    }
143
144    async fn upload_archive(&self, path: &str, archive: Vec<u8>) -> Result<String, ClientError> {
145        let part = reqwest::multipart::Part::bytes(archive)
146            .mime_str("application/gzip")
147            .map_err(ClientError::Http)?;
148        let form = reqwest::multipart::Form::new().part("archive", part);
149        let resp = self.authed(self.client.post(self.api(path))).multipart(form).send().await?;
150        extract_message(resp).await
151    }
152
153    pub async fn start_worker(&self, app_id: &str) -> Result<String, ClientError> {
154        self.worker_action(app_id, "start").await
155    }
156
157    pub async fn stop_worker(&self, app_id: &str) -> Result<String, ClientError> {
158        self.worker_action(app_id, "stop").await
159    }
160
161    pub async fn worker_status(&self, app_id: &str) -> Result<String, ClientError> {
162        let resp = self.authed(self.client.get(self.api(&format!("/apps/{app_id}/worker/status")))).send().await?;
163        let body: JsonValue = check_response(resp).await?.json().await?;
164        Ok(body["status"].as_str().unwrap_or("unknown").to_string())
165    }
166
167    pub async fn list_integrations(&self) -> Result<Vec<JsonValue>, ClientError> {
168        let resp = self.authed(self.client.get(self.api("/integrations"))).send().await?;
169        check_response(resp).await?.json().await.map_err(Into::into)
170    }
171
172    pub async fn get_forge_config(&self) -> Result<JsonValue, ClientError> {
173        let resp = self.authed(self.client.get(self.api("/config/ai/forge"))).send().await?;
174        check_response(resp).await?.json().await.map_err(Into::into)
175    }
176
177    pub async fn get_platform_env(&self) -> Result<HashMap<String, String>, ClientError> {
178        let resp = self.authed(self.client.get(self.api("/platform/secrets/env"))).send().await?;
179        let body: HashMap<String, String> = check_response(resp).await?.json().await?;
180        Ok(body)
181    }
182
183    pub async fn list_platform_secrets(&self) -> Result<Vec<String>, ClientError> {
184        let resp = self.authed(self.client.get(self.api("/platform/secrets"))).send().await?;
185        check_response(resp).await?.json().await.map_err(Into::into)
186    }
187
188    pub async fn set_platform_secret(&self, key: &str, value: &str) -> Result<(), ClientError> {
189        let body = serde_json::json!({ "key": key, "value": value });
190        let resp = self.authed(self.client.post(self.api("/platform/secrets"))).json(&body).send().await?;
191        check_response(resp).await?;
192        Ok(())
193    }
194
195    pub async fn delete_platform_secret(&self, key: &str) -> Result<(), ClientError> {
196        let resp = self.authed(self.client.delete(self.api(&format!("/platform/secrets/{key}")))).send().await?;
197        check_response(resp).await?;
198        Ok(())
199    }
200
201    async fn worker_action(&self, app_id: &str, action: &str) -> Result<String, ClientError> {
202        let resp = self
203            .authed(self.client.post(self.api(&format!("/apps/{app_id}/worker/{action}"))))
204            .send()
205            .await?;
206        extract_message(resp).await
207    }
208}
209
210async fn extract_message(resp: reqwest::Response) -> Result<String, ClientError> {
211    let body: JsonValue = check_response(resp).await?.json().await?;
212    Ok(body["message"].as_str().unwrap_or("ok").to_string())
213}
214
215async fn check_response(resp: reqwest::Response) -> Result<reqwest::Response, ClientError> {
216    if resp.status().is_success() {
217        return Ok(resp);
218    }
219    let status = resp.status().as_u16();
220    let body: JsonValue = resp.json().await.unwrap_or_default();
221    let message = body["error"].as_str().unwrap_or("unknown error").to_string();
222    Err(ClientError::Api { status, message })
223}