@aws/nx-plugin-mcp 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/guides/fastapi.mdx +225 -3
- package/docs/guides/trpc.mdx +208 -7
- package/package.json +1 -1
- package/src/py/api/schema.json +11 -4
- package/src/py/fast-api/schema.json +11 -4
- package/src/trpc/backend/schema.json +11 -4
- package/src/ts/api/schema.json +15 -5
package/docs/guides/fastapi.mdx
CHANGED
|
@@ -21,7 +21,15 @@ import { PY_VERSIONS } from '../../../../../../packages/nx-plugin/src/utils/vers
|
|
|
21
21
|
|
|
22
22
|
[FastAPI](https://fastapi.tiangolo.com/) is a framework for building APIs in Python.
|
|
23
23
|
|
|
24
|
-
The FastAPI generator creates a new FastAPI with AWS CDK or Terraform infrastructure setup. The generated backend
|
|
24
|
+
The FastAPI generator creates a new FastAPI with AWS CDK or Terraform infrastructure setup. The generated backend is exposed via an AWS API Gateway API. It sets up [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/python/latest/) for observability, including structured logging and CloudWatch metrics.
|
|
25
|
+
|
|
26
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Lambda hosting">
|
|
27
|
+
The backend uses AWS Lambda for serverless deployment, and AWS X-Ray tracing is set up too.
|
|
28
|
+
</OptionFilter>
|
|
29
|
+
|
|
30
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="ECS hosting">
|
|
31
|
+
Your API runs as a long-lived uvicorn server in a container on Amazon ECS, behind an API Gateway HTTP API, rather than in a Lambda function. See <a href="#running-on-amazon-ecs">Running on Amazon ECS</a> for what that changes, including why X-Ray tracing produces no traces there.
|
|
32
|
+
</OptionFilter>
|
|
25
33
|
|
|
26
34
|
## Usage
|
|
27
35
|
|
|
@@ -43,7 +51,21 @@ Select `rest-lambda` (default) as your `infra` if you intend to build any stream
|
|
|
43
51
|
|
|
44
52
|
:::tip[Integration Pattern]
|
|
45
53
|
The `integrationPattern` option defaults to `isolated`, which creates one Lambda per FastAPI operation. Select `shared` if you would prefer a single shared Lambda handler for the whole API, with optional per-operation overrides.
|
|
54
|
+
|
|
55
|
+
With `infra` set to `http-ecs` the option is always `shared`, since one container service answers every operation.
|
|
56
|
+
:::
|
|
57
|
+
|
|
58
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="ECS hosting is experimental">
|
|
59
|
+
:::caution[Experimental]
|
|
60
|
+
`http-ecs` is experimental. Its generated output may change between releases without a migration to carry an existing workspace across, so expect to reconcile those changes yourself when you upgrade.
|
|
61
|
+
|
|
62
|
+
It needs the CDK IaC provider: Terraform support is not implemented yet. If the workspace resolves to Terraform, the generator fails with a message naming the fix.
|
|
63
|
+
|
|
64
|
+
`integrationPattern` is always `shared` here. Passing `--integrationPattern=isolated` alongside `http-ecs` does not fail: the generator warns that the option is ignored and uses `shared`. Running the generator interactively, it asks for `integrationPattern` before `infra`, with `isolated` preselected, so that warning is what you see if you leave the preselection alone and then choose `http-ecs`. In the command builder on this page, picking `http-ecs` disables `isolated` and clears it if it was selected, so the command it writes never carries the flag.
|
|
65
|
+
|
|
66
|
+
The `architecture` option sets whether the container runs on `ARM64` or `X86_64`, and the Python wheels in its bundle follow it. Leave it out to use the architecture of the machine you run the generator on. See <Link path="/guides/py-container#cpu-architecture">CPU Architecture</Link> in the container guide.
|
|
46
67
|
:::
|
|
68
|
+
</OptionFilter>
|
|
47
69
|
|
|
48
70
|
## Generator Output
|
|
49
71
|
|
|
@@ -63,6 +85,20 @@ The generator will create the following project structure in the `<directory>/<a
|
|
|
63
85
|
|
|
64
86
|
</FileTree>
|
|
65
87
|
|
|
88
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Files that differ when the API runs on ECS">
|
|
89
|
+
With `infra` set to `http-ecs` the API runs as its own HTTP server rather than behind the Lambda Web Adapter, so `run.sh` is not generated. In its place you get a container folder inside your module, named after your API:
|
|
90
|
+
|
|
91
|
+
<FileTree>
|
|
92
|
+
- \<module_name>
|
|
93
|
+
- \<api_name>_container
|
|
94
|
+
- main.py Entry point: adds `GET /health`, writes out the metrics the API collects, and starts uvicorn on `HOST` and `PORT`. The bundle, the image and the `serve` target all start from this file
|
|
95
|
+
- Dockerfile Container image definition
|
|
96
|
+
- .dockerignore Files left out of the image build context
|
|
97
|
+
</FileTree>
|
|
98
|
+
|
|
99
|
+
Your `init.py`, `main.py` and the operations you add to them are the same for every `infra` value.
|
|
100
|
+
</OptionFilter>
|
|
101
|
+
|
|
66
102
|
### Infrastructure
|
|
67
103
|
|
|
68
104
|
<Snippet name="shared-constructs" />
|
|
@@ -101,8 +137,18 @@ The generator sets up several features automatically:
|
|
|
101
137
|
2. Error handling middleware
|
|
102
138
|
3. Request/response correlation
|
|
103
139
|
4. Metrics collection
|
|
104
|
-
|
|
105
|
-
|
|
140
|
+
|
|
141
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Streaming, which needs a REST API">
|
|
142
|
+
Type-safe streaming is set up too, for the `rest-lambda` infrastructure only.
|
|
143
|
+
</OptionFilter>
|
|
144
|
+
|
|
145
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="How the Lambda variants serve the app">
|
|
146
|
+
The app is served in a Lambda function by the [Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter) running uvicorn.
|
|
147
|
+
</OptionFilter>
|
|
148
|
+
|
|
149
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="How the ECS variant serves the app">
|
|
150
|
+
The app is served by uvicorn in the container, with no Lambda Web Adapter. See <a href="#running-on-amazon-ecs">Running on Amazon ECS</a>.
|
|
151
|
+
</OptionFilter>
|
|
106
152
|
|
|
107
153
|
### Observability with AWS Lambda Powertools
|
|
108
154
|
|
|
@@ -140,6 +186,12 @@ def read_item(item_id: int):
|
|
|
140
186
|
return {"item_id": item_id}
|
|
141
187
|
```
|
|
142
188
|
|
|
189
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="X-Ray produces no traces on ECS">
|
|
190
|
+
:::caution[No traces on ECS]
|
|
191
|
+
The decorator and the subsegment above run without error in a container, but produce no traces. Powertools turns its tracer off when it is not running in Lambda. See <a href="#observability">Observability</a> for what you do get, and what to add if you need traces.
|
|
192
|
+
:::
|
|
193
|
+
</OptionFilter>
|
|
194
|
+
|
|
143
195
|
#### Metrics
|
|
144
196
|
|
|
145
197
|
CloudWatch metrics are collected automatically for each request. You can add custom metrics:
|
|
@@ -187,9 +239,17 @@ It's recommended to specify response models for your API operations for better c
|
|
|
187
239
|
|
|
188
240
|
### Accessing the Calling User
|
|
189
241
|
|
|
242
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Identity on ECS — the authorizer context does not arrive">
|
|
243
|
+
On ECS there is no Lambda Web Adapter and no API Gateway request context header: API Gateway does not forward the authorizer's claims to a private load balancer integration. The authorizer still decides whether a request reaches the container at all, but your handlers cannot read the caller from the request as written below.
|
|
244
|
+
|
|
245
|
+
To read the caller's identity in an operation, map the authorizer's context onto a request header in your API construct, and read that header from the FastAPI `Request`.
|
|
246
|
+
</OptionFilter>
|
|
247
|
+
|
|
248
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Identity on the Lambda variants">
|
|
190
249
|
When your API is protected by authentication, your route handlers often need to know who is calling. The generated FastAPI runs inside AWS Lambda via the [Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter), which forwards the API Gateway request context as JSON on the `x-amzn-request-context` header. You can read it from the FastAPI `Request` to extract the caller's identity.
|
|
191
250
|
|
|
192
251
|
As an example, let's add a `/me` endpoint that returns details about the calling user. We'll implement the extraction as a [FastAPI dependency](https://fastapi.tiangolo.com/tutorial/dependencies/) so it can be reused across routes. The shape of the request context — and therefore how you extract the identity — depends on both your selected `auth` method and whether you deployed a REST or HTTP API.
|
|
252
|
+
</OptionFilter>
|
|
193
253
|
|
|
194
254
|
<OptionFilter when={{ auth: 'iam' }} description="Identity extraction for IAM-authenticated APIs">
|
|
195
255
|
For `IAM` authentication, we look up the caller in Cognito using the sub extracted from the API Gateway request context, which requires `boto3`. Add it to your API project:
|
|
@@ -444,6 +504,7 @@ The FastAPI generator creates CDK or Terraform infrastructure as code based on y
|
|
|
444
504
|
|
|
445
505
|
<Infrastructure>
|
|
446
506
|
<Fragment slot="cdk">
|
|
507
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="CDK usage for the Lambda variants">
|
|
447
508
|
The CDK construct for deploying your API in the `common/constructs` folder. You can use this in a CDK application:
|
|
448
509
|
|
|
449
510
|
```ts {6-8}
|
|
@@ -467,6 +528,47 @@ This sets up:
|
|
|
467
528
|
4. CloudWatch log group
|
|
468
529
|
5. X-Ray tracing configuration
|
|
469
530
|
6. CloudWatch metrics namespace
|
|
531
|
+
</OptionFilter>
|
|
532
|
+
|
|
533
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="CDK usage when the API runs on ECS — pass the VPC">
|
|
534
|
+
`defaultIntegrations` takes the VPC your service runs in, and builds everything inside it: the ECS service, the internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through. The construct never creates a VPC, so you create or import one in your stack.
|
|
535
|
+
|
|
536
|
+
```ts {10,13-15}
|
|
537
|
+
import { MyApi } from '@my-scope/common-constructs';
|
|
538
|
+
import { Stack } from 'aws-cdk-lib';
|
|
539
|
+
import { Vpc } from 'aws-cdk-lib/aws-ec2';
|
|
540
|
+
import { Construct } from 'constructs';
|
|
541
|
+
|
|
542
|
+
export class ExampleStack extends Stack {
|
|
543
|
+
constructor(scope: Construct, id: string) {
|
|
544
|
+
super(scope, id);
|
|
545
|
+
|
|
546
|
+
const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
|
|
547
|
+
|
|
548
|
+
const api = new MyApi(this, 'MyApi', {
|
|
549
|
+
integrations: MyApi.defaultIntegrations(this, { vpc }).build(),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
To use an existing VPC, look it up with `Vpc.fromLookup(this, 'Vpc', { vpcId: '<vpc-id>' })` and pass it as `vpc`.
|
|
556
|
+
|
|
557
|
+
Pass `service` to change the container service itself — its `cpu`, `memoryLimitMiB`, `desiredCount`, `environment`, or `grantTaskRole` to give the task role a permission:
|
|
558
|
+
|
|
559
|
+
```ts
|
|
560
|
+
MyApi.defaultIntegrations(this, {
|
|
561
|
+
vpc,
|
|
562
|
+
service: {
|
|
563
|
+
cpu: 512,
|
|
564
|
+
memoryLimitMiB: 1024,
|
|
565
|
+
grantTaskRole: (taskRole) => myTable.grantReadWriteData(taskRole),
|
|
566
|
+
},
|
|
567
|
+
}).build();
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
This sets up an AWS API Gateway HTTP API with authentication based on your chosen `auth` method, an Amazon ECS service running your container, an internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through.
|
|
571
|
+
</OptionFilter>
|
|
470
572
|
|
|
471
573
|
<Snippet name="api/cors-configuration-cdk-note" />
|
|
472
574
|
|
|
@@ -502,6 +604,12 @@ Authorizer results are cached for 5 minutes, keyed on the `Authorization` header
|
|
|
502
604
|
</OptionFilter>
|
|
503
605
|
</Fragment>
|
|
504
606
|
<Fragment slot="terraform">
|
|
607
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Terraform is not implemented for ECS hosting">
|
|
608
|
+
:::caution[CDK only]
|
|
609
|
+
`http-ecs` is not implemented for Terraform. The generator fails with a message saying so. Choose `rest-lambda` or `http-lambda` for a Terraform workspace.
|
|
610
|
+
:::
|
|
611
|
+
</OptionFilter>
|
|
612
|
+
|
|
505
613
|
The Terraform modules for deploying your API are in the `common/terraform` folder. You can use this in a Terraform configuration.
|
|
506
614
|
|
|
507
615
|
The API module stages its Lambda deployment zip in a shared S3 asset bucket — see the <Link path="/guides/terraform-project">Terraform infrastructure guide</Link> for details. Instantiate the `core/asset-bucket` module once per deployment and pass its `bucket_name` output into every API / Lambda module via the `asset_bucket_name` input:
|
|
@@ -730,16 +838,130 @@ The generator configures a local development server that you can run with:
|
|
|
730
838
|
|
|
731
839
|
<NxCommands commands={['serve <project-name>']} />
|
|
732
840
|
|
|
841
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Local server for the Lambda variants">
|
|
733
842
|
This starts a local FastAPI development server with:
|
|
734
843
|
|
|
735
844
|
- Auto-reload on code changes
|
|
736
845
|
- Interactive API documentation at `/docs` or `/redoc`
|
|
737
846
|
- OpenAPI schema at `/openapi.json`
|
|
847
|
+
</OptionFilter>
|
|
848
|
+
|
|
849
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Local server when the API runs on ECS">
|
|
850
|
+
This starts the container's entry point, the same file the image runs, with:
|
|
851
|
+
|
|
852
|
+
- `GET /health`, answering as it does for the load balancer
|
|
853
|
+
- Interactive API documentation at `/docs` or `/redoc`
|
|
854
|
+
- OpenAPI schema at `/openapi.json`
|
|
855
|
+
|
|
856
|
+
The server binds `127.0.0.1`, so it answers only on your own machine. It reloads nothing: restart it to pick up a code change. To reach it from another machine, a VM or a container, set `HOST=0.0.0.0` on the `serve` target — which makes the API reachable by anything that can reach your machine, unauthenticated.
|
|
857
|
+
</OptionFilter>
|
|
738
858
|
|
|
739
859
|
:::note[Project Names]
|
|
740
860
|
Python project names use underscores, so an API generated with `--name=MyApi` is addressed as `my_api` (or by its fully qualified name, `<scope>.my_api`). The port the server listens on is assigned per project — read it from the `serve` target in your project's `project.json`.
|
|
741
861
|
:::
|
|
742
862
|
|
|
863
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="How ECS hosting works, what it costs and what it limits">
|
|
864
|
+
## Running on Amazon ECS
|
|
865
|
+
|
|
866
|
+
With `infra` set to `http-ecs`, your API runs as a long-lived uvicorn server in a container rather than in a Lambda function behind the Lambda Web Adapter. A request takes this path:
|
|
867
|
+
|
|
868
|
+
1. A caller signs a request to the API Gateway HTTP API, which is the only public entry point. Every route carries the authorizer for the `auth` you chose, so an unauthenticated request is rejected at the edge.
|
|
869
|
+
2. API Gateway forwards the request through a VPC link, which is its private path into your VPC.
|
|
870
|
+
3. The VPC link reaches an internal load balancer. The load balancer has no public address, and its only inbound rule allows the VPC link's security group on the listener port.
|
|
871
|
+
4. The load balancer forwards the request to a task. The tasks' only inbound rule allows the load balancer's security group on the container port, so nothing else in the VPC can open a connection to them.
|
|
872
|
+
|
|
873
|
+
The tasks run in private subnets and never get a public IP address. Nothing in this path allows an address range inbound.
|
|
874
|
+
|
|
875
|
+
By default the service, the load balancer and the VPC link go in the VPC's `PRIVATE_WITH_EGRESS` subnets, which reach AWS through a NAT gateway. Passing `vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED }` to `defaultIntegrations` drops the NAT gateway and its hourly charge, but isolated subnets have no route out, so the VPC then needs four VPC endpoints for the tasks to start at all: interface endpoints for `ecr.api` and `ecr.dkr` to pull the image, an S3 gateway endpoint because the image layers are S3 objects, and an interface endpoint for `logs` so the `awslogs` driver can write. Without them a task cannot pull its image and ECS rolls the deployment back on the circuit breaker without saying why.
|
|
876
|
+
|
|
877
|
+
The VPC link, the load balancer, its listener, the target group and the bucket the load balancer writes its access logs to are created by one construct, `core/api/ecs-http-endpoint.ts` in `common/constructs`, which every API hosted on ECS shares. Your API's own construct names its container service and routes every operation to that endpoint.
|
|
878
|
+
|
|
879
|
+
### What Runs in the Container
|
|
880
|
+
|
|
881
|
+
`<module_name>/<api_name>_container/main.py` imports the app from your `main.py`, so every operation you write is served exactly as it is on Lambda. It adds two things of its own:
|
|
882
|
+
|
|
883
|
+
- `GET /health`, which the load balancer's target group and the container health check call. It is declared `include_in_schema=False`, so it stays out of your OpenAPI spec and therefore out of the API Gateway routes and the generated clients. It is also left out of the request metrics, so the target group's call every 15 seconds does not count as an API request.
|
|
884
|
+
- A middleware that writes out the metrics the API's own middleware collects. On Lambda the handler does that at the end of each invocation; this server lives across requests, so it flushes them itself.
|
|
885
|
+
|
|
886
|
+
The API Gateway routes still come from your OpenAPI spec, so an operation you add is deployed once `nx build` has regenerated the spec.
|
|
887
|
+
|
|
888
|
+
### Observability
|
|
889
|
+
|
|
890
|
+
Logs and metrics work as they do on Lambda: the container writes to its own CloudWatch log group, and metrics are written in the embedded metric format for CloudWatch Logs to extract.
|
|
891
|
+
|
|
892
|
+
One thing about metrics is different here, and it is worth knowing before you read a dashboard or add a metric of your own. `metrics`, the object the <a href="#metrics">Metrics</a> section above tells you to import from `.init`, is a Powertools `Metrics`, and every `Metrics` object in a process shares one metric store. On Lambda one invocation owns that store from start to finish. A uvicorn server handles requests at the same time, and both the API's own per-request metrics and any you add go to that one store, so two requests in flight together can have their metrics written out in one document and attributed to whichever route was added first. The other request's document can come out with no `route` dimension at all, holding only the metrics added after the first flush, and Powertools logs `PowertoolsUserWarning: Dimension 'route' has already been added` when it happens. Under light traffic, where requests rarely overlap, you will not see it.
|
|
893
|
+
|
|
894
|
+
So treat `RequestCount` and `Success` per route as approximate on ECS. If you need a metric attributed to exactly one request, add it to an `EphemeralMetrics` you create in the request and flush before returning, which keeps a store of its own:
|
|
895
|
+
|
|
896
|
+
```python
|
|
897
|
+
from aws_lambda_powertools.metrics import EphemeralMetrics, MetricUnit
|
|
898
|
+
|
|
899
|
+
@app.get("/items/{item_id}")
|
|
900
|
+
def read_item(item_id: int):
|
|
901
|
+
request_metrics = EphemeralMetrics()
|
|
902
|
+
request_metrics.add_metric(name="ItemViewed", unit=MetricUnit.Count, value=1)
|
|
903
|
+
request_metrics.flush_metrics()
|
|
904
|
+
return {"item_id": item_id}
|
|
905
|
+
```
|
|
906
|
+
|
|
907
|
+
AWS X-Ray tracing does not. `@tracer.capture_method` is a no-op outside Lambda, and there is no X-Ray daemon in the task to receive segments either. Add one as a sidecar in your container service if you need traces.
|
|
908
|
+
|
|
909
|
+
The API Gateway HTTP API's access log records every request that reaches the API. The load balancer writes its own access logs to a bucket the `EcsHttpEndpoint` construct creates, which is where you can see which task served a request and what it answered.
|
|
910
|
+
|
|
911
|
+
### Image Build and Scanning
|
|
912
|
+
|
|
913
|
+
The container generator vends the image targets, named after your API:
|
|
914
|
+
|
|
915
|
+
- `<api-name>-container-docker` builds an image for the CPU architecture in the `architecture` option, `linux/arm64` or `linux/amd64`. The option defaults to the architecture of the machine you run the generator on, and you set it with `--architecture`. The target runs the matching bundle target first, `bundle-arm` or `bundle-x86`, so the image holds your package and its dependencies built for that architecture.
|
|
916
|
+
- `<api-name>-container-trivy` scans that image for vulnerabilities.
|
|
917
|
+
|
|
918
|
+
See <Link path="/guides/py-container">Python Container Service</Link> for how the image is built, and <Link path="/guides/docker-bundling">Docker Bundling</Link> for how it is published at deploy time.
|
|
919
|
+
|
|
920
|
+
### Deploying and Tearing Down
|
|
921
|
+
|
|
922
|
+
`deploy-sandbox` deploys in <Link path="/guides/typescript-infrastructure#deploying-your-sandbox-stage">CloudFormation express mode</Link>, which returns once each resource's configuration is applied rather than waiting for the ECS service to reach a steady state. So the target can finish while the first task is still starting, and until a task has passed two health checks fifteen seconds apart the load balancer has no target to send a request to and answers `503`. Expect about a minute of that after the deploy returns. Wait a minute or two and call again. A `503` that never clears is a real failure rather than a slow start: the service's deployment circuit breaker rolls it back when no task becomes healthy.
|
|
923
|
+
|
|
924
|
+
ECS runs a health check of its own inside the container. It calls `GET /health` every 30 seconds, and failures in the first 30 seconds after a task starts do not count against it. Until that check first reports, `aws ecs describe-tasks` gives the task a `healthStatus` of `UNKNOWN`, which turns to `HEALTHY` once it passes. `UNKNOWN` means the check has not reported yet rather than that it failed.
|
|
925
|
+
|
|
926
|
+
The API's URL is a stack output, but not under the name you would guess. The `CfnOutput` is created inside your API construct and nothing overrides its logical ID, so CDK builds the output key from the construct's path plus an eight-character hash: an API added as `new MyApi(this, 'MyApi', …)` outputs `MyApiMyApiUrl` and that hash, not `MyApiUrl`. `cdk deploy` prints the value, and a script should match on the suffix rather than the whole key:
|
|
927
|
+
|
|
928
|
+
```bash
|
|
929
|
+
aws cloudformation describe-stacks --stack-name <stack-name> \
|
|
930
|
+
--query "Stacks[0].Outputs[?contains(OutputKey, 'Url')].OutputValue" --output text
|
|
931
|
+
```
|
|
932
|
+
|
|
933
|
+
`destroy-sandbox` leaves the HTTP API's access log group and the customer-managed KMS key that encrypts it behind. Neither sets a removal policy, so CDK's default of `Retain` applies and CloudFormation skips them rather than deleting them. List them before you tear the stack down, since a deleted stack no longer reports its resources:
|
|
934
|
+
|
|
935
|
+
```bash
|
|
936
|
+
aws cloudformation describe-stack-resources --stack-name <stack-name> \
|
|
937
|
+
--query "StackResources[?contains(LogicalResourceId, 'AccessLogs') && (ResourceType=='AWS::Logs::LogGroup' || ResourceType=='AWS::KMS::Key')].[ResourceType,PhysicalResourceId]" \
|
|
938
|
+
--output text
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
Then remove them with `aws logs delete-log-group --log-group-name <log-group-name>` and `aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7`, seven days being the shortest window KMS accepts.
|
|
942
|
+
|
|
943
|
+
### Limits
|
|
944
|
+
|
|
945
|
+
- **Integration timeout.** API Gateway HTTP APIs cap an integration at about 30 seconds. An operation that takes longer than that fails at the gateway however long the container keeps working.
|
|
946
|
+
- **No streaming.** Streaming operations need the `rest-lambda` infrastructure. An HTTP API cannot stream a response.
|
|
947
|
+
- **Payload size.** Requests and responses follow API Gateway's 10 MB limit.
|
|
948
|
+
- **One service for every operation.** `integrationPattern` is `shared`: there is one container service, and every route is routed to it. The option always resolves to `shared` for this infrastructure, and `isolated` is ignored with a warning.
|
|
949
|
+
|
|
950
|
+
### Cost
|
|
951
|
+
|
|
952
|
+
The load balancer is the new fixed cost compared with Lambda, where you pay per request and nothing when idle. Rough monthly figures in us-east-1, before data transfer:
|
|
953
|
+
|
|
954
|
+
| Item | Approximately |
|
|
955
|
+
| --- | --- |
|
|
956
|
+
| Internal load balancer | $16 plus load balancer capacity units |
|
|
957
|
+
| Fargate task, 0.25 vCPU / 0.5 GB | $7 per task on ARM64, and more on X86_64, which Fargate bills at a higher rate per vCPU and per GB |
|
|
958
|
+
| NAT gateway, if your VPC has one | $33 |
|
|
959
|
+
| VPC link | no hourly charge |
|
|
960
|
+
| S3 storage for the load balancer's access logs | cents per GB a month |
|
|
961
|
+
|
|
962
|
+
So a one-task service costs roughly $23 a month on ARM64 before any traffic, and more if the VPC you pass in has a NAT gateway. The access logs grow with traffic: add a lifecycle rule to `endpoint.accessLogsBucket` to expire them. Check the [Elastic Load Balancing](https://aws.amazon.com/elasticloadbalancing/pricing/) and [AWS Fargate](https://aws.amazon.com/fargate/pricing/) pricing pages for current prices in your Region.
|
|
963
|
+
</OptionFilter>
|
|
964
|
+
|
|
743
965
|
## Invoking your FastAPI
|
|
744
966
|
|
|
745
967
|
To invoke your API from a React website, you can use the <Link path="guides/connection/react-fastapi">`connection` generator</Link>.
|
package/docs/guides/trpc.mdx
CHANGED
|
@@ -4,7 +4,7 @@ description: Reference documentation for tRPC
|
|
|
4
4
|
generator: ts#api
|
|
5
5
|
when:
|
|
6
6
|
framework: [trpc]
|
|
7
|
-
infra: [rest-lambda, http-lambda]
|
|
7
|
+
infra: [rest-lambda, http-lambda, http-ecs]
|
|
8
8
|
---
|
|
9
9
|
import { FileTree, Tabs, TabItem, CardGrid } from '@astrojs/starlight/components';
|
|
10
10
|
import Astro from '@astrojs/react';
|
|
@@ -21,7 +21,17 @@ import { TS_VERSIONS } from '../../../../../../packages/nx-plugin/src/utils/vers
|
|
|
21
21
|
|
|
22
22
|
[tRPC](https://trpc.io/) is a framework for building APIs in TypeScript with end-to-end type safety. Using tRPC, updates to API operation inputs and outputs are immediately reflected in client code and are visible in your IDE without the need to rebuild your project.
|
|
23
23
|
|
|
24
|
-
The tRPC API generator creates a new tRPC API with AWS CDK or Terraform infrastructure setup. The generated backend
|
|
24
|
+
The tRPC API generator creates a new tRPC API with AWS CDK or Terraform infrastructure setup. The generated backend is exposed via an AWS API Gateway API, and includes schema validation using [Zod](https://zod.dev/). It sets up [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/typescript/latest/) for observability, including structured logging and CloudWatch metrics.
|
|
25
|
+
|
|
26
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Lambda hosting">
|
|
27
|
+
AWS X-Ray tracing is set up too.
|
|
28
|
+
|
|
29
|
+
Your procedures run on AWS Lambda, so there is no server to manage and you pay only for the requests you serve.
|
|
30
|
+
</OptionFilter>
|
|
31
|
+
|
|
32
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="ECS hosting">
|
|
33
|
+
Your procedures run as a long-lived HTTP server in a container on Amazon ECS, behind an API Gateway HTTP API. See <a href="#running-on-amazon-ecs">Running on Amazon ECS</a> for what that changes, including why X-Ray tracing produces no traces there.
|
|
34
|
+
</OptionFilter>
|
|
25
35
|
|
|
26
36
|
## Usage
|
|
27
37
|
|
|
@@ -43,8 +53,22 @@ Select `rest-lambda` (default) as your `infra` if you would like to use [tRPC Su
|
|
|
43
53
|
|
|
44
54
|
:::tip[Integration Pattern]
|
|
45
55
|
The `integrationPattern` option defaults to `isolated`, which creates one Lambda per tRPC procedure. Select `shared` if you would prefer a single shared Lambda handler for the whole API, with optional per-procedure overrides.
|
|
56
|
+
|
|
57
|
+
With `infra` set to `http-ecs` the option is always `shared`, since one container service answers every operation.
|
|
46
58
|
:::
|
|
47
59
|
|
|
60
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="ECS hosting is experimental">
|
|
61
|
+
:::caution[Experimental]
|
|
62
|
+
`http-ecs` is experimental. Its generated output may change between releases without a migration to carry an existing workspace across, so expect to reconcile those changes yourself when you upgrade.
|
|
63
|
+
|
|
64
|
+
It needs the CDK IaC provider: Terraform support is not implemented yet. If the workspace resolves to Terraform, the generator fails with a message naming the fix.
|
|
65
|
+
|
|
66
|
+
`integrationPattern` is always `shared` here. Passing `--integrationPattern=isolated` alongside `http-ecs` does not fail: the generator warns that the option is ignored and uses `shared`. Running the generator interactively, it asks for `integrationPattern` before `infra`, with `isolated` preselected, so that warning is what you see if you leave the preselection alone and then choose `http-ecs`. In the command builder on this page, picking `http-ecs` disables `isolated` and clears it if it was selected, so the command it writes never carries the flag.
|
|
67
|
+
|
|
68
|
+
The `architecture` option sets whether the container runs on `ARM64` or `X86_64`. Leave it out to use the architecture of the machine you run the generator on. See <Link path="/guides/ts-container#cpu-architecture">CPU Architecture</Link> in the container guide.
|
|
69
|
+
:::
|
|
70
|
+
</OptionFilter>
|
|
71
|
+
|
|
48
72
|
## Generator Output
|
|
49
73
|
|
|
50
74
|
The generator will create the following project structure in the `<directory>/<api-name>` directory:
|
|
@@ -82,6 +106,21 @@ The generator will create the following project structure in the `<directory>/<a
|
|
|
82
106
|
|
|
83
107
|
</FileTree>
|
|
84
108
|
|
|
109
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Files that differ when the API runs on ECS">
|
|
110
|
+
With `infra` set to `http-ecs` the API runs as an HTTP server rather than a Lambda handler, so `src/handler.ts` and `src/local-server.ts` are not generated. In their place you get a container folder named after your API:
|
|
111
|
+
|
|
112
|
+
<FileTree>
|
|
113
|
+
- src
|
|
114
|
+
- \<api-name>-container/
|
|
115
|
+
- server.ts The `node:http` server: `GET /health`, and the tRPC standalone adapter for every procedure
|
|
116
|
+
- index.ts Entry point that reads `PORT` and `HOST` and starts the server. The bundle, the image and the `serve` target all start from this file
|
|
117
|
+
- Dockerfile Container image definition
|
|
118
|
+
- .dockerignore Files left out of the image build context
|
|
119
|
+
</FileTree>
|
|
120
|
+
|
|
121
|
+
Your router, procedures, schema, middleware and client are the same for every `infra` value.
|
|
122
|
+
</OptionFilter>
|
|
123
|
+
|
|
85
124
|
### Infrastructure
|
|
86
125
|
|
|
87
126
|
<Snippet name="shared-constructs" />
|
|
@@ -134,7 +173,15 @@ Zod provides powerful utilities to combine or derive schemas such as `.merge`, `
|
|
|
134
173
|
|
|
135
174
|
### Router and Procedures
|
|
136
175
|
|
|
137
|
-
Your tRPC router is defined in `src/router.ts`, which registers all procedures. Each procedure defines the expected input, output, and implementation.
|
|
176
|
+
Your tRPC router is defined in `src/router.ts`, which registers all procedures. Each procedure defines the expected input, output, and implementation.
|
|
177
|
+
|
|
178
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="The Lambda entry point">
|
|
179
|
+
The Lambda handler entry point is in `src/handler.ts`, which forwards requests to your router.
|
|
180
|
+
</OptionFilter>
|
|
181
|
+
|
|
182
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="The container entry point">
|
|
183
|
+
The entry point is `src/<api-name>-container/server.ts`, the HTTP server the container runs, which forwards requests to your router.
|
|
184
|
+
</OptionFilter>
|
|
138
185
|
|
|
139
186
|
The sample router generated for you has a single operation, called `echo`:
|
|
140
187
|
|
|
@@ -299,13 +346,19 @@ export const echo = publicProcedure
|
|
|
299
346
|
|
|
300
347
|
For more information, please refer to the [AWS Lambda Powertools Tracer documentation](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer/).
|
|
301
348
|
|
|
349
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="X-Ray produces no traces on ECS">
|
|
350
|
+
:::caution[No traces on ECS]
|
|
351
|
+
The calls above run without error in a container, but produce no traces. Powertools turns its tracer off when it is not running in Lambda, so `getSegment()` returns a placeholder subsegment that is never sent anywhere. See <a href="#observability">Observability</a> for what you do get, and what to add if you need traces.
|
|
352
|
+
:::
|
|
353
|
+
</OptionFilter>
|
|
354
|
+
|
|
302
355
|
### Implementing Custom Middleware
|
|
303
356
|
|
|
304
357
|
You can add additional values to the context provided to procedures by implementing middleware.
|
|
305
358
|
|
|
306
359
|
As an example, let's implement some middlware to extract some details about the calling user from our API in `src/middleware/identity.ts`.
|
|
307
360
|
|
|
308
|
-
<OptionFilter when={{ auth: 'iam' }} description="Identity middleware example for IAM-authenticated APIs">
|
|
361
|
+
<OptionFilter when={{ auth: 'iam', infra: ['rest-lambda', 'http-lambda'] }} description="Identity middleware example for IAM-authenticated APIs on Lambda">
|
|
309
362
|
This example walks through identity middleware for `IAM` authentication. We look up the caller in Cognito using the sub extracted from the API Gateway event.
|
|
310
363
|
|
|
311
364
|
The lookup uses the Cognito Identity Provider client, which is not a dependency of a generated tRPC API. Install it into your API project first:
|
|
@@ -490,7 +543,7 @@ export const createIdentityPlugin = () => {
|
|
|
490
543
|
</Tabs>
|
|
491
544
|
</OptionFilter>
|
|
492
545
|
|
|
493
|
-
<OptionFilter when={{ auth: 'cognito' }} description="Identity middleware example for Cognito-authenticated APIs">
|
|
546
|
+
<OptionFilter when={{ auth: 'cognito', infra: ['rest-lambda', 'http-lambda'] }} description="Identity middleware example for Cognito-authenticated APIs on Lambda">
|
|
494
547
|
When you deploy with `auth: 'cognito'`, the API Gateway Cognito authorizer verifies the JWT that the caller supplies in the `Authorization` header and places the verified claims on the Lambda event. Our middleware just reads those claims — no extra AWS SDK calls, no manual JWT verification.
|
|
495
548
|
|
|
496
549
|
First, we define what we'll add to the context:
|
|
@@ -641,7 +694,7 @@ The tRPC API generator creates CDK or Terraform infrastructure as code based on
|
|
|
641
694
|
<Fragment slot="cdk">
|
|
642
695
|
The CDK construct for deploying your API lives in the `common/constructs` folder. You can consume this in a CDK application, for example:
|
|
643
696
|
|
|
644
|
-
<OptionFilter when={{ auth: ['iam', 'custom'] }} description="CDK usage for IAM or Custom authentication">
|
|
697
|
+
<OptionFilter when={{ auth: ['iam', 'custom'], infra: ['rest-lambda', 'http-lambda'] }} description="CDK usage for IAM or Custom authentication on Lambda">
|
|
645
698
|
```ts {6-8}
|
|
646
699
|
import { MyApi } from '@my-scope/common-constructs';
|
|
647
700
|
|
|
@@ -662,7 +715,7 @@ Authorizer results are cached for 5 minutes, keyed on the `Authorization` header
|
|
|
662
715
|
:::
|
|
663
716
|
</OptionFilter>
|
|
664
717
|
|
|
665
|
-
<OptionFilter when={{ auth: 'cognito' }} description="CDK usage with Cognito authentication — pass the identity construct">
|
|
718
|
+
<OptionFilter when={{ auth: 'cognito', infra: ['rest-lambda', 'http-lambda'] }} description="CDK usage with Cognito authentication — pass the identity construct">
|
|
666
719
|
```ts {6,10}
|
|
667
720
|
import { MyApi, UserIdentity } from '@my-scope/common-constructs';
|
|
668
721
|
|
|
@@ -682,11 +735,63 @@ export class ExampleStack extends Stack {
|
|
|
682
735
|
The `UserIdentity` construct can be generated using the <Link path="/guides/react-website-auth">`ts#website#auth` generator</Link>.
|
|
683
736
|
</OptionFilter>
|
|
684
737
|
|
|
738
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="CDK usage when the API runs on ECS — pass the VPC">
|
|
739
|
+
`defaultIntegrations` takes the VPC your service runs in, and builds everything inside it: the ECS service, the internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through. The construct never creates a VPC, so you create or import one in your stack.
|
|
740
|
+
|
|
741
|
+
```ts {10,13-15}
|
|
742
|
+
import { MyApi } from '@my-scope/common-constructs';
|
|
743
|
+
import { Stack } from 'aws-cdk-lib';
|
|
744
|
+
import { Vpc } from 'aws-cdk-lib/aws-ec2';
|
|
745
|
+
import { Construct } from 'constructs';
|
|
746
|
+
|
|
747
|
+
export class ExampleStack extends Stack {
|
|
748
|
+
constructor(scope: Construct, id: string) {
|
|
749
|
+
super(scope, id);
|
|
750
|
+
|
|
751
|
+
const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
|
|
752
|
+
|
|
753
|
+
const api = new MyApi(this, 'MyApi', {
|
|
754
|
+
integrations: MyApi.defaultIntegrations(this, { vpc }).build(),
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
To use an existing VPC, look it up with `Vpc.fromLookup(this, 'Vpc', { vpcId: '<vpc-id>' })` and pass it as `vpc`.
|
|
761
|
+
|
|
762
|
+
Pass `service` to change the container service itself — its `cpu`, `memoryLimitMiB`, `desiredCount`, `environment`, or `grantTaskRole` to give the task role a permission:
|
|
763
|
+
|
|
764
|
+
```ts
|
|
765
|
+
MyApi.defaultIntegrations(this, {
|
|
766
|
+
vpc,
|
|
767
|
+
service: {
|
|
768
|
+
cpu: 512,
|
|
769
|
+
memoryLimitMiB: 1024,
|
|
770
|
+
grantTaskRole: (taskRole) => myTable.grantReadWriteData(taskRole),
|
|
771
|
+
},
|
|
772
|
+
}).build();
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
With `auth` set to `cognito`, also pass `identity` to the construct as the Cognito example above does.
|
|
776
|
+
</OptionFilter>
|
|
777
|
+
|
|
778
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="What the Lambda variants deploy">
|
|
685
779
|
This sets up your API infrastructure, including an AWS API Gateway REST or HTTP API, AWS Lambda functions for business logic, and authentication based on your chosen `auth` method.
|
|
780
|
+
</OptionFilter>
|
|
781
|
+
|
|
782
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="What the ECS variant deploys">
|
|
783
|
+
This sets up an AWS API Gateway HTTP API with authentication based on your chosen `auth` method, an Amazon ECS service running your container, an internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through.
|
|
784
|
+
</OptionFilter>
|
|
686
785
|
|
|
687
786
|
<Snippet name="api/cors-configuration-cdk-note" />
|
|
688
787
|
</Fragment>
|
|
689
788
|
<Fragment slot="terraform">
|
|
789
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Terraform is not implemented for ECS hosting">
|
|
790
|
+
:::caution[CDK only]
|
|
791
|
+
`http-ecs` is not implemented for Terraform. The generator fails with a message saying so. Choose `rest-lambda` or `http-lambda` for a Terraform workspace.
|
|
792
|
+
:::
|
|
793
|
+
</OptionFilter>
|
|
794
|
+
|
|
690
795
|
The Terraform modules for deploying your API are in the `common/terraform` folder. You can use this in a Terraform configuration.
|
|
691
796
|
|
|
692
797
|
The API module stages its Lambda deployment zip in a shared S3 asset bucket — see the <Link path="/guides/terraform-project">Terraform infrastructure guide</Link> for details. Instantiate the `core/asset-bucket` module once per deployment and pass its `bucket_name` output into every API / Lambda module via the `asset_bucket_name` input:
|
|
@@ -891,13 +996,109 @@ The key outputs from the API module that you can use for IAM policies are:
|
|
|
891
996
|
|
|
892
997
|
<Snippet name="ts-bundle" />
|
|
893
998
|
|
|
999
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="How ECS hosting works, what it costs and what it limits">
|
|
1000
|
+
## Running on Amazon ECS
|
|
1001
|
+
|
|
1002
|
+
With `infra` set to `http-ecs`, your procedures run as a long-lived HTTP server in a container rather than in a Lambda function. A request takes this path:
|
|
1003
|
+
|
|
1004
|
+
1. A caller signs a request to the API Gateway HTTP API, which is the only public entry point. Every route carries the authorizer for the `auth` you chose, so an unauthenticated request is rejected at the edge.
|
|
1005
|
+
2. API Gateway forwards the request through a VPC link, which is its private path into your VPC.
|
|
1006
|
+
3. The VPC link reaches an internal load balancer. The load balancer has no public address, and its only inbound rule allows the VPC link's security group on the listener port.
|
|
1007
|
+
4. The load balancer forwards the request to a task. The tasks' only inbound rule allows the load balancer's security group on the container port, so nothing else in the VPC can open a connection to them.
|
|
1008
|
+
|
|
1009
|
+
The tasks run in private subnets and never get a public IP address. Nothing in this path allows an address range inbound.
|
|
1010
|
+
|
|
1011
|
+
By default the service, the load balancer and the VPC link go in the VPC's `PRIVATE_WITH_EGRESS` subnets, which reach AWS through a NAT gateway. Passing `vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED }` to `defaultIntegrations` drops the NAT gateway and its hourly charge, but isolated subnets have no route out, so the VPC then needs four VPC endpoints for the tasks to start at all: interface endpoints for `ecr.api` and `ecr.dkr` to pull the image, an S3 gateway endpoint because the image layers are S3 objects, and an interface endpoint for `logs` so the `awslogs` driver can write. Without them a task cannot pull its image and ECS rolls the deployment back on the circuit breaker without saying why.
|
|
1012
|
+
|
|
1013
|
+
The VPC link, the load balancer, its listener, the target group and the bucket the load balancer writes its access logs to are created by one construct, `core/api/ecs-http-endpoint.ts` in `common/constructs`, which every API hosted on ECS shares. Your API's own construct names its container service and routes every operation to that endpoint.
|
|
1014
|
+
|
|
1015
|
+
### What Runs in the Container
|
|
1016
|
+
|
|
1017
|
+
`src/<api-name>-container/server.ts` is a `node:http` server with two jobs. `GET /health` answers `{"status":"ok"}`, which is what the load balancer's target group and the container health check call. Every other request goes to the [tRPC standalone adapter](https://trpc.io/docs/server/adapters/standalone), which resolves it against your router.
|
|
1018
|
+
|
|
1019
|
+
There is no API Gateway event in the container, so the procedure context carries no `event`, `context` or `info` field: for `http-ecs` the vended `IMiddlewareContext` names only what the middleware puts there. The authorizer still decides whether a request reaches the container at all, but its claims do not arrive with the request, so the identity middleware examples above do not apply. To read the caller's identity in a procedure, map the authorizer's context onto a request header in your API construct and read that header.
|
|
1020
|
+
|
|
1021
|
+
### Observability
|
|
1022
|
+
|
|
1023
|
+
Logs and metrics work as they do on Lambda: the container writes to its own CloudWatch log group, and the metrics plugin publishes each request's metrics in the embedded metric format for CloudWatch Logs to extract.
|
|
1024
|
+
|
|
1025
|
+
The metrics plugin builds a metrics object for each request and hands it to your procedures as `opts.ctx.metrics`, so a metric one request adds is never published with another's. That matters more here than on Lambda, where one invocation owns the metrics from start to finish; this server handles requests at the same time. Add your own metrics through `opts.ctx.metrics` rather than a `Metrics` object of your own, which would share one store across every request in the process.
|
|
1026
|
+
|
|
1027
|
+
AWS X-Ray tracing does not. Powertools turns its tracer off outside Lambda, and there is no X-Ray daemon in the task to receive segments, so `opts.ctx.tracer` calls run without error and produce no traces. Add a daemon as a sidecar in your container service if you need them.
|
|
1028
|
+
|
|
1029
|
+
The API Gateway HTTP API's access log records every request that reaches the API. The load balancer writes its own access logs to a bucket the `EcsHttpEndpoint` construct creates, which is where you can see which task served a request and what it answered.
|
|
1030
|
+
|
|
1031
|
+
### Image Build and Scanning
|
|
1032
|
+
|
|
1033
|
+
The container generator vends the image targets, named after your API:
|
|
1034
|
+
|
|
1035
|
+
- `<api-name>-container-docker` builds a linux/arm64 image, running `bundle` first so the image holds the bundled server.
|
|
1036
|
+
- `<api-name>-container-trivy` scans that image for vulnerabilities.
|
|
1037
|
+
|
|
1038
|
+
See <Link path="/guides/ts-container">TypeScript Container Service</Link> for how the image is built, and <Link path="/guides/docker-bundling">Docker Bundling</Link> for how it is published at deploy time.
|
|
1039
|
+
|
|
1040
|
+
### Deploying and Tearing Down
|
|
1041
|
+
|
|
1042
|
+
`deploy-sandbox` deploys in <Link path="/guides/typescript-infrastructure#deploying-your-sandbox-stage">CloudFormation express mode</Link>, which returns once each resource's configuration is applied rather than waiting for the ECS service to reach a steady state. So the target can finish while the first task is still starting, and until a task has passed two health checks fifteen seconds apart the load balancer has no target to send a request to and answers `503`. Wait a minute or two and call again. A `503` that never clears is a real failure rather than a slow start: the service's deployment circuit breaker rolls it back when no task becomes healthy.
|
|
1043
|
+
|
|
1044
|
+
The API's URL is a stack output, but not under the name you would guess. The `CfnOutput` is created inside your API construct and nothing overrides its logical ID, so CDK builds the output key from the construct's path plus an eight-character hash: an API added as `new MyApi(this, 'MyApi', …)` outputs `MyApiMyApiUrl` and that hash, not `MyApiUrl`. `cdk deploy` prints the value, and a script should match on the suffix rather than the whole key:
|
|
1045
|
+
|
|
1046
|
+
```bash
|
|
1047
|
+
aws cloudformation describe-stacks --stack-name <stack-name> \
|
|
1048
|
+
--query "Stacks[0].Outputs[?contains(OutputKey, 'Url')].OutputValue" --output text
|
|
1049
|
+
```
|
|
1050
|
+
|
|
1051
|
+
`destroy-sandbox` leaves the HTTP API's access log group and the customer-managed KMS key that encrypts it behind. Neither sets a removal policy, so CDK's default of `Retain` applies and CloudFormation skips them rather than deleting them. List them before you tear the stack down, since a deleted stack no longer reports its resources:
|
|
1052
|
+
|
|
1053
|
+
```bash
|
|
1054
|
+
aws cloudformation describe-stack-resources --stack-name <stack-name> \
|
|
1055
|
+
--query "StackResources[?contains(LogicalResourceId, 'AccessLogs') && (ResourceType=='AWS::Logs::LogGroup' || ResourceType=='AWS::KMS::Key')].[ResourceType,PhysicalResourceId]" \
|
|
1056
|
+
--output text
|
|
1057
|
+
```
|
|
1058
|
+
|
|
1059
|
+
Then remove them with `aws logs delete-log-group --log-group-name <log-group-name>` and `aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7`, seven days being the shortest window KMS accepts.
|
|
1060
|
+
|
|
1061
|
+
### Limits
|
|
1062
|
+
|
|
1063
|
+
- **Integration timeout.** API Gateway HTTP APIs cap an integration at about 30 seconds. A procedure that takes longer than that fails at the gateway however long the container keeps working.
|
|
1064
|
+
- **No streaming.** tRPC subscriptions need the `rest-lambda` infrastructure. An HTTP API cannot stream a response.
|
|
1065
|
+
- **Payload size.** Requests and responses follow API Gateway's 10 MB limit.
|
|
1066
|
+
- **One service for every operation.** `integrationPattern` is `shared`: there is one container service, and every route is routed to it. The option always resolves to `shared` for this infrastructure, and `isolated` is ignored with a warning.
|
|
1067
|
+
|
|
1068
|
+
### Cost
|
|
1069
|
+
|
|
1070
|
+
The load balancer is the new fixed cost compared with Lambda, where you pay per request and nothing when idle. Rough monthly figures in us-east-1, before data transfer:
|
|
1071
|
+
|
|
1072
|
+
| Item | Approximately |
|
|
1073
|
+
| --- | --- |
|
|
1074
|
+
| Internal load balancer | $16 plus load balancer capacity units |
|
|
1075
|
+
| Fargate task, 0.25 vCPU / 0.5 GB arm64 | $7 per task |
|
|
1076
|
+
| NAT gateway, if your VPC has one | $33 |
|
|
1077
|
+
| VPC link | no hourly charge |
|
|
1078
|
+
| S3 storage for the load balancer's access logs | cents per GB a month |
|
|
1079
|
+
|
|
1080
|
+
So a one-task service costs roughly $23 a month before any traffic, and more if the VPC you pass in has a NAT gateway. The access logs grow with traffic: add a lifecycle rule to `endpoint.accessLogsBucket` to expire them. Check the [Elastic Load Balancing](https://aws.amazon.com/elasticloadbalancing/pricing/) and [AWS Fargate](https://aws.amazon.com/fargate/pricing/) pricing pages for current prices in your Region.
|
|
1081
|
+
</OptionFilter>
|
|
1082
|
+
|
|
894
1083
|
## Local tRPC Server
|
|
895
1084
|
|
|
896
1085
|
You can use the `serve` target to run a local server for your API, for example:
|
|
897
1086
|
|
|
898
1087
|
<NxCommands commands={['serve my-api']} />
|
|
899
1088
|
|
|
1089
|
+
<OptionFilter not when={{ infra: 'http-ecs' }} description="Local server entry point for the Lambda variants">
|
|
900
1090
|
The entry point for the local server is `src/local-server.ts`.
|
|
1091
|
+
</OptionFilter>
|
|
1092
|
+
|
|
1093
|
+
<OptionFilter when={{ infra: 'http-ecs' }} description="Local server entry point when the API runs on ECS">
|
|
1094
|
+
The entry point for the local server is `src/<api-name>-container/index.ts`, the same file the container runs. It listens on the address in `HOST`, which defaults to `127.0.0.1`, so the local server accepts connections only from your own machine. The image sets `HOST=0.0.0.0` so the server listens on the task's own network interface, where the task's security group decides who may connect.
|
|
1095
|
+
|
|
1096
|
+
Check that the server is up with its health route, which returns status 200 and `{"status":"ok"}`:
|
|
1097
|
+
|
|
1098
|
+
```bash
|
|
1099
|
+
curl http://localhost:2022/health
|
|
1100
|
+
```
|
|
1101
|
+
</OptionFilter>
|
|
901
1102
|
|
|
902
1103
|
This will automatically reload when you make changes to your API.
|
|
903
1104
|
|
package/package.json
CHANGED
package/src/py/api/schema.json
CHANGED
|
@@ -35,9 +35,11 @@
|
|
|
35
35
|
},
|
|
36
36
|
"integrationPattern": {
|
|
37
37
|
"type": "string",
|
|
38
|
-
"description": "How API Gateway integrations are generated for the API. Choose between isolated
|
|
39
|
-
"default": "isolated",
|
|
38
|
+
"description": "How API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.",
|
|
40
39
|
"enum": ["isolated", "shared"],
|
|
40
|
+
"x-value-when": {
|
|
41
|
+
"isolated": { "infra": ["rest-lambda", "http-lambda", "none"] }
|
|
42
|
+
},
|
|
41
43
|
"x-priority": "important",
|
|
42
44
|
"x-prompt": {
|
|
43
45
|
"message": "How would you like to map integrations to your API operations?",
|
|
@@ -89,12 +91,17 @@
|
|
|
89
91
|
},
|
|
90
92
|
"infra": {
|
|
91
93
|
"type": "string",
|
|
92
|
-
"description": "The type of infrastructure to use to deploy this API.",
|
|
94
|
+
"description": "The type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.",
|
|
93
95
|
"default": "rest-lambda",
|
|
94
|
-
"enum": ["rest-lambda", "http-lambda", "none"],
|
|
96
|
+
"enum": ["rest-lambda", "http-lambda", "http-ecs", "none"],
|
|
95
97
|
"x-prompt": "What infrastructure would you like to deploy your API with?",
|
|
96
98
|
"x-priority": "important"
|
|
97
99
|
},
|
|
100
|
+
"architecture": {
|
|
101
|
+
"type": "string",
|
|
102
|
+
"description": "The CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.",
|
|
103
|
+
"enum": ["ARM64", "X86_64"]
|
|
104
|
+
},
|
|
98
105
|
"preferInstallDependencies": {
|
|
99
106
|
"type": "boolean",
|
|
100
107
|
"description": "Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.",
|
|
@@ -18,9 +18,11 @@
|
|
|
18
18
|
},
|
|
19
19
|
"integrationPattern": {
|
|
20
20
|
"type": "string",
|
|
21
|
-
"description": "How API Gateway integrations are generated for the API. Choose between isolated
|
|
22
|
-
"default": "isolated",
|
|
21
|
+
"description": "How API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.",
|
|
23
22
|
"enum": ["isolated", "shared"],
|
|
23
|
+
"x-value-when": {
|
|
24
|
+
"isolated": { "infra": ["rest-lambda", "http-lambda", "none"] }
|
|
25
|
+
},
|
|
24
26
|
"x-priority": "important",
|
|
25
27
|
"x-prompt": {
|
|
26
28
|
"message": "How would you like to map integrations to your FastAPI operations?",
|
|
@@ -72,12 +74,17 @@
|
|
|
72
74
|
},
|
|
73
75
|
"infra": {
|
|
74
76
|
"type": "string",
|
|
75
|
-
"description": "The type of infrastructure to use to deploy this API.",
|
|
77
|
+
"description": "The type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.",
|
|
76
78
|
"default": "rest-lambda",
|
|
77
|
-
"enum": ["rest-lambda", "http-lambda", "none"],
|
|
79
|
+
"enum": ["rest-lambda", "http-lambda", "http-ecs", "none"],
|
|
78
80
|
"x-prompt": "What infrastructure would you like to deploy your API with?",
|
|
79
81
|
"x-priority": "important"
|
|
80
82
|
},
|
|
83
|
+
"architecture": {
|
|
84
|
+
"type": "string",
|
|
85
|
+
"description": "The CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.",
|
|
86
|
+
"enum": ["ARM64", "X86_64"]
|
|
87
|
+
},
|
|
81
88
|
"preferInstallDependencies": {
|
|
82
89
|
"type": "boolean",
|
|
83
90
|
"description": "Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.",
|
|
@@ -16,9 +16,11 @@
|
|
|
16
16
|
},
|
|
17
17
|
"integrationPattern": {
|
|
18
18
|
"type": "string",
|
|
19
|
-
"description": "How API Gateway integrations are generated for the API. Choose between isolated
|
|
20
|
-
"default": "isolated",
|
|
19
|
+
"description": "How API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.",
|
|
21
20
|
"enum": ["isolated", "shared"],
|
|
21
|
+
"x-value-when": {
|
|
22
|
+
"isolated": { "infra": ["rest-lambda", "http-lambda", "none"] }
|
|
23
|
+
},
|
|
22
24
|
"x-priority": "important",
|
|
23
25
|
"x-prompt": {
|
|
24
26
|
"message": "How would you like to map integrations to your tRPC procedures?",
|
|
@@ -67,12 +69,17 @@
|
|
|
67
69
|
},
|
|
68
70
|
"infra": {
|
|
69
71
|
"type": "string",
|
|
70
|
-
"description": "The type of infrastructure to use to deploy this API.",
|
|
72
|
+
"description": "The type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.",
|
|
71
73
|
"default": "rest-lambda",
|
|
72
|
-
"enum": ["rest-lambda", "http-lambda", "none"],
|
|
74
|
+
"enum": ["rest-lambda", "http-lambda", "http-ecs", "none"],
|
|
73
75
|
"x-prompt": "What infrastructure would you like to deploy your API with?",
|
|
74
76
|
"x-priority": "important"
|
|
75
77
|
},
|
|
78
|
+
"architecture": {
|
|
79
|
+
"type": "string",
|
|
80
|
+
"description": "The CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.",
|
|
81
|
+
"enum": ["ARM64", "X86_64"]
|
|
82
|
+
},
|
|
76
83
|
"preferInstallDependencies": {
|
|
77
84
|
"type": "boolean",
|
|
78
85
|
"description": "Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.",
|
package/src/ts/api/schema.json
CHANGED
|
@@ -44,9 +44,11 @@
|
|
|
44
44
|
},
|
|
45
45
|
"integrationPattern": {
|
|
46
46
|
"type": "string",
|
|
47
|
-
"description": "How API Gateway integrations are generated for the API. Choose between isolated
|
|
48
|
-
"default": "isolated",
|
|
47
|
+
"description": "How API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.",
|
|
49
48
|
"enum": ["isolated", "shared"],
|
|
49
|
+
"x-value-when": {
|
|
50
|
+
"isolated": { "infra": ["rest-lambda", "http-lambda", "none"] }
|
|
51
|
+
},
|
|
50
52
|
"x-priority": "important",
|
|
51
53
|
"x-prompt": {
|
|
52
54
|
"message": "How would you like to map integrations to your API operations?",
|
|
@@ -95,13 +97,21 @@
|
|
|
95
97
|
},
|
|
96
98
|
"infra": {
|
|
97
99
|
"type": "string",
|
|
98
|
-
"description": "The type of infrastructure to use to deploy this API.",
|
|
100
|
+
"description": "The type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the trpc framework and the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.",
|
|
99
101
|
"default": "rest-lambda",
|
|
100
|
-
"enum": ["rest-lambda", "http-lambda", "none"],
|
|
101
|
-
"x-value-when": {
|
|
102
|
+
"enum": ["rest-lambda", "http-lambda", "http-ecs", "none"],
|
|
103
|
+
"x-value-when": {
|
|
104
|
+
"http-lambda": { "framework": "trpc" },
|
|
105
|
+
"http-ecs": { "framework": "trpc" }
|
|
106
|
+
},
|
|
102
107
|
"x-prompt": "What infrastructure would you like to deploy your API with?",
|
|
103
108
|
"x-priority": "important"
|
|
104
109
|
},
|
|
110
|
+
"architecture": {
|
|
111
|
+
"type": "string",
|
|
112
|
+
"description": "The CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.",
|
|
113
|
+
"enum": ["ARM64", "X86_64"]
|
|
114
|
+
},
|
|
105
115
|
"preferInstallDependencies": {
|
|
106
116
|
"type": "boolean",
|
|
107
117
|
"description": "Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.",
|