Skip to main content

sim_run_core/
crates_io.rs

1use std::{
2    cmp::Ordering,
3    fmt, fs,
4    path::{Path, PathBuf},
5    str::FromStr,
6};
7
8use crate::CliError;
9#[cfg(feature = "registry")]
10use crate::GitRegistryResolver;
11
12const DEFAULT_FALLBACK_REQ: &str = "^0.1";
13pub(crate) const ARTIFACT_FILE: &str = "artifact.simlib";
14
15/// A parsed `crates.io:NAME@REQ` source.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct CratesIoSpec {
18    /// crates.io package name.
19    pub package: String,
20    /// Version requirement applied to that package.
21    pub requirement: VersionReq,
22}
23
24impl CratesIoSpec {
25    /// Builds a spec from a package name and version requirement.
26    ///
27    /// Returns an error when the package name is empty.
28    ///
29    /// # Examples
30    ///
31    /// ```
32    /// use sim_run_core::CratesIoSpec;
33    ///
34    /// let spec = CratesIoSpec::new("sim-codec-lisp", "^0.1".parse().unwrap()).unwrap();
35    /// assert_eq!(spec.package, "sim-codec-lisp");
36    /// assert!(CratesIoSpec::new("", "*".parse().unwrap()).is_err());
37    /// ```
38    pub fn new(package: impl Into<String>, requirement: VersionReq) -> Result<Self, CliError> {
39        let package = package.into();
40        if package.is_empty() {
41            return Err(CliError::new("crates.io package name is empty"));
42        }
43        Ok(Self {
44            package,
45            requirement,
46        })
47    }
48}
49
50impl FromStr for CratesIoSpec {
51    type Err = CliError;
52
53    fn from_str(source: &str) -> Result<Self, Self::Err> {
54        let Some((package, requirement)) = source.split_once('@') else {
55            return Err(CliError::new("crates.io source must use NAME@REQ syntax"));
56        };
57        Self::new(package.to_owned(), requirement.parse::<VersionReq>()?)
58    }
59}
60
61impl fmt::Display for CratesIoSpec {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "{}@{}", self.package, self.requirement)
64    }
65}
66
67/// Version requirement syntax accepted by the CLI crates.io resolver.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct VersionReq {
70    raw: String,
71    kind: VersionReqKind,
72}
73
74impl VersionReq {
75    /// Reports whether a concrete version satisfies this requirement.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use sim_run_core::VersionReq;
81    ///
82    /// let caret: VersionReq = "^0.1".parse().unwrap();
83    /// assert!(caret.matches("0.1.9"));
84    /// assert!(!caret.matches("0.2.0"));
85    /// ```
86    pub fn matches(&self, version: &str) -> bool {
87        match &self.kind {
88            VersionReqKind::Any => true,
89            VersionReqKind::Exact(exact) => version == exact,
90            VersionReqKind::Caret(minimum) => {
91                compare_versions(version, minimum) != Ordering::Less
92                    && same_caret_range(version, minimum)
93            }
94        }
95    }
96
97    /// Returns the original requirement text.
98    pub fn as_str(&self) -> &str {
99        &self.raw
100    }
101}
102
103impl FromStr for VersionReq {
104    type Err = CliError;
105
106    fn from_str(source: &str) -> Result<Self, Self::Err> {
107        if source.is_empty() {
108            return Err(CliError::new("crates.io version requirement is empty"));
109        }
110        let kind = if source == "*" {
111            VersionReqKind::Any
112        } else if let Some(minimum) = source.strip_prefix('^') {
113            if minimum.is_empty() {
114                return Err(CliError::new("crates.io caret requirement is empty"));
115            }
116            VersionReqKind::Caret(minimum.to_owned())
117        } else if let Some(exact) = source.strip_prefix('=') {
118            if exact.is_empty() {
119                return Err(CliError::new("crates.io exact requirement is empty"));
120            }
121            VersionReqKind::Exact(exact.to_owned())
122        } else {
123            VersionReqKind::Exact(source.to_owned())
124        };
125        Ok(Self {
126            raw: source.to_owned(),
127            kind,
128        })
129    }
130}
131
132impl fmt::Display for VersionReq {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.write_str(&self.raw)
135    }
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
139enum VersionReqKind {
140    Any,
141    Exact(String),
142    Caret(String),
143}
144
145/// A crates.io source resolved to a local artifact path.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct ResolvedCratesIoSource {
148    /// The spec that was resolved.
149    pub requested: CratesIoSpec,
150    /// Resolved package name.
151    pub package: String,
152    /// Concrete version selected for the package.
153    pub version: String,
154    /// Local path to the resolved artifact.
155    pub artifact: PathBuf,
156}
157
158/// A crates.io artifact available without network access.
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub(crate) struct CratesIoListing {
161    pub(crate) package: String,
162    pub(crate) version: String,
163    pub(crate) artifact: PathBuf,
164    pub(crate) source: CratesIoListingSource,
165}
166
167/// Where an offline crates.io artifact listing came from.
168#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
169pub(crate) enum CratesIoListingSource {
170    Cache,
171    Registry,
172}
173
174/// crates.io-style artifact resolver owned by the CLI layer.
175///
176/// The default resolver performs **no network access**. It resolves a spec only
177/// from an already-seeded local cache or an explicitly registered registry
178/// artifact. With the `registry` feature, callers can install `GitRegistryResolver`
179/// so unresolved specs fetch from an explicit git registry artifact endpoint and
180/// then enter the same cache layout.
181#[derive(Clone, Debug)]
182pub struct CratesIoResolver {
183    cache_dir: PathBuf,
184    registry: Vec<RegistryArtifact>,
185    #[cfg(feature = "registry")]
186    git_registry: Option<GitRegistryResolver>,
187}
188
189impl CratesIoResolver {
190    /// Builds a cache-only resolver rooted at a cache directory.
191    pub fn new(cache_dir: PathBuf) -> Self {
192        Self {
193            cache_dir,
194            registry: Vec::new(),
195            #[cfg(feature = "registry")]
196            git_registry: None,
197        }
198    }
199
200    /// Returns the cache directory this resolver reads from.
201    pub fn cache_dir(&self) -> &Path {
202        &self.cache_dir
203    }
204
205    /// Registers an in-memory registry artifact available for resolution.
206    pub fn add_registry_artifact(
207        &mut self,
208        package: impl Into<String>,
209        version: impl Into<String>,
210        artifact: impl Into<PathBuf>,
211    ) {
212        self.registry.push(RegistryArtifact {
213            package: package.into(),
214            version: version.into(),
215            artifact: artifact.into(),
216        });
217    }
218
219    /// Registers an in-memory registry artifact, returning `self`.
220    pub fn with_registry_artifact(
221        mut self,
222        package: impl Into<String>,
223        version: impl Into<String>,
224        artifact: impl Into<PathBuf>,
225    ) -> Self {
226        self.add_registry_artifact(package, version, artifact);
227        self
228    }
229
230    /// Sets the networked git registry artifact resolver used after cache and
231    /// explicit in-memory registry misses.
232    #[cfg(feature = "registry")]
233    pub fn add_git_registry_resolver(&mut self, resolver: GitRegistryResolver) {
234        self.git_registry = Some(resolver);
235    }
236
237    /// Sets the networked git registry artifact resolver, returning `self`.
238    #[cfg(feature = "registry")]
239    pub fn with_git_registry_resolver(mut self, resolver: GitRegistryResolver) -> Self {
240        self.add_git_registry_resolver(resolver);
241        self
242    }
243
244    /// Builds a git registry resolver from an endpoint and this resolver's cache.
245    #[cfg(feature = "registry")]
246    pub fn with_git_registry_endpoint(
247        mut self,
248        endpoint: impl Into<String>,
249    ) -> Result<Self, CliError> {
250        let resolver = GitRegistryResolver::new(endpoint, self.cache_dir.clone())?;
251        self.add_git_registry_resolver(resolver);
252        Ok(self)
253    }
254
255    /// Builds a git registry resolver with platform-supplied cleartext policy.
256    #[cfg(feature = "registry")]
257    pub fn with_git_registry_endpoint_policy(
258        mut self,
259        endpoint: impl Into<String>,
260        allow_insecure_remote: bool,
261    ) -> Result<Self, CliError> {
262        let resolver = GitRegistryResolver::with_policy(
263            endpoint,
264            self.cache_dir.clone(),
265            allow_insecure_remote,
266        )?;
267        self.add_git_registry_resolver(resolver);
268        Ok(self)
269    }
270
271    /// Resolves a spec to a cached artifact, seeding the cache when needed.
272    ///
273    /// Prefers an already-cached artifact, then a registered registry artifact.
274    /// With the `registry` feature and an installed git registry resolver, misses
275    /// can fetch through that resolver. Otherwise misses fail closed with a
276    /// clear cache-only error rather than pretending to fetch one.
277    pub fn resolve(&self, spec: &CratesIoSpec) -> Result<ResolvedCratesIoSource, CliError> {
278        if let Some((version, artifact)) = self.cached_artifact(spec)? {
279            return Ok(ResolvedCratesIoSource {
280                requested: spec.clone(),
281                package: spec.package.clone(),
282                version,
283                artifact,
284            });
285        }
286        if let Some(entry) = self.registry_artifact(spec) {
287            let artifact = self.cache_artifact(&entry)?;
288            return Ok(ResolvedCratesIoSource {
289                requested: spec.clone(),
290                package: entry.package,
291                version: entry.version,
292                artifact,
293            });
294        }
295        #[cfg(feature = "registry")]
296        if let Some(git_registry) = &self.git_registry {
297            return git_registry.resolve(spec);
298        }
299        Err(CliError::new(format!(
300            "crates.io network fetch is not implemented (cache-only resolver); seed the cache for {spec}"
301        )))
302    }
303
304    pub(crate) fn available_artifacts(&self) -> Result<Vec<CratesIoListing>, CliError> {
305        let mut listings = self.registry_artifact_listings();
306        listings.extend(self.cached_artifact_listings()?);
307        listings.sort_by(|left, right| {
308            left.package
309                .cmp(&right.package)
310                .then_with(|| compare_versions(&right.version, &left.version))
311                .then_with(|| left.artifact.cmp(&right.artifact))
312                .then_with(|| left.source.cmp(&right.source))
313        });
314        Ok(listings)
315    }
316
317    fn registry_artifact_listings(&self) -> Vec<CratesIoListing> {
318        self.registry
319            .iter()
320            .map(|entry| CratesIoListing {
321                package: entry.package.clone(),
322                version: entry.version.clone(),
323                artifact: entry.artifact.clone(),
324                source: CratesIoListingSource::Registry,
325            })
326            .collect()
327    }
328
329    fn cached_artifact_listings(&self) -> Result<Vec<CratesIoListing>, CliError> {
330        let root = self.cache_dir.join("crates.io");
331        let Ok(package_entries) = fs::read_dir(&root) else {
332            return Ok(Vec::new());
333        };
334        let mut listings = Vec::new();
335        for package_entry in package_entries {
336            let package_entry = package_entry.map_err(|err| {
337                CliError::new(format!("read crates.io cache {}: {err}", root.display()))
338            })?;
339            if !package_entry
340                .file_type()
341                .map(|ty| ty.is_dir())
342                .unwrap_or(false)
343            {
344                continue;
345            }
346            let package = package_entry.file_name().to_string_lossy().into_owned();
347            let version_root = package_entry.path();
348            for version_entry in fs::read_dir(&version_root).map_err(|err| {
349                CliError::new(format!(
350                    "read crates.io cache {}: {err}",
351                    version_root.display()
352                ))
353            })? {
354                let version_entry = version_entry.map_err(|err| {
355                    CliError::new(format!(
356                        "read crates.io cache {}: {err}",
357                        version_root.display()
358                    ))
359                })?;
360                if !version_entry
361                    .file_type()
362                    .map(|ty| ty.is_dir())
363                    .unwrap_or(false)
364                {
365                    continue;
366                }
367                if let Some(artifact) = cached_artifact_file(&version_entry.path())? {
368                    listings.push(CratesIoListing {
369                        package: package.clone(),
370                        version: version_entry.file_name().to_string_lossy().into_owned(),
371                        artifact,
372                        source: CratesIoListingSource::Cache,
373                    });
374                }
375            }
376        }
377        Ok(listings)
378    }
379
380    fn cached_artifact(&self, spec: &CratesIoSpec) -> Result<Option<(String, PathBuf)>, CliError> {
381        let package_dir = self.cache_dir.join("crates.io").join(&spec.package);
382        let Ok(entries) = fs::read_dir(&package_dir) else {
383            return Ok(None);
384        };
385        let mut matches = Vec::new();
386        for entry in entries {
387            let entry = entry.map_err(|err| {
388                CliError::new(format!(
389                    "read crates.io cache {}: {err}",
390                    package_dir.display()
391                ))
392            })?;
393            if !entry.file_type().map(|ty| ty.is_dir()).unwrap_or(false) {
394                continue;
395            }
396            let version = entry.file_name().to_string_lossy().into_owned();
397            if let Some(artifact) = cached_artifact_file(&entry.path())?
398                && spec.requirement.matches(&version)
399            {
400                matches.push((version, artifact));
401            }
402        }
403        matches.sort_by(|left, right| compare_versions(&right.0, &left.0));
404        Ok(matches.into_iter().next())
405    }
406
407    fn registry_artifact(&self, spec: &CratesIoSpec) -> Option<RegistryArtifact> {
408        let mut matches = self
409            .registry
410            .iter()
411            .filter(|entry| {
412                entry.package == spec.package && spec.requirement.matches(&entry.version)
413            })
414            .cloned()
415            .collect::<Vec<_>>();
416        matches.sort_by(|left, right| compare_versions(&right.version, &left.version));
417        matches.into_iter().next()
418    }
419
420    fn cache_artifact(&self, entry: &RegistryArtifact) -> Result<PathBuf, CliError> {
421        let artifact = cache_artifact_path(&self.cache_dir, &entry.package, &entry.version);
422        let parent = artifact
423            .parent()
424            .ok_or_else(|| CliError::new("crates.io cache artifact has no parent"))?;
425        fs::create_dir_all(parent)
426            .map_err(|err| CliError::new(format!("create crates.io cache: {err}")))?;
427        fs::copy(&entry.artifact, &artifact).map_err(|err| {
428            CliError::new(format!(
429                "cache crates.io artifact {}: {err}",
430                entry.artifact.display()
431            ))
432        })?;
433        Ok(artifact)
434    }
435}
436
437impl Default for CratesIoResolver {
438    fn default() -> Self {
439        Self::new(PathBuf::from(".sim/cache/libs"))
440    }
441}
442
443#[derive(Clone, Debug)]
444struct RegistryArtifact {
445    package: String,
446    version: String,
447    artifact: PathBuf,
448}
449
450pub(crate) fn fallback_spec_for_symbol(symbol: &str) -> Option<CratesIoSpec> {
451    if let Some(codec) = symbol.strip_prefix("codec/") {
452        return fallback_spec(format!("sim-codec-{codec}"));
453    }
454    if !symbol.is_empty() && !symbol.contains('/') {
455        return fallback_spec(format!("sim-lib-{symbol}"));
456    }
457    None
458}
459
460fn fallback_spec(package: String) -> Option<CratesIoSpec> {
461    CratesIoSpec::new(package, DEFAULT_FALLBACK_REQ.parse().ok()?).ok()
462}
463
464pub(crate) fn cache_artifact_path(cache_dir: &Path, package: &str, version: &str) -> PathBuf {
465    cache_artifact_path_with_file(cache_dir, package, version, ARTIFACT_FILE)
466}
467
468pub(crate) fn cache_artifact_path_with_file(
469    cache_dir: &Path,
470    package: &str,
471    version: &str,
472    file_name: &str,
473) -> PathBuf {
474    cache_dir
475        .join("crates.io")
476        .join(package)
477        .join(version)
478        .join(file_name)
479}
480
481fn cached_artifact_file(version_dir: &Path) -> Result<Option<PathBuf>, CliError> {
482    let preferred = version_dir.join(ARTIFACT_FILE);
483    if preferred.is_file() {
484        return Ok(Some(preferred));
485    }
486    let Ok(entries) = fs::read_dir(version_dir) else {
487        return Ok(None);
488    };
489    let mut files = Vec::new();
490    for entry in entries {
491        let entry = entry.map_err(|err| {
492            CliError::new(format!(
493                "read crates.io cache {}: {err}",
494                version_dir.display()
495            ))
496        })?;
497        if entry.file_type().map(|ty| ty.is_file()).unwrap_or(false) {
498            files.push(entry.path());
499        }
500    }
501    files.sort();
502    Ok(files.into_iter().next())
503}
504
505pub(crate) fn compare_versions(left: &str, right: &str) -> Ordering {
506    let left = version_components(left);
507    let right = version_components(right);
508    let len = left.len().max(right.len());
509    for index in 0..len {
510        let ordering = left
511            .get(index)
512            .copied()
513            .unwrap_or(0)
514            .cmp(&right.get(index).copied().unwrap_or(0));
515        if ordering != Ordering::Equal {
516            return ordering;
517        }
518    }
519    Ordering::Equal
520}
521
522fn same_caret_range(version: &str, minimum: &str) -> bool {
523    let version = version_components(version);
524    let minimum = version_components(minimum);
525    let major = *minimum.first().unwrap_or(&0);
526    let minor = *minimum.get(1).unwrap_or(&0);
527    let patch = *minimum.get(2).unwrap_or(&0);
528    if major > 0 {
529        version.first() == Some(&major)
530    } else if minor > 0 {
531        version.first() == Some(&0) && version.get(1) == Some(&minor)
532    } else {
533        version.first() == Some(&0) && version.get(1) == Some(&0) && version.get(2) == Some(&patch)
534    }
535}
536
537fn version_components(version: &str) -> Vec<u64> {
538    version
539        .split('.')
540        .map(|part| {
541            part.chars()
542                .take_while(|ch| ch.is_ascii_digit())
543                .collect::<String>()
544                .parse::<u64>()
545                .unwrap_or(0)
546        })
547        .collect()
548}
549
550#[cfg(test)]
551mod tests {
552    use super::*;
553
554    #[test]
555    fn parses_crates_io_specs_and_requirements() {
556        let exact = "sim-codec-lisp@0.1.0".parse::<CratesIoSpec>().unwrap();
557        assert_eq!(exact.package, "sim-codec-lisp");
558        assert_eq!(exact.requirement.as_str(), "0.1.0");
559        assert!(exact.requirement.matches("0.1.0"));
560        assert!(!exact.requirement.matches("0.1.1"));
561
562        let caret = "sim-lib-demo@^0.1".parse::<CratesIoSpec>().unwrap();
563        assert!(caret.requirement.matches("0.1.0"));
564        assert!(caret.requirement.matches("0.1.9"));
565        assert!(!caret.requirement.matches("0.2.0"));
566    }
567
568    #[test]
569    fn cache_hit_resolves_without_registry() {
570        let cache = temp_dir("cache-hit");
571        let artifact = cache_artifact_path(&cache, "sim-lib-demo", "0.1.0");
572        fs::create_dir_all(artifact.parent().unwrap()).unwrap();
573        fs::write(&artifact, b"cached").unwrap();
574        let resolver = CratesIoResolver::new(cache.clone());
575
576        let resolved = resolver
577            .resolve(&"sim-lib-demo@0.1.0".parse().unwrap())
578            .unwrap();
579
580        assert_eq!(resolved.version, "0.1.0");
581        assert_eq!(resolved.artifact, artifact);
582        let _ = fs::remove_dir_all(cache);
583    }
584
585    #[test]
586    fn cache_miss_is_a_clear_cache_only_failure() {
587        let cache = temp_dir("cache-miss");
588        let resolver = CratesIoResolver::new(cache.clone());
589
590        let err = resolver
591            .resolve(&"sim-lib-demo@0.1.0".parse().unwrap())
592            .unwrap_err();
593
594        assert_eq!(
595            err.to_string(),
596            "crates.io network fetch is not implemented (cache-only resolver); \
597             seed the cache for sim-lib-demo@0.1.0"
598        );
599        let _ = fs::remove_dir_all(cache);
600    }
601
602    #[test]
603    fn fake_registry_resolve_caches_artifact() {
604        let cache = temp_dir("fake-registry-cache");
605        let source_dir = temp_dir("fake-registry-source");
606        fs::create_dir_all(&source_dir).unwrap();
607        let source_artifact = source_dir.join("artifact.simlib");
608        fs::write(&source_artifact, b"registry").unwrap();
609        let resolver = CratesIoResolver::new(cache.clone()).with_registry_artifact(
610            "sim-lib-demo",
611            "0.1.2",
612            source_artifact,
613        );
614
615        let resolved = resolver
616            .resolve(&"sim-lib-demo@^0.1".parse().unwrap())
617            .unwrap();
618
619        assert_eq!(resolved.version, "0.1.2");
620        assert_eq!(fs::read(resolved.artifact).unwrap(), b"registry");
621        let _ = fs::remove_dir_all(cache);
622        let _ = fs::remove_dir_all(source_dir);
623    }
624
625    #[test]
626    fn fallback_mapping_names_codec_and_lib_packages() {
627        assert_eq!(
628            fallback_spec_for_symbol("codec/lisp").unwrap().to_string(),
629            "sim-codec-lisp@^0.1"
630        );
631        assert_eq!(
632            fallback_spec_for_symbol("demo").unwrap().to_string(),
633            "sim-lib-demo@^0.1"
634        );
635        assert!(fallback_spec_for_symbol("domain/demo").is_none());
636    }
637
638    fn temp_dir(label: &str) -> PathBuf {
639        PathBuf::from("target/model-fixtures").join(format!("sim-run-core-crates-{label}"))
640    }
641}