budibase/packages/server/src/api/controllers/deploy/aws.js

166 lines
3.9 KiB
JavaScript
Raw Normal View History

const fs = require("fs")
const { join } = require("../../../utilities/sanitisedPath")
const AWS = require("aws-sdk")
const fetch = require("node-fetch")
2020-07-07 22:29:20 +02:00
const { budibaseAppsDir } = require("../../../utilities/budibaseDir")
2020-09-16 13:18:47 +02:00
const PouchDB = require("../../../db")
2020-07-07 18:47:18 +02:00
async function invalidateCDN(cfDistribution, appId) {
2020-07-06 20:43:40 +02:00
const cf = new AWS.CloudFront({})
2020-07-07 22:29:20 +02:00
return cf
.createInvalidation({
DistributionId: cfDistribution,
InvalidationBatch: {
CallerReference: appId,
Paths: {
Quantity: 1,
Items: [`/assets/${appId}/*`],
},
},
})
.promise()
2020-07-06 20:43:40 +02:00
}
2020-07-03 00:22:20 +02:00
2020-07-08 17:31:26 +02:00
exports.fetchTemporaryCredentials = async function() {
2020-07-06 20:43:40 +02:00
const response = await fetch(process.env.DEPLOYMENT_CREDENTIALS_URL, {
method: "POST",
body: JSON.stringify({
2020-07-07 22:29:20 +02:00
apiKey: process.env.BUDIBASE_API_KEY,
}),
})
if (response.status !== 200) {
2020-07-07 22:29:20 +02:00
throw new Error(
`Error fetching temporary credentials for api key: ${process.env.BUDIBASE_API_KEY}`
)
}
const json = await response.json()
return json
2020-07-07 22:29:20 +02:00
}
2020-07-03 00:22:20 +02:00
const CONTENT_TYPE_MAP = {
html: "text/html",
css: "text/css",
2020-07-07 22:29:20 +02:00
js: "application/javascript",
}
2020-07-03 00:22:20 +02:00
2020-07-06 20:43:40 +02:00
/**
* Recursively walk a directory tree and execute a callback on all files.
2020-07-07 18:47:18 +02:00
* @param {String} dirPath - Directory to traverse
* @param {Function} callback - callback to execute on files
2020-07-06 20:43:40 +02:00
*/
function walkDir(dirPath, callback) {
for (let filename of fs.readdirSync(dirPath)) {
2020-07-07 22:29:20 +02:00
const filePath = `${dirPath}/${filename}`
2020-07-06 20:43:40 +02:00
const stat = fs.lstatSync(filePath)
2020-07-07 22:29:20 +02:00
2020-07-06 20:43:40 +02:00
if (stat.isFile()) {
2020-07-07 18:47:18 +02:00
callback(filePath)
2020-07-06 20:43:40 +02:00
} else {
walkDir(filePath, callback)
}
}
}
2020-09-23 21:23:40 +02:00
async function prepareUploadForS3({ s3Key, metadata, s3, file }) {
const extension = [...file.name.split(".")].pop()
const fileBytes = fs.readFileSync(file.path)
2020-09-23 17:15:09 +02:00
const upload = await s3
2020-09-16 13:18:47 +02:00
.upload({
Key: s3Key,
Body: fileBytes,
2020-09-23 21:23:40 +02:00
ContentType: file.type || CONTENT_TYPE_MAP[extension.toLowerCase()],
2020-09-16 13:18:47 +02:00
Metadata: metadata,
})
.promise()
2020-09-23 17:15:09 +02:00
return {
2020-09-23 21:23:40 +02:00
size: file.size,
name: file.name,
extension,
2020-09-23 17:15:09 +02:00
url: upload.Location,
key: upload.Key,
}
2020-09-16 13:18:47 +02:00
}
2020-09-23 17:15:09 +02:00
exports.prepareUploadForS3 = prepareUploadForS3
2020-07-08 17:31:26 +02:00
exports.uploadAppAssets = async function({
appId,
2020-09-16 13:18:47 +02:00
instanceId,
2020-07-08 17:31:26 +02:00
credentials,
bucket,
cfDistribution,
accountId,
}) {
AWS.config.update({
2020-07-07 22:29:20 +02:00
accessKeyId: credentials.AccessKeyId,
secretAccessKey: credentials.SecretAccessKey,
2020-07-07 22:29:20 +02:00
sessionToken: credentials.SessionToken,
})
const s3 = new AWS.S3({
params: {
2020-07-07 22:29:20 +02:00
Bucket: bucket,
},
})
const appAssetsPath = join(budibaseAppsDir(), appId, "public")
const appPages = fs.readdirSync(appAssetsPath)
let uploads = []
for (let page of appPages) {
// Upload HTML, CSS and JS for each page of the web app
walkDir(join(appAssetsPath, page), function(filePath) {
2020-09-16 13:18:47 +02:00
const appAssetUpload = prepareUploadForS3({
2020-09-23 21:23:40 +02:00
file: {
path: filePath,
name: [...filePath.split("/")].pop(),
},
2020-09-17 13:45:28 +02:00
s3Key: filePath.replace(appAssetsPath, `assets/${appId}`),
2020-09-16 13:18:47 +02:00
s3,
2020-09-17 17:36:39 +02:00
metadata: { accountId },
2020-09-16 13:18:47 +02:00
})
uploads.push(appAssetUpload)
})
}
// Upload file attachments
2020-09-16 13:18:47 +02:00
const db = new PouchDB(instanceId)
const fileUploads = await db.get("_local/fileuploads")
if (fileUploads) {
for (let file of fileUploads.uploads) {
if (file.uploaded) continue
2020-09-16 13:18:47 +02:00
2020-09-17 17:36:39 +02:00
const attachmentUpload = prepareUploadForS3({
2020-09-23 21:23:40 +02:00
file,
2020-09-23 18:02:06 +02:00
s3Key: `assets/${appId}/attachments/${file.processedFileName}`,
2020-09-17 17:36:39 +02:00
s3,
metadata: { accountId },
})
2020-09-16 13:18:47 +02:00
2020-09-17 17:36:39 +02:00
uploads.push(attachmentUpload)
2020-09-17 17:36:39 +02:00
// mark file as uploaded
file.uploaded = true
}
2020-09-17 17:36:39 +02:00
db.put(fileUploads)
2020-09-16 13:18:47 +02:00
}
try {
2020-07-07 18:47:18 +02:00
await Promise.all(uploads)
// TODO: update dynamoDB with a synopsis of the app deployment for historical purposes
2020-07-07 22:29:20 +02:00
await invalidateCDN(cfDistribution, appId)
} catch (err) {
console.error("Error uploading budibase app assets to s3", err)
throw err
}
2020-07-07 22:29:20 +02:00
}