Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 7 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName

**LambdaFunctionConstruct** (`src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs`)
- Main CDK construct that creates Lambda functions with comprehensive configuration
- Automatically creates IAM roles and policies with CloudWatch Logs permissions
- Automatically creates an IAM role whose logging policy is scoped to the construct's own log group (`logs:CreateLogStream`, `logs:PutLogEvents` on the log group ARN)
- Code from a local asset (`AssetPath`) or any `Code` source such as an S3 artifact (`Code.FromBucketV2`); exactly one is required
- Supports configurable OpenTelemetry layer integration via AWS managed layer (disabled by default)
- Configurable OTEL layer version and architecture (amd64/arm64)
- Supports AWS Lambda SnapStart for improved cold start performance
- Creates function versions and aliases for deployment management
- Handles Lambda permissions for multiple targets (function, version, alias)
- Creates a version on every deployment and an alias (`AliasName`, default `live`); both are public (`Version`, `Alias`)
- Applies each `LambdaPermission` to its `Targets` (`LambdaPermissionTargets` flags; default alias only)

**WebFunctionConstruct** (`src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs`)
- Creates an AWS Lambda Web Function from a versioned S3 artifact (`WebFunctionCode.FromBucket`), plus its immutable revision, default endpoint, execution role (optional), logging (optional), and the function's **single** resource-based policy
Expand Down Expand Up @@ -80,7 +81,7 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName

**Configuration Models** (`src/LayeredCraft.Cdk.Constructs/Models/`)
- `LambdaFunctionConstructProps`: Main configuration interface and record for Lambda construct
- `LambdaPermission`: Record for defining Lambda invocation permissions
- `LambdaPermission`: Record for defining Lambda invocation permissions; `Targets` (`LambdaPermissionTargets`) selects function, version and/or alias (default alias)
- `StaticSiteConstructProps`: Configuration interface and record for static site construct
- `DynamoDbTableConstructProps`: Configuration interface and record for DynamoDB table construct
- `WebFunctionConstructProps`, `WebFunctionCode`/`WebFunctionCodeFromBucketOptions`/`WebFunctionCodeBucketPolicy`, `WebFunctionEndpointOptions`/`IWebFunctionEndpointOptions`, `WebFunctionEndpointAttributes`, `WebFunctionLogs`, `WebFunctionRuntime`, `WebFunctionAuthType`, `WebFunctionEndpointType`, `WebFunctionCallerPolicy`/`WebFunctionInvokeGrantOptions`, `WebFunctionOriginProps`/`WebFunctionOriginWithOacProps`/`WebFunctionOriginPermissions`: Web Function configuration (see `docs/constructs/web-function.md`)
Expand All @@ -93,9 +94,9 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName

1. **Construct Pattern**: Uses AWS CDK construct pattern for reusable infrastructure components
2. **Interface + Record Pattern**: Props classes use both interface and record for flexibility and immutability
3. **Multi-Target Permissions**: Automatically applies permissions to function, version, and alias
3. **Least-Privilege Permissions**: Invocation permissions go on the alias by default; function and version targets are opt-in
4. **OpenTelemetry Integration**: Configurable support for AWS OTEL collector layer with version and architecture options
5. **Versioning Strategy**: Creates new versions on every deployment with "live" alias
5. **Versioning Strategy**: Creates new versions on every deployment with a configurable alias (default "live")

### Target Frameworks
- .NET 10 and .NET 11
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ public class MyStack : Stack
- **[DynamoDB Table Construct](https://layeredcraft.github.io/cdk-constructs/constructs/dynamodb-table)** - Production-ready DynamoDB tables with streams and indexes
- **[Cognito User Pool Construct](https://layeredcraft.github.io/cdk-constructs/constructs/cognito-user-pool)** - Full-featured Cognito user pool with custom domains, OAuth clients, and branding
- **[Testing Guide](https://layeredcraft.github.io/cdk-constructs/testing)** - Comprehensive testing utilities and patterns
- **[Upgrading to 3.0](https://layeredcraft.github.io/cdk-constructs/migration/v3)** - Breaking changes and migration steps from 2.x
- **[Examples](https://layeredcraft.github.io/cdk-constructs/examples)** - Real-world usage examples and patterns
- **[Web Function Workloads](https://layeredcraft.github.io/cdk-constructs/examples/web-functions)** - Next.js, ASP.NET Core, and Blazor Static SSR recipes

Expand Down
106 changes: 96 additions & 10 deletions docs/constructs/lambda-function.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ The `LambdaFunctionConstruct` provides a comprehensive, production-ready Lambda
## :rocket: Features

- **:chart_with_upwards_trend: OpenTelemetry Integration**: Configurable AWS OpenTelemetry collector layer with version and architecture support
- **:shield: IAM Management**: Automatic role and policy creation with CloudWatch Logs permissions
- **:shield: IAM Management**: Automatic role and policy creation with a CloudWatch Logs policy scoped to the construct's own log group
- **:gear: Environment Configuration**: Easy environment variable management
- **:link: Function URLs**: Optional HTTP endpoint generation
- **:rocket: SnapStart Support**: Improved cold start performance for Java runtimes
- **:label: Versioning & Aliases**: Automatic version management with "live" alias
- **:key: Lambda Permissions**: Multi-target permission management (function, version, alias)
- **:label: Versioning & Aliases**: Automatic version management with a configurable alias name (default `"live"`)
- **:key: Lambda Permissions**: Permission targets per permission (function, version, alias) with an alias-only default
- **:package: Artifact Sources**: Deploy from a local asset (`AssetPath`) or existing Lambda code such as an S3 object (`Code`)

## Basic Usage

Expand Down Expand Up @@ -44,25 +45,41 @@ public class MyStack : Stack
|----------|------|-------------|
| `FunctionName` | `string` | Base name of the Lambda function |
| `FunctionSuffix` | `string` | Suffix appended to function name (e.g., "prod", "dev") |
| `AssetPath` | `string` | Path to Lambda deployment package |
| `RoleName` | `string` | Name of the IAM role |
| `PolicyName` | `string` | Name of the IAM policy |

### Artifact Code (exactly one required)

Exactly one of `AssetPath` or `Code` must be set. Providing both or neither throws an `ArgumentException` at construction.

| Property | Type | Description |
|----------|------|-------------|
| `AssetPath` | `string?` | Path to a local Lambda deployment package (asset) |
| `Code` | `Code?` | Existing Lambda code, for example `Code.FromBucketV2(bucket, key, options)` |

### Optional Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `AliasName` | `string` | `"live"` | Name of the alias pointing at the published version |
| `MemorySize` | `double` | `1024` | Memory allocation in MB |
| `TimeoutInSeconds` | `double` | `6` | Function timeout in seconds |
| `PolicyStatements` | `PolicyStatement[]` | `[]` | Additional IAM policy statements |
| `EnvironmentVariables` | `IDictionary<string, string>` | `{}` | Environment variables |
| `IncludeOtelLayer` | `bool` | `false` | Enable OpenTelemetry layer |
| `OtelLayerVersion` | `string` | `"0-117-0"` | OpenTelemetry layer version |
| `Architecture` | `string` | `"amd64"` | Lambda architecture applied to both the function and OTEL layer (amd64/arm64) |
| `Permissions` | `List<LambdaPermission>` | `[]` | Lambda invocation permissions |
| `Permissions` | `List<LambdaPermission>` | `[]` | Lambda invocation permissions, each with its own `Targets` |
| `EnableSnapStart` | `bool` | `false` | Enable SnapStart (Java runtimes only; the default `PROVIDED_AL2023` runtime is not eligible) |
| `GenerateUrl` | `bool` | `false` | Generate Function URL for HTTP access |

!!! warning "Breaking changes in 3.0.0"
- Lambda permissions now default to the **alias only**; the function and version permission
resources are no longer created unless `Targets` requests them.
- The execution-role logging policy is scoped to the construct's own log group ARN. It no longer
grants `logs:CreateLogGroup` or `logs:TagResource` and no longer uses a wildcard log-group resource.
- `AssetPath` is no longer required: provide exactly one of `AssetPath` or `Code`.

## Advanced Examples

### Lambda with DynamoDB Access
Expand Down Expand Up @@ -112,12 +129,16 @@ var functionUrl = lambda.LiveAliasFunctionUrlDomain;

### Lambda with API Gateway Permissions

By default a permission is granted on the **alias only**. Set `Targets` to grant it on the
function, the version, and/or the alias.

```csharp
var apiPermission = new LambdaPermission
{
Principal = "apigateway.amazonaws.com",
Action = "lambda:InvokeFunction",
SourceArn = "arn:aws:execute-api:us-east-1:123456789012:abcdef123/*"
// Targets defaults to LambdaPermissionTargets.Alias
};

var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps
Expand All @@ -131,6 +152,52 @@ var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionCon
});
```

To restore the 2.x behavior (function, version, and alias), opt in explicitly:

```csharp
var apiPermission = new LambdaPermission
{
Principal = "apigateway.amazonaws.com",
Action = "lambda:InvokeFunction",
SourceArn = "arn:aws:execute-api:us-east-1:123456789012:abcdef123/*",
Targets = LambdaPermissionTargets.Function
| LambdaPermissionTargets.Version
| LambdaPermissionTargets.Alias
};
```

### Lambda with an S3 Artifact

Provide existing code instead of a local asset. With `Code.FromBucketV2` the construct adds no
bucket grants to the execution role.

```csharp
var bucket = Bucket.FromBucketName(this, "ArtifactBucket", "my-lambda-artifacts");

var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps
{
FunctionName = "my-api",
FunctionSuffix = "prod",
Code = Code.FromBucketV2(bucket, "my-api/app.zip", new BucketOptions()),
RoleName = "my-api-role",
PolicyName = "my-api-policy"
});
```

### Lambda with a Custom Alias Name

```csharp
var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps
{
FunctionName = "my-api",
FunctionSuffix = "prod",
AssetPath = "./lambda-deployment.zip",
AliasName = "prod",
RoleName = "my-api-role",
PolicyName = "my-api-policy"
});
```

### Lambda with SnapStart

```csharp
Expand Down Expand Up @@ -177,6 +244,22 @@ var underlyingFunction = lambda.LambdaFunction;
underlyingFunction.AddEnvironment("CUSTOM_VAR", "value");
```

### Alias

The deployed alias as an `IAlias`:

```csharp
var alias = lambda.Alias;
```

### Version

The published version backing the alias as an `IVersion`:

```csharp
var version = lambda.Version;
```

### LiveAliasFunctionUrlDomain
Get the domain of the Function URL (if enabled):

Expand Down Expand Up @@ -206,20 +289,23 @@ The Lambda functions use the following runtime configuration:

The construct automatically creates:

1. **CloudWatch Logs Permissions**:
1. **CloudWatch Logs Permissions** (scoped to the construct's own log group ARN):
- `logs:CreateLogStream`
- `logs:CreateLogGroup`
- `logs:TagResource`
- `logs:PutLogEvents`

The construct creates the log group itself, so it does not grant `logs:CreateLogGroup`,
`logs:TagResource`, or a wildcard log-group resource.

2. **Custom Policy Statements**: Any additional policies you provide

3. **Lambda Permissions**: Applied to function, version, and alias
3. **Lambda Permissions**: Each `LambdaPermission` is applied to its `Targets`
(`Function`, `Version`, and/or `Alias`). The default is **alias only**. `LambdaPermissionTargets.None`
is invalid and throws an `ArgumentException` at construction.

## Versioning Strategy

- Creates a new version on every deployment
- Maintains a "live" alias pointing to the latest version
- Maintains an alias pointing to the latest version; the alias name is configurable (`AliasName`, default `"live"`)
- Versions have `RemovalPolicy.RETAIN` to prevent deletion

## Testing
Expand Down
21 changes: 14 additions & 7 deletions docs/designs/v3-modernization.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

| | |
|---|---|
| **Status** | **Proposed** (revision 1, 2026-11-24), awaiting owner review. Approval of this document is an acceptance criterion of [#109](https://github.com/LayeredCraft/cdk-constructs/issues/109); it does not authorize [#110](https://github.com/LayeredCraft/cdk-constructs/issues/110), [#111](https://github.com/LayeredCraft/cdk-constructs/issues/111) or [#112](https://github.com/LayeredCraft/cdk-constructs/issues/112). |
| **Status** | **Accepted** (revision 2, 2026-11-24). The owner approved the design on 2026-11-24 ([#109 comment](https://github.com/LayeredCraft/cdk-constructs/issues/109#issuecomment-7131032469)) and authorized [#110](https://github.com/LayeredCraft/cdk-constructs/issues/110) and [#111](https://github.com/LayeredCraft/cdk-constructs/issues/111). [#112](https://github.com/LayeredCraft/cdk-constructs/issues/112) and the stable release remain owner-gated. |
| **Milestone** | [v3.0.0](https://github.com/LayeredCraft/cdk-constructs/milestone/1), epic [#108](https://github.com/LayeredCraft/cdk-constructs/issues/108) |
| **Authority** | This document is the design record for 3.0.0. No standalone ADRs are written. |
| **Target frameworks** | `net10.0`, `net11.0` |
Expand Down Expand Up @@ -279,16 +279,23 @@ on this construct):
`StaticSiteConstruct`.
7. **Consumer test projects** — no change required; the library's own tests moved to Compono.

## 11. Open questions for the owner
## 11. Owner decisions (2026-11-24)

1. Approve this design (an acceptance criterion of #109).
2. Approve or decline the proposed Web Function L2 spike issue ([§9.5](#95-recommendation)).
3. Confirm U7's shape: `Code` as an alternative to `AssetPath` (additive) rather than replacing
`AssetPath`.
4. Confirm the working name `PrivateStaticAssetsConstruct` for U6.
1. The design is approved: .NET 10/11 only, updated dependencies and tooling, Compono-first tests,
U1–U4 and U7, U6.
2. `WebFunctionConstruct` keeps its current implementation for 3.0.0 (option A). The composition
investigation ([§9.5](#95-recommendation)) is tracked separately and deferred in
[#114](https://github.com/LayeredCraft/cdk-constructs/issues/114); it does not block 3.0.0, and no
Web Function refactor is authorized.
3. U7: `Code` is an alternative to `AssetPath`; existing asset-based usage is preserved.
4. U6 is named `PrivateStaticAssetsConstruct`.

The §7 open question (exposing Lambda logging configuration) was not taken up in #110: no consumer
needs it, and adding it would need its own owner decision.

## 12. Revision history

| Revision | Date | Change |
|---|---|---|
| 1 | 2026-11-24 | Initial proposal for owner review |
| 2 | 2026-11-24 | Accepted; owner decisions recorded in §11; Web Function investigation deferred to #114 |
Loading