Skip to content

Commit af2f4b5

Browse files
committed
Merge main into auth-unification (#1105)
Brings in "feat(core): serve an API namespace from a container compute" (#1105) and "ci(cleanup): fail the sweep leg when REST APIs can't be counted" (#959). packages/core/src/api.ts: ApiNamespaceOptions keeps this branch's httpErrorStatus option and its docs, and takes #1105's container compute docs and widened `compute` type ('serverless' | 'container'). A container compute serves the whole backend module through the shared dispatch core, which already answers a 4xx ApiError of an httpErrorStatus namespace with its status; http-server.test.ts now checks that against the Lambda handler. .github/workflows/cleanup-stacks.yml (REST API sweep): takes #959's list-stacks fail-safe (retries, the CLI's reason as a warning), its rest-api-quota.sh headroom check and its exit on a listing or count failure, and keeps this branch's separate ownership and budget deferral counts in the summary and warnings. # Conflicts: # .github/workflows/cleanup-stacks.yml # packages/core/src/api.ts
2 parents d58efd4 + 9ebf67a commit af2f4b5

35 files changed

Lines changed: 2704 additions & 182 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@aws-blocks/core': minor
3+
'@aws-blocks/bb-container-compute': minor
4+
'@aws-blocks/bb-compute': patch
5+
'@aws-blocks/blocks': minor
6+
---
7+
8+
An API namespace can run on a `container` compute:
9+
10+
```ts
11+
const renderCompute = new Compute(scope, 'render', { type: 'container', size: { vcpu: 2, memory: 4096 } });
12+
export const render = new ApiNamespace(scope, 'render', (context) => ({ … }), { compute: renderCompute });
13+
```
14+
15+
The container's tasks serve the namespace with the same dispatch as the Lambda handler (CORS, cookies, error envelopes), so clients call it exactly as before at `/aws-blocks/api/render`.
16+
17+
- The shared API gateway reaches the tasks through a VPC link to an internal Application Load Balancer that the compute provisions in the app's VPC: one load balancer and one listener per backend, with a path rule per namespace forwarding to its container's target group, health-checked on the task's readiness port. A container that only runs jobs gets no target group.
18+
- The tasks admit the load balancer on a security group of their own; the shared compute security group stays closed to inbound traffic.
19+
- The load balancer drops request headers that aren't valid HTTP before they reach a task.
20+
- API calls to a container keep the gateway's ~29-second cap. A stopping task finishes its in-flight requests (up to 35 s) before it shuts down.
21+
- A `Scope` with a container `compute` now places its `ApiNamespace`s on that container too, instead of failing synth.
22+
- A container that serves API namespaces needs a running task: `scaling.minInstances: 0` fails synth. Without a `scaling.strategy`, one that also runs an `AsyncJob` scales on CPU, and its queue backlog adds tasks too.
23+
- Moving a namespace that already serves traffic onto a container: during that deploy, its calls can get 503s for the minute or two the new tasks take to start.
24+
- `runContainer()` takes the backend module (`runContainer({ backend })`) and serves its API on port 8080, with readiness on port 8081; called without it, the container answers a health check on port 8080 as before. A container compute passes it only when the compute serves API traffic.
25+
- The container compute's dashboard section gains API request, 5xx, latency and task-health widgets.

‎.github/workflows/cleanup-stacks.yml‎

Lines changed: 145 additions & 69 deletions
Large diffs are not rendered by default.

‎.github/workflows/pr-checks.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,12 @@ jobs:
316316
- name: Test the E2E cleanup wrapper
317317
run: node --test scripts/ci/e2e-cleanup.test.mjs
318318

319+
# The scheduled stack cleanup (cleanup-stacks.yml): a REST API or IAM role
320+
# count it can't read must fail its leg, and no listing failure may read
321+
# as "nothing to sweep".
322+
- name: Test the stack cleanup's listing failures
323+
run: node --test scripts/ci/rest-api-quota.test.mjs scripts/ci/cleanup-listings.test.mjs
324+
319325
# Runs on the root build output, before Unit Tests: a package `pretest` that
320326
# bundles an asset would otherwise hide a bundle the release build skips.
321327
- name: Test the packed-assets guard

‎packages/bb-compute/README.md‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ new CronJob(scope, 'nightly', { compute: api, schedule: 'cron(0 2 * * ? *)', han
3131
| Workload | Option | Compute types |
3232
| --- | --- | --- |
3333
| `AsyncJob` | `compute` | `serverless`, `container` |
34-
| `ApiNamespace` | `compute` (4th argument) | `serverless` |
35-
| `CronJob` | `compute` | `serverless` |
34+
| `ApiNamespace` | `compute` (4th argument) | `serverless`, `container` |
35+
| `CronJob` | `compute` | `serverless`, `container` |
3636
| `Scope` (everything under it) | `compute` | `serverless`, `container` (see below) |
3737

3838
## Placing a whole scope
@@ -53,10 +53,10 @@ new CronJob(reports, 'nightly', { schedule: 'cron(0 2 * * ? *)', handler: async
5353
both are child constructs of it.
5454
- **Nearest wins.** A block's own `compute` option, then the nearest scope that
5555
sets `compute`, then the app's default compute.
56-
- **A container scope** places its `AsyncJob`s and `CronJob`s on the container.
57-
An `ApiNamespace` under it fails synth with an error naming the compute,
58-
because it runs only on a `serverless` compute for now: give it its own
59-
serverless `compute`, or create it outside that scope. Setting an
56+
- **A container scope** places its `AsyncJob`s, `CronJob`s and `ApiNamespace`s
57+
on the container. Its namespaces are served through the container's load
58+
balancer (see [API namespaces](#api-namespaces)), so the container needs at
59+
least one running task: `scaling.minInstances: 0` fails synth. Setting an
6060
`AsyncJob`'s `maxConcurrencyPerCPU` still needs the container passed as the
6161
job's own `compute`, so the option is typed for it.
6262
- **`Realtime` and `RawRoute` stay on the default compute**, inside such a scope
@@ -101,6 +101,8 @@ type is a compile error.
101101
`AsyncJob` or `CronJob` on the compute and the default (or `queue-depth`)
102102
scaling strategy; anything else fails synth, because nothing would start a task
103103
or scale-in could stop one under a running job.
104+
A compute that serves an `ApiNamespace` can't use `minInstances: 0` either:
105+
nothing starts a task for an incoming request.
104106
- **Deploys restart running jobs.** A deploy that changes your code replaces
105107
the container's tasks. A stopping task stops taking new jobs and gives running
106108
ones up to about 2 minutes to finish (the AWS Fargate maximum). A job still
@@ -147,9 +149,31 @@ export const reports = new ApiNamespace(scope, 'reports', (context) => ({
147149
(`export const reports = …` → `reports`), not the second `ApiNamespace`
148150
argument.
149151
- **Share a compute** across namespaces and `AsyncJob`s by passing the same
150-
`Compute` to each; they then run in the same function.
151-
- **Only `serverless` computes serve API namespaces** today; passing a
152-
`container` compute is a type error.
152+
`Compute` to each; they then run in the same function (or the same
153+
container tasks).
154+
- **A `container` compute serves its namespaces from its long-running tasks** —
155+
no cold starts, CPU and memory sized for the workload:
156+
157+
```ts
158+
const renderCompute = new Compute(scope, 'render', { type: 'container', size: { vcpu: 2, memory: 4096 } });
159+
export const render = new ApiNamespace(scope, 'render', (context) => ({ /* methods */ }), { compute: renderCompute });
160+
```
161+
162+
The gateway reaches the tasks through an internal Application Load Balancer
163+
the compute provisions in the app's VPC (with a VPC link), so the same
164+
~29-second cap applies. One load balancer (and one listener) is shared by
165+
every container in the backend that hosts a namespace.
166+
167+
- It needs at least one running task: `scaling.minInstances: 0` fails synth.
168+
- Without a `scaling.strategy`, a container that also runs an `AsyncJob`
169+
scales on CPU (the API load), and its queue backlog adds tasks too.
170+
- Moving a namespace that already serves traffic onto a container: during
171+
that deploy, its calls can get 503s for the minute or two the new tasks take
172+
to start, because the route switches before they're healthy.
173+
- The load balancer allows 100 namespaces by default (synth warns past that;
174+
the quota can be raised), and an export name can be at most 112 characters
175+
(the load balancer's 128-character rule path limit, minus the 16-character
176+
`/aws-blocks/api/` prefix).
153177
- **Everything else stays on the default compute:** namespaces with no
154178
`compute` of their own or from their scope, `RawRoute`s, and the auth HTTP
155179
routes (`/aws-blocks/auth/*`).

‎packages/bb-container-compute/DESIGN.md‎

Lines changed: 90 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,86 @@ self-starts the SQS pollers for the event handlers assigned to it.
4242
Blocks VPC when none was provided. Tasks are placed in the
4343
`private-with-egress` tier.
4444

45+
## API traffic
46+
47+
A container compute that hosts an `ApiNamespace` serves it over HTTP: the
48+
container parent runs core's `serveHttp` (via `runContainer({ backend })`) —
49+
the same transport-neutral dispatch as the Lambda handler — on port **8080**,
50+
with readiness on port **8081** (503 while draining).
51+
52+
- **Provisioned on demand.** The shared API gateway calls `apiIngress()` for a
53+
compute only when a namespace is routed to it (after the backend import,
54+
before `finalize()`), and the ingress is created then. A container that only
55+
runs jobs gets no load balancer, listener or target group, and its image entry
56+
keeps a plain health check on 8080: only a compute that serves API traffic
57+
sets `BLOCKS_CONTAINER_SERVES_API`, which makes the entry pass the backend
58+
module to `runContainer`.
59+
- **A running task.** The load balancer forwards only to running tasks and
60+
nothing starts one on a request, so a compute that serves API traffic with
61+
`scaling.minInstances: 0` fails synth.
62+
- **One internal ALB per backend**, in the compute subnets, shared by every
63+
container that serves API traffic, with **one listener for all their API
64+
namespaces** on port 10000. Each namespace gets an exact-path rule
65+
(`/aws-blocks/api/{name}` → its compute's target group); any other path gets a
66+
404 from the load balancer. The gateway's VPC link integration targets the
67+
load balancer's ARN on that port.
68+
- A rule belongs to the shared listener and is named after its path, so moving
69+
a namespace to another container compute updates its target in place.
70+
- Its priority is derived from the path, so it is stable across deploys
71+
whatever namespaces come and go. Two paths that hash to the same priority
72+
fail synth (rename one export): shifting one to a free priority would make
73+
it depend on its neighbours, and break a later deploy that adds or removes one.
74+
- A rule's path pattern is at most 128 characters, so a longer namespace path
75+
fails synth: with the 16-character `/aws-blocks/api/` prefix, an export name
76+
is at most 112. Past the default quota of 100 rules per load balancer, synth
77+
warns.
78+
- **Only namespace paths reach a container; `RawRoute`s run on the default
79+
compute.** A namespace path is exact (`/aws-blocks/api/{name}`), so each one
80+
gets its own gateway resource and listener rule. `RawRoute` paths can be
81+
patterns (`/files/{id}`, `/files/*`): the gateway serves them through its
82+
catch-all resources, which integrate the default compute.
83+
- **Reserved ports.** `10001–10999` is kept for listeners a single compute will
84+
own — e.g. one for a container's `RawRoute`s, forwarding everything to the
85+
compute so the container's own route matching decides. The whole
86+
`10000–10999` range is one security group rule per source, so adding a
87+
listener never adds a rule.
88+
- **Target group** on task port 8080, health-checked on 8081. A stopping task
89+
is deregistered first — with a 35 s delay, past API Gateway's 29 s integration
90+
timeout (the VPC link is the only path to the load balancer), so in-flight
91+
requests finish — then gets SIGTERM and drains for up to 110 s
92+
(`DRAIN_GRACE_SECONDS`, passed as `BLOCKS_DRAIN_GRACE_SECONDS`) within the
93+
120 s stop timeout (`STOP_TIMEOUT_SECONDS`).
94+
- **Load balancers on the service.** The service is registered with its target
95+
group at the CloudFormation level, because the L2 route would open the load
96+
balancer to every group on the service. Its `LoadBalancers` property is always
97+
rendered — `[]` for a compute that serves no API — since CloudFormation keeps
98+
an attached target group when the property is simply absent.
99+
- **Security groups.** The tasks get a group of their own that admits only the
100+
load balancer on 8080–8081 (one rule); the shared compute group (also used by
101+
in-VPC Lambdas and VPC endpoints) stays closed to inbound traffic. The load
102+
balancer admits only the gateway's VPC link, on the listener port range.
103+
- **Transport.** TLS terminates at API Gateway. The hop from the gateway's VPC
104+
link to the load balancer, and on to the task, is plain HTTP inside the VPC:
105+
the load balancer is internal and its security group admits only the VPC
106+
link, and the tasks' security group admits only the load balancer, on the API
107+
and readiness ports.
108+
- **Request URL.** A request reaches the task as the load balancer's hop — the
109+
integration URI's host, plain `http`, no stage — whereas the Lambda handler
110+
gets the gateway's `Host` and the stage in its API Gateway event. So the
111+
gateway stamps its public host and stage (`x-blocks-forwarded-host` /
112+
`x-blocks-forwarded-stage`, from its request context, overwriting any client
113+
value), and the container builds `ctx.request.url` from them: the same URL
114+
the Lambda handler reports. A request whose stamped headers aren't one
115+
well-formed value each — a client copy under another letter case, say — is
116+
refused with a 400.
117+
- **Moving a live namespace onto a container.** CloudFormation switches the
118+
namespace's route to the load balancer without waiting for the new tasks to
119+
become healthy (making the gateway wait on the ECS service would be a
120+
dependency cycle once the config the service waits for carries a CloudFront
121+
URL). So during that deploy, calls to the namespace can get 503s for the minute
122+
or two the tasks take to start and pass their health check.
123+
- **Limits.** API calls keep the gateway's ~29-second integration timeout.
124+
45125
## Autoscaling
46126

47127
`finalize()` (called once per compute by `create()` after the backend import)
@@ -59,16 +139,23 @@ wires Application Auto Scaling from `scaling`:
59139
assigned here calls at synth. Autoscaling is wired at `finalize()` precisely so
60140
every owned queue is known first.
61141
- Omitted `strategy` → inferred: queue-depth when the compute drains queues, else
62-
CPU. `maxInstances ≤ 1` wires no policy, unless `minInstances` is 0.
142+
CPU. A compute that drains queues **and** serves API traffic gets both: CPU
143+
target tracking follows the API load and removes capacity, while the queue
144+
backlog only adds it (no scale-in step) — a queue-depth scale-in step would
145+
remove tasks the API still needs whenever the queue is empty. With I/O-bound
146+
jobs, CPU tracking can scale in while a backlog remains, and the queue step adds
147+
the task back. `maxInstances ≤ 1` wires no policy, unless `minInstances` is 0.
63148

64149
### Scaling to zero (`minInstances: 0`)
65150

66151
`minInstances: 0` is for long-running jobs that can tolerate high start-up
67152
latency; `1` or more is recommended otherwise. `finalize()` rejects it on a
68153
compute that drains no queue (nothing would start a task) or whose strategy
69154
includes `cpu`/`memory` (those policies can't see in-flight jobs, so they could
70-
scale in to zero under one). With `0` the service can scale in
71-
to zero tasks, where nothing polls the owned queues. The queue-depth policy
155+
scale in to zero under one). A compute that serves API namespaces can't use it
156+
either: nothing starts a task for an incoming request, so `apiIngress()` rejects
157+
it when the gateway routes the first namespace there, before `finalize()` runs.
158+
With `0` the service can scale in to zero tasks, where nothing polls the owned queues. The queue-depth policy
72159
can't wake it: [step adjustments](https://docs.aws.amazon.com/autoscaling/application/userguide/step-scaling-policy-overview.html)
73160
are relative to the current task count, and a backlog under `backlogPerInstance`
74161
falls in the `change: 0` step, so 0 tasks stay 0 tasks and the message is never

‎packages/bb-container-compute/src/bundle.ts‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { fileURLToPath } from 'node:url';
3232
* the asset + command override are wired, and `bootstrap.mjs` for the fetch.
3333
* ─────────────────────────────────────────────────────────────────────────────
3434
*/
35+
import { CONTAINER_SERVES_API_ENV } from '@aws-blocks/core/cdk/internal';
3536
import { buildSync } from 'esbuild';
3637

3738
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -45,6 +46,33 @@ const PKG_ROOT = join(__dirname, '..');
4546
*/
4647
const CJS_BANNER = 'const importMetaUrl = require("url").pathToFileURL(__filename).href;';
4748

49+
/**
50+
* Source of the container's parent entry (`main.js`): loads config, points the
51+
* runtime at the worker bundle it spawns per job, imports the backend (constructs
52+
* and registers every BB and its pollers), then runs the parent loop. Wrapped in an
53+
* async IIFE (CJS has no TLA).
54+
*
55+
* The backend module is also what the container serves its API from — exactly as
56+
* the Lambda handler does — but only on a compute that serves API traffic (its
57+
* CDK sets {@link CONTAINER_SERVES_API_ENV}); a compute that only runs jobs keeps
58+
* a plain health check.
59+
*
60+
* @internal Exported for testing.
61+
*/
62+
export function containerMainEntry(backendModulePath: string): string {
63+
return [
64+
"import { loadConfigToProcessEnv, runContainer } from '@aws-blocks/core';",
65+
'(async () => {',
66+
' await loadConfigToProcessEnv();',
67+
// Absolute in-image path to the co-bundled worker; dispatchJobToWorker reads this.
68+
// bootstrap.mjs writes both bundles here before exec, so the path is stable.
69+
" process.env.BLOCKS_JOB_WORKER_ENTRY = '/app/worker.js';",
70+
` const backend = await import(${JSON.stringify(backendModulePath)});`,
71+
` await runContainer(process.env.${CONTAINER_SERVES_API_ENV} === 'true' ? { backend } : {});`,
72+
'})();',
73+
].join('\n');
74+
}
75+
4876
/**
4977
* Co-bundle the app backend + `runContainer()` into a self-contained S3 asset
5078
* directory (not a Docker build context).
@@ -73,24 +101,8 @@ export function bundleContainerAsset(backendModulePath: string, outDir: string):
73101
define: { 'import.meta.url': 'importMetaUrl' },
74102
} satisfies Partial<Parameters<typeof buildSync>[0]>;
75103

76-
// ── Parent entry (main.js) ──────────────────────────────────────────────
77-
// Loads config, points the runtime at the worker bundle it will spawn per
78-
// job, imports the backend (constructs + registers every BB and its pollers),
79-
// then runs the parent loop. Wrapped in an async IIFE (CJS has no TLA).
80-
const mainEntry = [
81-
"import { loadConfigToProcessEnv, runContainer } from '@aws-blocks/core';",
82-
'(async () => {',
83-
' await loadConfigToProcessEnv();',
84-
// Absolute in-image path to the co-bundled worker; dispatchJobToWorker reads this.
85-
// bootstrap.mjs writes both bundles here before exec, so the path is stable.
86-
" process.env.BLOCKS_JOB_WORKER_ENTRY = '/app/worker.js';",
87-
` await import(${JSON.stringify(backendModulePath)});`,
88-
' await runContainer();',
89-
'})();',
90-
].join('\n');
91-
92104
buildSync({
93-
stdin: { contents: mainEntry, resolveDir: PKG_ROOT, sourcefile: '__container_main.mjs', loader: 'js' },
105+
stdin: { contents: containerMainEntry(backendModulePath), resolveDir: PKG_ROOT, sourcefile: '__container_main.mjs', loader: 'js' },
94106
outfile: join(outDir, 'main.js'),
95107
...shared,
96108
});

0 commit comments

Comments
 (0)