Skip to content

Commit

Permalink
fix: cloudfront functions rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
thijsdaniels committed Sep 1, 2024
1 parent 56c7815 commit 951ff0b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-apricots-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codedazur/cdk-site-distribution": patch
---

The CloudFront functions are now created in sequence in order to stay under the rate limit.
39 changes: 28 additions & 11 deletions packages/cdk-site-distribution/src/constructs/SiteDistribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ export class SiteDistribution extends Construct {
public readonly alias?: ARecord;
public readonly cacheInvalidator?: CacheInvalidator;

private readonly functions: CloudFrontFunction[] = [];

constructor(
scope: Construct,
id: string,
Expand Down Expand Up @@ -147,6 +149,8 @@ export class SiteDistribution extends Construct {
: undefined,
});

this.avoidFunctionRateLimit();

new CfnOutput(this, "DistributionId", {
value: distribution.distributionId,
});
Expand All @@ -158,6 +162,20 @@ export class SiteDistribution extends Construct {
return distribution;
}

/**
* Ddefines dependencies on functions to avoid a service rate limit that may
* occur when several are created simultaneously.
*/
private avoidFunctionRateLimit() {
if (this.functions.length > 1) {
for (let i = 1; i < this.functions.length; i++) {
const a = this.functions[i - 1];
const b = this.functions[i];
a.node.addDependency(b);
}
}
}

protected behavior({
pattern = "/*",
authentication,
Expand Down Expand Up @@ -214,15 +232,6 @@ export class SiteDistribution extends Construct {
code: functions?.viewerResponse,
});

/**
* Although the response function doesn't actually depend on the request
* function, we define a dependency to avoid a service rate limit that may
* occur when both are created simultaneously.
*/
if (viewerRequest && viewerResponse) {
viewerResponse.node.addDependency(viewerRequest);
}

return {
viewerRequest,
viewerResponse,
Expand All @@ -246,9 +255,13 @@ export class SiteDistribution extends Construct {
return undefined;
}

return new CloudFrontFunction(this, id, {
const func = new CloudFrontFunction(this, id, {
code: this.getHandlerChainCode(handlers, "request"),
});

this.functions.push(func);

return func;
}

protected createViewerResponseFunction({
Expand All @@ -266,9 +279,13 @@ export class SiteDistribution extends Construct {
return undefined;
}

return new CloudFrontFunction(this, id, {
const func = new CloudFrontFunction(this, id, {
code: this.getHandlerChainCode(handlers, "response"),
});

this.functions.push(func);

return func;
}

protected getHandlerChainCode(
Expand Down

0 comments on commit 951ff0b

Please sign in to comment.