-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
package.rs
345 lines (321 loc) · 12.9 KB
/
package.rs
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
use std::fmt;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::path::PathBuf;
use async_std::sync::Arc;
use oro_common::{CorgiPackument, CorgiVersionMetadata, Packument, VersionMetadata};
use oro_package_spec::PackageSpec;
use ssri::Integrity;
use crate::entries::Entries;
#[cfg(not(target_arch = "wasm32"))]
use crate::error::NassunError;
use crate::error::Result;
use crate::fetch::PackageFetcher;
use crate::resolver::PackageResolution;
use crate::tarball::Tarball;
#[cfg(not(target_arch = "wasm32"))]
use crate::tarball::TarballIndex;
/// A resolved package. A concrete version has been determined from its
/// PackageSpec by the version resolver.
#[derive(Clone)]
pub struct Package {
pub(crate) from: PackageSpec,
pub(crate) name: String,
pub(crate) resolved: PackageResolution,
pub(crate) fetcher: Arc<dyn PackageFetcher>,
pub(crate) base_dir: PathBuf,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) cache: Arc<Option<PathBuf>>,
}
impl Package {
/// Original package spec that this `Package` was resolved from.
pub fn from(&self) -> &PackageSpec {
&self.from
}
/// Name of the package, as it should be used in the dependency graph.
pub fn name(&self) -> &str {
&self.name
}
/// The [`PackageResolution`] that this `Package` was created from.
pub fn resolved(&self) -> &PackageResolution {
&self.resolved
}
/// The full [`Packument`] that this `Package` was resolved from.
pub async fn packument(&self) -> Result<Arc<Packument>> {
self.fetcher.packument(&self.from, &self.base_dir).await
}
/// The [`VersionMetadata`], aka the manifest, aka roughly the metadata
/// defined in `package.json`.
pub async fn metadata(&self) -> Result<VersionMetadata> {
self.fetcher.metadata(self).await
}
/// The partial (corgi) version of the [`Packument`] that this `Package`
/// was resolved from.
pub async fn corgi_packument(&self) -> Result<Arc<CorgiPackument>> {
self.fetcher
.corgi_packument(&self.from, &self.base_dir)
.await
}
/// The partial (corgi) version of the [`VersionMetadata`], aka the
/// manifest, aka roughly the metadata defined in `package.json`.
pub async fn corgi_metadata(&self) -> Result<CorgiVersionMetadata> {
self.fetcher.corgi_metadata(self).await
}
/// `AsyncRead` of the raw tarball data for this package. The data will
/// not be checked for integrity based on the current `Package`'s
/// [`Integrity`]. That is, bad or incomplete data may be returned.
pub async fn tarball_unchecked(&self) -> Result<Tarball> {
let data = self.fetcher.tarball(self).await?;
Ok(Tarball::new_unchecked(data))
}
/// `AsyncRead` of the raw tarball data for this package. The data will
/// be checked for integrity based on the current `Package`'s
/// [`Integrity`], if present in its [`Package::metadata`]. An
/// [`std::io::Error`] with [`std::io::ErrorKind::InvalidData`] will be
/// returned in case of integrity validation failure.
pub async fn tarball(&self) -> Result<Tarball> {
let data = self.fetcher.tarball(self).await?;
if let Some(integrity) = self.resolved.integrity() {
Ok(Tarball::new(data, integrity.clone()))
} else {
self.tarball_unchecked().await
}
}
/// `AsyncRead` of the raw tarball data for this package. The data will
/// be checked for integrity based on the given [`Integrity`]. An
/// [`std::io::Error`] with [`std::io::ErrorKind::InvalidData`] will be
/// returned in case of integrity validation failure.
pub async fn tarball_checked(&self, integrity: Integrity) -> Result<Tarball> {
let data = self.fetcher.tarball(self).await?;
Ok(Tarball::new(data, integrity))
}
/// A `Stream` of extracted entries from the `Package`'s tarball. The
/// tarball stream will have its integrity validated based on package
/// metadata. See [`Package::tarball`] for more information.
pub async fn entries(&self) -> Result<Entries> {
self.tarball().await?.entries()
}
/// A `Stream` of extracted entries from the `Package`'s tarball. The
/// tarball stream will NOT have its integrity validated. See
/// [`Package::tarball_unchecked`] for more information.
pub async fn entries_unchecked(&self) -> Result<Entries> {
self.tarball_unchecked().await?.entries()
}
/// A `Stream` of extracted entries from the `Package`'s tarball. The
/// tarball stream will have its integrity validated based on
/// [`Integrity`]. See [`Package::tarball_checked`] for more information.
pub async fn entries_checked(&self, integrity: Integrity) -> Result<Entries> {
self.tarball_checked(integrity).await?.entries()
}
/// Extract tarball to a directory, optionally caching its contents. The
/// tarball stream will have its integrity validated based on package
/// metadata. See [`Package::tarball`] for more information.
#[cfg(not(target_arch = "wasm32"))]
pub async fn extract_to_dir(
&self,
dir: impl AsRef<Path>,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
async fn inner(
me: &Package,
dir: &Path,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
me.extract_to_dir_inner(dir, me.resolved.integrity(), prefer_copy, validate)
.await
}
inner(self, dir.as_ref(), prefer_copy, validate).await
}
/// Extract tarball to a directory, optionally caching its contents. The
/// tarball stream will NOT have its integrity validated. See
/// [`Package::tarball_unchecked`] for more information.
#[cfg(not(target_arch = "wasm32"))]
pub async fn extract_to_dir_unchecked(
&self,
dir: impl AsRef<Path>,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
async fn inner(
me: &Package,
dir: &Path,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
me.extract_to_dir_inner(dir, None, prefer_copy, validate)
.await
}
inner(self, dir.as_ref(), prefer_copy, validate).await
}
/// Extract tarball to a directory, optionally caching its contents. The
/// tarball stream will have its integrity validated based on
/// [`Integrity`]. See [`Package::tarball_checked`] for more information.
#[cfg(not(target_arch = "wasm32"))]
pub async fn extract_to_dir_checked(
&self,
dir: impl AsRef<Path>,
sri: Integrity,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
async fn inner(
me: &Package,
dir: &Path,
sri: Integrity,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
me.extract_to_dir_inner(dir, Some(&sri), prefer_copy, validate)
.await
}
inner(self, dir.as_ref(), sri, prefer_copy, validate).await
}
#[cfg(not(target_arch = "wasm32"))]
async fn extract_to_dir_inner(
&self,
dir: &Path,
integrity: Option<&Integrity>,
prefer_copy: bool,
validate: bool,
) -> Result<Integrity> {
if let Some(sri) = integrity {
if let Some(cache) = self.cache.as_deref() {
if let Some(entry) = cacache::index::find(cache, &crate::tarball::tarball_key(sri))
.map_err(|e| NassunError::ExtractCacheError(e, None))?
{
let sri = sri.clone();
// If extracting from the cache failed for some reason
// (bad data, etc), then go ahead and do a network
// extract.
match self
.extract_from_cache(dir, cache, entry, prefer_copy, validate)
.await
{
Ok(_) => return Ok(sri),
Err(e) => {
tracing::warn!("extracting package {:?} from cache failed, possily due to cache corruption: {e}", self.resolved());
if let Some(entry) =
cacache::index::find(cache, &crate::tarball::tarball_key(&sri))
.map_err(|e| NassunError::ExtractCacheError(e, None))?
{
tracing::debug!("removing corrupted cache entry.");
clean_from_cache(cache, &sri, entry)?;
}
return self
.tarball_checked(sri)
.await?
.extract_from_tarball_data(dir, self.cache.as_deref(), prefer_copy)
.await;
}
}
} else {
return self
.tarball_checked(sri.clone())
.await?
.extract_from_tarball_data(dir, self.cache.as_deref(), prefer_copy)
.await;
}
}
self.tarball_checked(sri.clone())
.await?
.extract_from_tarball_data(dir, self.cache.as_deref(), prefer_copy)
.await
} else {
self.tarball_unchecked()
.await?
.extract_from_tarball_data(dir, self.cache.as_deref(), prefer_copy)
.await
}
}
#[cfg(not(target_arch = "wasm32"))]
async fn extract_from_cache(
&self,
dir: &Path,
cache: &Path,
entry: cacache::Metadata,
mut prefer_copy: bool,
validate: bool,
) -> Result<()> {
let dir = PathBuf::from(dir);
let cache = PathBuf::from(cache);
let name = self.name().to_owned();
async_std::task::spawn_blocking(move || {
let mut created = std::collections::HashSet::new();
let index = unsafe {
rkyv::util::archived_root::<TarballIndex>(
entry
.raw_metadata
.as_ref()
.ok_or_else(|| NassunError::CacheMissingIndexError(name))?,
)
};
prefer_copy = index.should_copy || prefer_copy;
for (path, (sri, mode)) in index.files.iter() {
let sri: Integrity = sri.parse()?;
let path = dir.join(&path[..]);
let parent = PathBuf::from(path.parent().expect("this will always have a parent"));
if !created.contains(&parent) {
std::fs::create_dir_all(path.parent().expect("this will always have a parent"))
.map_err(|e| {
NassunError::ExtractIoError(
e,
Some(PathBuf::from(path.parent().unwrap())),
"creating destination directory for tarball.".into(),
)
})?;
created.insert(parent);
}
crate::tarball::extract_from_cache(
&cache,
&sri,
&path,
prefer_copy,
validate,
*mode,
)?;
}
#[cfg(unix)]
for binpath in index.bin_paths.iter() {
{
crate::tarball::set_bin_mode(&dir.join(&binpath[..]))?;
}
}
Ok::<_, NassunError>(())
})
.await?;
Ok(())
}
}
impl fmt::Debug for Package {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Package")
.field("from", &self.from)
.field("name", &self.name)
.field("resolved", &self.resolved)
.field("base_dir", &self.resolved)
.finish()
}
}
#[cfg(not(target_arch = "wasm32"))]
fn clean_from_cache(cache: &Path, sri: &Integrity, entry: cacache::Metadata) -> Result<()> {
let map = entry
.metadata
.as_object()
.expect("how is this not an object?");
for sri in map.values() {
let sri: Integrity = sri.as_str().expect("how is this not a string?").parse()?;
match cacache::remove_hash_sync(cache, &sri) {
Ok(_) => {}
// We don't care if the file doesn't exist.
Err(cacache::Error::IoError(e, _)) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
return Err(NassunError::ExtractCacheError(e, None));
}
}
}
cacache::remove_sync(cache, crate::tarball::tarball_key(sri))
.map_err(|e| NassunError::ExtractCacheError(e, None))?;
Ok(())
}