-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
452 lines (425 loc) · 13.6 KB
/
index.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/**
* Top-level s3-asset-uploader module
* @module s3-asset-uploader
* @see README.md
*/
// Node imports
const fs = require('fs')
const path = require('path')
// NPM imports
const debug = require('debug')('s3-asset-uploader')
const AWS = require('aws-sdk')
const Bluebird = require('bluebird')
// Lib imports
const directoryLib = require('./lib/directory')
const fileLib = require('./lib/file')
const hashLib = require('./lib/hash')
const streamLib = require('./lib/stream')
const transformLib = require('./lib/transform')
const FILE_EXTENSION_REGEXP = /((\.\w+)?\.\w+)$/
const HASHED_FILENAME_REGEXP = /(-[0-9a-f]{32})((\.\w+)+)$/
const DEFAULT_ACL = 'public-read'
const DEFAULT_DIGEST_FILE_NAME = 'asset-map.json'
const DEFAULT_GZIP_CACHE_CONTROL = `max-age=${365*24*60*60}` // 1 year (in seconds)
const DEFAULT_GZIP_HEADERS = {
'ContentEncoding': 'gzip',
'CacheControl': DEFAULT_GZIP_CACHE_CONTROL
}
/**
* The configuration Object passed into the `S3Sync` constructor
* @typedef {Object} S3SyncConfig
* @property {string} [key] - your AWS access key ID
* @property {string} [secret] - your AWS secret access key
* @property {AWS.S3.BucketName} bucket - the name of the destination AWS S3 bucket
*/
/**
* The options Object passed into the `S3Sync` constructor
* @typedef {Object} S3SyncOptions
* @property {string} path - the base path to synchronize with S3
* @property {Array.<RegExp|string>} [ignorePaths] - skip these paths when gathering files
* @property {AWS.S3.ObjectKey} [digestFileKey] - the destination key of the generated digest file
* @property {string} [prefix] - prepended to all destination file names when uploaded
* @property {S3UploadHeaders} [headers] - extra params used by `AWS.S3` upload method
* @property {S3UploadHeaders} [gzipHeaders] - extra params used by `AWS.S3` upload method for GZIP files
* @property {RegExp} [gzipHashedFileKeyRegexp] - gzip files when hashing them
* @property {RegExp|boolean} [hashedOriginalFileRegexp] - respect hashes in original filenames
* @property {boolean} [includePseudoUnhashedOriginalFilesInDigest] - add pseudo-entries to the digest
* @property {boolean} [forceUpload] - skip `shouldUpload` etag modified lookup for keys before uploading
* @property {boolean} [noUpload] - don't upload anything, just generate a digest mapping
* @property {boolean} [noUploadDigestFile] - don't upload the digest mapping file
* @property {boolean} [noUploadOriginalFiles] - don't upload the original (unhashed) files
* @property {boolean} [noUploadHashedFiles] - don't upload the hashed files
*/
/** @typedef {string} AbsoluteFilePath */
/** @typedef {string} RelativeFileName */
/** @typedef {AWS.S3.ObjectKey} HashedS3Key */
/** @typedef {Object.<RelativeFileName,HashedS3Key>} S3SyncDigest */
/** @typedef {AWS.S3.PutObjectRequest} S3UploadParams */
/** @typedef {AWS.S3.CompleteMultipartUploadOutput|void} S3UploadResult */
/**
* @typedef {Object} S3SyncFileResult
* @property {string} filePath
* @property {S3UploadResult} originalFile
* @property {S3UploadResult} hashedFile
*/
/**
* Some (but not all) of the parameters needed for `S3UploadParams`
* @typedef {Object} S3UploadHeaders
* @property {AWS.S3.ObjectCannedACL} ACL
* @property {AWS.S3.BucketName} Bucket
* @property {AWS.S3.CacheControl} [CacheControl]
* @property {AWS.S3.ContentType} ContentType
* @property {AWS.S3.ContentEncoding} [ContentEncoding]
*/
/**
* Class representing an operation to synchronize a directory with an Amazon S3 bucket
*/
class S3Sync {
/**
* @param {S3SyncConfig} config
* @param {S3SyncOptions} options
* @constructor
*/
constructor(config, options) {
let s3ClientConfiguration = {}
if (config.key && config.secret) {
s3ClientConfiguration = {
accessKeyId: config.key,
secretAccessKey: config.secret
}
}
this.client = new AWS.S3(s3ClientConfiguration)
this.bucket = config.bucket
this.path = fs.realpathSync(options.path)
this.ignorePaths = options.ignorePaths || []
this.digestFileKey = options.digestFileKey || DEFAULT_DIGEST_FILE_NAME
this.prefix = options.prefix || ''
// Header options
this.headers = options.headers || {}
this.gzipHeaders = options.gzipHeaders || DEFAULT_GZIP_HEADERS
// Upload options
this.forceUpload = Boolean(options.forceUpload)
this.noUpload = Boolean(options.noUpload)
this.noUploadDigestFile = Boolean(options.noUploadDigestFile)
this.noUploadOriginalFiles = Boolean(options.noUploadOriginalFiles)
this.noUploadHashedFiles = Boolean(options.noUploadHashedFiles)
// gzip options
this.gzipHashedFileKeyRegexp = options.gzipHashedFileKeyRegexp
// Hashed original file options
if (options.hashedOriginalFileRegexp instanceof RegExp) {
this.hashedOriginalFileRegexp = options.hashedOriginalFileRegexp
} else if (options.hashedOriginalFileRegexp === true) {
this.hashedOriginalFileRegexp = HASHED_FILENAME_REGEXP
}
this.includePseudoUnhashedOriginalFilesInDigest =
Boolean(options.includePseudoUnhashedOriginalFilesInDigest)
this.reset()
}
/**
* The main work-horse method that performs all of the sub-tasks to synchronize
* @returns {Promise.<S3SyncDigest>}
* @public
*/
async run() {
try {
await this.gatherFiles()
await this.addFilesToDigest()
await this.syncFiles()
await this.uploadDigestFile()
return this.digest
} finally {
this.reset()
}
}
/**
* Resets the `S3Sync` instance back to its initial state
* @returns {void}
* @private
*/
reset() {
/** @type {Array.<AbsoluteFilePath>} */
this.gatheredFilePaths = []
/** @type {Object.<AbsoluteFilePath,AWS.S3.ETag>} */
this.filePathToEtagMap = {}
/** @type {S3SyncDigest} */
this.digest = {}
}
/**
* Walks the `this.path` directory and collects all of the file paths
* @returns {Promise.<void>}
* @private
*/
async gatherFiles() {
const filePaths = await directoryLib.getFileNames(this.path, this.ignorePaths)
this.gatheredFilePaths.push(...filePaths)
}
/**
* Iterates through the gathered files and generates the hashed digest mapping
* @returns {Promise.<S3SyncDigest>}
* @private
*/
async addFilesToDigest() {
for (let filePath of this.gatheredFilePaths) {
await this.addFileToDigest(filePath)
}
return this.digest
}
/**
* Uploads the gathered files
* @returns {Promise.<Array.<S3SyncFileResult>>}
* @private
*/
async syncFiles() {
return Bluebird.mapSeries(this.gatheredFilePaths, filePath => {
return Bluebird.props({
filePath,
originalFile: this.uploadOriginalFile(filePath),
hashedFile: this.uploadHashedFile(filePath)
})
})
}
/**
* Hashes the file and adds it to the digest
* @param {AbsoluteFilePath} filePath
* @returns {Promise.<void>}
* @private
*/
async addFileToDigest(filePath) {
const hash = await hashLib.hashFromFile(filePath)
this.filePathToEtagMap[filePath] = hash
const originalFileName = this.relativeFileName(filePath)
const originalFileKey = this.s3KeyForRelativeFileName(originalFileName)
if (this.isHashedFileName(originalFileName)) {
if (this.includePseudoUnhashedOriginalFilesInDigest) {
const unhashedFileName = this.unhashedFileName(originalFileName)
this.digest[unhashedFileName] = originalFileKey
}
this.digest[originalFileName] = originalFileKey
} else {
const hashedFileKey = this.hashedFileKey(originalFileKey, hash)
this.digest[originalFileName] = hashedFileKey
}
}
/**
* @returns {Promise.<S3UploadResult>}
* @private
*/
async uploadDigestFile() {
const key = this.digestFileKey
if (this.noUploadDigestFile) {
debug(`SKIPPING key[${key}] reason[noUploadDigestFile]`)
return
}
return this.upload({
'ACL': DEFAULT_ACL,
'Body': JSON.stringify(this.digest),
'Bucket': this.bucket,
'ContentType': 'application/json',
'Key': key
})
}
/**
* @param {AbsoluteFilePath} filePath
* @returns {Promise.<S3UploadResult>}
* @private
*/
async uploadOriginalFile(filePath) {
const originalFileName = this.relativeFileName(filePath)
const originalFileKey = this.s3KeyForRelativeFileName(originalFileName)
const isHashedOriginalFile = this.isHashedFileName(originalFileName)
if (this.noUploadOriginalFiles && !isHashedOriginalFile) {
debug(`SKIPPING key[${originalFileKey}] reason[noUploadOriginalFiles]`)
return
}
const etag = this.filePathToEtagMap[filePath]
if (await this.shouldUpload(originalFileKey, etag)) {
/** @type {NodeJS.ReadableStream} */
let fileStream = fs.createReadStream(filePath)
let fileHeaders = this.fileHeaders(filePath)
if (isHashedOriginalFile && this.shouldGzipHashedFileKey(originalFileKey)) {
fileStream = streamLib.gzipStream(fileStream)
fileHeaders = { ...fileHeaders, ...this.gzipHeaders }
}
return this.upload({
...fileHeaders,
'Key': originalFileKey,
'Body': fileStream
})
}
}
/**
* @param {AbsoluteFilePath} filePath
* @returns {Promise.<S3UploadResult>}
* @private
*/
async uploadHashedFile(filePath) {
const originalFileName = this.relativeFileName(filePath)
const originalFileKey = this.s3KeyForRelativeFileName(originalFileName)
const hashedFileKey = this.digest[originalFileName]
if (!hashedFileKey) {
// This should never happen under normal circumstances!
debug(`SKIPPING filePath[${filePath}] reason[NotInDigest]`)
return
}
if (hashedFileKey === originalFileKey) {
debug(`SKIPPING key[${hashedFileKey}] reason[originalFileIsHashed]`)
return
}
if (this.noUploadHashedFiles) {
debug(`SKIPPING key[${hashedFileKey}] reason[noUploadHashedFiles]`)
return
}
const transformResult = await transformLib.replaceHashedFilenames({
filePath,
relativeFileName: originalFileName,
digest: this.digest
})
const etag = transformResult.hash || this.filePathToEtagMap[filePath]
if (await this.shouldUpload(hashedFileKey, etag)) {
let fileStream = transformResult.stream
let fileHeaders = this.fileHeaders(filePath)
if (this.shouldGzipHashedFileKey(originalFileKey)) {
fileStream = streamLib.gzipStream(fileStream)
fileHeaders = { ...fileHeaders, ...this.gzipHeaders }
}
return this.upload({
...fileHeaders,
'Key': hashedFileKey,
'Body': fileStream
})
}
}
/**
* @param {S3UploadParams} params
* @returns {Promise.<S3UploadResult>}
* @see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
* @private
*/
async upload(params) {
const key = params['Key']
if (this.noUpload) {
debug(`SKIPPING key[${key}] reason[noUpload]`)
return
}
debug(`UPLOADING key[${key}]`)
return Bluebird.fromCallback(callback => {
this.client.upload(params, callback)
})
}
/**
* @param {AWS.S3.ObjectKey} key
* @param {AWS.S3.ETag} etag
* @returns {Promise.<boolean>}
* @private
*/
async shouldUpload(key, etag) {
if (this.noUpload) {
debug(`SKIPPING key[${key}] reason[noUpload]`)
return false
}
if (this.forceUpload) {
return true
}
try {
await Bluebird.fromCallback(callback => {
this.client.headObject({
'Bucket': this.bucket,
'Key': key,
'IfNoneMatch': etag
}, callback)
})
// File found, ETag does not match
return true
} catch (err) {
switch (err.name) {
case 'NotModified':
debug(`SKIPPING key[${key}] reason[NotModified]`)
return false
case 'NotFound':
return true
default:
throw err
}
}
}
/**
* @param {AbsoluteFilePath} filePath
* @returns {RelativeFileName}
* @private
*/
relativeFileName(filePath) {
return filePath.substring(this.path.length + path.sep.length)
}
/**
* @param {RelativeFileName} fileName
* @returns {AWS.S3.ObjectKey}
* @private
*/
s3KeyForRelativeFileName(fileName) {
return path.posix.join(this.prefix, fileName)
}
/**
* @param {AWS.S3.ObjectKey} fileKey
* @param {AWS.S3.ETag} hash
* @returns {HashedS3Key}
* @private
*/
hashedFileKey(fileKey, hash) {
return fileKey.replace(FILE_EXTENSION_REGEXP, `-${hash}$1`)
}
/**
* @param {RelativeFileName} fileName
* @returns {boolean}
* @private
*/
isHashedFileName(fileName) {
return this.hashedOriginalFileRegexp
? this.hashedOriginalFileRegexp.test(fileName)
: false
}
/**
* @param {RelativeFileName} hashedFileName
* @returns {RelativeFileName}
* @private
*/
unhashedFileName(hashedFileName) {
return hashedFileName.replace(this.hashedOriginalFileRegexp, '$2')
}
/**
* @param {string} originalFileKey
* @returns {boolean}
* @private
*/
shouldGzipHashedFileKey(originalFileKey) {
if (this.gzipHashedFileKeyRegexp instanceof RegExp) {
return this.gzipHashedFileKeyRegexp.test(originalFileKey)
}
return false
}
/**
* @param {AbsoluteFilePath} filePath
* @returns {S3UploadHeaders}
* @private
*/
fileHeaders(filePath) {
const defaultHeaders = {
'ACL': DEFAULT_ACL,
'Bucket': this.bucket
}
const fileHeaders = {
'ContentType': fileLib.getContentType(filePath)
}
const gzipHeaders = fileLib.isGzipped(filePath)
? this.gzipHeaders
: {}
return Object.assign(
defaultHeaders,
this.headers,
fileHeaders,
gzipHeaders
)
}
}
module.exports = {
S3Sync
}