Skip to content

Commit

Permalink
feat: integrate lambda web adapter layer for zip packaged lambdas
Browse files Browse the repository at this point in the history
  • Loading branch information
dangreaves committed Sep 20, 2024
1 parent 620ce44 commit 8461b80
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/adapter/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ export async function prepareFunction(
to: path.join(entryPointDir, "handler.js"),
});

// Copy run file.
await fs.copyFile(
path.join(__dirname, "../assets/run.sh"),
path.join(functionDir, "run.sh"),
);

// Replace entrypoint in run file.
await replaceInFile(path.join(functionDir, "run.sh"), {
from: "__HANDLER_PATH__",
to: path.join(entryPointDir, "handler.js"),
});

// Bundle handler using esbuild.
await esbuild.build({
bundle: true,
Expand Down Expand Up @@ -169,6 +181,8 @@ const ALLOWED_PATTERNS: string[] = [
"public/**/*",
// Required for docker targets (e.g. Fargate).
"Dockerfile",
// Required for AWS Lambda Web Adapter.
"run.sh",
];

/**
Expand Down
3 changes: 3 additions & 0 deletions src/assets/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash

node __HANDLER_PATH__
21 changes: 18 additions & 3 deletions src/cdk/GatsbySite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,24 @@ export class GatsbySite extends Construct {
);
}

/**
* Lambda layer for web adapter.
* For docker packaged lambda functions, this is baked into the container image.
* @see https://github.com/awslabs/aws-lambda-web-adapter
*/
const webAdapterLayer = lambda.LayerVersion.fromLayerVersionArn(
this,
"SecretsLayer",
`arn:aws:lambda:${cdk.Aws.REGION}:753240598075:layer:LambdaAdapterLayerX86:23`,
);

// Resolve gatsby functions for each manifest function.
this.gatsbyFunctions = functionsWithOptions.reduce((acc, fn) => {
const { options, isSsrEngine } = fn;

if ("DISABLED" === options.target) return acc;

if ("LAMBDA" === options.target) {
const entryPointDir = path.dirname(fn.pathToEntryPoint);

const functionOptions: lambda.FunctionOptions = {
timeout:
options.timeout ?? isSsrEngine
Expand Down Expand Up @@ -194,9 +203,15 @@ export class GatsbySite extends Construct {
)
: new lambda.Function(this, `Function-${fn.functionId}`, {
...functionOptions,
handler: "run.sh",
runtime: lambda.Runtime.NODEJS_20_X,
code: lambda.Code.fromAsset(fn.functionDir),
handler: `${entryPointDir}/handler.handler`,
layers: [webAdapterLayer, ...(functionOptions.layers ?? [])],
environment: {
...functionOptions.environment,
// Required by web adapter.
AWS_LAMBDA_EXEC_WRAPPER: "/opt/bootstrap",
},
});

const lambdaAlias = lambdaFunction.addAlias("current", {
Expand Down

0 comments on commit 8461b80

Please sign in to comment.