mecha10-deploy 0.6.2

Mecha10 deploy services — Docker management, binary distribution, remote deployment
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
480
481
482
483
484
485
//! Binary Manager service for downloading and caching node binaries via `mecha10-api`
//!
//! This service implements the Node Binary Distribution architecture, providing:
//! - Downloading pre-built node binaries via the public `mecha10-api` downloads proxy
//!   (`GET /api/downloads/node/{name}`), never the private Minio instance directly
//! - Caching binaries to `~/.mecha10/bin/`
//! - Platform detection and target triple resolution
//! - Fallback to cargo install for unsupported platforms
//!
//! # Design
//!
//! - Binaries are downloaded from `{mecha10_api}/downloads/node/{node}?os=..&arch=..&version=..`
//! - Binary naming: `{node}-{version}-{target}.tar.gz`
//! - Cached to: `~/.mecha10/bin/{node}-{version}-{target}`
//! - Symlink created: `~/.mecha10/bin/{node}` -> latest version
//!
//! # Usage
//!
//! ```no_run
//! use mecha10_cli::services::BinaryManager;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let manager = BinaryManager::new()?;
//!
//! // Resolve binary path (downloads if needed)
//! let path = manager.resolve("speaker").await?;
//!
//! // Execute the binary
//! std::process::Command::new(&path).spawn()?;
//! # Ok(())
//! # }
//! ```

#![allow(dead_code)]

use crate::paths;
use anyhow::{Context, Result};
use indicatif::{ProgressBar, ProgressStyle};
use std::path::PathBuf;

/// Framework version (should match workspace Cargo.toml)
const FRAMEWORK_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Service for managing node binary downloads and caching
pub struct BinaryManager {
    /// Binary cache directory (~/.mecha10/bin)
    cache_dir: PathBuf,
    /// Framework version for binary resolution
    version: String,
    /// Current platform target triple
    target: String,
}

impl BinaryManager {
    /// Create a new binary manager
    pub fn new() -> Result<Self> {
        let cache_dir = paths::user::bin_dir();
        let version = FRAMEWORK_VERSION.to_string();
        let target = mecha10_binary_naming::detect_target()?;

        Ok(Self {
            cache_dir,
            version,
            target,
        })
    }

    /// Create a binary manager with a specific version
    #[allow(dead_code)]
    pub fn with_version(version: String) -> Result<Self> {
        let cache_dir = paths::user::bin_dir();
        let target = mecha10_binary_naming::detect_target()?;

        Ok(Self {
            cache_dir,
            version,
            target,
        })
    }

    /// Check if pre-built binaries are available for current platform
    pub fn is_prebuilt_available(&self) -> bool {
        mecha10_binary_naming::is_prebuilt_available(&self.target)
    }

    /// Get the binary cache directory
    #[allow(dead_code)]
    pub fn cache_dir(&self) -> &PathBuf {
        &self.cache_dir
    }

    /// Get the current version
    #[allow(dead_code)]
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Get the current target
    #[allow(dead_code)]
    pub fn target(&self) -> &str {
        &self.target
    }

    /// Resolve binary path for a node, downloading if needed
    ///
    /// Resolution strategy:
    /// 1. Check if cached binary exists for current version/target
    /// 2. If not, try to download from GitHub releases
    /// 3. If download fails and platform unsupported, fall back to cargo install
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node (e.g., "speaker", "motor")
    ///
    /// # Returns
    ///
    /// Path to the executable binary
    pub async fn resolve(&self, node_name: &str) -> Result<PathBuf> {
        self.resolve_with_version(node_name, None).await
    }

    /// Resolve binary path for a node with a specific version
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node (e.g., "speaker", "motor")
    /// * `version` - Optional specific version to download (e.g., "0.1.48").
    ///   If None, downloads the latest available version.
    ///
    /// # Returns
    ///
    /// Path to the executable binary
    pub async fn resolve_with_version(&self, node_name: &str, version: Option<&str>) -> Result<PathBuf> {
        // Check cache first (for specific version if provided)
        if let Some(v) = version {
            if let Some(path) = self.find_cached_version(node_name, v) {
                tracing::debug!("Using cached binary: {}", path.display());
                return Ok(path);
            }
        } else if let Some(cached) = self.find_cached(node_name) {
            tracing::debug!("Using cached binary: {}", cached.display());
            return Ok(cached);
        }

        // Try to download
        if self.is_prebuilt_available() {
            let result = if let Some(v) = version {
                self.download_version(node_name, v).await
            } else {
                self.download(node_name).await
            };

            match result {
                Ok(path) => {
                    tracing::info!("Downloaded binary for {}: {}", node_name, path.display());
                    return Ok(path);
                }
                Err(e) => {
                    tracing::warn!("Failed to download binary for {}: {}", node_name, e);
                    // Show actionable message for macOS (binaries built manually)
                    if self.target.ends_with("-apple-darwin") {
                        println!("⚠️  macOS binaries for '{}' v{} not found.", node_name, self.version);
                        println!("   Compiling from source instead (this may take a few minutes)...");
                    }
                    // Fall through to cargo install
                }
            }
        } else {
            tracing::info!("Pre-built binary not available for {} on {}", node_name, self.target);
        }

        // Fallback: cargo install (uses framework version, not specified version)
        self.cargo_install(node_name).await
    }

    /// Check for cached binary with specific version
    fn find_cached_version(&self, node_name: &str, version: &str) -> Option<PathBuf> {
        mecha10_binary_naming::find_cached_version(&self.cache_dir, node_name, version, &self.target)
    }

    /// Check for cached binary (any version)
    ///
    /// Looks for any cached version of the binary, preferring the symlink which
    /// points to the most recently downloaded version.
    fn find_cached(&self, node_name: &str) -> Option<PathBuf> {
        mecha10_binary_naming::find_cached(&self.cache_dir, node_name, &self.target)
    }

    /// Build the binary name for a node with a specific version
    fn binary_name_with_version(&self, node_name: &str, version: &str) -> String {
        mecha10_binary_naming::binary_name(node_name, version, &self.target)
    }

    /// Build the binary name for a node (uses current version)
    fn binary_name(&self, node_name: &str) -> String {
        self.binary_name_with_version(node_name, &self.version)
    }

    /// Build the tarball name for a node with a specific version
    fn tarball_name_with_version(&self, node_name: &str, version: &str) -> String {
        mecha10_binary_naming::tarball_name(node_name, version, &self.target)
    }

    /// Build the tarball name for a node (uses current version)
    #[allow(dead_code)]
    fn tarball_name(&self, node_name: &str) -> String {
        self.tarball_name_with_version(node_name, &self.version)
    }

    /// Download binary at the current framework version via mecha10-api
    async fn download(&self, node_name: &str) -> Result<PathBuf> {
        self.download_version(node_name, &self.version.clone()).await
    }

    /// Download a specific version of a node binary via `mecha10-api`
    async fn download_version(&self, node_name: &str, version: &str) -> Result<PathBuf> {
        let tarball = self.tarball_name_with_version(node_name, version);
        let (os, arch) = mecha10_binary_naming::os_arch_query(&self.target)?;
        let url = format!(
            "{}/downloads/node/{}?os={}&arch={}&version={}",
            paths::urls::mecha10_api_base_url(),
            node_name,
            os,
            arch,
            version
        );

        println!("📦 Downloading {} v{}...", node_name, version);
        tracing::info!("Downloading binary from mecha10-api: {}", url);

        let client = Self::build_client()?;
        let response = client
            .get(&url)
            .send()
            .await
            .context(format!("Failed to connect to mecha10-api for binary '{}'", node_name))?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Binary '{}' not found: HTTP {}\n\
                 URL: {}\n\
                 Falling back to cargo install...",
                tarball,
                response.status(),
                url
            ));
        }

        let size = response.content_length().unwrap_or(0);
        self.download_and_extract_versioned(node_name, version, response, size)
            .await
    }

    /// Download and extract a binary tarball with a specific version
    async fn download_and_extract_versioned(
        &self,
        node_name: &str,
        version: &str,
        response: reqwest::Response,
        size: u64,
    ) -> Result<PathBuf> {
        // Create progress bar
        let pb = ProgressBar::new(size);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.green} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                .unwrap()
                .progress_chars("#>-"),
        );

        // Download to temp file
        let temp_dir = tempfile::tempdir()?;
        let temp_file = temp_dir.path().join("binary.tar.gz");

        let mut file = tokio::fs::File::create(&temp_file).await?;
        let mut stream = response.bytes_stream();

        use futures_util::StreamExt;
        use tokio::io::AsyncWriteExt;

        while let Some(chunk) = stream.next().await {
            let chunk = chunk.context("Error downloading chunk")?;
            file.write_all(&chunk).await?;
            pb.inc(chunk.len() as u64);
        }

        file.flush().await?;
        pb.finish_with_message("Download complete");

        // Create cache directory
        tokio::fs::create_dir_all(&self.cache_dir).await?;

        // Extract tarball
        let tar_gz = std::fs::File::open(&temp_file)?;
        let tar = flate2::read::GzDecoder::new(tar_gz);
        let mut archive = tar::Archive::new(tar);

        // Extract to temp, then move to cache
        let extract_dir = temp_dir.path().join("extract");
        std::fs::create_dir_all(&extract_dir)?;
        archive.unpack(&extract_dir)?;

        // Find the binary in the extracted files (should be just the node name)
        let extracted_binary = extract_dir.join(node_name);
        if !extracted_binary.exists() {
            return Err(anyhow::anyhow!("Binary '{}' not found in tarball", node_name));
        }

        // Move to cache with versioned name
        let binary_name = self.binary_name_with_version(node_name, version);
        let dest_path = self.cache_dir.join(&binary_name);

        tokio::fs::copy(&extracted_binary, &dest_path).await?;

        // Make executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = tokio::fs::metadata(&dest_path).await?.permissions();
            perms.set_mode(0o755);
            tokio::fs::set_permissions(&dest_path, perms).await?;
        }

        // Create/update symlink
        let symlink_path = self.cache_dir.join(node_name);
        if symlink_path.exists() || symlink_path.is_symlink() {
            tokio::fs::remove_file(&symlink_path).await.ok();
        }

        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&binary_name, &symlink_path)?;
        }

        #[cfg(windows)]
        {
            std::os::windows::fs::symlink_file(&dest_path, &symlink_path)?;
        }

        println!("✅ Installed {} v{} to {}", node_name, version, dest_path.display());

        Ok(dest_path)
    }

    /// Fallback: install via cargo
    async fn cargo_install(&self, node_name: &str) -> Result<PathBuf> {
        println!(
            "⚠️  Pre-built binary not available for {} on {}",
            node_name, self.target
        );
        println!("🔨 Compiling via cargo install...");

        let crate_name = format!("mecha10-nodes-{}", node_name);

        let output = tokio::process::Command::new("cargo")
            .args([
                "install",
                &crate_name,
                "--version",
                &self.version,
                "--root",
                &self.cache_dir.to_string_lossy(),
            ])
            .output()
            .await
            .context("Failed to run cargo install")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow::anyhow!("cargo install failed for {}: {}", crate_name, stderr));
        }

        // cargo install puts binary in {root}/bin/{name}
        let binary_path = self.cache_dir.join("bin").join(node_name);
        if !binary_path.exists() {
            return Err(anyhow::anyhow!(
                "Binary not found after cargo install: {}",
                binary_path.display()
            ));
        }

        println!("✅ Compiled {} via cargo install", node_name);

        Ok(binary_path)
    }

    /// Build an HTTP client
    fn build_client() -> Result<reqwest::Client> {
        reqwest::Client::builder()
            .user_agent("mecha10-cli")
            .build()
            .context("Failed to build HTTP client")
    }

    /// Remove a cached binary
    pub async fn remove(&self, node_name: &str) -> Result<()> {
        let binary_name = self.binary_name(node_name);
        let binary_path = self.cache_dir.join(&binary_name);
        let symlink_path = self.cache_dir.join(node_name);

        if binary_path.exists() {
            tokio::fs::remove_file(&binary_path).await?;
            println!("Removed {}", binary_path.display());
        }

        if symlink_path.exists() || symlink_path.is_symlink() {
            tokio::fs::remove_file(&symlink_path).await?;
            println!("Removed symlink {}", symlink_path.display());
        }

        Ok(())
    }

    /// Clear all cached binaries
    pub async fn clear_cache(&self) -> Result<()> {
        if self.cache_dir.exists() {
            tokio::fs::remove_dir_all(&self.cache_dir).await?;
            println!("Cleared binary cache at {}", self.cache_dir.display());
        }
        Ok(())
    }
}

impl Default for BinaryManager {
    fn default() -> Self {
        Self::new().expect("Failed to create BinaryManager")
    }
}

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

    // Naming/target-detection logic itself is covered by mecha10-binary-naming's own
    // tests; these confirm BinaryManager's methods correctly wrap it with the
    // struct's version/target.

    #[test]
    fn test_binary_name() {
        let manager = BinaryManager {
            cache_dir: PathBuf::from("/tmp"),
            version: "0.1.44".to_string(),
            target: "aarch64-apple-darwin".to_string(),
        };

        assert_eq!(manager.binary_name("speaker"), "speaker-0.1.44-aarch64-apple-darwin");
    }

    #[test]
    fn test_tarball_name() {
        let manager = BinaryManager {
            cache_dir: PathBuf::from("/tmp"),
            version: "0.1.44".to_string(),
            target: "x86_64-apple-darwin".to_string(),
        };

        assert_eq!(manager.tarball_name("motor"), "motor-0.1.44-x86_64-apple-darwin.tar.gz");
    }

    #[test]
    fn test_prebuilt_available() {
        let manager = BinaryManager {
            cache_dir: PathBuf::from("/tmp"),
            version: "0.1.44".to_string(),
            target: "aarch64-apple-darwin".to_string(),
        };
        assert!(manager.is_prebuilt_available());

        // aarch64-unknown-linux-gnu is now supported (for Pi, Jetson with glibc)
        let manager_arm_linux = BinaryManager {
            cache_dir: PathBuf::from("/tmp"),
            version: "0.1.44".to_string(),
            target: "aarch64-unknown-linux-gnu".to_string(),
        };
        assert!(manager_arm_linux.is_prebuilt_available());

        // musl variant is not supported (we use gnu for system library compatibility)
        let manager_unsupported = BinaryManager {
            cache_dir: PathBuf::from("/tmp"),
            version: "0.1.44".to_string(),
            target: "aarch64-unknown-linux-musl".to_string(),
        };
        assert!(!manager_unsupported.is_prebuilt_available());
    }
}