Skip to main content

virtuoso_cli/
models.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5pub enum ExecutionStatus {
6    Success,
7    Failure,
8    Partial,
9    Error,
10}
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct VirtuosoResult {
14    pub status: ExecutionStatus,
15    pub output: String,
16    pub errors: Vec<String>,
17    pub warnings: Vec<String>,
18    pub execution_time: Option<f64>,
19    pub metadata: HashMap<String, String>,
20}
21
22impl VirtuosoResult {
23    /// Transport-level success: bridge returned STX (not NAK/timeout).
24    /// Does NOT mean the SKILL call succeeded — SKILL functions return "nil"
25    /// on failure via STX. Use skill_ok() to check SKILL-level success.
26    pub fn ok(&self) -> bool {
27        self.status == ExecutionStatus::Success
28    }
29
30    /// True when the bridge succeeded AND SKILL returned a non-nil value.
31    /// Use this whenever a SKILL function signals failure by returning nil
32    /// (e.g. design(), dbOpenCellViewByType(), getData()).
33    pub fn skill_ok(&self) -> bool {
34        self.status == ExecutionStatus::Success && self.output.trim() != "nil"
35    }
36
37    pub fn success(output: impl Into<String>) -> Self {
38        Self {
39            status: ExecutionStatus::Success,
40            output: output.into(),
41            errors: Vec::new(),
42            warnings: Vec::new(),
43            execution_time: None,
44            metadata: HashMap::new(),
45        }
46    }
47
48    pub fn error(errors: Vec<String>) -> Self {
49        Self {
50            status: ExecutionStatus::Error,
51            output: String::new(),
52            errors,
53            warnings: Vec::new(),
54            execution_time: None,
55            metadata: HashMap::new(),
56        }
57    }
58
59    pub fn save_json(&self, path: &std::path::Path) -> std::io::Result<()> {
60        let json = serde_json::to_string_pretty(self)
61            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
62        std::fs::write(path, json)
63    }
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct SimulationResult {
68    pub status: ExecutionStatus,
69    pub tool_version: Option<String>,
70    pub data: HashMap<String, Vec<f64>>,
71    pub errors: Vec<String>,
72    pub warnings: Vec<String>,
73    pub metadata: HashMap<String, String>,
74}
75
76impl SimulationResult {
77    pub fn ok(&self) -> bool {
78        self.status == ExecutionStatus::Success
79    }
80
81    pub fn save_json(&self, path: &std::path::Path) -> std::io::Result<()> {
82        let json = serde_json::to_string_pretty(self)
83            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
84        std::fs::write(path, json)
85    }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct RemoteTaskResult {
90    pub success: bool,
91    pub returncode: i32,
92    pub stdout: String,
93    pub stderr: String,
94    pub remote_dir: Option<String>,
95    pub error: Option<String>,
96    pub timings: HashMap<String, f64>,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct RemoteSshEnv {
101    pub remote_host: String,
102    pub remote_user: Option<String>,
103    pub jump_host: Option<String>,
104    pub jump_user: Option<String>,
105}
106
107fn default_version() -> u32 {
108    1
109}
110
111/// Registration record written by bridge.il when a Virtuoso session starts.
112/// Lives at ~/.cache/virtuoso_bridge/sessions/<id>.json
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct SessionInfo {
115    pub id: String,
116    pub port: u16,
117    pub pid: u32,
118    pub host: String,
119    pub user: String,
120    pub created: String,
121}
122
123impl SessionInfo {
124    pub(crate) fn sessions_dir() -> std::path::PathBuf {
125        dirs::cache_dir()
126            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
127            .join("virtuoso_bridge")
128            .join("sessions")
129    }
130
131    pub fn load(id: &str) -> std::io::Result<Self> {
132        let path = Self::sessions_dir().join(format!("{id}.json"));
133        let json = std::fs::read_to_string(&path).map_err(|e| {
134            std::io::Error::new(e.kind(), format!("session '{id}' not found: {e}"))
135        })?;
136        serde_json::from_str(&json)
137            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
138    }
139
140    pub fn list() -> std::io::Result<Vec<Self>> {
141        let dir = Self::sessions_dir();
142        if !dir.exists() {
143            return Ok(Vec::new());
144        }
145        let mut sessions = Vec::new();
146        for entry in std::fs::read_dir(&dir)? {
147            let entry = entry?;
148            let path = entry.path();
149            if path.extension().map_or(false, |e| e == "json") {
150                if let Ok(json) = std::fs::read_to_string(&path) {
151                    if let Ok(s) = serde_json::from_str::<Self>(&json) {
152                        sessions.push(s);
153                    }
154                }
155            }
156        }
157        sessions.sort_by(|a, b| a.id.cmp(&b.id));
158        Ok(sessions)
159    }
160
161    /// Check if the daemon is still alive by checking if the port is bound.
162    pub fn is_alive(&self) -> bool {
163        use std::net::TcpStream;
164        use std::time::Duration;
165        TcpStream::connect_timeout(
166            &format!("127.0.0.1:{}", self.port).parse().unwrap(),
167            Duration::from_millis(200),
168        )
169        .is_ok()
170    }
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct TunnelState {
175    #[serde(default = "default_version")]
176    pub version: u32,
177    pub port: u16,
178    pub pid: u32,
179    pub remote_host: String,
180    pub setup_path: Option<String>,
181}
182
183impl TunnelState {
184    pub fn save(&self) -> std::io::Result<()> {
185        let cache_dir = dirs::cache_dir()
186            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
187            .join("virtuoso_bridge");
188        std::fs::create_dir_all(&cache_dir)?;
189        let state_path = cache_dir.join("state.json");
190        let json = serde_json::to_string_pretty(self)
191            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
192        std::fs::write(state_path, json)
193    }
194
195    pub fn load() -> std::io::Result<Option<Self>> {
196        let cache_dir = dirs::cache_dir()
197            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
198            .join("virtuoso_bridge");
199        let state_path = cache_dir.join("state.json");
200        if !state_path.exists() {
201            return Ok(None);
202        }
203        let json = std::fs::read_to_string(state_path)?;
204        serde_json::from_str(&json)
205            .map(Some)
206            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
207    }
208
209    pub fn clear() -> std::io::Result<()> {
210        let cache_dir = dirs::cache_dir()
211            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
212            .join("virtuoso_bridge");
213        let state_path = cache_dir.join("state.json");
214        if state_path.exists() {
215            std::fs::remove_file(state_path)?;
216        }
217        Ok(())
218    }
219}