Skip to main content

smbcloud_model/
project.rs

1use {
2    crate::{app_auth::AuthApp, ar_date_format, runner::Runner, tenant::Tenant},
3    chrono::{DateTime, Utc},
4    serde::{Deserialize, Serialize},
5    serde_repr::{Deserialize_repr, Serialize_repr},
6    std::fmt::Display,
7    tsync::tsync,
8};
9
10fn default_datetime() -> DateTime<Utc> {
11    DateTime::UNIX_EPOCH
12}
13
14/// How the project's files are delivered to the server.
15///
16/// `Git`   — the classic smbCloud flow: push to a remote git repo, the server
17///           builds and restarts the process.
18/// `Rsync` — files are transferred directly with rsync over SSH; no build step
19///           runs on the server. Ideal for pre-built static sites or assets.
20#[derive(Deserialize_repr, Serialize_repr, Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[repr(u8)]
22#[tsync]
23pub enum DeploymentMethod {
24    #[default]
25    Git = 0,
26    Rsync = 1,
27}
28
29impl Display for DeploymentMethod {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            DeploymentMethod::Git => write!(f, "Git"),
33            DeploymentMethod::Rsync => write!(f, "Rsync"),
34        }
35    }
36}
37
38#[derive(Deserialize, Debug, Serialize, Clone, Default)]
39pub struct Config {
40    /// Legacy project field — kept for backward compatibility during migration.
41    pub current_project: Option<Project>,
42    /// The active FrontendApp for CLI deploy operations.
43    #[serde(default)]
44    pub current_frontend_app: Option<crate::frontend_app::FrontendApp>,
45    pub current_auth_app: Option<AuthApp>,
46    /// The tenant selected with `smb tenant use`. Determines which workspace
47    /// tenant-scoped operations (e.g. `smb project new`) target — the API
48    /// falls back to the user's personal tenant when this isn't set.
49    #[serde(default)]
50    pub current_tenant: Option<Tenant>,
51}
52
53#[derive(Deserialize, Serialize, Debug, Clone)]
54#[tsync]
55pub struct Project {
56    /// Umbrella smbCloud workspace ID.
57    pub id: i32,
58    /// The tenant this project belongs to. Optional for older API responses
59    /// that predate the tenant/workspace split.
60    #[serde(default)]
61    pub tenant_id: Option<i64>,
62    #[serde(default)]
63    pub name: String,
64    #[serde(default)]
65    pub runner: Runner,
66    /// Defaults to `Git` when absent (older API responses won't include the field).
67    #[serde(default)]
68    pub deployment_method: DeploymentMethod,
69    pub path: Option<String>,
70    pub repository: Option<String>,
71    pub description: Option<String>,
72    /// Deployable app ID for precise deployment tracking. Optional during the
73    /// migration away from project-as-app semantics.
74    pub frontend_app_id: Option<String>,
75    /// Repo ID backing this deploy target. Optional until the API exposes it
76    /// consistently to the CLI.
77    pub deploy_repo_id: Option<i64>,
78    /// Repo-relative app path for monorepo targets, e.g. "apps/web/console".
79    pub source_path: Option<String>,
80    #[serde(default = "default_datetime")]
81    pub created_at: DateTime<Utc>,
82    #[serde(default = "default_datetime")]
83    pub updated_at: DateTime<Utc>,
84    /// Deployment kind, e.g. "vite-spa", "nextjs-ssr", or "rust".
85    pub kind: Option<String>,
86    /// Local source directory to build from, e.g. "frontend/connected-devices"
87    /// or a Rust crate root like ".".
88    /// Used by local-build deploys such as vite-spa, nextjs-ssr, and rust.
89    /// Distinct from `path`, which is the remote destination on the server.
90    pub source: Option<String>,
91    /// Build output directory relative to `source`, e.g. "dist".
92    pub output: Option<String>,
93    /// Package manager to use for the build step, e.g. "pnpm".
94    pub package_manager: Option<String>,
95    /// PM2 process name to restart after a nextjs-ssr deploy, e.g. "my-app".
96    /// Matches the name passed to `pm2 start` on the server.
97    pub pm2_app: Option<String>,
98    /// Environment variables to seed into the PM2 ecosystem `env_production` block.
99    /// Populated from the server-side App record; not written to `.smb/config.toml`.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub pm2_env: Option<std::collections::HashMap<String, serde_json::Value>>,
102    /// Port the standalone server binds to (default: 3000). Must match nginx upstream configuration.
103    #[serde(default)]
104    pub port: Option<u16>,
105    /// Path to a shared lib directory to rsync to the server before deploying,
106    /// e.g. "lib". Used by Rails apps that depend on native gems built from
107    /// monorepo-level source. Relative to the repo root.
108    pub shared_lib: Option<String>,
109    /// SSH command to run on the server after rsyncing the shared lib,
110    /// e.g. "cd ~/lib/gems/gem_error_codes && rbenv local 3.4.2 && bundle install && bundle exec rake compile".
111    pub compile_cmd: Option<String>,
112    /// Install command override, e.g. "pnpm install --frozen-lockfile".
113    #[serde(default)]
114    pub install_command: Option<String>,
115    /// Rust binary filename to upload and restart, e.g. "onde-cloud".
116    /// When absent, the CLI falls back to the Cargo package name.
117    pub binary_name: Option<String>,
118    /// Rust target triple used for local cross-compilation before upload,
119    /// e.g. "x86_64-unknown-linux-gnu".
120    pub rust_target: Option<String>,
121    /// Swift SDK identifier used to cross-compile a Swift/Vapor app for Linux,
122    /// e.g. "x86_64-swift-linux-musl" (the Static Linux SDK). Defaults to
123    /// "x86_64-swift-linux-musl" when absent. Built natively on the host with
124    /// `swift build --swift-sdk <id>` — no Docker, no emulation.
125    pub swift_sdk: Option<String>,
126    /// Optional toolchain identifier passed via the `TOOLCHAINS` env var when
127    /// cross-compiling Swift. Needed on macOS where the default `swift` is
128    /// Apple's Xcode toolchain (which lacks `lld`); point it at an installed
129    /// swift.org toolchain, e.g. "swift" (resolves to swift-latest) or a bundle
130    /// id like "org.swift.632202605101a". Unnecessary when `swift` is already a
131    /// swift.org toolchain (e.g. via swiftly).
132    pub swift_toolchain: Option<String>,
133}
134
135impl Display for Project {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        write!(f, "ID: {}, Name: {}", self.id, self.name,)
138    }
139}
140/// Payload for creating the umbrella workspace. Deploy concerns (runner,
141/// repository, deployment method) live on the App, not the Project.
142#[derive(Serialize, Debug, Deserialize, Clone)]
143#[tsync]
144pub struct ProjectCreate {
145    pub name: String,
146    pub description: String,
147}
148
149#[derive(Deserialize, Serialize, Debug)]
150#[tsync]
151pub struct Deployment {
152    pub id: i32,
153    pub project_id: i32,
154    pub frontend_app_id: Option<String>,
155    pub frontend_app_name: Option<String>,
156    pub commit_hash: String,
157    pub status: DeploymentStatus,
158    #[serde(with = "ar_date_format")]
159    pub created_at: DateTime<Utc>,
160    #[serde(with = "ar_date_format")]
161    pub updated_at: DateTime<Utc>,
162}
163
164#[derive(Deserialize, Serialize, Debug)]
165pub struct DeploymentPayload {
166    pub commit_hash: String,
167    pub status: DeploymentStatus,
168    pub frontend_app_id: Option<String>,
169}
170
171#[derive(Deserialize_repr, Serialize_repr, Debug, Clone, Copy)] // Added Clone, Copy
172#[repr(u8)]
173#[tsync]
174pub enum DeploymentStatus {
175    Started = 0,
176    Failed,
177    Done,
178}
179
180impl Display for DeploymentStatus {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        match self {
183            DeploymentStatus::Started => write!(f, "🚀"),
184            DeploymentStatus::Failed => write!(f, "❌"),
185            DeploymentStatus::Done => write!(f, "✅"),
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use serde_json::json;
194    #[test]
195    fn test_project_create() {
196        let project_create = ProjectCreate {
197            name: "test".to_owned(),
198            description: "test".to_owned(),
199        };
200        let json = json!({
201            "name": "test",
202            "description": "test"
203        });
204        assert_eq!(serde_json::to_value(project_create).unwrap(), json);
205    }
206
207    #[test]
208    fn test_deployment_status_display() {
209        assert_eq!(format!("{}", DeploymentStatus::Started), "🚀");
210        assert_eq!(DeploymentStatus::Started.to_string(), "🚀");
211
212        assert_eq!(format!("{}", DeploymentStatus::Failed), "❌");
213        assert_eq!(DeploymentStatus::Failed.to_string(), "❌");
214
215        assert_eq!(format!("{}", DeploymentStatus::Done), "✅");
216        assert_eq!(DeploymentStatus::Done.to_string(), "✅");
217    }
218}