Skip to main content

lux_lib/operations/install/
mod.rs

1use std::{collections::HashMap, io, sync::Arc};
2
3use crate::{
4    build::{Build, BuildBehaviour, BuildError, RemotePackageSourceSpec, SrcRockSource},
5    config::Config,
6    lockfile::{
7        FlushLockfileError, LocalPackage, LocalPackageId, LockConstraint, Lockfile, OptState,
8        PinnedState, ReadWrite,
9    },
10    lua_installation::{LuaInstallation, LuaInstallationError},
11    lua_rockspec::BuildBackendSpec,
12    lua_version::LuaVersionUnset,
13    luarocks::{
14        install_binary_rock::{BinaryRockInstall, InstallBinaryRockError},
15        luarocks_installation::{LuaRocksError, LuaRocksInstallError, LuaRocksInstallation},
16    },
17    operations::resolve::{Resolve, ResolveDependenciesError},
18    package::{PackageName, PackageNameList},
19    progress::{MultiProgress, Progress, ProgressBar},
20    remote_package_db::{RemotePackageDB, RemotePackageDBError, RemotePackageDbIntegrityError},
21    rockspec::Rockspec,
22    tree::{self, InstallTree, Tree, TreeError},
23    workspace::{Workspace, WorkspaceTreeError},
24};
25
26pub use crate::operations::install::spec::PackageInstallSpec;
27
28use super::{DownloadedRockspec, RemoteRockDownload};
29use bon::Builder;
30use bytes::Bytes;
31use futures::StreamExt;
32use itertools::Itertools;
33use miette::Diagnostic;
34use thiserror::Error;
35
36pub mod spec;
37
38/// A rocks package installer, providing fine-grained control
39/// over how packages should be installed.
40/// Can install multiple packages in parallel.
41#[derive(Builder)]
42#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
43pub struct Install<'a, T>
44where
45    T: InstallTree + Clone + Send + Sync,
46{
47    #[builder(start_fn)]
48    config: &'a Config,
49    #[builder(field)]
50    packages: Vec<PackageInstallSpec>,
51    #[builder(setters(name = "_tree", vis = ""))]
52    tree: T,
53    package_db: Option<RemotePackageDB>,
54    progress: Option<Arc<Progress<MultiProgress>>>,
55}
56
57impl<'a, State> InstallBuilder<'a, Tree, State>
58where
59    State: install_builder::State,
60{
61    pub fn workspace(
62        self,
63        workspace: &'a Workspace,
64    ) -> Result<InstallBuilder<'a, Tree, install_builder::SetTree<State>>, WorkspaceTreeError>
65    where
66        State::Tree: install_builder::IsUnset,
67    {
68        let config = self.config;
69        Ok(self._tree(workspace.tree(config)?))
70    }
71}
72
73impl<'a, T, State> InstallBuilder<'a, T, State>
74where
75    State: install_builder::State,
76    T: InstallTree + Clone + Send + Sync,
77{
78    pub fn tree(self, tree: T) -> InstallBuilder<'a, T, install_builder::SetTree<State>>
79    where
80        State::Tree: install_builder::IsUnset,
81    {
82        self._tree(tree)
83    }
84
85    pub fn packages(self, packages: Vec<PackageInstallSpec>) -> Self {
86        Self { packages, ..self }
87    }
88
89    pub fn package(self, package: PackageInstallSpec) -> Self {
90        Self {
91            packages: self
92                .packages
93                .into_iter()
94                .chain(std::iter::once(package))
95                .collect(),
96            ..self
97        }
98    }
99}
100
101impl<State, T> InstallBuilder<'_, T, State>
102where
103    State: install_builder::State + install_builder::IsComplete,
104    T: InstallTree + Clone + Send + Sync + 'static,
105{
106    /// Install the packages.
107    pub async fn install(self) -> Result<Vec<LocalPackage>, InstallError> {
108        let install_built = self._build();
109        if install_built.packages.is_empty() {
110            return Ok(Vec::default());
111        }
112        let progress = match install_built.progress {
113            Some(p) => p,
114            None => MultiProgress::new_arc(install_built.config),
115        };
116        let package_db = match install_built.package_db {
117            Some(db) => db,
118            None => {
119                let bar = progress.map(|p| p.new_bar());
120                RemotePackageDB::from_config(install_built.config, &bar).await?
121            }
122        };
123
124        let duplicate_entrypoints = install_built
125            .packages
126            .iter()
127            .filter(|pkg| pkg.entry_type == tree::EntryType::Entrypoint)
128            .map(|pkg| pkg.package.name())
129            .duplicates()
130            .cloned()
131            .collect_vec();
132
133        if !duplicate_entrypoints.is_empty() {
134            return Err(InstallError::DuplicateEntrypoints(PackageNameList::new(
135                duplicate_entrypoints,
136            )));
137        }
138
139        install_impl(
140            install_built.packages,
141            Arc::new(package_db),
142            install_built.config,
143            &install_built.tree,
144            progress,
145        )
146        .await
147    }
148}
149
150#[derive(Error, Debug, Diagnostic)]
151pub enum InstallError {
152    #[error("unable to resolve dependencies:\n{0}")]
153    #[diagnostic(forward(0))]
154    ResolveDependencies(#[from] ResolveDependenciesError),
155    #[error(transparent)]
156    #[diagnostic(transparent)]
157    LuaVersionUnset(#[from] LuaVersionUnset),
158    #[error(transparent)]
159    #[diagnostic(transparent)]
160    LuaInstallation(#[from] LuaInstallationError),
161    #[error(transparent)]
162    #[diagnostic(transparent)]
163    FlushLockfile(#[from] FlushLockfileError),
164    #[error(transparent)]
165    #[diagnostic(transparent)]
166    Tree(#[from] TreeError),
167    #[error(transparent)]
168    #[diagnostic(transparent)]
169    WorkspaceTree(#[from] WorkspaceTreeError),
170    #[error("error instantiating LuaRocks compatibility layer:\n{0}")]
171    #[diagnostic(forward(0))]
172    LuaRocks(#[from] LuaRocksError),
173    #[error("error installing LuaRocks compatibility layer:\n{0}")]
174    #[diagnostic(forward(0))]
175    LuaRocksInstall(#[from] LuaRocksInstallError),
176    #[error("failed to build {0}: {1}")]
177    Build(PackageName, BuildError),
178    #[error("failed to install build depencency {0}:\n{1}")]
179    BuildDependency(PackageName, BuildError),
180    #[error("error initialising remote package DB:\n{0}")]
181    #[diagnostic(forward(0))]
182    RemotePackageDB(#[from] RemotePackageDBError),
183    #[error("failed to install pre-built rock {0}:\n{1}")]
184    InstallBinaryRock(PackageName, InstallBinaryRockError),
185    #[error("integrity error for package {0}:\n{1}")]
186    Integrity(PackageName, RemotePackageDbIntegrityError),
187    #[error("cannot install duplicate entrypoints:\n{0}")]
188    DuplicateEntrypoints(PackageNameList),
189}
190
191// TODO(vhyrro): This function has too many arguments. Refactor it.
192#[allow(clippy::too_many_arguments)]
193async fn install_impl<T>(
194    packages: Vec<PackageInstallSpec>,
195    package_db: Arc<RemotePackageDB>,
196    config: &Config,
197    tree: &T,
198    progress_arc: Arc<Progress<MultiProgress>>,
199) -> Result<Vec<LocalPackage>, InstallError>
200where
201    T: InstallTree + Clone + Send + Sync + 'static,
202{
203    let (dep_tx, mut dep_rx) = tokio::sync::mpsc::unbounded_channel();
204    let (build_dep_tx, mut build_dep_rx) = tokio::sync::mpsc::unbounded_channel();
205
206    let lockfile = tree.lockfile()?;
207    let build_lockfile = tree.build_tree(config)?.lockfile()?;
208
209    Resolve::new()
210        .dependencies_tx(dep_tx)
211        .build_dependencies_tx(build_dep_tx)
212        .packages(packages)
213        .package_db(package_db.clone())
214        .lockfile(Arc::new(lockfile.clone()))
215        .build_lockfile(Arc::new(build_lockfile.clone()))
216        .config(config)
217        .progress(progress_arc.clone())
218        .get_all_dependencies()
219        .await?;
220
221    let lua = Arc::new(
222        LuaInstallation::new_from_config(config, &progress_arc.map(|progress| progress.new_bar()))
223            .await?,
224    );
225
226    // We have to install transitive build dependencies sequentially
227    while let Some(build_dep_spec) = build_dep_rx.recv().await {
228        let rockspec = build_dep_spec.downloaded_rock.rockspec();
229        let bar = progress_arc.map(|p| {
230            p.add(ProgressBar::from(format!(
231                "💻 Installing build dependency: {}",
232                build_dep_spec.downloaded_rock.rockspec().package(),
233            )))
234        });
235        let package = rockspec.package().clone();
236        let build_tree = tree.build_tree(config)?;
237        // We have to write to the build tree's lockfile after each build,
238        // so that each transitive build dependency is available for the
239        // next build dependencies that may depend on it.
240        let mut build_lockfile = build_tree.lockfile()?.write_guard();
241        let pkg = Build::new()
242            .rockspec(rockspec)
243            .lua(&lua)
244            .tree(&build_tree)
245            .entry_type(tree::EntryType::Entrypoint)
246            .config(config)
247            .progress(&bar)
248            .constraint(build_dep_spec.spec.constraint())
249            .behaviour(build_dep_spec.build_behaviour)
250            .build()
251            .await
252            .map_err(|err| InstallError::BuildDependency(package, err))?;
253        build_lockfile.add_entrypoint(&pkg);
254    }
255
256    let mut all_packages = HashMap::with_capacity(dep_rx.len());
257    while let Some(dep) = dep_rx.recv().await {
258        all_packages.insert(dep.spec.id(), dep);
259    }
260
261    let installed_packages =
262        futures::stream::iter(all_packages.clone().into_values().map(|install_spec| {
263            let progress_arc = progress_arc.clone();
264            let downloaded_rock = install_spec.downloaded_rock;
265            let config = config.clone();
266            let tree = tree.clone();
267            let lua = lua.clone();
268
269            tokio::spawn({
270                async move {
271                    let pkg = match downloaded_rock {
272                        RemoteRockDownload::RockspecOnly { rockspec_download } => {
273                            install_rockspec(
274                                rockspec_download,
275                                None,
276                                install_spec.spec.constraint(),
277                                install_spec.build_behaviour,
278                                install_spec.pin,
279                                install_spec.opt,
280                                install_spec.entry_type,
281                                &lua,
282                                &tree,
283                                &config,
284                                progress_arc,
285                            )
286                            .await?
287                        }
288                        RemoteRockDownload::BinaryRock {
289                            rockspec_download,
290                            packed_rock,
291                        } => {
292                            install_binary_rock(
293                                rockspec_download,
294                                packed_rock,
295                                install_spec.spec.constraint(),
296                                install_spec.build_behaviour,
297                                install_spec.pin,
298                                install_spec.opt,
299                                install_spec.entry_type,
300                                &config,
301                                &tree,
302                                progress_arc,
303                            )
304                            .await?
305                        }
306                        RemoteRockDownload::SrcRock {
307                            rockspec_download,
308                            src_rock,
309                            source_url,
310                        } => {
311                            let src_rock_source = SrcRockSource {
312                                bytes: src_rock,
313                                source_url,
314                            };
315                            install_rockspec(
316                                rockspec_download,
317                                Some(src_rock_source),
318                                install_spec.spec.constraint(),
319                                install_spec.build_behaviour,
320                                install_spec.pin,
321                                install_spec.opt,
322                                install_spec.entry_type,
323                                &lua,
324                                &tree,
325                                &config,
326                                progress_arc,
327                            )
328                            .await?
329                        }
330                    };
331
332                    Ok::<_, InstallError>((pkg.id(), (pkg, install_spec.entry_type)))
333                }
334            })
335        }))
336        .buffered(config.max_jobs())
337        .collect::<Vec<_>>()
338        .await
339        .into_iter()
340        .flatten()
341        .try_collect::<_, HashMap<LocalPackageId, (LocalPackage, tree::EntryType)>, _>()?;
342
343    let write_dependency = |lockfile: &mut Lockfile<ReadWrite>,
344                            id: &LocalPackageId,
345                            pkg: &LocalPackage,
346                            entry_type: tree::EntryType|
347     -> io::Result<()> {
348        if entry_type == tree::EntryType::Entrypoint {
349            lockfile.add_entrypoint(pkg);
350        }
351
352        for dependency_id in all_packages
353            .get(id)
354            .map(|pkg| pkg.spec.dependencies())
355            .unwrap_or_default()
356            .into_iter()
357        {
358            lockfile.add_dependency(
359                pkg,
360                installed_packages
361                    .get(dependency_id)
362                    .map(|(pkg, _)| pkg)
363                    .ok_or(io::Error::other(
364                        r#"
365error writing dependencies to the lockfile.
366A required dependency was not installed correctly.
367This is likely because an install thread panicked and was interrupted unexpectedly.
368
369[THIS IS A BUG!]
370"#,
371                    ))?,
372            );
373        }
374        Ok(())
375    };
376
377    lockfile.map_then_flush(|lockfile| {
378        for (id, (pkg, is_entrypoint)) in installed_packages.iter() {
379            write_dependency(lockfile, id, pkg, *is_entrypoint)?;
380        }
381        Ok::<_, io::Error>(())
382    })?;
383
384    Ok(installed_packages
385        .into_values()
386        .map(|(pkg, _)| pkg)
387        .collect_vec())
388}
389
390#[allow(clippy::too_many_arguments)]
391async fn install_rockspec<T>(
392    rockspec_download: DownloadedRockspec,
393    src_rock_source: Option<SrcRockSource>,
394    constraint: LockConstraint,
395    behaviour: BuildBehaviour,
396    pin: PinnedState,
397    opt: OptState,
398    entry_type: tree::EntryType,
399    lua: &LuaInstallation,
400    tree: &T,
401    config: &Config,
402    progress_arc: Arc<Progress<MultiProgress>>,
403) -> Result<LocalPackage, InstallError>
404where
405    T: InstallTree + Sync,
406{
407    let progress = Arc::clone(&progress_arc);
408    let rockspec = rockspec_download.rockspec;
409    let source = rockspec_download.source;
410    let package = rockspec.package().clone();
411    let bar = progress.map(|p| p.add(ProgressBar::from(format!("💻 Installing {}", &package,))));
412
413    if let Some(BuildBackendSpec::LuaRock(_)) = &rockspec.build().current_platform().build_backend {
414        let luarocks_tree = tree.build_tree(config)?;
415        let luarocks = LuaRocksInstallation::new(config, luarocks_tree)?;
416        luarocks.ensure_installed(lua, &bar).await?;
417    }
418
419    let source_spec = match src_rock_source {
420        Some(src_rock_source) => RemotePackageSourceSpec::SrcRock(src_rock_source),
421        None => RemotePackageSourceSpec::RockSpec(rockspec_download.source_url),
422    };
423
424    let pkg = Build::new()
425        .rockspec(&rockspec)
426        .lua(lua)
427        .tree(tree)
428        .entry_type(entry_type)
429        .config(config)
430        .progress(&bar)
431        .pin(pin)
432        .opt(opt)
433        .constraint(constraint)
434        .behaviour(behaviour)
435        .source(source)
436        .source_spec(source_spec)
437        .build()
438        .await
439        .map_err(|err| InstallError::Build(package, err))?;
440
441    bar.map(|b| b.finish_and_clear());
442
443    Ok(pkg)
444}
445
446#[allow(clippy::too_many_arguments)]
447async fn install_binary_rock(
448    rockspec_download: DownloadedRockspec,
449    packed_rock: Bytes,
450    constraint: LockConstraint,
451    behaviour: BuildBehaviour,
452    pin: PinnedState,
453    opt: OptState,
454    entry_type: tree::EntryType,
455    config: &Config,
456    tree: &impl InstallTree,
457    progress_arc: Arc<Progress<MultiProgress>>,
458) -> Result<LocalPackage, InstallError> {
459    let progress = Arc::clone(&progress_arc);
460    let rockspec = rockspec_download.rockspec;
461    let package = rockspec.package().clone();
462    let bar = progress.map(|p| {
463        p.add(ProgressBar::from(format!(
464            "💻 Installing {} (pre-built)",
465            &package,
466        )))
467    });
468    let pkg = BinaryRockInstall::new(
469        &rockspec,
470        rockspec_download.source,
471        packed_rock,
472        entry_type,
473        config,
474        tree,
475        &bar,
476    )
477    .pin(pin)
478    .opt(opt)
479    .constraint(constraint)
480    .behaviour(behaviour)
481    .install()
482    .await
483    .map_err(|err| InstallError::InstallBinaryRock(package, err))?;
484
485    bar.map(|b| b.finish_and_clear());
486
487    Ok(pkg)
488}