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

65 lines
1.7 KiB
JavaScript
Raw Normal View History

const CouchDB = require("pouchdb")
const PouchDB = require("../../../db")
2020-07-08 17:31:26 +02:00
const { uploadAppAssets, fetchTemporaryCredentials } = require("./aws")
2020-07-03 00:22:20 +02:00
function replicate(local, remote) {
return new Promise((resolve, reject) => {
2020-07-07 22:29:20 +02:00
const replication = local.sync(remote)
replication.on("complete", () => resolve())
replication.on("error", err => reject(err))
2020-07-07 22:29:20 +02:00
})
}
2020-07-08 17:31:26 +02:00
async function replicateCouch({ instanceId, clientId, credentials }) {
2020-07-07 22:29:20 +02:00
const databases = [`client_${clientId}`, "client_app_lookup", instanceId]
2020-07-03 00:22:20 +02:00
2020-07-08 17:31:26 +02:00
const replications = databases.map(localDbName => {
const localDb = new PouchDB(localDbName)
2020-07-07 22:29:20 +02:00
const remoteDb = new CouchDB(
2020-07-08 17:31:26 +02:00
`${process.env.DEPLOYMENT_DB_URL}/${localDbName}`,
{
auth: {
...credentials,
},
}
2020-07-07 22:29:20 +02:00
)
2020-07-03 00:22:20 +02:00
2020-07-07 22:29:20 +02:00
return replicate(localDb, remoteDb)
})
2020-07-07 18:47:18 +02:00
2020-07-07 22:29:20 +02:00
await Promise.all(replications)
2020-07-03 00:22:20 +02:00
}
exports.deployApp = async function(ctx) {
try {
const clientAppLookupDB = new PouchDB("client_app_lookup")
const { clientId } = await clientAppLookupDB.get(ctx.user.appId)
2020-07-07 22:29:20 +02:00
ctx.log.info(`Uploading assets for appID ${ctx.user.appId} assets to s3..`)
2020-07-08 17:31:26 +02:00
const credentials = await fetchTemporaryCredentials()
2020-07-07 22:29:20 +02:00
await uploadAppAssets({
clientId,
2020-07-07 22:29:20 +02:00
appId: ctx.user.appId,
2020-09-16 13:18:47 +02:00
instanceId: ctx.user.instanceId,
2020-07-08 17:31:26 +02:00
...credentials,
})
// replicate the DB to the couchDB cluster in prod
2020-07-07 22:29:20 +02:00
ctx.log.info("Replicating local PouchDB to remote..")
2020-07-08 17:31:26 +02:00
await replicateCouch({
instanceId: ctx.user.instanceId,
clientId,
credentials: credentials.couchDbCreds,
})
2020-07-07 22:29:20 +02:00
ctx.body = {
status: "SUCCESS",
completed: Date.now(),
}
2020-07-07 18:47:18 +02:00
} catch (err) {
2020-07-07 22:29:20 +02:00
ctx.throw(err.status || 500, `Deployment Failed: ${err.message}`)
2020-07-07 18:47:18 +02:00
}
2020-07-07 22:29:20 +02:00
}