@@ -27,35 +27,55 @@ class ServerlessLambdaEdgePreExistingCloudFront {
2727 for ( let idx = 0 ; idx < events . length ; idx += 1 ) {
2828 const event = events [ idx ]
2929 const functionArn = await this . getlatestVersionLambdaArn ( functionObj . name )
30- const config = await this . provider . request ( 'CloudFront' , 'getDistribution' , {
31- Id : event . preExistingCloudFront . distributionId
32- } )
33-
34- if ( event . preExistingCloudFront . pathPattern === '*' ) {
35- config . DistributionConfig . DefaultCacheBehavior . LambdaFunctionAssociations = await this . associateFunction (
36- config . DistributionConfig . DefaultCacheBehavior . LambdaFunctionAssociations ,
37- event ,
38- functionObj . name ,
39- functionArn
40- )
41- } else {
42- config . DistributionConfig . CacheBehaviors = await this . associateNonDefaultCacheBehaviors (
43- config . DistributionConfig . CacheBehaviors ,
44- event ,
45- functionObj . name ,
46- functionArn
47- )
48- }
4930
5031 this . serverless . cli . consoleLog (
5132 `${ functionArn } is associating to ${ event . preExistingCloudFront . distributionId } CloudFront Distribution. waiting for deployed status.`
5233 )
5334
54- await this . provider . request ( 'CloudFront' , 'updateDistribution' , {
55- Id : event . preExistingCloudFront . distributionId ,
56- IfMatch : config . ETag ,
57- DistributionConfig : config . DistributionConfig
58- } )
35+ let retryCount = 5
36+
37+ const updateDistribution = async ( ) => {
38+ const config = await this . provider . request ( 'CloudFront' , 'getDistribution' , {
39+ Id : event . preExistingCloudFront . distributionId
40+ } )
41+
42+ if ( event . preExistingCloudFront . pathPattern === '*' ) {
43+ config . DistributionConfig . DefaultCacheBehavior . LambdaFunctionAssociations = await this . associateFunction (
44+ config . DistributionConfig . DefaultCacheBehavior . LambdaFunctionAssociations ,
45+ event ,
46+ functionObj . name ,
47+ functionArn
48+ )
49+ } else {
50+ config . DistributionConfig . CacheBehaviors = await this . associateNonDefaultCacheBehaviors (
51+ config . DistributionConfig . CacheBehaviors ,
52+ event ,
53+ functionObj . name ,
54+ functionArn
55+ )
56+ }
57+
58+ await this . provider
59+ . request ( 'CloudFront' , 'updateDistribution' , {
60+ Id : event . preExistingCloudFront . distributionId ,
61+ IfMatch : config . ETag ,
62+ DistributionConfig : config . DistributionConfig
63+ } )
64+ . catch ( async ( error ) => {
65+ if ( error . providerError . code === 'PreconditionFailed' && retryCount > 0 ) {
66+ this . serverless . cli . consoleLog (
67+ `received precondition failed error, retrying... (${ retryCount } /5)`
68+ )
69+ retryCount -= 1
70+ await new Promise ( ( res ) => setTimeout ( res , 5000 ) )
71+ return updateDistribution ( )
72+ }
73+ this . serverless . cli . consoleLog ( error )
74+ throw error
75+ } )
76+ }
77+
78+ await updateDistribution ( )
5979 }
6080 } )
6181 } , Promise . resolve ( ) )
0 commit comments