Skip to content

Commit 36ad61b

Browse files
committed
Merge branch 'main' into sebsto/apigatewayresponse
2 parents 7004638 + 18660fc commit 36ad61b

14 files changed

+1643
-1
lines changed

Diff for: .licenseignore

+2
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,5 @@ Package.resolved
3232
.swiftformat
3333
*.yaml
3434
*.yml
35+
**/.npmignore
36+
**/*.json

Diff for: Examples/CDK/Package.swift

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// swift-tools-version:6.0
2+
3+
import PackageDescription
4+
5+
// needed for CI to test the local version of the library
6+
import struct Foundation.URL
7+
8+
#if os(macOS)
9+
let platforms: [PackageDescription.SupportedPlatform]? = [.macOS(.v15)]
10+
#else
11+
let platforms: [PackageDescription.SupportedPlatform]? = nil
12+
#endif
13+
14+
let package = Package(
15+
name: "swift-aws-lambda-runtime-example",
16+
platforms: platforms,
17+
products: [
18+
.executable(name: "APIGatewayLambda", targets: ["APIGatewayLambda"])
19+
],
20+
dependencies: [
21+
// during CI, the dependency on local version of swift-aws-lambda-runtime is added dynamically below
22+
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main"),
23+
.package(url: "https://github.com/swift-server/swift-aws-lambda-events.git", branch: "main"),
24+
],
25+
targets: [
26+
.executableTarget(
27+
name: "APIGatewayLambda",
28+
dependencies: [
29+
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
30+
.product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"),
31+
],
32+
path: "."
33+
)
34+
]
35+
)
36+
37+
if let localDepsPath = Context.environment["LAMBDA_USE_LOCAL_DEPS"],
38+
localDepsPath != "",
39+
let v = try? URL(fileURLWithPath: localDepsPath).resourceValues(forKeys: [.isDirectoryKey]),
40+
v.isDirectory == true
41+
{
42+
// when we use the local runtime as deps, let's remove the dependency added above
43+
let indexToRemove = package.dependencies.firstIndex { dependency in
44+
if case .sourceControl(
45+
name: _,
46+
location: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
47+
requirement: _
48+
) = dependency.kind {
49+
return true
50+
}
51+
return false
52+
}
53+
if let indexToRemove {
54+
package.dependencies.remove(at: indexToRemove)
55+
}
56+
57+
// then we add the dependency on LAMBDA_USE_LOCAL_DEPS' path (typically ../..)
58+
print("[INFO] Compiling against swift-aws-lambda-runtime located at \(localDepsPath)")
59+
package.dependencies += [
60+
.package(name: "swift-aws-lambda-runtime", path: localDepsPath)
61+
]
62+
}

Diff for: Examples/CDK/README.md

+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# API Gateway and Cloud Development Kit
2+
3+
This is a simple example of an AWS Lambda function invoked through an Amazon API Gateway and deployed with the Cloud Development Kit (CDK).
4+
5+
## Code
6+
7+
The Lambda function takes all HTTP headers it receives as input and returns them as output. See the [API Gateway example](Examples/APIGateway/README.md) for a complete description of the code.
8+
9+
## Build & Package
10+
11+
To build the package, type the following commands.
12+
13+
```bash
14+
swift build
15+
swift package archive --allow-network-connections docker
16+
```
17+
18+
If there is no error, there is a ZIP file ready to deploy.
19+
The ZIP file is located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/APIGatewayLambda/APIGatewayLambda.zip`
20+
21+
## Deploy
22+
23+
>[NOTE]
24+
>Before deploying the infrastructure, you need to have NodeJS and the AWS CDK installed and configured.
25+
>For more information, see the [AWS CDK documentation](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html).
26+
27+
To deploy the infrastructure, type the following commands.
28+
29+
```sh
30+
# Change to the infra directory
31+
cd infra
32+
33+
# Install the dependencies (only before the first deployment)
34+
npm install
35+
36+
cdk deploy
37+
38+
✨ Synthesis time: 2.88s
39+
... redacted for brevity ...
40+
Do you wish to deploy these changes (y/n)? y
41+
... redacted for brevity ...
42+
✅ LambdaApiStack
43+
44+
✨ Deployment time: 42.96s
45+
46+
Outputs:
47+
LambdaApiStack.ApiUrl = https://tyqnjcawh0.execute-api.eu-central-1.amazonaws.com/
48+
Stack ARN:
49+
arn:aws:cloudformation:eu-central-1:401955065246:stack/LambdaApiStack/e0054390-be05-11ef-9504-065628de4b89
50+
51+
✨ Total time: 45.84s
52+
```
53+
54+
## Invoke your Lambda function
55+
56+
To invoke the Lambda function, use this `curl` command line.
57+
58+
```bash
59+
curl https://tyqnjcawh0.execute-api.eu-central-1.amazonaws.com
60+
```
61+
62+
Be sure to replace the URL with the API Gateway endpoint returned in the previous step.
63+
64+
This should print a JSON similar to
65+
66+
```bash
67+
{"version":"2.0","rawPath":"\/","isBase64Encoded":false,"rawQueryString":"","headers":{"user-agent":"curl\/8.7.1","accept":"*\/*","host":"a5q74es3k2.execute-api.us-east-1.amazonaws.com","content-length":"0","x-amzn-trace-id":"Root=1-66fb0388-691f744d4bd3c99c7436a78d","x-forwarded-port":"443","x-forwarded-for":"81.0.0.43","x-forwarded-proto":"https"},"requestContext":{"requestId":"e719cgNpoAMEcwA=","http":{"sourceIp":"81.0.0.43","path":"\/","protocol":"HTTP\/1.1","userAgent":"curl\/8.7.1","method":"GET"},"stage":"$default","apiId":"a5q74es3k2","time":"30\/Sep\/2024:20:01:12 +0000","timeEpoch":1727726472922,"domainPrefix":"a5q74es3k2","domainName":"a5q74es3k2.execute-api.us-east-1.amazonaws.com","accountId":"012345678901"}
68+
```
69+
70+
If you have `jq` installed, you can use it to pretty print the output.
71+
72+
```bash
73+
curl -s https://tyqnjcawh0.execute-api.eu-central-1.amazonaws.com | jq
74+
{
75+
"version": "2.0",
76+
"rawPath": "/",
77+
"requestContext": {
78+
"domainPrefix": "a5q74es3k2",
79+
"stage": "$default",
80+
"timeEpoch": 1727726558220,
81+
"http": {
82+
"protocol": "HTTP/1.1",
83+
"method": "GET",
84+
"userAgent": "curl/8.7.1",
85+
"path": "/",
86+
"sourceIp": "81.0.0.43"
87+
},
88+
"apiId": "a5q74es3k2",
89+
"accountId": "012345678901",
90+
"requestId": "e72KxgsRoAMEMSA=",
91+
"domainName": "a5q74es3k2.execute-api.us-east-1.amazonaws.com",
92+
"time": "30/Sep/2024:20:02:38 +0000"
93+
},
94+
"rawQueryString": "",
95+
"routeKey": "$default",
96+
"headers": {
97+
"x-forwarded-for": "81.0.0.43",
98+
"user-agent": "curl/8.7.1",
99+
"host": "a5q74es3k2.execute-api.us-east-1.amazonaws.com",
100+
"accept": "*/*",
101+
"x-amzn-trace-id": "Root=1-66fb03de-07533930192eaf5f540db0cb",
102+
"content-length": "0",
103+
"x-forwarded-proto": "https",
104+
"x-forwarded-port": "443"
105+
},
106+
"isBase64Encoded": false
107+
}
108+
```
109+
110+
## Undeploy
111+
112+
When done testing, you can delete the infrastructure with this command.
113+
114+
```bash
115+
cdk destroy
116+
117+
Are you sure you want to delete: LambdaApiStack (y/n)? y
118+
LambdaApiStack: destroying... [1/1]
119+
... redacted for brevity ...
120+
✅ LambdaApiStack: destroyed
121+
```

Diff for: Examples/CDK/Sources/main.swift

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftAWSLambdaRuntime open source project
4+
//
5+
// Copyright (c) 2024 Apple Inc. and the SwiftAWSLambdaRuntime project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
import AWSLambdaEvents
16+
import AWSLambdaRuntime
17+
18+
#if canImport(FoundationEssentials)
19+
import FoundationEssentials
20+
#else
21+
import Foundation
22+
#endif
23+
24+
let encoder = JSONEncoder()
25+
let runtime = LambdaRuntime {
26+
(event: APIGatewayV2Request, context: LambdaContext) -> APIGatewayV2Response in
27+
28+
var header = HTTPHeaders()
29+
context.logger.debug("HTTP API Message received")
30+
31+
header["content-type"] = "application/json"
32+
33+
// echo the request in the response
34+
let data = try encoder.encode(event)
35+
let response = String(decoding: data, as: Unicode.UTF8.self)
36+
37+
return APIGatewayV2Response(statusCode: .ok, headers: header, body: response)
38+
}
39+
40+
try await runtime.run()

Diff for: Examples/CDK/infra/.gitignore

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
*.js
2+
!jest.config.js
3+
*.d.ts
4+
node_modules
5+
6+
# CDK asset staging directory
7+
.cdk.staging
8+
cdk.out
9+

Diff for: Examples/CDK/infra/.npmignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
*.ts
2+
!*.d.ts
3+
4+
# CDK asset staging directory
5+
.cdk.staging
6+
cdk.out

Diff for: Examples/CDK/infra/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Welcome to your CDK TypeScript project
2+
3+
This is a blank project for CDK development with TypeScript.
4+
5+
The `cdk.json` file tells the CDK Toolkit how to execute your app.
6+
7+
## Useful commands
8+
9+
* `npm run build` compile typescript to js
10+
* `npm run watch` watch for changes and compile
11+
* `npm run test` perform the jest unit tests
12+
* `npx cdk deploy` deploy this stack to your default AWS account/region
13+
* `npx cdk diff` compare deployed stack with current state
14+
* `npx cdk synth` emits the synthesized CloudFormation template

Diff for: Examples/CDK/infra/bin/deploy.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftAWSLambdaRuntime open source project
4+
//
5+
// Copyright (c) 2024 Apple Inc. and the SwiftAWSLambdaRuntime project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
import * as cdk from 'aws-cdk-lib';
16+
import { LambdaApiStack } from '../lib/lambda-api-project-stack';
17+
18+
const app = new cdk.App();
19+
new LambdaApiStack(app, 'LambdaApiStack');

Diff for: Examples/CDK/infra/cdk.json

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
{
2+
"app": "npx ts-node --prefer-ts-exts bin/deploy.ts",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"**/*.d.ts",
11+
"**/*.js",
12+
"tsconfig.json",
13+
"package*.json",
14+
"yarn.lock",
15+
"node_modules",
16+
"test"
17+
]
18+
},
19+
"context": {
20+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
21+
"@aws-cdk/core:checkSecretUsage": true,
22+
"@aws-cdk/core:target-partitions": [
23+
"aws",
24+
"aws-cn"
25+
],
26+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
27+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
28+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
29+
"@aws-cdk/aws-iam:minimizePolicies": true,
30+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
31+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
32+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
33+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
34+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
35+
"@aws-cdk/core:enablePartitionLiterals": true,
36+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
37+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
38+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
39+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
40+
"@aws-cdk/aws-route53-patters:useCertificate": true,
41+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
42+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
43+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
44+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
45+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
46+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
47+
"@aws-cdk/aws-redshift:columnId": true,
48+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
49+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
50+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
51+
"@aws-cdk/aws-kms:aliasNameRef": true,
52+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
53+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
54+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
55+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
56+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
57+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
58+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
59+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
60+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
61+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
62+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
63+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
64+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
65+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
66+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
67+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
68+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
69+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
70+
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
71+
"@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true,
72+
"@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": true,
73+
"@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true,
74+
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true,
75+
"@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true,
76+
"@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": true,
77+
"@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": true,
78+
"@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": true,
79+
"@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": true
80+
}
81+
}

0 commit comments

Comments
 (0)