Files
swift-openapi-lambda/Tests/OpenAPILambdaTests/ALBConversionTests.swift
T
Sébastien Stormacq 97b2e6d017 Add support for Lambda functions exposed behind an Application Load Balancer (ALB) (#29)
This PR adds support for exposing Swift OpenAPI Lambda functions behind
an Application Load Balancer (ALB), providing an alternative to API
Gateway for HTTP routing to Lambda functions.

## Changes

### New ALB Support
- **OpenAPILambdaALB Protocol**: New protocol for ALB integration
alongside existing API Gateway support
- **ALB Event Handling**: Added `ALBTargetGroupRequest` and
`ALBTargetGroupResponse` support
- **HTTP Request Conversion**: Extension methods to convert ALB events
to/from HTTP requests/responses

### Core Library Updates
- **ALB-related source files**: New `/Sources/ALB/` directory with
ALB-specific implementations
- **Event Type Support**: Support for `ALBTargetGroupRequest` events
from Elastic Load Balancing
- **Response Mapping**: Proper mapping from OpenAPI responses to ALB
target group responses

### Complete ALB Example
- **QuoteAPI ALB Example**: Full working example in
`Examples/quoteapi-alb/`
- **Infrastructure as Code**: Complete SAM template with VPC, subnets,
security groups, and ALB
- **Build System**: Makefile and Docker build support for ALB deployment
- **Documentation**: Comprehensive README with ALB-specific deployment
instructions

### Key Files Added
```
Sources/ALB/
├── OpenAPILambdaALB.swift
└── ALBTargetGroup+HTTPRequest.swift

Examples/quoteapi-alb/
├── Package.swift
├── template.yaml
├── Makefile
├── README.md
├── Sources/QuoteAPI/QuoteService.swift
├── Sources/QuoteAPI/openapi.yaml
├── Sources/QuoteAPI/openapi-generator-config.yaml
└── events/GetQuote.json
```

## Usage

### Simple ALB Integration
```swift
@main
struct QuoteServiceALBImpl: APIProtocol, OpenAPILambdaALB {
    func register(transport: OpenAPILambdaTransport) throws {
        try self.registerHandlers(on: transport)
    }
    
    static func main() async throws {
        let service = QuoteServiceALBImpl()
        try await service.run()
    }
    
    // Your OpenAPI implementation...
}
```

### Key Differences from API Gateway
- Uses `OpenAPILambdaALB` instead of `OpenAPILambdaHttpApi`
- Handles `ALBTargetGroupRequest` events instead of
`APIGatewayV2Request`
- Returns `ALBTargetGroupResponse` instead of `APIGatewayV2Response`
- Requires VPC infrastructure (included in SAM template)
- No built-in authorization (implement via custom middleware if needed)

## Benefits

- **Cost Optimization**: ALB can be more cost-effective for high-traffic
applications
- **VPC Integration**: Native VPC support for private network access
- **Load Balancing**: Advanced load balancing features and health checks
- **WebSocket Support**: Future WebSocket support through ALB
- **Flexibility**: Choice between API Gateway and ALB based on use case

## Testing

- ✅ ALB example builds successfully with `sam build`
- ✅ Local testing with `sam local invoke`
- ✅ Complete infrastructure deployment via SAM
- ✅ HTTP requests properly routed through ALB to Lambda
- ✅ OpenAPI specification compatibility maintained

## Deployment

Deploy the ALB example:
```bash
cd Examples/quoteapi-alb
sam build && sam deploy --guided
```

Test the deployed endpoint:
```bash
curl http://[alb-dns-name]/stocks/AAPL
```

## Backward Compatibility

This is a purely additive change:
- Existing API Gateway implementations continue to work unchanged
- No breaking changes to existing APIs
- New ALB support is opt-in via protocol conformance
2025-10-26 09:10:09 +01:00

140 lines
5.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift OpenAPI Lambda open source project
//
// Copyright Swift OpenAPI Lambda project authors
// Copyright (c) 2025 Amazon.com, Inc. or its affiliates.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift OpenAPI Lambda project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import AWSLambdaEvents
import Foundation
import HTTPTypes
import Testing
@testable import OpenAPILambda
struct ALBConversionTests {
static let albEventJSON = """
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-target/50dc6c495c0c9188"
}
},
"httpMethod": "GET",
"path": "/stocks/AAPL",
"queryStringParameters": {},
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"host": "lambda-alb-123578498.us-east-1.elb.amazonaws.com",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
},
"body": "",
"isBase64Encoded": false
}
"""
@Test("ALB request to HTTPRequest conversion")
func testALBRequestToHTTPRequest() throws {
let data = ALBConversionTests.albEventJSON.data(using: .utf8)!
let albRequest = try JSONDecoder().decode(ALBTargetGroupRequest.self, from: data)
let httpRequest = try albRequest.httpRequest()
#expect(httpRequest.method == HTTPRequest.Method.get)
#expect(httpRequest.path == "/stocks/AAPL")
#expect(
httpRequest.headerFields[HTTPField.Name.accept]
== "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
)
#expect(httpRequest.headerFields[HTTPField.Name("host")!] == "lambda-alb-123578498.us-east-1.elb.amazonaws.com")
#expect(
httpRequest.headerFields[HTTPField.Name.userAgent]
== "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
)
}
@Test("ALB X-Forwarded-Proto and Host mapping")
func testALBForwardedHeaders() throws {
let albEventWithForwardedHeaders = """
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-target/50dc6c495c0c9188"
}
},
"httpMethod": "GET",
"path": "/stocks/AAPL",
"queryStringParameters": {},
"headers": {
"Host": "lambda-alb-123578498.us-east-1.elb.amazonaws.com",
"X-Forwarded-Proto": "https"
},
"body": "",
"isBase64Encoded": false
}
"""
let data = albEventWithForwardedHeaders.data(using: .utf8)!
let albRequest = try JSONDecoder().decode(ALBTargetGroupRequest.self, from: data)
let httpRequest = try albRequest.httpRequest()
#expect(httpRequest.scheme == "https")
#expect(httpRequest.authority == "lambda-alb-123578498.us-east-1.elb.amazonaws.com")
}
@Test("ALB lowercase headers mapping")
func testALBLowercaseHeaders() throws {
let albEventWithLowercaseHeaders = """
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-target/50dc6c495c0c9188"
}
},
"httpMethod": "GET",
"path": "/stocks/AAPL",
"queryStringParameters": {},
"headers": {
"host": "lambda-alb-123578498.us-east-1.elb.amazonaws.com",
"x-forwarded-proto": "https"
},
"body": "",
"isBase64Encoded": false
}
"""
let data = albEventWithLowercaseHeaders.data(using: .utf8)!
let albRequest = try JSONDecoder().decode(ALBTargetGroupRequest.self, from: data)
let httpRequest = try albRequest.httpRequest()
#expect(httpRequest.scheme == "https")
#expect(httpRequest.authority == "lambda-alb-123578498.us-east-1.elb.amazonaws.com")
}
@Test("HTTPResponse to ALB response conversion")
func testHTTPResponseToALBResponse() throws {
var httpResponse = HTTPResponse(status: .ok)
httpResponse.headerFields[HTTPField.Name.contentType] = "application/json"
httpResponse.headerFields[HTTPField.Name.contentLength] = "42"
let albResponse = ALBTargetGroupResponse(from: httpResponse)
#expect(albResponse.statusCode == .ok)
#expect(albResponse.headers?[HTTPField.Name.contentType.rawName] == "application/json")
#expect(albResponse.headers?[HTTPField.Name.contentLength.rawName] == "42")
#expect(albResponse.isBase64Encoded == false)
}
}