-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
tarball-fetcher.js
244 lines (209 loc) · 8.09 KB
/
tarball-fetcher.js
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
/* @flow */
import http from 'http';
import {SecurityError, MessageError, ResponseError} from '../errors.js';
import type {FetchedOverride} from '../types.js';
import * as constants from '../constants.js';
import * as crypto from '../util/crypto.js';
import BaseFetcher from './base-fetcher.js';
import * as fsUtil from '../util/fs.js';
import {removePrefix, sleep} from '../util/misc.js';
const path = require('path');
const tarFs = require('tar-fs');
const url = require('url');
const fs = require('fs');
const stream = require('stream');
const gunzip = require('gunzip-maybe');
const invariant = require('invariant');
const RE_URL_NAME_MATCH = /\/(?:(@[^/]+)\/)?[^/]+\/-\/(?:@[^/]+\/)?([^/]+)$/;
export default class TarballFetcher extends BaseFetcher {
async setupMirrorFromCache(): Promise<?string> {
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
if (tarballMirrorPath == null) {
return;
}
if (!await fsUtil.exists(tarballMirrorPath) && (await fsUtil.exists(tarballCachePath))) {
// The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror
await fsUtil.mkdirp(path.dirname(tarballMirrorPath));
await fsUtil.copy(tarballCachePath, tarballMirrorPath, this.reporter);
}
}
getTarballCachePath(): string {
return path.join(this.dest, constants.TARBALL_FILENAME);
}
getTarballMirrorPath(): ?string {
const {pathname} = url.parse(this.reference);
if (pathname == null) {
return null;
}
const match = pathname.match(RE_URL_NAME_MATCH);
let packageFilename;
if (match) {
const [, scope, tarballBasename] = match;
packageFilename = scope ? `${scope}-${tarballBasename}` : tarballBasename;
} else {
// fallback to base name
packageFilename = path.basename(pathname);
}
return this.config.getOfflineMirrorPath(packageFilename);
}
createExtractor(
resolve: (fetched: FetchedOverride) => void,
reject: (error: Error) => void,
tarballPath?: string,
): {
validateStream: crypto.HashStream,
extractorStream: stream.Transform,
} {
const validateStream = new crypto.HashStream();
const extractorStream = gunzip();
const untarStream = tarFs.extract(this.dest, {
strip: 1,
dmode: 0o755, // all dirs should be readable
fmode: 0o644, // all files should be readable
chown: false, // don't chown. just leave as it is
});
extractorStream
.pipe(untarStream)
.on('error', error => {
error.message = `${error.message}${tarballPath ? ` (${tarballPath})` : ''}`;
reject(error);
})
.on('finish', async () => {
const expectHash = this.hash;
const actualHash = validateStream.getHash();
if (!expectHash || expectHash === actualHash) {
resolve({
hash: actualHash,
});
} else if (this.config.updateChecksums) {
// checksums differ and should be updated
// update hash, destination and cached package
const destUpdatedHash = this.dest.replace(this.hash || '', actualHash);
await fsUtil.unlink(destUpdatedHash);
await fsUtil.rename(this.dest, destUpdatedHash);
this.dest = this.dest.replace(this.hash || '', actualHash);
this.hash = actualHash;
resolve({
hash: actualHash,
});
} else {
reject(
new SecurityError(
this.config.reporter.lang(
'fetchBadHashWithPath',
this.packageName,
this.remote.reference,
actualHash,
expectHash,
),
),
);
}
});
return {validateStream, extractorStream};
}
*getLocalPaths(override: ?string): Generator<?string, void, void> {
if (override) {
yield path.resolve(this.config.cwd, override);
}
yield this.getTarballMirrorPath();
yield this.getTarballCachePath();
}
async fetchFromLocal(override: ?string): Promise<FetchedOverride> {
const {stream, triedPaths} = await fsUtil.readFirstAvailableStream(this.getLocalPaths(override));
return new Promise((resolve, reject) => {
if (!stream) {
reject(new MessageError(this.reporter.lang('tarballNotInNetworkOrCache', this.reference, triedPaths)));
return;
}
invariant(stream, 'stream should be available at this point');
// $FlowFixMe - This is available https://nodejs.org/api/fs.html#fs_readstream_path
const tarballPath = stream.path;
const {validateStream, extractorStream} = this.createExtractor(resolve, reject, tarballPath);
stream.pipe(validateStream).pipe(extractorStream).on('error', err => {
reject(new MessageError(this.config.reporter.lang('fetchErrorCorrupt', err.message, tarballPath)));
});
});
}
async fetchFromExternal(): Promise<FetchedOverride> {
const registry = this.config.registries[this.registry];
let retriesRemaining = 2;
do {
try {
return await registry.request(
this.reference,
{
headers: {
'Accept-Encoding': 'gzip',
},
buffer: true,
process: (req, resolve, reject) => {
// should we save this to the offline cache?
const {reporter} = this.config;
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
const {validateStream, extractorStream} = this.createExtractor(resolve, reject);
req.on('response', res => {
if (res.statusCode >= 400) {
const statusDescription = http.STATUS_CODES[res.statusCode];
reject(
new ResponseError(
reporter.lang('requestFailed', `${res.statusCode} ${statusDescription}`),
res.statusCode,
),
);
}
});
req.pipe(validateStream);
if (tarballMirrorPath) {
validateStream.pipe(fs.createWriteStream(tarballMirrorPath)).on('error', reject);
}
if (tarballCachePath) {
validateStream.pipe(fs.createWriteStream(tarballCachePath)).on('error', reject);
}
validateStream.pipe(extractorStream).on('error', reject);
},
},
this.packageName,
);
} catch (err) {
if (err instanceof ResponseError && err.responseCode >= 500 && retriesRemaining > 1) {
retriesRemaining--;
this.reporter.warn(this.reporter.lang('retryOnInternalServerError'));
await sleep(3000);
} else {
const tarballMirrorPath = this.getTarballMirrorPath();
const tarballCachePath = this.getTarballCachePath();
if (tarballMirrorPath && (await fsUtil.exists(tarballMirrorPath))) {
await fsUtil.unlink(tarballMirrorPath);
}
if (tarballCachePath && (await fsUtil.exists(tarballCachePath))) {
await fsUtil.unlink(tarballCachePath);
}
throw err;
}
}
} while (retriesRemaining > 0);
// Unreachable code, this is just to make Flow happy
throw new Error('Ran out of retries!');
}
_fetch(): Promise<FetchedOverride> {
const isFilePath = this.reference.startsWith('file:');
this.reference = removePrefix(this.reference, 'file:');
const urlParse = url.parse(this.reference);
// legacy support for local paths in yarn.lock entries
const isRelativePath = urlParse.protocol
? urlParse.protocol.match(/^[a-z]:$/i)
: urlParse.pathname ? urlParse.pathname.match(/^(?:\.{1,2})?[\\\/]/) : false;
if (isFilePath || isRelativePath) {
return this.fetchFromLocal(this.reference);
}
return this.fetchFromLocal().catch(err => this.fetchFromExternal());
}
}
export class LocalTarballFetcher extends TarballFetcher {
_fetch(): Promise<FetchedOverride> {
return this.fetchFromLocal(this.reference);
}
}