Skip to main content

lux_lib/pipeline/
resolve.rs

1use crate::lockfile::locked_package;
2use crate::package;
3use crate::remote;
4use crate::rockspec;
5use std::collections::{HashMap, HashSet, VecDeque};
6use std::sync::Arc;
7
8use bon::Builder;
9use itertools::Itertools;
10use miette::Diagnostic;
11use thiserror::Error;
12use tokio::task::JoinSet;
13
14use crate::{
15    build,
16    config::Config,
17    lockfile::{
18        LockedPackage, LockedPackageLockType, OptState, PinnedState, RemotePackageSourceUrl,
19    },
20    operations::install,
21    package::db::PackageDB,
22    rockspec::Rockspec,
23    tree::EntryType,
24};
25
26use super::{
27    discover::{self, Discover, FoundPackage},
28    materialise::PackageSource,
29    Artifacts,
30};
31
32/// The build dependencies of a rockspec that still need to be installed, with the
33/// LuaRocks build backend (if any) first.
34pub(crate) fn build_dependencies_to_install<R: Rockspec>(rockspec: &R) -> Vec<package::Name> {
35    let mut names = rockspec
36        .build_dependencies()
37        .current_platform()
38        .iter()
39        .filter(|dep| {
40            !matches!(
41                dep.name().to_string().as_str(),
42                "luarocks-build-rust-mlua"
43                    | "luarocks-build-rust-binary"
44                    | "luarocks-build-treesitter-parser"
45            )
46        })
47        .map(|dep| dep.name().clone())
48        .collect_vec();
49
50    if let Some(backend) = luarocks_build_backend_name(rockspec) {
51        names.insert(0, backend);
52    }
53    names
54}
55
56/// The name of the luarocks build backend rock required to build this rockspec (if any).
57pub(crate) fn luarocks_build_backend_name<R: Rockspec>(rockspec: &R) -> Option<package::Name> {
58    match &rockspec.build().current_platform().backend {
59        Some(rockspec::build::backend::Spec::LuaRock(backend)) => {
60            Some(package::Name::new(format!("luarocks-build-{backend}")))
61        }
62        _ => None,
63    }
64}
65
66pub(crate) struct ResolvedPackage {
67    pub(crate) spec: locked_package::Spec,
68    pub(crate) rockspec: rockspec::lua::Remote,
69    pub(crate) source: remote::package::Source,
70    pub(crate) source_url: Option<RemotePackageSourceUrl>,
71    pub(crate) entry_type: EntryType,
72    pub(crate) build_behaviour: build::Behaviour,
73    pub(crate) artifact: Option<PackageSource>,
74}
75
76pub(crate) type ResolvedArtifacts = Artifacts<HashMap<locked_package::ID, ResolvedPackage>>;
77
78#[derive(Error, Debug, Diagnostic)]
79#[non_exhaustive]
80pub enum Error {
81    #[error(transparent)]
82    #[diagnostic(transparent)]
83    Discover(#[from] Box<discover::Error>),
84    #[error("cyclic dependency detected:\n{0}")]
85    CyclicDependency(String),
86    #[error(transparent)]
87    Join(#[from] tokio::task::JoinError),
88}
89
90impl From<discover::Error> for Error {
91    fn from(err: discover::Error) -> Self {
92        Self::Discover(Box::new(err))
93    }
94}
95
96#[derive(Builder)]
97#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
98pub(crate) struct ResolvePackageDependencies<'a> {
99    #[builder(start_fn)]
100    pub(crate) package_db: PackageDB,
101    #[builder(start_fn)]
102    pub(crate) config: &'a Config,
103    #[builder(field)]
104    pub(crate) packages: Artifacts<Vec<install::Spec>>,
105    #[builder(default)]
106    pub(crate) installed: HashMap<LockedPackageLockType, Vec<LockedPackage>>,
107}
108
109impl<State> ResolvePackageDependenciesBuilder<'_, State>
110where
111    State: resolve_package_dependencies_builder::State,
112{
113    fn set(mut self, section: LockedPackageLockType, packages: Vec<install::Spec>) -> Self {
114        *self.packages.get_mut(section) = Some(packages);
115        self
116    }
117
118    pub(crate) fn packages(self, packages: Vec<install::Spec>) -> Self {
119        self.set(LockedPackageLockType::Regular, packages)
120    }
121
122    pub(crate) fn build_packages(self, packages: Vec<install::Spec>) -> Self {
123        self.set(LockedPackageLockType::Build, packages)
124    }
125
126    pub(crate) fn test_packages(self, packages: Vec<install::Spec>) -> Self {
127        self.set(LockedPackageLockType::Test, packages)
128    }
129}
130
131impl<State> ResolvePackageDependenciesBuilder<'_, State>
132where
133    State: resolve_package_dependencies_builder::State
134        + resolve_package_dependencies_builder::IsComplete,
135{
136    pub(crate) async fn resolve(self) -> Result<ResolvedArtifacts, Error> {
137        let args = self._build();
138        Resolver::new(args.package_db, args.config, args.installed)
139            .run(args.packages)
140            .await
141    }
142}
143
144/// Identifies a single discovery request. Two requests with the same key resolve to the
145/// same package, so the diamond problem is solved by only discovering each key once.
146#[derive(Clone, PartialEq, Eq, Hash)]
147struct RequestKey {
148    section: LockedPackageLockType,
149    package: package::Req,
150    pin: PinnedState,
151    opt: OptState,
152}
153
154impl RequestKey {
155    fn from_install_spec(section: LockedPackageLockType, spec: &install::Spec) -> Self {
156        Self {
157            section,
158            package: spec.package.clone(),
159            pin: spec.pin,
160            opt: spec.opt,
161        }
162    }
163}
164
165/// A discovered node in the dependency graph.
166struct Node {
167    install_spec: install::Spec,
168    id: locked_package::ID,
169    found: FoundPackage,
170    children: Vec<(bool, RequestKey)>,
171}
172
173struct Resolver {
174    package_db: PackageDB,
175    config: Arc<Config>,
176    max_concurrent: usize,
177    joinset: JoinSet<(RequestKey, install::Spec, Result<FoundPackage, Error>)>,
178    pending: VecDeque<(RequestKey, install::Spec)>,
179    seen: HashSet<RequestKey>,
180    nodes: HashMap<RequestKey, Node>,
181    resolved: ResolvedArtifacts,
182    installed: HashMap<LockedPackageLockType, Vec<LockedPackage>>,
183    installed_ids: HashMap<RequestKey, locked_package::ID>,
184}
185
186impl Resolver {
187    fn new(
188        package_db: PackageDB,
189        config: &Config,
190        installed: HashMap<LockedPackageLockType, Vec<LockedPackage>>,
191    ) -> Self {
192        Self::with_max_concurrent(
193            package_db,
194            Arc::new(config.clone()),
195            config.max_jobs(),
196            installed,
197        )
198    }
199
200    fn with_max_concurrent(
201        package_db: PackageDB,
202        config: Arc<Config>,
203        max_concurrent: usize,
204        installed: HashMap<LockedPackageLockType, Vec<LockedPackage>>,
205    ) -> Self {
206        Self {
207            package_db,
208            config,
209            max_concurrent,
210            joinset: JoinSet::new(),
211            pending: VecDeque::new(),
212            seen: HashSet::new(),
213            nodes: HashMap::new(),
214            resolved: ResolvedArtifacts::default(),
215            installed,
216            installed_ids: HashMap::new(),
217        }
218    }
219
220    async fn run(
221        mut self,
222        packages: Artifacts<Vec<install::Spec>>,
223    ) -> Result<ResolvedArtifacts, Error> {
224        for (section, specs) in packages {
225            let Some(specs) = specs else {
226                continue;
227            };
228            // Mark the section as requested even if it resolves to nothing.
229            self.resolved
230                .get_mut(section)
231                .get_or_insert_with(HashMap::new);
232            for spec in specs {
233                let key = RequestKey::from_install_spec(section, &spec);
234                self.enqueue(key, spec);
235            }
236        }
237
238        self.spawn_ready();
239        while let Some(joined) = self.joinset.join_next().await {
240            let (key, spec, result) = joined.map_err(Error::Join)?;
241            self.on_discovered(key, spec, result?);
242            self.spawn_ready();
243        }
244
245        detect_cycles(&self.nodes)?;
246        Ok(self.assemble())
247    }
248
249    /// Registers a request for discovery, unless it has already been seen.
250    fn enqueue(&mut self, key: RequestKey, spec: install::Spec) {
251        if self.seen.insert(key.clone()) {
252            self.pending.push_back((key, spec));
253        }
254    }
255
256    /// Spawns queued discoveries up to the configured concurrency limit.
257    fn spawn_ready(&mut self) {
258        while self.joinset.len() < self.max_concurrent {
259            let Some((key, spec)) = self.pending.pop_front() else {
260                break;
261            };
262            let package_db = self.package_db.clone();
263            let config = Arc::clone(&self.config);
264            let task_spec = spec.clone();
265            self.joinset.spawn(async move {
266                let result = Discover::new(package_db, &config)
267                    .discover(&task_spec)
268                    .await
269                    .map_err(|err| err.into());
270                (key, spec, result)
271            });
272        }
273    }
274
275    /// Records a discovered package and queues any children it introduces.
276    fn on_discovered(&mut self, key: RequestKey, spec: install::Spec, found: FoundPackage) {
277        let section = key.section;
278        let is_binary = matches!(
279            found.remote.source,
280            remote::package::Source::LuarocksBinaryRock(_)
281        );
282        let constraint = spec
283            .constraint
284            .clone()
285            .unwrap_or_else(|| spec.package.version_req().clone().into());
286        let id = locked_package::ID::new(
287            found.remote.spec.name(),
288            found.remote.spec.version(),
289            spec.pin,
290            spec.opt,
291            constraint,
292        );
293
294        let mut child_specs: Vec<(bool, RequestKey, install::Spec)> = Vec::new();
295        if !is_binary {
296            for child_spec in build_dependency_specs(&found.rockspec, &spec) {
297                push_child(&mut child_specs, true, section, child_spec);
298            }
299        }
300        for dependency in found.rockspec.dependencies().current_platform() {
301            let child_spec =
302                install::Spec::new(dependency.package_req().clone(), EntryType::DependencyOnly)
303                    .build_behaviour(build::Behaviour::Ignore)
304                    .pin(spec.pin)
305                    .opt(spec.opt)
306                    .maybe_source(dependency.source().clone())
307                    .build();
308            push_child(&mut child_specs, false, section, child_spec);
309        }
310
311        let children = child_specs
312            .iter()
313            .map(|(is_build, child_key, _)| (*is_build, child_key.clone()))
314            .collect();
315        self.resolved
316            .get_mut(section)
317            .get_or_insert_with(HashMap::new);
318        self.nodes.insert(
319            key,
320            Node {
321                install_spec: spec,
322                id,
323                found,
324                children,
325            },
326        );
327
328        for (is_build, child_key, child_spec) in child_specs {
329            let child_section = if is_build {
330                LockedPackageLockType::Build
331            } else {
332                section
333            };
334            if let Some(installed_id) = self.installed_match(child_section, &child_spec) {
335                self.installed_ids.insert(child_key, installed_id);
336            } else {
337                self.enqueue(child_key, child_spec);
338            }
339        }
340    }
341
342    fn installed_match(
343        &self,
344        section: LockedPackageLockType,
345        spec: &install::Spec,
346    ) -> Option<locked_package::ID> {
347        if !matches!(spec.build_behaviour, build::Behaviour::Ignore) || spec.source.is_some() {
348            return None;
349        }
350        self.installed
351            .get(&section)?
352            .iter()
353            .rev()
354            .find(|package| {
355                package.name() == spec.package.name()
356                    && spec.package.version_req().matches(package.version())
357            })
358            .map(|package| package.id())
359    }
360
361    /// Computes the final specs and assembles the resolved packages now that discovery is
362    /// complete and every child id is known.
363    fn assemble(self) -> ResolvedArtifacts {
364        let Resolver {
365            nodes,
366            mut resolved,
367            installed_ids,
368            ..
369        } = self;
370
371        let mut ids: HashMap<RequestKey, locked_package::ID> = nodes
372            .iter()
373            .map(|(key, node)| (key.clone(), node.id.clone()))
374            .collect();
375        for (key, id) in installed_ids {
376            ids.entry(key).or_insert(id);
377        }
378
379        for (key, node) in nodes {
380            let Node {
381                install_spec,
382                id,
383                found,
384                children,
385            } = node;
386            let dependencies = children
387                .iter()
388                .filter(|(is_build, _)| !is_build)
389                .map(|(_, child)| ids[child].clone())
390                .collect_vec();
391            let build_dependencies = children
392                .iter()
393                .filter(|(is_build, _)| *is_build)
394                .map(|(_, child)| ids[child].clone())
395                .collect_vec();
396            let constraint = install_spec
397                .constraint
398                .clone()
399                .unwrap_or_else(|| install_spec.package.version_req().clone().into());
400
401            let spec = locked_package::Spec::new(
402                found.remote.spec.name(),
403                found.remote.spec.version(),
404                constraint,
405                dependencies,
406                build_dependencies,
407                &install_spec.pin,
408                &install_spec.opt,
409            );
410            let package = ResolvedPackage {
411                spec,
412                rockspec: found.rockspec,
413                source: found.remote.source,
414                source_url: found.remote.source_url,
415                entry_type: install_spec.entry_type,
416                build_behaviour: install_spec.build_behaviour,
417                artifact: found.artifact,
418            };
419
420            resolved
421                .get_mut(key.section)
422                .get_or_insert_with(HashMap::new)
423                .entry(id)
424                .or_insert(package);
425        }
426
427        resolved
428    }
429}
430
431/// Adds a child request unless an equivalent request is already present.
432fn push_child(
433    children: &mut Vec<(bool, RequestKey, install::Spec)>,
434    is_build: bool,
435    section: LockedPackageLockType,
436    spec: install::Spec,
437) {
438    let child_section = if is_build {
439        LockedPackageLockType::Build
440    } else {
441        section
442    };
443    let child_key = RequestKey::from_install_spec(child_section, &spec);
444    if !children
445        .iter()
446        .any(|(_, existing, _)| existing == &child_key)
447    {
448        children.push((is_build, child_key, spec));
449    }
450}
451
452/// Graph colouring algorithm for cycle detection.
453fn detect_cycles(nodes: &HashMap<RequestKey, Node>) -> Result<(), Error> {
454    #[derive(Clone, Copy, PartialEq, Eq)]
455    enum Colour {
456        /// Not yet visited
457        White,
458        /// On path: revisiting it indicates a cycle
459        Grey,
460        /// Fully explored
461        Black,
462    }
463
464    let mut colors: HashMap<&RequestKey, Colour> = HashMap::with_capacity(nodes.len());
465
466    for start in nodes.keys() {
467        if colors.get(start).copied().unwrap_or(Colour::White) != Colour::White {
468            continue;
469        }
470        colors.insert(start, Colour::Grey);
471        let mut stack: Vec<(&RequestKey, usize)> = vec![(start, 0)];
472        let mut path: Vec<&RequestKey> = vec![start];
473
474        while let Some(&(node, index)) = stack.last() {
475            let children = &nodes[node].children;
476            if index < children.len() {
477                if let Some(top) = stack.last_mut() {
478                    top.1 += 1;
479                }
480                let child = &children[index].1;
481                if !nodes.contains_key(child) {
482                    continue;
483                }
484                match colors.get(child).copied().unwrap_or(Colour::White) {
485                    Colour::White => {
486                        colors.insert(child, Colour::Grey);
487                        path.push(child);
488                        stack.push((child, 0));
489                    }
490                    Colour::Grey => {
491                        let Some(position) = path.iter().position(|key| *key == child) else {
492                            continue;
493                        };
494                        let chain = path[position..]
495                            .iter()
496                            .map(|key| key.package.name().to_string())
497                            .chain(std::iter::once(child.package.name().to_string()))
498                            .collect_vec()
499                            .join(" -> ");
500                        return Err(Error::CyclicDependency(chain));
501                    }
502                    Colour::Black => {}
503                }
504            } else {
505                colors.insert(node, Colour::Black);
506                stack.pop();
507                path.pop();
508            }
509        }
510    }
511
512    Ok(())
513}
514
515fn build_dependency_specs(
516    rockspec: &rockspec::lua::Remote,
517    parent: &install::Spec,
518) -> Vec<install::Spec> {
519    build_dependencies_to_install(rockspec)
520        .into_iter()
521        .filter_map(|name| {
522            rockspec
523                .build_dependencies()
524                .current_platform()
525                .iter()
526                .find(|dep| dep.name() == &name)
527                .map(|dep| {
528                    install::Spec::new(dep.package_req().clone(), EntryType::Entrypoint)
529                        .build_behaviour(build::Behaviour::Ignore)
530                        .pin(parent.pin)
531                        .opt(parent.opt)
532                        .maybe_source(dep.source().clone())
533                        .build()
534                })
535                .or_else(|| {
536                    Some(
537                        install::Spec::new(package::Req::from(name), EntryType::Entrypoint)
538                            .build_behaviour(build::Behaviour::Ignore)
539                            .pin(parent.pin)
540                            .opt(parent.opt)
541                            .build(),
542                    )
543                })
544        })
545        .collect()
546}
547
548#[cfg(test)]
549mod tests {
550    use std::sync::Arc;
551
552    use super::*;
553    use crate::config;
554    use crate::lockfile::locked_package;
555    use crate::lockfile::{self};
556    use crate::remote;
557
558    fn rockspec(package: &str, dependencies: &[&str]) -> String {
559        let dependencies = if dependencies.is_empty() {
560            String::new()
561        } else {
562            let list = dependencies
563                .iter()
564                .map(|dependency| format!("'{dependency}'"))
565                .collect::<Vec<_>>()
566                .join(", ");
567            format!("\ndependencies = {{ {list} }}")
568        };
569        format!(
570            "rockspec_format = '1.0'\npackage = '{package}'\nversion = '1.0.0-1'\nsource = {{ url = 'https://example.com/{package}.zip' }}{dependencies}"
571        )
572    }
573
574    fn local_packages(rockspecs: &[String]) -> PackageDB {
575        PackageDB::from_local(
576            rockspecs
577                .iter()
578                .map(|content| {
579                    let rockspec = match rockspec::lua::Remote::new(content) {
580                        Ok(rockspec) => rockspec,
581                        Err(err) => unreachable!("invalid test rockspec: {err}"),
582                    };
583                    FoundPackage {
584                        remote: remote::Package::new(
585                            package::Spec::new(
586                                rockspec.package().clone(),
587                                rockspec.version().clone(),
588                            ),
589                            remote::package::Source::RockspecContent(content.clone()),
590                            None,
591                        ),
592                        rockspec,
593                        artifact: None,
594                    }
595                })
596                .collect(),
597        )
598    }
599
600    fn install_spec(name: &str) -> install::Spec {
601        let package = match name.parse::<package::Req>() {
602            Ok(package) => package,
603            Err(err) => unreachable!("invalid package req: {err}"),
604        };
605        install::Spec::new(package, EntryType::Entrypoint)
606            .build_behaviour(build::Behaviour::Ignore)
607            .build()
608    }
609
610    fn installed_package(name: &str) -> LockedPackage {
611        let spec = package::Spec::parse(name.to_string(), "1.0.0-1".to_string()).unwrap();
612        LockedPackage::from(
613            &spec,
614            lockfile::Constraint::Unconstrained,
615            remote::package::Source::Test,
616            None,
617            locked_package::Hashes {
618                rockspec: "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
619                    .parse()
620                    .unwrap(),
621                source: "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
622                    .parse()
623                    .unwrap(),
624            },
625        )
626    }
627
628    fn roots(spec: install::Spec) -> Artifacts<Vec<install::Spec>> {
629        Artifacts {
630            regular: Some(vec![spec]),
631            build: None,
632            test: None,
633        }
634    }
635
636    fn test_config() -> Arc<Config> {
637        let builder = match config::Builder::new() {
638            Ok(builder) => builder,
639            Err(err) => unreachable!("invalid test config: {err}"),
640        };
641        let config = match builder.build() {
642            Ok(config) => config,
643            Err(err) => unreachable!("invalid test config: {err}"),
644        };
645        Arc::new(config)
646    }
647
648    #[tokio::test]
649    async fn diamond_problem() {
650        let packages = local_packages(&[
651            rockspec("a", &["b", "c"]),
652            rockspec("b", &["d"]),
653            rockspec("c", &["d"]),
654            rockspec("d", &[]),
655        ]);
656
657        let resolved =
658            match Resolver::with_max_concurrent(packages, test_config(), 8, HashMap::new())
659                .run(roots(install_spec("a")))
660                .await
661            {
662                Ok(resolved) => resolved,
663                Err(err) => panic!("resolution failed: {err}"),
664            };
665
666        assert_eq!(resolved.regular.as_ref().map(|rocks| rocks.len()), Some(4));
667    }
668
669    #[tokio::test]
670    async fn installed_dependency_is_reused() {
671        let packages = local_packages(&[rockspec("a", &["d"])]);
672        let installed =
673            HashMap::from([(LockedPackageLockType::Regular, vec![installed_package("d")])]);
674
675        let resolved = Resolver::with_max_concurrent(packages, test_config(), 8, installed)
676            .run(roots(install_spec("a")))
677            .await
678            .unwrap();
679
680        assert_eq!(resolved.regular.as_ref().map(|rocks| rocks.len()), Some(1));
681    }
682
683    #[tokio::test]
684    async fn cyclic_dependencies_are_rejected() {
685        let packages = local_packages(&[rockspec("a", &["b"]), rockspec("b", &["a"])]);
686
687        let result = Resolver::with_max_concurrent(packages, test_config(), 8, HashMap::new())
688            .run(roots(install_spec("a")))
689            .await;
690
691        assert!(matches!(result, Err(Error::CyclicDependency(_))));
692    }
693}