-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathcreate-remote-file-node.js
370 lines (329 loc) · 8.8 KB
/
create-remote-file-node.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const fs = require(`fs-extra`)
const got = require(`got`)
const crypto = require(`crypto`)
const path = require(`path`)
const { isWebUri } = require(`valid-url`)
const Queue = require(`better-queue`)
const readChunk = require(`read-chunk`)
const fileType = require(`file-type`)
const ProgressBar = require(`progress`)
const { createFileNode } = require(`./create-file-node`)
const { getRemoteFileExtension, getRemoteFileName } = require(`./utils`)
const cacheId = url => `create-remote-file-node-${url}`
const bar = new ProgressBar(
`Downloading remote files [:bar] :current/:total :elapsed secs :percent`,
{
total: 0,
width: 30,
}
)
/********************
* Type Definitions *
********************/
/**
* @typedef {Redux}
* @see [Redux Docs]{@link https://redux.js.org/api-reference}
*/
/**
* @typedef {GatsbyCache}
* @see gatsby/packages/gatsby/utils/cache.js
*/
/**
* @typedef {Auth}
* @type {Object}
* @property {String} htaccess_pass
* @property {String} htaccess_user
*/
/**
* @typedef {CreateRemoteFileNodePayload}
* @typedef {Object}
* @description Create Remote File Node Payload
*
* @param {String} options.url
* @param {Redux} options.store
* @param {GatsbyCache} options.cache
* @param {Function} options.createNode
* @param {Auth} [options.auth]
*/
/*********
* utils *
*********/
/**
* createHash
* --
*
* Create an md5 hash of the given str
* @param {Stringq} str
* @return {String}
*/
const createHash = str =>
crypto
.createHash(`md5`)
.update(str)
.digest(`hex`)
const CACHE_DIR = `.cache`
const FS_PLUGIN_DIR = `gatsby-source-filesystem`
/**
* createFilePath
* --
*
* @param {String} directory
* @param {String} filename
* @param {String} url
* @return {String}
*/
const createFilePath = (directory, filename, ext) =>
path.join(directory, `${filename}${ext}`)
/********************
* Queue Management *
********************/
/**
* Queue
* Use the task's url as the id
* When pushing a task with a similar id, prefer the original task
* as it's already in the processing cache
*/
const queue = new Queue(pushToQueue, {
id: `url`,
merge: (old, _, cb) => cb(old),
concurrent: 200,
})
/**
* @callback {Queue~queueCallback}
* @param {*} error
* @param {*} result
*/
/**
* pushToQueue
* --
* Handle tasks that are pushed in to the Queue
*
*
* @param {CreateRemoteFileNodePayload} task
* @param {Queue~queueCallback} cb
* @return {Promise<null>}
*/
async function pushToQueue(task, cb) {
try {
const node = await processRemoteNode(task)
return cb(null, node)
} catch (e) {
console.warn(`Failed to process remote content ${task.url}`)
return cb(e)
}
}
/******************
* Core Functions *
******************/
/**
* requestRemoteNode
* --
* Download the requested file
*
* @param {String} url
* @param {Headers} headers
* @param {String} tmpFilename
* @param {Object} httpOpts
* @return {Promise<Object>} Resolves with the [http Result Object]{@link https://nodejs.org/api/http.html#http_class_http_serverresponse}
*/
const requestRemoteNode = (url, headers, tmpFilename, httpOpts) =>
new Promise((resolve, reject) => {
const opts = Object.assign({}, { timeout: 30000, retries: 5 }, httpOpts)
const responseStream = got.stream(url, {
headers,
...opts,
})
const fsWriteStream = fs.createWriteStream(tmpFilename)
responseStream.pipe(fsWriteStream)
responseStream.on(`downloadProgress`, pro => console.log(pro))
// If there's a 400/500 response or other error.
responseStream.on(`error`, (error, body, response) => {
fs.removeSync(tmpFilename)
reject(error)
})
fsWriteStream.on(`error`, error => {
reject(error)
})
responseStream.on(`response`, response => {
fsWriteStream.on(`finish`, () => {
resolve(response)
})
})
})
/**
* processRemoteNode
* --
* Request the remote file and return the fileNode
*
* @param {CreateRemoteFileNodePayload} options
* @return {Promise<Object>} Resolves with the fileNode
*/
async function processRemoteNode({
url,
store,
cache,
createNode,
parentNodeId,
auth = {},
createNodeId,
ext,
name,
}) {
// Ensure our cache directory exists.
const pluginCacheDir = path.join(
store.getState().program.directory,
CACHE_DIR,
FS_PLUGIN_DIR
)
await fs.ensureDir(pluginCacheDir)
// See if there's response headers for this url
// from a previous request.
const cachedHeaders = await cache.get(cacheId(url))
const headers = {}
if (cachedHeaders && cachedHeaders.etag) {
headers[`If-None-Match`] = cachedHeaders.etag
}
// Add htaccess authentication if passed in. This isn't particularly
// extensible. We should define a proper API that we validate.
const httpOpts = {}
if (auth && (auth.htaccess_pass || auth.htaccess_user)) {
httpOpts.auth = `${auth.htaccess_user}:${auth.htaccess_pass}`
}
// Create the temp and permanent file names for the url.
const digest = createHash(url)
if (!name) {
name = getRemoteFileName(url)
}
if (!ext) {
ext = getRemoteFileExtension(url)
}
const tmpFilename = createFilePath(pluginCacheDir, `tmp-${digest}`, ext)
// Fetch the file.
const response = await requestRemoteNode(url, headers, tmpFilename, httpOpts)
if (response.statusCode == 200) {
// Save the response headers for future requests.
await cache.set(cacheId(url), response.headers)
}
// If the user did not provide an extension and we couldn't get one from remote file, try and guess one
if (ext === ``) {
const buffer = readChunk.sync(tmpFilename, 0, fileType.minimumBytes)
const filetype = fileType(buffer)
if (filetype) {
ext = `.${filetype.ext}`
}
}
const filename = createFilePath(path.join(pluginCacheDir, digest), name, ext)
// If the status code is 200, move the piped temp file to the real name.
if (response.statusCode === 200) {
await fs.move(tmpFilename, filename, { overwrite: true })
// Else if 304, remove the empty response.
} else {
await fs.remove(tmpFilename)
}
// Create the file node.
const fileNode = await createFileNode(filename, createNodeId, {})
fileNode.internal.description = `File "${url}"`
fileNode.url = url
fileNode.parent = parentNodeId
// Override the default plugin as gatsby-source-filesystem needs to
// be the owner of File nodes or there'll be conflicts if any other
// File nodes are created through normal usages of
// gatsby-source-filesystem.
createNode(fileNode, { name: `gatsby-source-filesystem` })
return fileNode
}
/**
* Index of promises resolving to File node from remote url
*/
const processingCache = {}
/**
* pushTask
* --
* pushes a task in to the Queue and the processing cache
*
* Promisfy a task in queue
* @param {CreateRemoteFileNodePayload} task
* @return {Promise<Object>}
*/
const pushTask = task =>
new Promise((resolve, reject) => {
queue
.push(task)
.on(`finish`, task => {
resolve(task)
})
.on(`failed`, () => {
resolve()
})
})
// Keep track of the total number of jobs we push in the queue
let totalJobs = 0
/***************
* Entry Point *
***************/
/**
* createRemoteFileNode
* --
*
* Download a remote file
* First checks cache to ensure duplicate requests aren't processed
* Then pushes to a queue
*
* @param {CreateRemoteFileNodePayload} options
* @return {Promise<Object>} Returns the created node
*/
module.exports = ({
url,
store,
cache,
createNode,
parentNodeId = null,
auth = {},
createNodeId,
ext = null,
name = null,
}) => {
// validation of the input
// without this it's notoriously easy to pass in the wrong `createNodeId`
// see gatsbyjs/gatsby#6643
if (typeof createNodeId !== `function`) {
throw new Error(
`createNodeId must be a function, was ${typeof createNodeId}`
)
}
if (typeof createNode !== `function`) {
throw new Error(`createNode must be a function, was ${typeof createNode}`)
}
if (typeof store !== `object`) {
throw new Error(`store must be the redux store, was ${typeof store}`)
}
if (typeof cache !== `object`) {
throw new Error(`cache must be the Gatsby cache, was ${typeof cache}`)
}
// Check if we already requested node for this remote file
// and return stored promise if we did.
if (processingCache[url]) {
return processingCache[url]
}
if (!url || isWebUri(url) === undefined) {
// should we resolve here, or reject?
// Technically, it's invalid input
return Promise.resolve()
}
totalJobs += 1
bar.total = totalJobs
const fileDownloadPromise = pushTask({
url,
store,
cache,
createNode,
parentNodeId,
createNodeId,
auth,
ext,
name,
})
fileDownloadPromise.then(() => bar.tick())
processingCache[url] = fileDownloadPromise
return fileDownloadPromise
}