virtuoso-cli 0.3.7

CLI tool to control Cadence Virtuoso from anywhere, locally or remotely
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::client::layout_ops::LayoutOps;
use crate::client::maestro_ops::MaestroOps;
use crate::client::schematic_ops::SchematicOps;
use crate::client::window_ops::WindowOps;
use crate::error::{Result, VirtuosoError};
use crate::models::{ExecutionStatus, VirtuosoResult};
use crate::transport::tunnel::SSHClient;
use crate::version::VirtuosoVersion;
use std::cell::Cell;
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Instant;

const STX: u8 = 0x02;
const NAK: u8 = 0x15;
const MAX_RESPONSE_SIZE: usize = 100 * 1024 * 1024; // 100MB

pub struct VirtuosoClient {
    host: String,
    port: u16,
    timeout: u64,
    tunnel: Option<SSHClient>,
    #[allow(dead_code)]
    pub layout: LayoutOps,
    pub maestro: MaestroOps,
    pub schematic: SchematicOps,
    pub window: WindowOps,
    cached_version: Cell<Option<VirtuosoVersion>>,
}

impl VirtuosoClient {
    pub fn new(host: &str, port: u16, timeout: u64) -> Self {
        Self {
            host: host.into(),
            port,
            timeout,
            tunnel: None,
            layout: LayoutOps::new(),
            maestro: MaestroOps,
            schematic: SchematicOps::new(),
            window: WindowOps,
            cached_version: Cell::new(None),
        }
    }

    pub fn from_env() -> Result<Self> {
        let cfg = crate::config::Config::from_env()?;

        let tunnel = if cfg.is_remote() {
            let state = crate::models::TunnelState::load().ok().flatten();
            if let Some(ref s) = state {
                if is_port_open(s.port) {
                    tracing::info!("reusing existing tunnel on port {}", s.port);
                    let client = SSHClient::from_env(cfg.keep_remote_files)?;
                    Some(client)
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

        // Session-aware port resolution:
        // 1. --session / VB_SESSION → load port from session file
        // 2. No session specified → auto-select if exactly one session exists
        // 3. Fallback to VB_PORT / config.port for backward compat
        let port = if let Some(base_port) = tunnel.as_ref().and_then(|t| t.saved_port()) {
            base_port
        } else if let Ok(session_id) = std::env::var("VB_SESSION") {
            // VB_SESSION may be a Maestro session name (e.g. "fnxSession8") rather than
            // a bridge session ID — Maestro sessions don't have session files.
            // Fall back to VB_PORT in that case.
            match crate::models::SessionInfo::load(&session_id) {
                Ok(s) => {
                    tracing::info!("connecting to session '{}' on port {}", s.id, s.port);
                    s.port
                }
                Err(_) => {
                    tracing::debug!(
                        "session '{}' not a bridge session (no file), using VB_PORT",
                        session_id
                    );
                    cfg.port
                }
            }
        } else {
            // No session specified — try auto-discovery
            match crate::models::SessionInfo::list() {
                Ok(sessions) if sessions.len() == 1 => {
                    let s = &sessions[0];
                    tracing::info!("auto-selected session '{}' on port {}", s.id, s.port);
                    s.port
                }
                Ok(sessions) if sessions.len() > 1 => {
                    let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
                    return Err(crate::error::VirtuosoError::Config(format!(
                        "multiple Virtuoso sessions active: {}. Use --session <id> to select one.",
                        ids.join(", ")
                    )));
                }
                _ => cfg.port, // 0 sessions or list failed → use VB_PORT
            }
        };

        Ok(Self {
            host: "127.0.0.1".into(),
            port,
            timeout: cfg.timeout,
            tunnel,
            layout: LayoutOps::new(),
            maestro: MaestroOps,
            schematic: SchematicOps::new(),
            window: WindowOps,
            cached_version: Cell::new(None),
        })
    }

    pub fn execute_skill(&self, skill_code: &str, timeout: Option<u64>) -> Result<VirtuosoResult> {
        // Guard: block SKILL expressions that can hang the daemon
        if let Some(warning) = check_blocking_skill(skill_code) {
            return Err(VirtuosoError::Execution(warning));
        }

        let timeout = timeout.unwrap_or(self.timeout);
        let start = Instant::now();

        let addr: std::net::SocketAddr = format!("{}:{}", self.host, self.port)
            .parse()
            .map_err(|e| VirtuosoError::Connection(format!("invalid address: {e}")))?;
        let req = serde_json::json!({"skill": skill_code, "timeout": timeout});
        let req_bytes = serde_json::to_string(&req).map_err(VirtuosoError::Json)?;

        // Drain loop: a new session may find stale "sync_N" responses queued in the
        // daemon from a previous client. Detect and transparently discard up to 10.
        for _ in 0..10u8 {
            let mut stream =
                TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(timeout))
                    .map_err(|e| VirtuosoError::Connection(e.to_string()))?;
            stream
                .set_read_timeout(Some(std::time::Duration::from_secs(timeout)))
                .ok();
            stream
                .write_all(req_bytes.as_bytes())
                .map_err(|e| VirtuosoError::Connection(e.to_string()))?;
            stream
                .shutdown(std::net::Shutdown::Write)
                .map_err(|e| VirtuosoError::Connection(e.to_string()))?;

            let mut data = Vec::new();
            let mut buf = [0u8; 65536];
            loop {
                match stream.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        if data.len() + n > MAX_RESPONSE_SIZE {
                            return Err(VirtuosoError::Execution(format!(
                                "response exceeds {}MB limit",
                                MAX_RESPONSE_SIZE / 1024 / 1024
                            )));
                        }
                        data.extend_from_slice(&buf[..n]);
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        return Err(VirtuosoError::Timeout(timeout));
                    }
                    Err(e) => return Err(VirtuosoError::Connection(e.to_string())),
                }
            }

            if data.is_empty() {
                return Err(VirtuosoError::Execution(
                    "empty response from daemon".into(),
                ));
            }

            let status_byte = data[0];
            let payload = String::from_utf8_lossy(&data[1..]).into_owned();

            // Stale sync_N: queued response from a previous session's command.
            // Discard and retry with the same command on a fresh connection.
            if status_byte == STX && is_stale_sync(&payload) {
                continue;
            }

            let elapsed = start.elapsed().as_secs_f64();
            let mut result = VirtuosoResult {
                status: ExecutionStatus::Success,
                output: String::new(),
                errors: Vec::new(),
                warnings: Vec::new(),
                execution_time: Some(elapsed),
                metadata: Default::default(),
            };

            // STX = transport success; NAK = transport error (includes daemon timeout).
            // The daemon sends NAK+"TimeoutError" (no RS) on deadline — no need to
            // text-match under STX. Doing so would reject any SKILL function that
            // legitimately returns the string "TimeoutError".
            if status_byte == STX {
                result.output = payload;
            } else if status_byte == NAK {
                result.status = ExecutionStatus::Error;
                result.errors.push(payload);
            } else {
                result.output = String::from_utf8_lossy(&data).into_owned();
                result.warnings.push("non-standard response marker".into());
            }

            let truncated = if skill_code.len() > 200 {
                format!("{}...", &skill_code[..200])
            } else {
                skill_code.to_string()
            };
            crate::command_log::log_command("SKILL", &truncated, Some(start.elapsed().as_millis()));

            return Ok(result);
        }

        Err(VirtuosoError::Execution(
            "bridge queue misaligned: 10 consecutive sync_N responses drained".into(),
        ))
    }

    /// Batch-fetch object slots from a SKILL list expression in a single RTT.
    ///
    /// `list_expr` evaluates to a SKILL list of objects; `fields` names the `~>slot`
    /// accessors to extract from each object. Returns one `HashMap` per object.
    ///
    /// Nil-valued slots are returned as empty strings. Example:
    /// ```rust,ignore
    /// client.execute_skill_fetch("maeGetSessions()", &["name", "status"])
    /// // → [{"name": "fnxSession0", "status": "idle"}, ...]
    /// ```
    #[allow(dead_code)]
    pub fn execute_skill_fetch(
        &self,
        list_expr: &str,
        fields: &[&str],
    ) -> Result<Vec<HashMap<String, String>>> {
        if fields.is_empty() {
            return Ok(Vec::new());
        }
        let skill = build_fetch_skill(list_expr, fields);
        let r = self.execute_skill(&skill, None)?;
        if !r.ok() {
            return Err(VirtuosoError::Execution(format!(
                "execute_skill_fetch failed: {}",
                r.errors.first().cloned().unwrap_or_default()
            )));
        }
        let sexp = crate::client::skill_sexp::parse_sexp(&r.output)?;
        match sexp {
            crate::client::skill_sexp::SexpVal::Nil => Ok(Vec::new()),
            crate::client::skill_sexp::SexpVal::List(items) => {
                Ok(items
                    .iter()
                    .filter_map(|item| {
                        let vals = crate::client::skill_sexp::sexp_to_str_list(item)?;
                        if vals.len() != fields.len() {
                            return None;
                        }
                        Some(
                            fields
                                .iter()
                                .zip(vals.iter())
                                .map(|(k, v)| (k.to_string(), v.clone().unwrap_or_default()))
                                .collect(),
                        )
                    })
                    .collect())
            }
            _ => Err(VirtuosoError::Execution(
                "execute_skill_fetch: expected list from SKILL".into(),
            )),
        }
    }

    pub fn test_connection(&self, timeout: Option<u64>) -> Result<bool> {
        let result = self.execute_skill("1+1", timeout)?;
        Ok(result.output.trim() == "2")
    }

    pub fn open_cell_view(
        &self,
        lib: &str,
        cell: &str,
        view: &str,
        mode: &str,
    ) -> Result<VirtuosoResult> {
        let lib = escape_skill_string(lib);
        let cell = escape_skill_string(cell);
        let view = escape_skill_string(view);
        let mode = escape_skill_string(mode);
        let skill = format!(
            r#"geOpenCellView(?libName "{lib}" ?cellName "{cell}" ?viewName "{view}" ?mode "{mode}")"#
        );
        self.execute_skill(&skill, None)
    }

    pub fn save_current_cellview(&self) -> Result<VirtuosoResult> {
        self.execute_skill("geSaveEdit()", None)
    }

    pub fn close_current_cellview(&self) -> Result<VirtuosoResult> {
        self.execute_skill("geCloseEdit()", None)
    }

    pub fn get_current_design(&self) -> Result<(String, String, String)> {
        let result = self.execute_skill(
            r#"let((cv) cv = geGetEditCellView() list(cv~>libName cv~>cellName cv~>viewName))"#,
            None,
        )?;
        let cleaned = result.output.trim().trim_matches(|c| c == '(' || c == ')');
        let parts: Vec<&str> = cleaned.split_whitespace().collect();
        if parts.len() >= 3 {
            let strip = |s: &str| s.trim_matches('"').to_string();
            Ok((strip(parts[0]), strip(parts[1]), strip(parts[2])))
        } else {
            Err(VirtuosoError::Execution(
                "failed to get current design".into(),
            ))
        }
    }

    pub fn load_il(&self, local_path: &str) -> Result<VirtuosoResult> {
        let filename = std::path::Path::new(local_path)
            .file_name()
            .ok_or_else(|| VirtuosoError::Config(format!("invalid path: {local_path}")))?
            .to_string_lossy();
        let remote_path = format!("/tmp/virtuoso_bridge/{filename}");

        self.upload_file(local_path, &remote_path)?;

        let remote_path_escaped = escape_skill_string(&remote_path);
        let skill = format!(r#"(load "{remote_path_escaped}")"#);
        self.execute_skill(&skill, None)
    }

    pub fn upload_file(&self, local: &str, remote: &str) -> Result<()> {
        if let Some(ref tunnel) = self.tunnel {
            tunnel.upload_file(local, remote)
        } else {
            std::fs::copy(local, remote)
                .map(|_| ())
                .map_err(VirtuosoError::Io)
        }
    }

    #[allow(dead_code)]
    pub fn download_file(&self, remote: &str, local: &str) -> Result<()> {
        if let Some(ref tunnel) = self.tunnel {
            tunnel.download_file(remote, local)
        } else {
            std::fs::copy(remote, local)
                .map(|_| ())
                .map_err(VirtuosoError::Io)
        }
    }

    pub fn execute_operations(&self, commands: &[String]) -> Result<VirtuosoResult> {
        if commands.is_empty() {
            return Ok(VirtuosoResult::success(""));
        }
        let body = commands.join("\n");
        let skill = format!("progn(\n{body}\n)");
        self.execute_skill(&skill, None)
    }

    #[allow(dead_code)]
    pub fn ciw_print(&self, message: &str) -> Result<VirtuosoResult> {
        let skill = format!(
            r#"printf("[virtuoso-cli] {}\n")"#,
            escape_skill_string(message)
        );
        self.execute_skill(&skill, None)
    }

    #[allow(dead_code)]
    pub fn run_shell_command(&self, cmd: &str) -> Result<VirtuosoResult> {
        let cmd = escape_skill_string(cmd);
        let skill = format!(r#"(csh "{cmd}")"#);
        self.execute_skill(&skill, None)
    }

    #[allow(dead_code)]
    pub fn tunnel(&self) -> Option<&SSHClient> {
        self.tunnel.as_ref()
    }

    /// Detect and cache the Virtuoso IC version.
    /// First call queries the daemon; subsequent calls return the cached result.
    pub fn version(&self) -> Result<VirtuosoVersion> {
        if let Some(v) = self.cached_version.get() {
            return Ok(v);
        }
        let v = crate::version::detect_version(self)?;
        self.cached_version.set(Some(v));
        Ok(v)
    }
}

fn is_port_open(port: u16) -> bool {
    TcpStream::connect(format!("127.0.0.1:{port}")).is_ok()
}

fn check_blocking_skill(code: &str) -> Option<String> {
    if code.contains("system(") || code.contains("sh(") {
        let lower = code.to_lowercase();
        if lower.contains("find /") || lower.contains("find \"/") {
            return Some(
                "Blocked: system()/sh() with recursive 'find /' can hang the SKILL daemon. \
                 Use a specific directory instead (e.g., find /home/...)."
                    .into(),
            );
        }
    }
    None
}

/// Returns true for stale `"sync_N"` responses queued from a previous session.
fn is_stale_sync(payload: &str) -> bool {
    let p = payload.trim().trim_matches('"');
    p.starts_with("sync_") && p[5..].parse::<u32>().is_ok()
}

pub fn escape_skill_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

/// Build a SKILL expression that fetches `~>slot` fields from each object in
/// `list_expr` and returns a native SKILL list-of-lists in a single RTT.
///
/// Generated form (for fields ["name", "value"]):
/// ```text
/// mapcar(lambda((o) list(o~>name o~>value)) list_expr)
/// ```
///
/// SKILL output: `(("fnxSession0" "idle") ("fnxSession1" nil) ...)`
/// Parsed by `execute_skill_fetch` using `skill_sexp::parse_sexp`.
/// This approach avoids the sprintf-JSON hack that silently corrupts field
/// values containing `"` or `\n`.
#[allow(dead_code)]
fn build_fetch_skill(list_expr: &str, fields: &[&str]) -> String {
    let field_exprs: Vec<String> = fields.iter().map(|f| format!("o~>{f}")).collect();
    let fields_str = field_exprs.join(" ");
    format!("mapcar(lambda((o) list({fields_str})) {list_expr})")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fetch_skill_single_field() {
        let s = build_fetch_skill("maeGetSessions()", &["name"]);
        assert_eq!(s, "mapcar(lambda((o) list(o~>name)) maeGetSessions())");
    }

    #[test]
    fn fetch_skill_multiple_fields() {
        let s = build_fetch_skill("myList()", &["name", "value"]);
        assert_eq!(s, "mapcar(lambda((o) list(o~>name o~>value)) myList())");
    }

    #[test]
    fn fetch_skill_three_fields() {
        let s = build_fetch_skill("getSessions()", &["id", "port", "status"]);
        assert!(s.contains("o~>id"), "{s}");
        assert!(s.contains("o~>port"), "{s}");
        assert!(s.contains("o~>status"), "{s}");
        assert!(s.starts_with("mapcar(lambda((o) list("), "{s}");
    }
}