Skip to content

Commit

Permalink
Merge pull request #13 from hoonoh/master
Browse files Browse the repository at this point in the history
fix: retry on stale ETag
  • Loading branch information
horike37 committed Oct 26, 2020
2 parents cea4c69 + 8e1ba7e commit 19dc0b6
Showing 1 changed file with 44 additions and 24 deletions.
68 changes: 44 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,35 +31,55 @@ class ServerlessLambdaEdgePreExistingCloudFront {
event.preExistingCloudFront.stage != `${serverless.service.provider.stage}`) { continue }

const functionArn = await this.getlatestVersionLambdaArn(functionObj.name)
const config = await this.provider.request('CloudFront', 'getDistribution', {
Id: event.preExistingCloudFront.distributionId
})

if (event.preExistingCloudFront.pathPattern === '*') {
config.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations = await this.associateFunction(
config.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations,
event,
functionObj.name,
functionArn
)
} else {
config.DistributionConfig.CacheBehaviors = await this.associateNonDefaultCacheBehaviors(
config.DistributionConfig.CacheBehaviors,
event,
functionObj.name,
functionArn
)
}

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
})
let retryCount = 5

const updateDistribution = async () => {
const config = await this.provider.request('CloudFront', 'getDistribution', {
Id: event.preExistingCloudFront.distributionId
})

if (event.preExistingCloudFront.pathPattern === '*') {
config.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations = await this.associateFunction(
config.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations,
event,
functionObj.name,
functionArn
)
} else {
config.DistributionConfig.CacheBehaviors = await this.associateNonDefaultCacheBehaviors(
config.DistributionConfig.CacheBehaviors,
event,
functionObj.name,
functionArn
)
}

await this.provider
.request('CloudFront', 'updateDistribution', {
Id: event.preExistingCloudFront.distributionId,
IfMatch: config.ETag,
DistributionConfig: config.DistributionConfig
})
.catch(async (error) => {
if (error.providerError.code === 'PreconditionFailed' && retryCount > 0) {
this.serverless.cli.consoleLog(
`received precondition failed error, retrying... (${retryCount}/5)`
)
retryCount -= 1
await new Promise((res) => setTimeout(res, 5000))
return updateDistribution()
}
this.serverless.cli.consoleLog(error)
throw error
})
}

await updateDistribution()
}
})
}, Promise.resolve())
Expand Down

0 comments on commit 19dc0b6

Please sign in to comment.