From 40def6d0106c56783cd197b20af04969404280c8 Mon Sep 17 00:00:00 2001 From: Ricardo Machado Date: Wed, 6 May 2020 21:47:18 +0200 Subject: [PATCH] fix: race condition when updating the distribution --- index.js | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 6ff0b6c..7dc7a28 100644 --- a/index.js +++ b/index.js @@ -11,11 +11,21 @@ class ServerlessLambdaEdgePreExistingCloudFront { this.hooks = { 'after:aws:deploy:finalize:cleanup': async () => { - this.serverless.service.getAllFunctions().forEach(async (functionName) => { - const functionObj = this.serverless.service.getFunction(functionName) - if (functionObj.events) { - functionObj.events.forEach(async (event) => { - if (event.preExistingCloudFront && this.checkAllowedDeployStage()) { + await this.serverless.service + .getAllFunctions() + .filter((functionName) => { + const functionObj = this.serverless.service.getFunction(functionName) + return functionObj.events + }) + .reduce((promiseOutput, functionName) => { + return promiseOutput.then(async () => { + const functionObj = this.serverless.service.getFunction(functionName) + const events = functionObj.events.filter( + (event) => event.preExistingCloudFront && this.checkAllowedDeployStage() + ) + + for (let idx = 0; idx < events.length; idx += 1) { + const event = events[idx] const functionArn = await this.getlatestVersionLambdaArn(functionObj.name) const config = await this.provider.request('CloudFront', 'getDistribution', { Id: event.preExistingCloudFront.distributionId @@ -37,18 +47,18 @@ class ServerlessLambdaEdgePreExistingCloudFront { ) } - this.provider.request('CloudFront', 'updateDistribution', { + this.serverless.cli.consoleLog( + `${functionArn} is associating to ${event.preExistingCloudFront.distributionId} CloudFront Distribution. waiting for deployed status.` + ) + + await this.provider.request('CloudFront', 'updateDistribution', { Id: event.preExistingCloudFront.distributionId, IfMatch: config.ETag, DistributionConfig: config.DistributionConfig }) - this.serverless.cli.consoleLog( - `${functionArn} is associating to ${event.preExistingCloudFront.distributionId} CloudFront Distribution. waiting for deployed status.` - ) } }) - } - }) + }, Promise.resolve()) } } }