mecha10-deploy 0.8.0

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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! 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
//!
//! There is a single resolution path: a cached binary if one already exists, otherwise a
//! download via `mecha10-api`. There is no `cargo install` fallback — an unsupported platform
//! or a failed download is a hard, immediate error naming what was tried and why it failed.
//!
//! # 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_deploy::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 mecha10_cli_core::utils::build_client;
use std::path::PathBuf;

const FRAMEWORK_VERSION: &str = env!("CARGO_PKG_VERSION");

pub struct BinaryManager {
    cache_dir: PathBuf,
    version: String,
    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 a cached binary exists for the current version/target
    /// 2. If not, download it from `mecha10-api`
    ///
    /// There is no further fallback: if the platform has no pre-built binary, or the
    /// download fails, this returns an error immediately instead of silently degrading to
    /// a slower/older resolution path.
    ///
    /// # 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
    ///
    /// Resolution strategy (`LAB-4558`: the ordered-tiers-with-aggregate-error control flow
    /// below is shared via `mecha10_binary_naming::try_resolution_tiers!` with
    /// `NodeResolver::resolve_with_version` and the CLI's `resolve_cli_binary` - only the
    /// concrete tiers here are specific to this type):
    /// 1. Check if a cached binary exists for the current version/target
    /// 2. If not, download it from `mecha10-api`
    ///
    /// There is no further fallback: if the platform has no pre-built binary, or the
    /// download fails, this returns an error immediately instead of silently degrading to
    /// a slower/older resolution path.
    ///
    /// # 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> {
        mecha10_binary_naming::try_resolution_tiers!(node_name, {
            "cached binary" => match version {
                Some(v) => self.find_cached_version(node_name, v),
                None => self.find_cached(node_name),
            }
            .inspect(|path| {
                tracing::debug!("Using cached binary: {}", path.display());
            })
            .ok_or_else(|| "no cached binary found for this version/target".to_string()),

            "mecha10-api download" => {
                if !self.is_prebuilt_available() {
                    Err(format!(
                        "No pre-built binary available for '{}' on platform '{}' (supported targets: {}). \
                         Binaries are resolved solely via mecha10-api downloads ({}); there is no \
                         cargo-install or build-from-source fallback.",
                        node_name,
                        self.target,
                        mecha10_binary_naming::SUPPORTED_TARGETS.join(", "),
                        paths::urls::mecha10_api_base_url(),
                    ))
                } else {
                    let result = if let Some(v) = version {
                        self.download_version(node_name, Some(v)).await
                    } else {
                        self.download(node_name).await
                    };

                    result
                        .inspect(|path| {
                            tracing::info!("Downloaded binary for {}: {}", node_name, path.display());
                        })
                        .map_err(|e| {
                            format!(
                                "Failed to resolve binary for '{}' via mecha10-api download: {:#}",
                                node_name, e
                            )
                        })
                }
            },
        })
        .map_err(|e| anyhow::anyhow!(e))
    }

    /// 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 the latest published binary for a node via mecha10-api.
    ///
    /// Deliberately does NOT request `version=<Self::version>` (this CLI's own framework
    /// version) - node binaries are versioned independently by `mecha10-nodes` (see that
    /// repo's README "Versioning" section), not guaranteed to equal this crate's
    /// `CARGO_PKG_VERSION`. Omitting `version` lets `mecha10-api` resolve "latest" itself
    /// (`binaries/latest.txt`), matching the one other caller that already needs this
    /// (`resolve_cli_binary`'s "no override" case) rather than guessing a version client-side
    /// that may not match what was actually published.
    ///
    /// Confirmed live (2026-10-15): assuming node version == framework version made every
    /// single node binary 404 the moment the two repos' versions drifted (this crate at
    /// `0.7.0`, `mecha10-nodes` still at `0.6.5`) - fixed both by automating the version
    /// lockstep CI-side (mecha10-nodes PR ci/bump-version-on-mecha10-release) and by removing
    /// this client-side assumption entirely.
    async fn download(&self, node_name: &str) -> Result<PathBuf> {
        self.download_version(node_name, None).await
    }

    /// Download a node binary via `mecha10-api`. `version`: `Some` pins an exact version
    /// (`resolve_with_version`'s explicit-version tier); `None` asks mecha10-api for whatever
    /// is latest (see [`Self::download`]'s doc comment for why that's the right default).
    /// Either way, the version actually downloaded is read back from the response's
    /// `Content-Disposition` filename rather than assumed - that's the version used to name
    /// the cached file, so a `None` download caches under the real resolved version, not a
    /// guess.
    async fn download_version(&self, node_name: &str, version: Option<&str>) -> Result<PathBuf> {
        let (os, arch) = mecha10_binary_naming::os_arch_query(&self.target)?;
        let mut url = format!(
            "{}/downloads/node/{}?os={}&arch={}",
            paths::urls::mecha10_api_base_url(),
            node_name,
            os,
            arch
        );
        if let Some(v) = version {
            url.push_str(&format!("&version={}", v));
        }

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

        let client = 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: {}",
                node_name,
                response.status(),
                url
            ));
        }

        let resolved_version = version
            .map(|v| v.to_string())
            .or_else(|| self.parse_resolved_version(node_name, &response))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "mecha10-api did not report which version it resolved for '{}' \
                     (missing/unparseable Content-Disposition header)",
                    node_name
                )
            })?;

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

    /// Extracts the actual resolved version out of a download response's
    /// `Content-Disposition` filename (`"{node_name}-{version}-{self.target}.tar.gz"` - see
    /// `mecha10-api`'s `node_key`), for the `version: None` ("give me latest") case where the
    /// caller doesn't already know what version it's getting.
    fn parse_resolved_version(&self, node_name: &str, response: &reqwest::Response) -> Option<String> {
        let header = response
            .headers()
            .get(reqwest::header::CONTENT_DISPOSITION)?
            .to_str()
            .ok()?;
        let filename = header.split("filename=\"").nth(1)?.strip_suffix('"')?;
        filename
            .strip_prefix(&format!("{node_name}-"))?
            .strip_suffix(&format!("-{}.tar.gz", self.target))
            .map(str::to_string)
    }

    /// 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> {
        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("#>-"),
        );

        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");

        tokio::fs::create_dir_all(&self.cache_dir).await?;

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

        let extract_dir = temp_dir.path().join("extract");
        std::fs::create_dir_all(&extract_dir)?;
        archive.unpack(&extract_dir)?;

        let extracted_binary = extract_dir.join(node_name);
        if !extracted_binary.exists() {
            return Err(anyhow::anyhow!("Binary '{}' not found in tarball", node_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?;

        #[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?;
        }

        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)
    }

    /// 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::*;

    #[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");
    }

    #[tokio::test]
    async fn resolve_errors_immediately_on_unsupported_platform_with_no_cargo_install_fallback() {
        let manager = BinaryManager {
            cache_dir: PathBuf::from("/tmp/mecha10-binary-manager-test-does-not-exist"),
            version: "0.1.44".to_string(),
            target: "aarch64-unknown-linux-musl".to_string(),
        };

        let err = manager
            .resolve("speaker")
            .await
            .expect_err("unsupported platform must error, not silently fall back");

        let message = err.to_string();
        assert!(
            message.contains("No pre-built binary available"),
            "error should name the missing source, got: {message}"
        );
        assert!(
            message.contains("no cargo-install or build-from-source fallback"),
            "error must make clear there is no fallback path, got: {message}"
        );
    }

    #[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());

        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());

        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());
    }
}