Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Lambda URL as CloudFront origin #368

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
/lib
/dist
/utils
/src/utils/GetWebLambdaFunctions.ts
/test/fixtures
62 changes: 55 additions & 7 deletions src/constructs/aws/ServerSideWebsite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const SCHEMA = {
properties: {
type: { const: "server-side-website" },
apiGateway: { enum: ["http", "rest"] },
originName: { type: "string" },
assets: {
type: "object",
additionalProperties: { type: "string" },
Expand Down Expand Up @@ -115,12 +116,6 @@ export class ServerSideWebsite extends AwsConstruct {
})();
const backendCachePolicy = CachePolicy.CACHING_DISABLED;

const apiId =
configuration.apiGateway === "rest"
? this.provider.naming.getRestApiLogicalId()
: this.provider.naming.getHttpApiLogicalId();
const apiGatewayDomain = Fn.join(".", [Fn.ref(apiId), `execute-api.${this.provider.region}.amazonaws.com`]);

// Cast the domains to an array
this.domains = configuration.domain !== undefined ? flatten([configuration.domain]) : undefined;
const certificate =
Expand All @@ -132,7 +127,7 @@ export class ServerSideWebsite extends AwsConstruct {
comment: `${provider.stackName} ${id} website CDN`,
defaultBehavior: {
// Origins are where CloudFront fetches content
origin: new HttpOrigin(apiGatewayDomain, {
origin: new HttpOrigin(this.getCloudFrontOrigin(), {
// API Gateway only supports HTTPS
protocolPolicy: OriginProtocolPolicy.HTTPS_ONLY,
}),
Expand Down Expand Up @@ -435,4 +430,57 @@ export class ServerSideWebsite extends AwsConstruct {
private getErrorPageFileName(): string {
return this.configuration.errorPage !== undefined ? path.basename(this.configuration.errorPage) : "";
}

private getCloudFrontOrigin(): string {
const functions = this.provider.getWebLambdaFunctions();
const functionsUsingLambdaUrl = functions.reduce((count, func) => count + (func.usesLambdaUrl ? 1 : 0), 0);

// Fail if no web functions defined
if (functions.length === 0) {
throw new ServerlessError(
"Error trying to detect CloudFront origin. Please check that at least one Lambda function uses 'url', 'events.httpApi', 'events.http' or 'events.alb'.",
"LIFT_INVALID_STACK_CONFIGURATION"
);
}

// Try to use ApiGateway if one or more functions are defined and none uses Lambda URL
if (functions.length >= 1 && functionsUsingLambdaUrl === 0) {
return this.getApiGatewayUrl();
}

// Try to use Lambda URL if only one web function is defined
if (functions.length === 1 && functionsUsingLambdaUrl === 1) {
return this.getLambdaUrl(functions[0].name);
}

// Try to use configured origin
if (this.configuration.originName !== undefined) {
const selectedWebFunction = functions.find((f) => f.name === this.configuration.originName);
if (selectedWebFunction) {
return selectedWebFunction.usesLambdaUrl
? this.getLambdaUrl(selectedWebFunction.name)
: this.getApiGatewayUrl();
}
}

throw new ServerlessError(
`Error trying to detect CloudFront origin. Invalid or missing 'constructs.${this.id}.originName' key.`,
"LIFT_INVALID_CONSTRUCT_CONFIGURATION"
);
}

private getApiGatewayUrl() {
const apiId =
this.configuration.apiGateway === "rest"
? this.provider.naming.getRestApiLogicalId()
: this.provider.naming.getHttpApiLogicalId();

return Fn.join(".", [Fn.ref(apiId), `execute-api.${this.provider.region}.amazonaws.com`]);
}

private getLambdaUrl(name: string) {
const lambdaUrlId = this.provider.naming.getLambdaFunctionUrlLogicalId(name);

return Fn.select(2, Fn.split("/", Fn.getAtt(lambdaUrlId, "FunctionUrl").toString()));
}
}
4 changes: 4 additions & 0 deletions src/interfaces/WebLambdaFunctionInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface WebLambdaFunctionInterface {
name: string;
usesLambdaUrl: boolean;
}
15 changes: 15 additions & 0 deletions src/providers/AwsProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { getStackOutput } from "../CloudFormation";
import type { CloudformationTemplate, Provider as LegacyAwsProvider, Serverless } from "../types/serverless";
import { awsRequest } from "../classes/aws";
import ServerlessError from "../utils/error";
import type { WebLambdaFunctionInterface } from "../interfaces/WebLambdaFunctionInterface";
import { GetWebLambdaFunctions } from "../utils/GetWebLambdaFunctions";

const AWS_DEFINITION = {
type: "object",
Expand Down Expand Up @@ -62,6 +64,7 @@ export class AwsProvider implements ProviderInterface {
public naming: {
getStackName: () => string;
getLambdaLogicalId: (functionName: string) => string;
getLambdaFunctionUrlLogicalId: (functionName: string) => string;
getRestApiLogicalId: () => string;
getHttpApiLogicalId: () => string;
};
Expand Down Expand Up @@ -160,6 +163,18 @@ export class AwsProvider implements ProviderInterface {
resources: this.app.synth().getStackByName(this.stack.stackName).template as CloudformationTemplate,
});
}

/**
* This function can be used by other constructs to get all web Lambda functions
* Web Lambda functions must contain at least one of the following keys:
* - url
* - events.http
* - events.httpApi
* - events.alb
*/
getWebLambdaFunctions(): WebLambdaFunctionInterface[] {
return GetWebLambdaFunctions(this.serverless.service.functions);
}
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/types/serverless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type Provider = {
naming: {
getStackName: () => string;
getLambdaLogicalId: (functionName: string) => string;
getLambdaFunctionUrlLogicalId: (functionName: string) => string;
getRestApiLogicalId: () => string;
getHttpApiLogicalId: () => string;
getCompiledTemplateFileName: () => string;
Expand Down
21 changes: 21 additions & 0 deletions src/utils/GetWebLambdaFunctions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { WebLambdaFunctionInterface } from "../interfaces/WebLambdaFunctionInterface";

export function GetWebLambdaFunctions(functions: any): WebLambdaFunctionInterface[] {
if (functions === undefined) {
return [];
}

return Object.keys(functions)
.filter((key) => {
const fn = functions[key];

return fn.url !== undefined || (fn.events !== undefined && fn.events.some((e: any) => e.httpApi || e.http || e.alb));
})
.map((key) => {
return {
name: key,
usesLambdaUrl: functions[key].url !== undefined,
};
})
;
}
Loading