-
Notifications
You must be signed in to change notification settings - Fork 10
/
remote-storage.js
284 lines (260 loc) · 9.76 KB
/
remote-storage.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
/*
Copyright 2019 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const { S3 } = require('@aws-sdk/client-s3')
const path = require('path')
const mime = require('mime-types')
const fs = require('fs-extra')
const joi = require('joi')
const klaw = require('klaw')
const http = require('http')
const { codes, logAndThrow } = require('./StorageError')
const fileExtensionPattern = /\*\.[0-9a-zA-Z]+$/
// /**
// * Joins url path parts
// * @param {...string} args url parts
// * @returns {string}
// */
function urlJoin (...args) {
let start = ''
if (args[0] &&
args[0].startsWith('/')) {
start = '/'
}
return start + args.map(a => a && a.replace(/(^\/|\/$)/g, ''))
.filter(a => a) // remove empty strings / nulls
.join('/')
}
module.exports = class RemoteStorage {
/**
* @param {object} creds
* @param {string} creds.accessKeyId
* @param {string} creds.secretAccessKey
* @param {string} creds.params.Bucket
* @param {string} [creds.sessionToken]
*/
constructor (creds) {
const res = joi.object().keys({
sessionToken: joi.string(),
accessKeyId: joi.string().required(),
secretAccessKey: joi.string().required(),
// hacky needs s3Bucket in creds.params.Bucket
params: joi.object().keys({ Bucket: joi.string().required() }).required()
}).unknown()
.validate(creds)
if (res.error) {
throw res.error
}
// the TVM response could be passed as is to the v2 client constructor, but the v3 client follows a different format
// see https://github.com/adobe/aio-tvm/issues/85
const region = creds.region || 'us-east-1'
// note this must supports TVM + BYO use cases
// see https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/credentials.html
const credentials = {
accessKeyId: creds.accessKeyId,
secretAccessKey: creds.secretAccessKey,
sessionToken: creds.sessionToken,
expiration: creds.expiration ? new Date(creds.expiration) : undefined
}
this.bucket = creds.params.Bucket
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/classes/s3.html#constructor
this.s3 = new S3({ credentials, region })
}
/**
* Checks if prefix exists
* @param {string} prefix
* @returns {boolean}
*/
async folderExists (prefix) {
if (typeof prefix !== 'string') {
throw new Error('prefix must be a valid string')
}
const listParams = {
Bucket: this.bucket,
Prefix: prefix
}
const listedObjects = await this.s3.listObjectsV2(listParams)
return listedObjects.KeyCount > 0
}
/**
* Deletes all files in a prefix location
* @param {string} prefix
*/
async emptyFolder (prefix) {
if (typeof prefix !== 'string') throw new Error('prefix must be a valid string')
const listParams = {
Bucket: this.bucket,
Prefix: prefix
}
const listedObjects = await this.s3.listObjectsV2(listParams)
if (listedObjects.KeyCount < 1) {
return
}
const deleteParams = {
Bucket: this.bucket,
Delete: { Objects: [] }
}
listedObjects.Contents.forEach(({ Key }) => {
deleteParams.Delete.Objects.push({ Key })
})
await this.s3.deleteObjects(deleteParams)
if (listedObjects.IsTruncated) {
await this.emptyFolder(prefix)
}
}
/**
* Uploads a file
* @param {string} file
* @param {string} prefix - prefix to upload the file to
* @param {Object} appConfig - application config
* @param {string} distRoot - Distribution root dir
*/
async uploadFile (file, prefix, appConfig, distRoot) {
if (typeof prefix !== 'string') {
throw new Error('prefix must be a valid string')
}
const content = await fs.readFile(file)
const mimeType = mime.lookup(path.extname(file))
const cacheControlString = this._getCacheControlConfig(mimeType, appConfig.app)
const uploadParams = {
Bucket: this.bucket,
Key: urlJoin(prefix, path.basename(file)),
Body: content,
CacheControl: cacheControlString
}
// add response headers if specified in manifest
const responseHeaders = this.getResponseHeadersForFile(file, distRoot, appConfig)
if (responseHeaders) {
uploadParams.Metadata = responseHeaders
}
// s3 misses some mime types like for css files
if (mimeType) {
uploadParams.ContentType = mimeType
}
// Note: putObject is recommended for files < 100MB and has a limit of 5GB, which is ok for our use case of storing static web assets
// if we intend to store larger files, we should use multipart upload and https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_lib_storage.html
return this.s3.putObject(uploadParams)
}
getResponseHeadersForFile (file, distRoot, appConfig) {
let responseHeaders
if (appConfig.web && appConfig.web['response-headers']) {
responseHeaders = {}
const cdnConfig = appConfig.web['response-headers']
const headerPrefix = 'adp-'
Object.keys(cdnConfig).forEach(rule => {
if (this.canAddHeader(file, distRoot, rule)) {
Object.keys(cdnConfig[rule]).forEach(header => {
this.validateHTTPHeader(header, cdnConfig[rule][header])
responseHeaders[headerPrefix + header] = cdnConfig[rule][header]
})
}
})
}
return responseHeaders
}
canAddHeader (file, distRoot, rule) {
const filePath = path.parse(file)
const normalisedRule = rule.replace(/\//g, path.sep)
const ruleFolderPath = path.parse(normalisedRule)
let folderPathToMatch = path.join(distRoot, ruleFolderPath.dir)
if (folderPathToMatch.endsWith(path.sep)) {
folderPathToMatch = folderPathToMatch.substring(0, folderPathToMatch.length - 1) // remove any trailing path separator
}
if (rule === '/*') { // all content
return true
} else if (rule.endsWith('/*')) { // all content in a folder ex. /test/*
if (filePath.dir.startsWith(folderPathToMatch)) { // matches with the folder
return true
}
} else if (fileExtensionPattern.test(rule)) { // all content with a given extension ex. /*.html or /test/*.js
// check file has same extension as specified in header
if ((filePath.ext === ruleFolderPath.ext) && (filePath.dir.startsWith(folderPathToMatch))) {
return true
}
} else { // specific file match ex. /test/foo.js
const uploadFilePath = path.join(distRoot, normalisedRule)
if (file === uploadFilePath) {
return true
}
}
return false
}
validateHTTPHeader (headerName, value) {
try {
http.validateHeaderName(headerName)
} catch (e) {
logAndThrow(new codes.ERROR_INVALID_HEADER_NAME({ messageValues: [headerName], sdkDetails: {} }))
}
try {
http.validateHeaderValue(headerName, value)
} catch (e) {
logAndThrow(new codes.ERROR_INVALID_HEADER_VALUE({ messageValues: [value, headerName], sdkDetails: {} }))
}
}
async walkDir (dir) {
return new Promise((resolve, reject) => {
const items = []
klaw(dir)
.on('data', fd => {
if (fd.stats.isFile()) {
items.push(fd.path)
}
})
.on('end', () => resolve(items))
})
}
/**
* Uploads all files in a dir to - recursion is supported
* @param {string} dir - directory with files to upload
* @param {string} prefix - prefix to upload the dir to
* @param {Object} appConfig - application config
* @param {function} [postFileUploadCallback] - called for each uploaded file
*/
async uploadDir (dir, prefix, appConfig, postFileUploadCallback) {
if (typeof prefix !== 'string') {
throw new Error('prefix must be a valid string')
}
// walk the whole directory recursively using klaw.
const files = await this.walkDir(dir)
// parallel upload
return Promise.all(files.map(async f => {
// get file's relative folder to the base directory.
let prefixDirectory = path.dirname(path.relative(dir, f))
// base directory returns ".", ignore that.
prefixDirectory = prefixDirectory === '.' ? '' : prefixDirectory
// newPrefix is now the initial prefix plus the files relative directory path.
const newPrefix = urlJoin(prefix, prefixDirectory)
const s3Res = await this.uploadFile(f, newPrefix, appConfig, dir)
if (postFileUploadCallback) {
postFileUploadCallback(f)
}
return s3Res
}))
}
/**
* Get cache control string based on mime type and config
* @param {string|boolean} mimeType - string if valid mimeType or false for unknown files
* @param {Object} appConfig - application config
*/
_getCacheControlConfig (mimeType, appConfig) {
const cacheControlStr = 's-maxage=0'
if (!mimeType) {
return cacheControlStr
} else if (mimeType === mime.lookup('html')) {
return cacheControlStr + ', max-age=' + appConfig.htmlCacheDuration
} else if (mimeType === mime.lookup('js')) {
return cacheControlStr + ', max-age=' + appConfig.jsCacheDuration
} else if (mimeType === mime.lookup('css')) {
return cacheControlStr + ', max-age=' + appConfig.cssCacheDuration
} else if (mimeType.startsWith('image')) {
return cacheControlStr + ', max-age=' + appConfig.imageCacheDuration
} else { return cacheControlStr }
}
}