lux_lib/operations/
install.rs

1use std::{collections::HashMap, io, sync::Arc};
2
3use crate::{
4    build::{Build, BuildBehaviour, BuildError},
5    config::{Config, LuaVersionUnset},
6    lockfile::{
7        LocalPackage, LocalPackageId, LockConstraint, Lockfile, OptState, PinnedState, ReadOnly,
8        ReadWrite,
9    },
10    lua_rockspec::BuildBackendSpec,
11    luarocks::{
12        install_binary_rock::{BinaryRockInstall, InstallBinaryRockError},
13        luarocks_installation::{
14            InstallBuildDependenciesError, LuaRocksError, LuaRocksInstallError,
15            LuaRocksInstallation,
16        },
17    },
18    package::{PackageName, PackageNameList},
19    progress::{MultiProgress, Progress, ProgressBar},
20    project::{Project, ProjectTreeError},
21    remote_package_db::{RemotePackageDB, RemotePackageDBError, RemotePackageDbIntegrityError},
22    rockspec::Rockspec,
23    tree::{self, Tree, TreeError},
24};
25
26use bon::Builder;
27use bytes::Bytes;
28use futures::future::join_all;
29use itertools::Itertools;
30use thiserror::Error;
31
32use super::{
33    install_spec::PackageInstallSpec, resolve::get_all_dependencies, DownloadedRockspec,
34    RemoteRockDownload, SearchAndDownloadError,
35};
36
37/// A rocks package installer, providing fine-grained control
38/// over how packages should be installed.
39/// Can install multiple packages in parallel.
40#[derive(Builder)]
41#[builder(start_fn = new, finish_fn(name = _install, vis = ""))]
42pub struct Install<'a> {
43    #[builder(start_fn)]
44    config: &'a Config,
45    #[builder(field)]
46    packages: Vec<PackageInstallSpec>,
47    #[builder(setters(name = "_tree", vis = ""))]
48    tree: Tree,
49    package_db: Option<RemotePackageDB>,
50    progress: Option<Arc<Progress<MultiProgress>>>,
51}
52
53impl<'a, State> InstallBuilder<'a, State>
54where
55    State: install_builder::State,
56{
57    pub fn tree(self, tree: Tree) -> InstallBuilder<'a, install_builder::SetTree<State>>
58    where
59        State::Tree: install_builder::IsUnset,
60    {
61        self._tree(tree)
62    }
63
64    pub fn project(
65        self,
66        project: &'a Project,
67    ) -> Result<InstallBuilder<'a, install_builder::SetTree<State>>, ProjectTreeError>
68    where
69        State::Tree: install_builder::IsUnset,
70    {
71        let config = self.config;
72        Ok(self._tree(project.tree(config)?))
73    }
74
75    pub fn packages(self, packages: Vec<PackageInstallSpec>) -> Self {
76        Self { packages, ..self }
77    }
78
79    pub fn package(self, package: PackageInstallSpec) -> Self {
80        Self {
81            packages: self
82                .packages
83                .into_iter()
84                .chain(std::iter::once(package))
85                .collect(),
86            ..self
87        }
88    }
89}
90
91impl<State> InstallBuilder<'_, State>
92where
93    State: install_builder::State + install_builder::IsComplete,
94{
95    /// Install the packages.
96    pub async fn install(self) -> Result<Vec<LocalPackage>, InstallError> {
97        let install_built = self._install();
98        let progress = match install_built.progress {
99            Some(p) => p,
100            None => MultiProgress::new_arc(),
101        };
102        let package_db = match install_built.package_db {
103            Some(db) => db,
104            None => {
105                let bar = progress.map(|p| p.new_bar());
106                RemotePackageDB::from_config(install_built.config, &bar).await?
107            }
108        };
109
110        let duplicate_entrypoints = install_built
111            .packages
112            .iter()
113            .filter(|pkg| pkg.entry_type == tree::EntryType::Entrypoint)
114            .map(|pkg| pkg.package.name())
115            .duplicates()
116            .cloned()
117            .collect_vec();
118
119        if !duplicate_entrypoints.is_empty() {
120            return Err(InstallError::DuplicateEntrypoints(PackageNameList::new(
121                duplicate_entrypoints,
122            )));
123        }
124
125        install_impl(
126            install_built.packages,
127            Arc::new(package_db),
128            install_built.config,
129            &install_built.tree,
130            install_built.tree.lockfile()?,
131            progress,
132        )
133        .await
134    }
135}
136
137#[derive(Error, Debug)]
138pub enum InstallError {
139    #[error(transparent)]
140    SearchAndDownloadError(#[from] SearchAndDownloadError),
141    #[error(transparent)]
142    LuaVersionUnset(#[from] LuaVersionUnset),
143    #[error(transparent)]
144    Io(#[from] io::Error),
145    #[error(transparent)]
146    Tree(#[from] TreeError),
147    #[error("error instantiating LuaRocks compatibility layer: {0}")]
148    LuaRocksError(#[from] LuaRocksError),
149    #[error("error installing LuaRocks compatibility layer: {0}")]
150    LuaRocksInstallError(#[from] LuaRocksInstallError),
151    #[error("error installing LuaRocks build dependencies: {0}")]
152    InstallBuildDependenciesError(#[from] InstallBuildDependenciesError),
153    #[error("failed to build {0}: {1}")]
154    BuildError(PackageName, BuildError),
155    #[error("error initialising remote package DB: {0}")]
156    RemotePackageDB(#[from] RemotePackageDBError),
157    #[error("failed to install pre-built rock {0}: {1}")]
158    InstallBinaryRockError(PackageName, InstallBinaryRockError),
159    #[error("integrity error for package {0}: {1}\n")]
160    Integrity(PackageName, RemotePackageDbIntegrityError),
161    #[error(transparent)]
162    ProjectTreeError(#[from] ProjectTreeError),
163    #[error("cannot install duplicate entrypoints: {0}")]
164    DuplicateEntrypoints(PackageNameList),
165}
166
167// TODO(vhyrro): This function has too many arguments. Refactor it.
168#[allow(clippy::too_many_arguments)]
169async fn install_impl(
170    packages: Vec<PackageInstallSpec>,
171    package_db: Arc<RemotePackageDB>,
172    config: &Config,
173    tree: &Tree,
174    lockfile: Lockfile<ReadOnly>,
175    progress_arc: Arc<Progress<MultiProgress>>,
176) -> Result<Vec<LocalPackage>, InstallError> {
177    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
178
179    get_all_dependencies(
180        tx,
181        packages,
182        package_db.clone(),
183        Arc::new(lockfile.clone()),
184        config,
185        progress_arc.clone(),
186    )
187    .await?;
188
189    let mut all_packages = HashMap::with_capacity(rx.len());
190
191    while let Some(dep) = rx.recv().await {
192        all_packages.insert(dep.spec.id(), dep);
193    }
194
195    let installed_packages = join_all(all_packages.clone().into_values().map(|install_spec| {
196        let progress_arc = progress_arc.clone();
197        let downloaded_rock = install_spec.downloaded_rock;
198        let config = config.clone();
199        let tree = tree.clone();
200
201        tokio::spawn(async move {
202            let rockspec = downloaded_rock.rockspec();
203            if let Some(BuildBackendSpec::LuaRock(build_backend)) =
204                &rockspec.build().current_platform().build_backend
205            {
206                let luarocks_tree = tree.build_tree(&config)?;
207                let luarocks = LuaRocksInstallation::new(&config, luarocks_tree)?;
208                luarocks
209                    .install_build_dependencies(build_backend, rockspec, progress_arc.clone())
210                    .await?;
211            }
212
213            let pkg = match downloaded_rock {
214                RemoteRockDownload::RockspecOnly { rockspec_download } => {
215                    install_rockspec(
216                        rockspec_download,
217                        install_spec.spec.constraint(),
218                        install_spec.build_behaviour,
219                        install_spec.pin,
220                        install_spec.opt,
221                        install_spec.entry_type,
222                        &tree,
223                        &config,
224                        progress_arc,
225                    )
226                    .await?
227                }
228                RemoteRockDownload::BinaryRock {
229                    rockspec_download,
230                    packed_rock,
231                } => {
232                    install_binary_rock(
233                        rockspec_download,
234                        packed_rock,
235                        install_spec.spec.constraint(),
236                        install_spec.build_behaviour,
237                        install_spec.pin,
238                        install_spec.opt,
239                        install_spec.entry_type,
240                        &config,
241                        &tree,
242                        progress_arc,
243                    )
244                    .await?
245                }
246                RemoteRockDownload::SrcRock { .. } => todo!(
247                    "lux does not yet support installing .src.rock packages without a rockspec"
248                ),
249            };
250
251            Ok::<_, InstallError>((pkg.id(), (pkg, install_spec.entry_type)))
252        })
253    }))
254    .await
255    .into_iter()
256    .flatten()
257    .try_collect::<_, HashMap<LocalPackageId, (LocalPackage, tree::EntryType)>, _>()?;
258
259    let write_dependency = |lockfile: &mut Lockfile<ReadWrite>,
260                            id: &LocalPackageId,
261                            pkg: &LocalPackage,
262                            entry_type: tree::EntryType| {
263        if entry_type == tree::EntryType::Entrypoint {
264            lockfile.add_entrypoint(pkg);
265        }
266
267        all_packages
268            .get(id)
269            .map(|pkg| pkg.spec.dependencies())
270            .unwrap_or_default()
271            .into_iter()
272            .for_each(|dependency_id| {
273                lockfile.add_dependency(
274                    pkg,
275                    installed_packages
276                        .get(dependency_id)
277                        .map(|(pkg, _)| pkg)
278                        // NOTE: This can happen if an install thread panics
279                        .expect("required dependency not found [This is a bug!]"),
280                );
281            });
282    };
283
284    lockfile.map_then_flush(|lockfile| {
285        installed_packages
286            .iter()
287            .for_each(|(id, (pkg, is_entrypoint))| {
288                write_dependency(lockfile, id, pkg, *is_entrypoint)
289            });
290
291        Ok::<_, io::Error>(())
292    })?;
293
294    Ok(installed_packages
295        .into_values()
296        .map(|(pkg, _)| pkg)
297        .collect_vec())
298}
299
300#[allow(clippy::too_many_arguments)]
301async fn install_rockspec(
302    rockspec_download: DownloadedRockspec,
303    constraint: LockConstraint,
304    behaviour: BuildBehaviour,
305    pin: PinnedState,
306    opt: OptState,
307    entry_type: tree::EntryType,
308    tree: &Tree,
309    config: &Config,
310    progress_arc: Arc<Progress<MultiProgress>>,
311) -> Result<LocalPackage, InstallError> {
312    let progress = Arc::clone(&progress_arc);
313    let rockspec = rockspec_download.rockspec;
314    let source = rockspec_download.source;
315    let package = rockspec.package().clone();
316    let bar = progress.map(|p| p.add(ProgressBar::from(format!("💻 Installing {}", &package,))));
317
318    if let Some(BuildBackendSpec::LuaRock(build_backend)) =
319        &rockspec.build().current_platform().build_backend
320    {
321        let luarocks_tree = tree.build_tree(config)?;
322        let luarocks = LuaRocksInstallation::new(config, luarocks_tree)?;
323        luarocks.ensure_installed(&bar).await?;
324        luarocks
325            .install_build_dependencies(build_backend, &rockspec, progress_arc)
326            .await?;
327    }
328
329    let pkg = Build::new(&rockspec, tree, entry_type, config, &bar)
330        .pin(pin)
331        .opt(opt)
332        .constraint(constraint)
333        .behaviour(behaviour)
334        .source(source)
335        .maybe_source_url(rockspec_download.source_url)
336        .build()
337        .await
338        .map_err(|err| InstallError::BuildError(package, err))?;
339
340    bar.map(|b| b.finish_and_clear());
341
342    Ok(pkg)
343}
344
345#[allow(clippy::too_many_arguments)]
346async fn install_binary_rock(
347    rockspec_download: DownloadedRockspec,
348    packed_rock: Bytes,
349    constraint: LockConstraint,
350    behaviour: BuildBehaviour,
351    pin: PinnedState,
352    opt: OptState,
353    entry_type: tree::EntryType,
354    config: &Config,
355    tree: &Tree,
356    progress_arc: Arc<Progress<MultiProgress>>,
357) -> Result<LocalPackage, InstallError> {
358    let progress = Arc::clone(&progress_arc);
359    let rockspec = rockspec_download.rockspec;
360    let package = rockspec.package().clone();
361    let bar = progress.map(|p| {
362        p.add(ProgressBar::from(format!(
363            "💻 Installing {} (pre-built)",
364            &package,
365        )))
366    });
367    let pkg = BinaryRockInstall::new(
368        &rockspec,
369        rockspec_download.source,
370        packed_rock,
371        entry_type,
372        config,
373        tree,
374        &bar,
375    )
376    .pin(pin)
377    .opt(opt)
378    .constraint(constraint)
379    .behaviour(behaviour)
380    .install()
381    .await
382    .map_err(|err| InstallError::InstallBinaryRockError(package, err))?;
383
384    bar.map(|b| b.finish_and_clear());
385
386    Ok(pkg)
387}