Skip to content

[WIP] test(aws): Run E2E tests with AWS SAM #17367

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

Draft
wants to merge 5 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1031,6 +1031,12 @@ jobs:
uses: actions/setup-node@v4
with:
node-version-file: 'dev-packages/e2e-tests/test-applications/${{ matrix.test-application }}/package.json'
- name: Set up AWS SAM
if: matrix.test-application == 'aws-lambda-sam'
uses: aws-actions/setup-sam@v2
with:
use-installer: true
token: ${{ secrets.GITHUB_TOKEN }}
- name: Restore caches
uses: ./.github/actions/restore-cache
with:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports.handler = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
event,
context,
}),
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as Sentry from '@sentry/aws-serverless';

export const handler = Sentry.wrapHandler(async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
event,
}),
};
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports.handler = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
event,
context,
}),
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as Sentry from '@sentry/aws-serverless';

export const handler = Sentry.wrapHandler(async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
event,
}),
};
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "aws-lambda-sam",
"version": "1.0.0",
"private": true,
"type": "commonjs",
"scripts": {
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install && npx rimraf node_modules/@sentry/aws-serverless/nodejs",
"test:assert": "pnpm test"
},
"//": "We just need the AWS layer zip file, not the NPM package",
"devDependencies": {
"@sentry/aws-serverless": "link:../../../../packages/aws-serverless/build/aws/dist-serverless/",
"@aws-sdk/client-lambda": "^3.863.0",
"@playwright/test": "~1.53.2",
"@sentry-internal/test-utils": "link:../../../test-utils",
"aws-cdk-lib": "^2.210.0",
"constructs": "^10.4.2",
"glob": "^11.0.3"
},
"volta": {
"extends": "../../package.json"
},
"sentryTest": {
"optional": true
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { getPlaywrightConfig } from '@sentry-internal/test-utils';

export default getPlaywrightConfig();
134 changes: 134 additions & 0 deletions dev-packages/e2e-tests/test-applications/aws-lambda-sam/stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { Stack, CfnResource, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as dns from 'node:dns/promises';
import { platform } from 'node:process';
import { globSync } from 'glob';
import { execSync } from 'node:child_process';

const LAMBDA_FUNCTIONS_WITH_LAYER_DIR = './lambda-functions-layer';
const LAMBDA_FUNCTIONS_WITH_NPM_DIR = './lambda-functions-npm';
const LAMBDA_FUNCTION_TIMEOUT = 10;
const LAYER_DIR = './node_modules/@sentry/aws-serverless/';
export const SAM_PORT = 3001;
const NODE_RUNTIME = `nodejs${process.version.split('.').at(0)?.replace('v', '')}.x`;

export class LocalLambdaStack extends Stack {
sentryLayer: CfnResource;

constructor(scope: Construct, id: string, props: StackProps, hostIp: string) {
console.log('[LocalLambdaStack] Creating local SAM Lambda Stack');
super(scope, id, props);

this.templateOptions.templateFormatVersion = '2010-09-09';
this.templateOptions.transforms = ['AWS::Serverless-2016-10-31'];

console.log('[LocalLambdaStack] Add Sentry Lambda layer containing the Sentry SDK to the SAM stack');

const [layerZipFile] = globSync('sentry-node-serverless-*.zip', { cwd: LAYER_DIR });

if (!layerZipFile) {
throw new Error(`[LocalLambdaStack] Could not find sentry-node-serverless zip file in ${LAYER_DIR}`);
}

this.sentryLayer = new CfnResource(this, 'SentryNodeServerlessSDK', {
type: 'AWS::Serverless::LayerVersion',
properties: {
ContentUri: path.join(LAYER_DIR, layerZipFile),
CompatibleRuntimes: ['nodejs18.x', 'nodejs20.x', 'nodejs22.x'],
},
});

const dsn = `http://public@${hostIp}:3031/1337`;
console.log(`[LocalLambdaStack] Using Sentry DSN: ${dsn}`);

this.addLambdaFunctions({ functionsDir: LAMBDA_FUNCTIONS_WITH_LAYER_DIR, dsn, addLayer: true });
this.addLambdaFunctions({ functionsDir: LAMBDA_FUNCTIONS_WITH_NPM_DIR, dsn, addLayer: false });
}

private addLambdaFunctions({
functionsDir,
dsn,
addLayer,
}: {
functionsDir: string;
dsn: string;
addLayer: boolean;
}) {
console.log(`[LocalLambdaStack] Add all Lambda functions defined in ${functionsDir} to the SAM stack`);

const lambdaDirs = fs
.readdirSync(functionsDir)
.filter(dir => fs.statSync(path.join(functionsDir, dir)).isDirectory());

for (const lambdaDir of lambdaDirs) {
const functionName = `${lambdaDir}${addLayer ? 'Layer' : 'Npm'}`;

if (!addLayer) {
console.log(`[LocalLambdaStack] Install dependencies for ${functionName}`);
const packageJson = { dependencies: { '@sentry/aws-serverless': '* || latest' } };
fs.writeFileSync(path.join(functionsDir, lambdaDir, 'package.json'), JSON.stringify(packageJson, null, 2));
execSync(`npm install --prefix ${path.join(functionsDir, lambdaDir)}`);
}

const isEsm = fs.existsSync(path.join(functionsDir, lambdaDir, 'index.mjs'));

new CfnResource(this, functionName, {
type: 'AWS::Serverless::Function',
properties: {
CodeUri: path.join(functionsDir, lambdaDir),
Handler: 'index.handler',
Runtime: NODE_RUNTIME,
Timeout: LAMBDA_FUNCTION_TIMEOUT,
Layers: addLayer ? [{ Ref: this.sentryLayer.logicalId }] : undefined,
Environment: {
Variables: {
SENTRY_DSN: dsn,
SENTRY_TRACES_SAMPLE_RATE: 1.0,
SENTRY_DEBUG: true,
NODE_OPTIONS: `--${isEsm ? 'import' : 'require'}=@sentry/aws-serverless/awslambda-auto`,
},
},
},
});

console.log(`[LocalLambdaStack] Added Lambda function: ${functionName}`);
}
}

static async waitForStack(timeout = 60000, port = SAM_PORT) {
const startTime = Date.now();
const maxWaitTime = timeout;

while (Date.now() - startTime < maxWaitTime) {
try {
const response = await fetch(`http://127.0.0.1:${port}/`);

if (response.ok || response.status === 404) {
console.log(`[LocalLambdaStack] SAM stack is ready`);
return;
}
} catch {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}

throw new Error(`[LocalLambdaStack] Failed to start SAM stack after ${timeout}ms`);
}
}

export async function getHostIp() {
if (process.env.GITHUB_ACTIONS) {
const host = await dns.lookup(os.hostname());
return host.address;
}

if (platform === 'darwin' || platform === 'win32') {
return 'host.docker.internal';
}

const host = await dns.lookup(os.hostname());
return host.address;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { startEventProxyServer } from '@sentry-internal/test-utils';

startEventProxyServer({
port: 3031,
proxyServerName: 'aws-serverless-lambda-sam',
});
Loading
Loading