rialo-build-lib 0.10.1

Shared library for Rialo program building logic
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Rialo custom Rust toolchain management
//!
//! This module manages the Rialo custom Rust toolchain with the
//! riscv64emac-solana-solana target for building Rust programs.

use std::{
    fs::{File, OpenOptions},
    path::{Path, PathBuf},
    thread,
    time::{Duration, Instant},
};

use anyhow::{Context, Result};

use super::{
    extract_tar_gz, get_platform, get_s3_bucket, get_toolchain_root, S3StorageBackend, Toolchain,
    ToolchainConfig,
};

/// Rust nightly version to use for source builds
pub const RUST_NIGHTLY_VERSION: &str = "nightly-2025-05-10";

/// How the toolchain version was resolved
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum ToolchainSource {
    /// From an explicit caller-provided override
    Explicit,
    /// From `RIALO_RUST_TOOLCHAIN_VERSION` environment variable
    Environment,
    /// From the nearest ancestor `.rialo-toolchain` file
    WorkspaceFile,
    /// From release manifest (rialoman-managed binary)
    Rialoman,
    /// First installed toolchain found on disk
    Installed,
}

impl std::fmt::Display for ToolchainSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Explicit => write!(f, "explicit"),
            Self::Environment => write!(f, "environment"),
            Self::WorkspaceFile => write!(f, "workspace-file"),
            Self::Rialoman => write!(f, "manifest"),
            Self::Installed => write!(f, "installed"),
        }
    }
}

/// Resolved toolchain version, its source, and an optional source path.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ResolvedToolchainVersion {
    pub version: String,
    pub source: ToolchainSource,
    pub source_path: Option<PathBuf>,
}

/// Rust commit hash for source builds
pub const RUST_COMMIT_HASH: &str = "dcecb99176edf2eec51613730937d21cdd5c8f6e";

/// Embedded RISC-V backend patch
/// This patch adds the riscv64emac-solana-solana target to the Rust compiler
const RISCV_BACKEND_PATCH: &str = include_str!("../../patches/0001-risc-v-backend.patch");
const INSTALL_LOCK_FILE_NAME: &str = ".rialo-rust-install.lock";
const INSTALL_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(200);
const INSTALL_LOCK_TIMEOUT: Duration = Duration::from_secs(300);

/// Rialo Rust toolchain manager
///
/// Manages the Rialo custom Rust toolchain which includes:
/// - rustc with riscv64emac-solana-solana target
/// - cargo
/// - std library for the custom target
#[derive(Debug, Clone)]
pub struct RialoRustToolchain {
    pub(crate) config: ToolchainConfig,
}

impl RialoRustToolchain {
    /// Create a new Rialo Rust toolchain with auto-resolved version.
    ///
    /// Resolution order:
    /// 1. `RIALO_RUST_TOOLCHAIN_VERSION` environment variable
    /// 2. Release manifest `rust_toolchain` field (if running from rialoman-installed binary)
    /// 3. First installed toolchain
    pub fn new() -> Result<Self> {
        let (version, _) = Self::resolve_version()?;
        Self::with_version(&version)
    }

    /// Create a new Rialo Rust toolchain with an explicit version.
    pub fn with_version(version: &str) -> Result<Self> {
        // Backwards compatibility: redirect magic strings to new()
        if version == "auto" || version == "latest" {
            return Self::new();
        }

        let toolchain_root = get_toolchain_root()?;
        let install_path = toolchain_root.join(format!("rialo-rust-{}", version));
        let platform = get_platform()?;
        let download_url = Self::get_download_url(version, &platform)?;

        Ok(Self {
            config: ToolchainConfig {
                name: "rialo-rust".to_string(),
                version: version.to_string(),
                download_url,
                install_path,
                checksum: None,
            },
        })
    }

    /// Resolve the toolchain version automatically and its source.
    ///
    /// Resolution order:
    /// 1. `RIALO_RUST_TOOLCHAIN_VERSION` environment variable
    /// 2. Release manifest `rust_toolchain` field (rialoman-installed binary)
    /// 3. First installed toolchain
    pub fn resolve_version() -> Result<(String, ToolchainSource)> {
        if let Ok(version) = std::env::var("RIALO_RUST_TOOLCHAIN_VERSION") {
            log::info!("Using toolchain {} from environment variable", version);
            return Ok((version, ToolchainSource::Environment));
        }

        if let Some(version) = super::detect_rialoman_release_toolchain_version()? {
            log::info!("Using toolchain {} from Rialoman release manifest", version);
            return Ok((version, ToolchainSource::Rialoman));
        }

        if let Some(version) = Self::find_installed_version()? {
            log::info!("Using installed Rialo Rust toolchain: {}", version);
            return Ok((version, ToolchainSource::Installed));
        }

        Err(anyhow::anyhow!(
            "No Rialo Rust toolchains installed. Install one with:\n  \
             rialoman toolchain install rialo-rust --version <VERSION>\n\n\
             Or build from source with:\n  \
             rialoman toolchain build"
        ))
    }

    /// Resolve the toolchain version for a specific program directory.
    ///
    /// Resolution order:
    /// 1. Explicit override
    /// 2. `RIALO_RUST_TOOLCHAIN_VERSION`
    /// 3. Nearest ancestor `.rialo-toolchain`
    /// 4. Release manifest `rust_toolchain` field
    /// 5. First installed toolchain
    pub fn resolve_version_for_program(
        program_path: &Path,
        explicit_override: Option<&str>,
    ) -> Result<ResolvedToolchainVersion> {
        let program_path = if program_path.is_absolute() {
            program_path.to_path_buf()
        } else {
            std::env::current_dir()
                .context("Failed to determine current working directory")?
                .join(program_path)
        };

        resolve_version_for_program_with_sources(
            &program_path,
            explicit_override,
            std::env::var("RIALO_RUST_TOOLCHAIN_VERSION").ok(),
            super::detect_rialoman_release_toolchain_version()?,
            Self::find_installed_version()?,
        )
    }

    /// Find the first installed Rialo Rust toolchain version.
    ///
    /// Returns `None` if no toolchains are installed.
    pub fn find_installed_version() -> Result<Option<String>> {
        let toolchains = crate::toolchain::list_installed_toolchains()?;
        for (name, version) in toolchains {
            if name == "rialo-rust" {
                log::debug!("Found installed Rialo Rust toolchain: {}", version);
                return Ok(Some(version));
            }
        }
        Ok(None)
    }

    /// Create a new Rialo Rust toolchain for building from source
    pub fn new_from_source() -> Result<Self> {
        let toolchain_root = get_toolchain_root()?;
        let install_path = toolchain_root.join("rialo-rust-source");

        Ok(Self {
            config: ToolchainConfig {
                name: "rialo-rust".to_string(),
                version: RUST_NIGHTLY_VERSION.to_string(),
                download_url: String::new(), // Not used for source builds
                install_path,
                checksum: None,
            },
        })
    }

    /// Get the download URL for prebuilt binaries
    fn get_download_url(version: &str, platform: &str) -> Result<String> {
        // Using Rialo prebuilt toolchain releases
        // These are hosted on GitHub releases at subzerolabs/rialo-toolchains
        let base_url = "https://github.com/subzerolabs/rialo-toolchains/releases/download";

        // Map our platform strings to the toolchain naming convention
        let toolchain_platform = match platform {
            "x86_64-apple-darwin" => "x86_64-apple-darwin",
            "aarch64-apple-darwin" => "aarch64-apple-darwin",
            "x86_64-unknown-linux-gnu" => "x86_64-unknown-linux-gnu",
            "aarch64-unknown-linux-gnu" => "aarch64-unknown-linux-gnu",
            _ => {
                return Err(anyhow::anyhow!(
                    "No Rialo Rust toolchain available for platform: {platform}"
                ))
            }
        };

        // Format: rialo-rust-{version}-{platform}.tar.gz
        let archive_name = format!("rialo-rust-{version}-{toolchain_platform}.tar.gz");
        let url = format!("{base_url}/{version}/{archive_name}");

        Ok(url)
    }

    /// Get the embedded RISC-V backend patch
    pub fn get_patch_content() -> &'static str {
        RISCV_BACKEND_PATCH
    }

    /// Write the patch file to a directory
    pub fn write_patch_file(dest_dir: &Path) -> Result<PathBuf> {
        std::fs::create_dir_all(dest_dir)
            .with_context(|| format!("Failed to create directory {}", dest_dir.display()))?;

        let patch_path = dest_dir.join("0001-risc-v-backend.patch");
        std::fs::write(&patch_path, RISCV_BACKEND_PATCH)
            .with_context(|| format!("Failed to write patch file to {}", patch_path.display()))?;

        Ok(patch_path)
    }

    /// Check if rustup is installed
    pub(crate) fn check_rustup() -> Result<()> {
        which::which("rustup")
            .context("rustup not found. Please install rustup from https://rustup.rs/")?;
        Ok(())
    }

    /// Check if the toolchain is currently registered with rustup
    fn check_rustup_registration() -> Result<bool> {
        let output = std::process::Command::new("rustup")
            .args(["toolchain", "list"])
            .output()
            .context("Failed to run rustup toolchain list")?;

        let output_str = String::from_utf8_lossy(&output.stdout);
        Ok(output_str.lines().any(|line| line.starts_with("rialo")))
    }

    /// Register the toolchain with rustup as 'rialo', possibly overwriting the
    /// old alias, if exists.
    ///
    /// # Errors
    ///
    /// Returns an error if rustup is not installed or the link operation fails.
    pub fn register_with_rustup(&self) -> Result<()> {
        Self::check_rustup()?;
        self.with_install_lock(|toolchain| toolchain.register_with_rustup_unlocked())
    }

    pub(crate) fn register_with_rustup_unlocked(&self) -> Result<()> {
        log::info!("Registering toolchain with rustup as 'rialo'...");

        // `rustup toolchain link` is idempotent - it overwrites existing links
        let status = std::process::Command::new("rustup")
            .args([
                "toolchain",
                "link",
                "rialo",
                self.config.install_path.to_str().unwrap(),
            ])
            .status()
            .context("Failed to link toolchain with rustup")?;

        if !status.success() {
            return Err(anyhow::anyhow!("Failed to register toolchain with rustup"));
        }

        log::info!("Toolchain registered as 'rialo'");
        Ok(())
    }

    /// Unregister the toolchain from rustup
    fn unregister_from_rustup() -> Result<()> {
        if Self::check_rustup_registration()? {
            log::info!("Unregistering toolchain from rustup...");
            std::process::Command::new("rustup")
                .args(["toolchain", "remove", "rialo"])
                .status()
                .context("Failed to unregister toolchain")?;
            log::info!("Toolchain unregistered");
        }
        Ok(())
    }

    /// Validate that a toolchain exists and is complete at the given path
    ///
    /// Checks for the presence of rustc and cargo binaries in the bin/ directory
    fn validate_toolchain_at(path: &Path) -> Result<()> {
        if !path.exists() {
            return Err(anyhow::anyhow!(
                "Toolchain path does not exist: {}",
                path.display()
            ));
        }

        let bin_path = path.join("bin");
        if !bin_path.exists() {
            return Err(anyhow::anyhow!(
                "Toolchain bin directory not found at {}",
                bin_path.display()
            ));
        }

        let rustc = bin_path.join("rustc");
        let cargo = bin_path.join("cargo");

        if !rustc.exists() {
            return Err(anyhow::anyhow!(
                "rustc not found in toolchain at {}",
                bin_path.display()
            ));
        }

        if !cargo.exists() {
            return Err(anyhow::anyhow!(
                "cargo not found in toolchain at {}",
                bin_path.display()
            ));
        }

        Ok(())
    }

    /// Ensure the toolchain is installed and validated.
    ///
    /// Toolchain installation and rustup-link updates are serialized under the
    /// global toolchain lock via `install()`.
    pub fn ensure_installed_atomically(&self) -> Result<()> {
        if self.validate_if_installed()? {
            return Ok(());
        }

        Self::check_rustup()?;
        self.with_install_lock(|toolchain| toolchain.ensure_usable_unlocked())
    }

    pub(crate) fn with_install_lock<T>(
        &self,
        action: impl FnOnce(&RialoRustToolchain) -> Result<T>,
    ) -> Result<T> {
        let _guard = Self::acquire_install_lock()?;
        action(self)
    }

    fn acquire_install_lock() -> Result<InstallLockGuard> {
        let toolchain_root = get_toolchain_root()?;
        Self::acquire_install_lock_in_root(&toolchain_root)
    }

    fn acquire_install_lock_in_root(toolchain_root: &Path) -> Result<InstallLockGuard> {
        std::fs::create_dir_all(toolchain_root)
            .with_context(|| format!("Failed to create {}", toolchain_root.display()))?;

        let lock_path = toolchain_root.join(INSTALL_LOCK_FILE_NAME);
        InstallLockGuard::acquire(lock_path)
    }
}

struct InstallLockGuard {
    path: PathBuf,
    file: File,
}

impl InstallLockGuard {
    fn acquire(path: PathBuf) -> Result<Self> {
        let deadline = Instant::now() + INSTALL_LOCK_TIMEOUT;
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(&path)
            .with_context(|| format!("Failed to open {}", path.display()))?;

        loop {
            match file.try_lock() {
                Ok(()) => return Ok(Self { path, file }),
                Err(std::fs::TryLockError::WouldBlock) => {
                    if Instant::now() >= deadline {
                        return Err(anyhow::anyhow!(
                            "Timed out waiting for toolchain install lock at {}",
                            path.display()
                        ));
                    }
                    thread::sleep(INSTALL_LOCK_RETRY_INTERVAL);
                }
                Err(std::fs::TryLockError::Error(error)) => {
                    return Err(error).with_context(|| format!("Failed to lock {}", path.display()))
                }
            }
        }
    }
}

impl Drop for InstallLockGuard {
    fn drop(&mut self) {
        if let Err(error) = self.file.unlock() {
            log::warn!(
                "Failed to unlock toolchain install lock {}: {}",
                self.path.display(),
                error
            );
        }
    }
}

fn resolve_version_for_program_with_sources(
    program_path: &Path,
    explicit_override: Option<&str>,
    env_override: Option<String>,
    manifest_override: Option<String>,
    installed_override: Option<String>,
) -> Result<ResolvedToolchainVersion> {
    if let Some(version) = normalize_toolchain_version(explicit_override) {
        return Ok(ResolvedToolchainVersion {
            version: version.to_string(),
            source: ToolchainSource::Explicit,
            source_path: None,
        });
    }

    if let Some(version) = normalize_toolchain_version(env_override.as_deref()) {
        return Ok(ResolvedToolchainVersion {
            version: version.to_string(),
            source: ToolchainSource::Environment,
            source_path: None,
        });
    }

    if let Some((path, version)) = find_workspace_toolchain_version(program_path)? {
        return Ok(ResolvedToolchainVersion {
            version,
            source: ToolchainSource::WorkspaceFile,
            source_path: Some(path),
        });
    }

    if let Some(version) = normalize_toolchain_version(manifest_override.as_deref()) {
        return Ok(ResolvedToolchainVersion {
            version: version.to_string(),
            source: ToolchainSource::Rialoman,
            source_path: None,
        });
    }

    if let Some(version) = normalize_toolchain_version(installed_override.as_deref()) {
        return Ok(ResolvedToolchainVersion {
            version: version.to_string(),
            source: ToolchainSource::Installed,
            source_path: None,
        });
    }

    Err(anyhow::anyhow!(
        "No Rialo Rust toolchains installed. Install one with:\n  \
         rialoman toolchain install rialo-rust --version <VERSION>\n\n\
         Or build from source with:\n  \
         rialoman toolchain build"
    ))
}

fn find_workspace_toolchain_version(program_path: &Path) -> Result<Option<(PathBuf, String)>> {
    for ancestor in program_path.ancestors() {
        let toolchain_path = ancestor.join(".rialo-toolchain");
        if !toolchain_path.exists() {
            continue;
        }

        let toolchain_path = toolchain_path
            .canonicalize()
            .with_context(|| format!("Failed to canonicalize {}", toolchain_path.display()))?;
        let version = std::fs::read_to_string(&toolchain_path)
            .with_context(|| format!("Failed to read {}", toolchain_path.display()))?;
        let version = version.trim();

        if version.is_empty() {
            return Err(anyhow::anyhow!(
                "Empty toolchain version in {}",
                toolchain_path.display()
            ));
        }

        return Ok(Some((toolchain_path, version.to_string())));
    }

    Ok(None)
}

fn normalize_toolchain_version(version: Option<&str>) -> Option<&str> {
    match version.map(str::trim) {
        Some("") | None => None,
        Some("auto" | "latest") => None,
        Some(version) => Some(version),
    }
}

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

impl Toolchain for RialoRustToolchain {
    fn is_installed(&self) -> Result<bool> {
        // Check if toolchain files exist at the install path
        if Self::validate_toolchain_at(&self.config.install_path).is_ok() {
            log::debug!(
                "Found Rialo Rust toolchain at {}",
                self.config.install_path.display()
            );

            // When invoked from a Bazel rialo_program action (RIALO_BUILD_CARGO_PATH is set),
            // cargo is called directly — no rustup shim is involved. Skip the rustup
            // registration check so that a Bazel repo-cache restore (which re-populates files
            // but does NOT re-run `rustup toolchain link`) is still considered "installed".
            let using_direct_cargo = std::env::var("RIALO_BUILD_CARGO_PATH")
                .map(|p| !p.is_empty())
                .unwrap_or(false);
            if using_direct_cargo {
                log::debug!("Direct cargo mode — skipping rustup registration check");
                return Ok(true);
            }

            // Require rustup registration for the toolchain to be considered installed
            if !Self::check_rustup_registration()? {
                log::debug!("Toolchain files exist but not registered with rustup");
                return Ok(false);
            }

            return Ok(true);
        }

        Ok(false)
    }

    fn install(&self) -> Result<()> {
        if self.is_installed()? {
            log::info!(
                "Rialo Rust toolchain {} is already installed at {}",
                self.config.version,
                self.config.install_path.display()
            );
            return Ok(());
        }

        Self::check_rustup()?;
        self.with_install_lock(|toolchain| toolchain.install_unlocked())
    }

    fn validate(&self) -> Result<()> {
        if !self.is_installed()? {
            return Err(anyhow::anyhow!(
                "Rialo Rust toolchain {} is not installed. Run 'rialo-build toolchain install rialo-rust' to install it.",
                self.config.version
            ));
        }

        // When invoked from a Bazel rialo_program action, cargo is called directly via
        // RIALO_BUILD_CARGO_PATH — no rustup shim (`cargo +rialo`) is available or needed.
        let using_direct_cargo = std::env::var("RIALO_BUILD_CARGO_PATH")
            .map(|p| !p.is_empty())
            .unwrap_or(false);
        if using_direct_cargo {
            log::info!(
                "Rialo Rust toolchain {} available (direct cargo mode)",
                self.config.version
            );
            return Ok(());
        }

        // Validate that we can run cargo +rialo --version
        let output = std::process::Command::new("cargo")
            .args(["+rialo", "--version"])
            .output()
            .context("Failed to run cargo +rialo --version. Is rustup configured correctly?")?;

        if !output.status.success() {
            return Err(anyhow::anyhow!(
                "cargo +rialo returned non-zero exit code. The toolchain may be corrupted."
            ));
        }

        log::info!("Rialo Rust toolchain validation:");
        let version_output = String::from_utf8_lossy(&output.stdout);
        log::info!("  {}", version_output.trim());

        // Check that the custom target is available
        let output = std::process::Command::new("rustc")
            .args(["+rialo", "--print", "target-list"])
            .output()
            .context("Failed to run rustc +rialo --print target-list")?;

        let targets = String::from_utf8_lossy(&output.stdout);
        if !targets.contains("riscv64emac-solana-solana") {
            return Err(anyhow::anyhow!(
                "Custom target riscv64emac-solana-solana not found in toolchain. The toolchain may be incorrectly built."
            ));
        }

        log::info!("  Custom target: riscv64emac-solana-solana");
        log::info!("Toolchain is functional");

        Ok(())
    }

    fn get_bin_path(&self) -> Result<PathBuf> {
        let bin_path = self.config.install_path.join("bin");
        if !bin_path.exists() {
            return Err(anyhow::anyhow!(
                "Toolchain bin directory not found at {}",
                bin_path.display()
            ));
        }
        Ok(bin_path)
    }

    fn get_config(&self) -> &ToolchainConfig {
        &self.config
    }
}

impl RialoRustToolchain {
    fn validate_if_installed(&self) -> Result<bool> {
        if !self.is_installed()? {
            return Ok(false);
        }

        match self.validate() {
            Ok(()) => Ok(true),
            Err(error) => {
                log::warn!(
                    "Installed Rialo Rust toolchain {} failed validation before acquiring the shared lock: {}",
                    self.config.version,
                    error
                );
                Ok(false)
            }
        }
    }

    fn ensure_usable_unlocked(&self) -> Result<()> {
        if !self.is_installed()? {
            self.install_unlocked()?;
        }

        self.validate()
    }

    fn install_unlocked(&self) -> Result<()> {
        log::info!("Installing Rialo Rust toolchain {}...", self.config.version);

        // Create toolchain root directory
        let toolchain_root = get_toolchain_root()?;
        std::fs::create_dir_all(&toolchain_root).with_context(|| {
            format!(
                "Failed to create toolchain directory {}",
                toolchain_root.display()
            )
        })?;

        // Create a temporary directory for download
        let temp_dir = tempfile::tempdir()
            .context("Failed to create temporary directory for toolchain download")?;

        let archive_path = temp_dir.path().join("rialo-rust-toolchain.tar.gz");

        self.download_with_fallback(&archive_path)
            .with_context(|| {
                format!(
                    "Failed to download Rialo Rust toolchain version {}",
                    self.config.version
                )
            })?;

        // Create install directory
        std::fs::create_dir_all(&self.config.install_path).with_context(|| {
            format!(
                "Failed to create install directory {}",
                self.config.install_path.display()
            )
        })?;

        // Extract the archive
        extract_tar_gz(&archive_path, &self.config.install_path)?;

        // Register with rustup
        self.register_with_rustup_unlocked()?;

        log::info!(
            "Rialo Rust toolchain {} installed successfully at {}",
            self.config.version,
            self.config.install_path.display()
        );

        Ok(())
    }

    /// Uninstall the toolchain, including rustup registration
    pub fn uninstall(&self) -> Result<()> {
        // Unregister from rustup first
        Self::unregister_from_rustup()?;

        // Remove installation directory
        if self.config.install_path.exists() {
            std::fs::remove_dir_all(&self.config.install_path).with_context(|| {
                format!(
                    "Failed to remove installation directory {}",
                    self.config.install_path.display()
                )
            })?;
            log::info!(
                "Removed Rialo Rust toolchain from {}",
                self.config.install_path.display()
            );
        }

        Ok(())
    }

    fn download_with_fallback(&self, dest: &Path) -> Result<()> {
        self.download_from_http(dest)
    }

    /// Download toolchain from HTTP (public S3 bucket via HTTPS)
    ///
    /// Downloads from rialo-artifacts S3 bucket via HTTP - no AWS credentials needed.
    fn download_from_http(&self, dest: &Path) -> Result<()> {
        use crate::toolchain::HttpToolchainClient;

        let client =
            HttpToolchainClient::new().context("Failed to create HTTP toolchain client")?;

        let platform = get_platform()?;
        let archive_name = format!("rialo-rust-{}-{}", self.config.version, platform);

        client
            .download_toolchain("rialo-rust", &self.config.version, &archive_name, dest)
            .with_context(|| {
                format!(
                    "Failed to download Rialo Rust toolchain version {}",
                    self.config.version
                )
            })
    }

    /// Upload this toolchain to S3
    ///
    /// Packages the installed toolchain as a tarball and uploads it to S3.
    /// Requires AWS credentials to be configured.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The toolchain is not installed
    /// - AWS credentials are not available
    /// - The upload fails
    pub fn upload_to_s3(&self) -> Result<()> {
        if !self.is_installed()? {
            return Err(anyhow::anyhow!(
                "Toolchain is not installed. Cannot upload to S3."
            ));
        }

        log::debug!("Packaging Rialo Rust toolchain for upload...");

        // Create tarball
        let temp_dir =
            tempfile::tempdir().context("Failed to create temporary directory for tarball")?;
        let archive_path = temp_dir.path().join("rialo-rust-toolchain.tar.gz");

        self.create_tarball(&archive_path)?;

        log::info!("Uploading to S3...");

        // Upload to S3
        let runtime = tokio::runtime::Runtime::new()
            .context("Failed to create tokio runtime for S3 upload")?;

        runtime.block_on(async {
            let bucket = get_s3_bucket();
            let backend = S3StorageBackend::new(bucket).await?.context(
                "S3 backend not available. Ensure AWS credentials are configured \
                     (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY).",
            )?;

            let platform = get_platform()?;
            backend
                .upload_toolchain("rialo-rust", &self.config.version, &platform, &archive_path)
                .await
        })
    }

    /// Create a tarball of the installed toolchain
    fn create_tarball(&self, dest: &Path) -> Result<()> {
        use std::fs::File;

        use flate2::{write::GzEncoder, Compression};
        use tar::Builder;

        log::debug!("Creating tarball at {}...", dest.display());

        let tar_gz = File::create(dest)
            .with_context(|| format!("Failed to create tarball file {}", dest.display()))?;

        let enc = GzEncoder::new(tar_gz, Compression::default());
        let mut tar = Builder::new(enc);

        // Add all files from the installation directory
        tar.append_dir_all(".", &self.config.install_path)
            .with_context(|| {
                format!(
                    "Failed to add files from {} to tarball",
                    self.config.install_path.display()
                )
            })?;

        tar.finish().context("Failed to finalize tarball")?;

        log::debug!("Tarball created");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::mpsc;

    use super::*;

    #[test]
    fn test_create_rialo_rust_toolchain() {
        // Test creating a toolchain struct with a specific version
        // This should work regardless of whether toolchains are actually installed
        let toolchain = RialoRustToolchain::with_version("v1.0.0");
        assert!(
            toolchain.is_ok(),
            "Failed to create toolchain: {:?}",
            toolchain.err()
        );

        let tc = toolchain.unwrap();
        assert_eq!(tc.config.version, "v1.0.0");
        assert_eq!(tc.config.name, "rialo-rust");
    }

    #[test]
    fn test_toolchain_with_different_version() {
        // Test with a different version to ensure version parameter works correctly
        let toolchain = RialoRustToolchain::with_version("v2.5.3");
        assert!(toolchain.is_ok());
        let tc = toolchain.unwrap();
        assert_eq!(tc.config.version, "v2.5.3");
        assert_eq!(tc.config.name, "rialo-rust");
    }

    #[test]
    fn test_patch_content_exists() {
        let patch = RialoRustToolchain::get_patch_content();
        assert!(!patch.is_empty());
        assert!(patch.contains("riscv64emac-solana-solana"));
        assert!(patch.contains("risc-v backend"));
    }

    #[test]
    fn test_source_build_constants() {
        assert_eq!(RUST_NIGHTLY_VERSION, "nightly-2025-05-10");
        assert_eq!(RUST_COMMIT_HASH, "dcecb99176edf2eec51613730937d21cdd5c8f6e");
    }

    #[test]
    fn resolve_version_for_program_prefers_explicit_override() {
        let temp_dir = tempfile::tempdir().unwrap();
        let program_dir = temp_dir.path().join("program");
        std::fs::create_dir_all(&program_dir).unwrap();
        std::fs::write(temp_dir.path().join(".rialo-toolchain"), "0.0.3\n").unwrap();

        let resolved = resolve_version_for_program_with_sources(
            &program_dir,
            Some("1.2.3"),
            Some("9.9.9".to_string()),
            Some("8.8.8".to_string()),
            Some("7.7.7".to_string()),
        )
        .unwrap();

        assert_eq!(resolved.version, "1.2.3");
        assert_eq!(resolved.source, ToolchainSource::Explicit);
        assert!(resolved.source_path.is_none());
    }

    #[test]
    fn resolve_version_for_program_prefers_workspace_file_over_manifest_and_installed() {
        let temp_dir = tempfile::tempdir().unwrap();
        let program_dir = temp_dir.path().join("program");
        std::fs::create_dir_all(&program_dir).unwrap();
        let toolchain_path = temp_dir.path().join(".rialo-toolchain");
        std::fs::write(&toolchain_path, "0.0.3\n").unwrap();

        let resolved = resolve_version_for_program_with_sources(
            &program_dir,
            None,
            None,
            Some("8.8.8".to_string()),
            Some("7.7.7".to_string()),
        )
        .unwrap();

        assert_eq!(resolved.version, "0.0.3");
        assert_eq!(resolved.source, ToolchainSource::WorkspaceFile);
        assert_eq!(
            resolved.source_path,
            Some(toolchain_path.canonicalize().unwrap())
        );
    }

    #[test]
    fn install_lock_serializes_install_and_rustup_link_step() {
        let temp_dir = tempfile::tempdir().unwrap();
        let first_guard =
            RialoRustToolchain::acquire_install_lock_in_root(temp_dir.path()).unwrap();
        let (sender, receiver) = mpsc::channel();
        let lock_root = temp_dir.path().to_path_buf();

        let worker = std::thread::spawn(move || {
            let _guard = RialoRustToolchain::acquire_install_lock_in_root(&lock_root).unwrap();
            sender.send(()).unwrap();
        });

        assert!(receiver.recv_timeout(Duration::from_millis(250)).is_err());
        drop(first_guard);
        receiver.recv_timeout(Duration::from_secs(15)).unwrap();
        worker.join().unwrap();
    }
}