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    /// Runtime supervisor for `nextjs-ssr` apps: `"pm2"` (default) or `"systemd"`.
103    /// When `"systemd"`, the deploy restart step drives a git-owned
104    /// `systemctl --user restart <pm2_app>.service` (created by the
105    /// pm2-to-systemd migration) instead of `pm2 delete`/`pm2 start`.
106    /// `pm2_app` is still used as the unit name.
107    #[serde(default)]
108    pub process_manager: Option<String>,
109    /// Port the standalone server binds to (default: 3000). Must match nginx upstream configuration.
110    #[serde(default)]
111    pub port: Option<u16>,
112    /// Path to a shared lib directory to rsync to the server before deploying,
113    /// e.g. "lib". Used by Rails apps that depend on native gems built from
114    /// monorepo-level source. Relative to the repo root.
115    pub shared_lib: Option<String>,
116    /// SSH command to run on the server after rsyncing the shared lib,
117    /// e.g. "cd ~/lib/gems/gem_error_codes && rbenv local 3.4.2 && bundle install && bundle exec rake compile".
118    pub compile_cmd: Option<String>,
119    /// Install command override, e.g. "pnpm install --frozen-lockfile".
120    #[serde(default)]
121    pub install_command: Option<String>,
122    /// Rust binary filename to upload and restart, e.g. "onde-cloud".
123    /// When absent, the CLI falls back to the Cargo package name.
124    pub binary_name: Option<String>,
125    /// Rust target triple used for local cross-compilation before upload,
126    /// e.g. "x86_64-unknown-linux-gnu".
127    pub rust_target: Option<String>,
128    /// Swift SDK identifier used to cross-compile a Swift/Vapor app for Linux,
129    /// e.g. "x86_64-swift-linux-musl" (the Static Linux SDK). Defaults to
130    /// "x86_64-swift-linux-musl" when absent. Built natively on the host with
131    /// `swift build --swift-sdk <id>` — no Docker, no emulation.
132    pub swift_sdk: Option<String>,
133    /// Optional toolchain identifier passed via the `TOOLCHAINS` env var when
134    /// cross-compiling Swift. Needed on macOS where the default `swift` is
135    /// Apple's Xcode toolchain (which lacks `lld`); point it at an installed
136    /// swift.org toolchain, e.g. "swift" (resolves to swift-latest) or a bundle
137    /// id like "org.swift.632202605101a". Unnecessary when `swift` is already a
138    /// swift.org toolchain (e.g. via swiftly).
139    pub swift_toolchain: Option<String>,
140}
141
142impl Display for Project {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        write!(f, "ID: {}, Name: {}", self.id, self.name,)
145    }
146}
147/// Payload for creating the umbrella workspace. Deploy concerns (runner,
148/// repository, deployment method) live on the App, not the Project.
149#[derive(Serialize, Debug, Deserialize, Clone)]
150#[tsync]
151pub struct ProjectCreate {
152    pub name: String,
153    pub description: String,
154}
155
156#[derive(Deserialize, Serialize, Debug)]
157#[tsync]
158pub struct Deployment {
159    pub id: i32,
160    pub project_id: i32,
161    pub frontend_app_id: Option<String>,
162    pub frontend_app_name: Option<String>,
163    pub commit_hash: String,
164    pub status: DeploymentStatus,
165    #[serde(with = "ar_date_format")]
166    pub created_at: DateTime<Utc>,
167    #[serde(with = "ar_date_format")]
168    pub updated_at: DateTime<Utc>,
169}
170
171#[derive(Deserialize, Serialize, Debug)]
172pub struct DeploymentPayload {
173    pub commit_hash: String,
174    pub status: DeploymentStatus,
175    pub frontend_app_id: Option<String>,
176}
177
178#[derive(Deserialize_repr, Serialize_repr, Debug, Clone, Copy)] // Added Clone, Copy
179#[repr(u8)]
180#[tsync]
181pub enum DeploymentStatus {
182    Started = 0,
183    Failed,
184    Done,
185}
186
187impl Display for DeploymentStatus {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        match self {
190            DeploymentStatus::Started => write!(f, "🚀"),
191            DeploymentStatus::Failed => write!(f, "❌"),
192            DeploymentStatus::Done => write!(f, "✅"),
193        }
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use serde_json::json;
201    #[test]
202    fn test_project_create() {
203        let project_create = ProjectCreate {
204            name: "test".to_owned(),
205            description: "test".to_owned(),
206        };
207        let json = json!({
208            "name": "test",
209            "description": "test"
210        });
211        assert_eq!(serde_json::to_value(project_create).unwrap(), json);
212    }
213
214    #[test]
215    fn test_deployment_status_display() {
216        assert_eq!(format!("{}", DeploymentStatus::Started), "🚀");
217        assert_eq!(DeploymentStatus::Started.to_string(), "🚀");
218
219        assert_eq!(format!("{}", DeploymentStatus::Failed), "❌");
220        assert_eq!(DeploymentStatus::Failed.to_string(), "❌");
221
222        assert_eq!(format!("{}", DeploymentStatus::Done), "✅");
223        assert_eq!(DeploymentStatus::Done.to_string(), "✅");
224    }
225}