Skip to content

Instantly share code, notes, and snippets.

@pbadenski
Last active June 28, 2024 15:58
Show Gist options
  • Save pbadenski/2011f2763ca572c2475a37433cb59549 to your computer and use it in GitHub Desktop.
Save pbadenski/2011f2763ca572c2475a37433cb59549 to your computer and use it in GitHub Desktop.
Node 18.X layer for AWS lambda
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#ifndef NODE_MAJOR
#error Must pass NODE_MAJOR to the compiler (eg "10")
#define NODE_MAJOR ""
#endif
#define AWS_EXECUTION_ENV "AWS_Lambda_nodejs" NODE_MAJOR "_lambci"
#define NODE_PATH "/opt/nodejs/node" NODE_MAJOR "/node_modules:" \
"/opt/nodejs/node_modules:" \
"/var/runtime/node_modules:" \
"/var/runtime:" \
"/var/task"
#define MIN_MEM_SIZE 128
#define ARG_BUF_SIZE 32
int main(void) {
setenv("AWS_EXECUTION_ENV", AWS_EXECUTION_ENV, true);
setenv("NODE_PATH", NODE_PATH, true);
setenv("LD_LIBRARY_PATH", "/opt/lib:/lib64", true);
const char *mem_size_str = getenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE");
int mem_size = mem_size_str != NULL ? atoi(mem_size_str) : MIN_MEM_SIZE;
char max_semi_space_size[ARG_BUF_SIZE];
snprintf(max_semi_space_size, ARG_BUF_SIZE, "--max-semi-space-size=%d", mem_size * 5 / 100);
char max_old_space_size[ARG_BUF_SIZE];
snprintf(max_old_space_size, ARG_BUF_SIZE, "--max-old-space-size=%d", mem_size * 90 / 100);
execv("/opt/bin/node", (char *[]){
"node",
"--expose-gc",
"--max-http-header-size=16378",
max_semi_space_size,
max_old_space_size,
"/opt/bootstrap.js",
NULL});
perror("Could not execv");
return EXIT_FAILURE;
}
const http = require('http')
const RUNTIME_PATH = '/2018-06-01/runtime'
const CALLBACK_USED = Symbol('CALLBACK_USED')
const {
AWS_LAMBDA_FUNCTION_NAME,
AWS_LAMBDA_FUNCTION_VERSION,
AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
AWS_LAMBDA_LOG_GROUP_NAME,
AWS_LAMBDA_LOG_STREAM_NAME,
LAMBDA_TASK_ROOT,
_HANDLER,
AWS_LAMBDA_RUNTIME_API,
} = process.env
const [HOST, PORT] = AWS_LAMBDA_RUNTIME_API.split(':')
start()
async function start() {
let handler
try {
handler = getHandler()
} catch (e) {
await initError(e)
return process.exit(1)
}
tryProcessEvents(handler)
}
async function tryProcessEvents(handler) {
try {
await processEvents(handler)
} catch (e) {
console.error(e)
return process.exit(1)
}
}
async function processEvents(handler) {
while (true) {
const { event, context } = await nextInvocation()
let result
try {
result = await handler(event, context)
} catch (e) {
await invokeError(e, context)
continue
}
const callbackUsed = context[CALLBACK_USED]
await invokeResponse(result, context)
if (callbackUsed && context.callbackWaitsForEmptyEventLoop) {
return process.prependOnceListener('beforeExit', () => tryProcessEvents(handler))
}
}
}
function initError(err) {
return postError(`${RUNTIME_PATH}/init/error`, err)
}
async function nextInvocation() {
const res = await request({ path: `${RUNTIME_PATH}/invocation/next` })
if (res.statusCode !== 200) {
throw new Error(`Unexpected /invocation/next response: ${JSON.stringify(res)}`)
}
if (res.headers['lambda-runtime-trace-id']) {
process.env._X_AMZN_TRACE_ID = res.headers['lambda-runtime-trace-id']
} else {
delete process.env._X_AMZN_TRACE_ID
}
const deadlineMs = +res.headers['lambda-runtime-deadline-ms']
let context = {
awsRequestId: res.headers['lambda-runtime-aws-request-id'],
invokedFunctionArn: res.headers['lambda-runtime-invoked-function-arn'],
logGroupName: AWS_LAMBDA_LOG_GROUP_NAME,
logStreamName: AWS_LAMBDA_LOG_STREAM_NAME,
functionName: AWS_LAMBDA_FUNCTION_NAME,
functionVersion: AWS_LAMBDA_FUNCTION_VERSION,
memoryLimitInMB: AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
getRemainingTimeInMillis: () => deadlineMs - Date.now(),
callbackWaitsForEmptyEventLoop: true,
}
if (res.headers['lambda-runtime-client-context']) {
context.clientContext = JSON.parse(res.headers['lambda-runtime-client-context'])
}
if (res.headers['lambda-runtime-cognito-identity']) {
context.identity = JSON.parse(res.headers['lambda-runtime-cognito-identity'])
}
const event = JSON.parse(res.body)
return { event, context }
}
async function invokeResponse(result, context) {
const res = await request({
method: 'POST',
path: `${RUNTIME_PATH}/invocation/${context.awsRequestId}/response`,
body: JSON.stringify(result === undefined ? null : result),
})
if (res.statusCode !== 202) {
throw new Error(`Unexpected /invocation/response response: ${JSON.stringify(res)}`)
}
}
function invokeError(err, context) {
return postError(`${RUNTIME_PATH}/invocation/${context.awsRequestId}/error`, err)
}
async function postError(path, err) {
const lambdaErr = toLambdaErr(err)
const res = await request({
method: 'POST',
path,
headers: {
'Content-Type': 'application/json',
'Lambda-Runtime-Function-Error-Type': lambdaErr.errorType,
},
body: JSON.stringify(lambdaErr),
})
if (res.statusCode !== 202) {
throw new Error(`Unexpected ${path} response: ${JSON.stringify(res)}`)
}
}
function getHandler() {
const appParts = _HANDLER.split('.')
if (appParts.length !== 2) {
throw new Error(`Bad handler ${_HANDLER}`)
}
const [modulePath, handlerName] = appParts
// Let any errors here be thrown as-is to aid debugging
const app = require(LAMBDA_TASK_ROOT + '/' + modulePath)
const userHandler = app[handlerName]
if (userHandler == null) {
throw new Error(`Handler '${handlerName}' missing on module '${modulePath}'`)
} else if (typeof userHandler !== 'function') {
throw new Error(`Handler '${handlerName}' from '${modulePath}' is not a function`)
}
return (event, context) => new Promise((resolve, reject) => {
context.succeed = resolve
context.fail = reject
context.done = (err, data) => err ? reject(err) : resolve(data)
const callback = (err, data) => {
context[CALLBACK_USED] = true
context.done(err, data)
}
let result
try {
result = userHandler(event, context, callback)
} catch (e) {
return reject(e)
}
if (result != null && typeof result.then === 'function') {
result.then(resolve, reject)
}
})
}
function request(options) {
options.host = HOST
options.port = PORT
return new Promise((resolve, reject) => {
let req = http.request(options, res => {
let bufs = []
res.on('data', data => bufs.push(data))
res.on('end', () => resolve({
statusCode: res.statusCode,
headers: res.headers,
body: Buffer.concat(bufs).toString(),
}))
res.on('error', reject)
})
req.on('error', reject)
req.end(options.body)
})
}
function toLambdaErr(err) {
const { name, message, stack } = err
return {
errorType: name || typeof err,
errorMessage: message || ('' + err),
stackTrace: (stack || '').split('\n').slice(1),
}
}
#!/bin/sh
export NODE_VERSION=18.2.0
docker build --build-arg NODE_VERSION -t node-provided-lambda-v18.x .
docker run --rm node-provided-lambda-v18.x cat /tmp/node-v${NODE_VERSION}.zip > ./layer.zip
FROM public.ecr.aws/amazonlinux/amazonlinux:2
RUN yum groupinstall -y development
RUN yum install -y tar xz python3
RUN yum install -y which clang cmake
RUN mkdir -p /build /opt
WORKDIR /build
RUN curl -fsL https://ftp.gnu.org/gnu/make/make-4.3.tar.gz | tar xzf -
RUN curl -fsL https://ftp.gnu.org/gnu/glibc/glibc-2.35.tar.xz | tar xJf -
# Build make 4.3
WORKDIR /build/make-4.3
RUN ./configure
RUN make -j `nproc`
RUN make -j `nproc` install
ENV MAKE=/usr/local/bin/make
# Build glibc
RUN mkdir -p /build/glibc-2.35/build
WORKDIR /build/glibc-2.35/build
RUN ../configure --prefix /opt
RUN make -j `nproc`
RUN make -j `nproc` install
COPY bootstrap.c bootstrap.js /opt/
ARG NODE_VERSION
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin
RUN curl -sSL https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz | \
tar -xJ -C /opt --strip-components 1 -- node-v${NODE_VERSION}-linux-x64/bin/node && \
strip /opt/bin/node
WORKDIR /opt
RUN export NODE_MAJOR=$(echo $NODE_VERSION | awk -F. '{print "\""$1"\""}') && \
clang -Wall -Werror -s -O2 -D NODE_MAJOR="$NODE_MAJOR" -o bootstrap bootstrap.c && \
rm bootstrap.c
# Patch interpreter location (ld-linux-x86-64.so.2) into the node binary
RUN curl -fsL https://github.com/NixOS/patchelf/releases/download/0.14.5/patchelf-0.14.5-x86_64.tar.gz | tar xzf - -C /build
RUN /build/bin/patchelf --set-interpreter /opt/lib/ld-linux-x86-64.so.2 /opt/bin/node
RUN zip -yr /tmp/node-v${NODE_VERSION}.zip ./*
# Can execute node in AL2 with a different glibc from the OS.
# RUN LD_LIBRARY_PATH=/opt/lib:/lib64 /opt/bin/node
Copyright 2018 Michael Hart and LambCI contributors
Copyright 2019-2022 Pawel Badenski
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment