@ericminassian/platform-engine 0.2.0 → 0.4.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.
Files changed (98) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/ecr.d.ts +109 -0
  11. package/dist/drivers/ecr.js +303 -0
  12. package/dist/drivers/ecr.js.map +1 -0
  13. package/dist/drivers/ecs.d.ts +163 -0
  14. package/dist/drivers/ecs.js +447 -0
  15. package/dist/drivers/ecs.js.map +1 -0
  16. package/dist/drivers/events.d.ts +10 -0
  17. package/dist/drivers/events.js +13 -1
  18. package/dist/drivers/events.js.map +1 -1
  19. package/dist/drivers/index.d.ts +5 -0
  20. package/dist/drivers/index.js +5 -0
  21. package/dist/drivers/index.js.map +1 -1
  22. package/dist/drivers/kvs.d.ts +3 -0
  23. package/dist/drivers/kvs.js +14 -7
  24. package/dist/drivers/kvs.js.map +1 -1
  25. package/dist/drivers/lambda.d.ts +22 -0
  26. package/dist/drivers/lambda.js +74 -3
  27. package/dist/drivers/lambda.js.map +1 -1
  28. package/dist/drivers/request-function.d.ts +60 -0
  29. package/dist/drivers/request-function.js +167 -0
  30. package/dist/drivers/request-function.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +7 -0
  32. package/dist/drivers/s3.js +31 -0
  33. package/dist/drivers/s3.js.map +1 -1
  34. package/dist/drivers/scheduler.d.ts +24 -0
  35. package/dist/drivers/scheduler.js +60 -5
  36. package/dist/drivers/scheduler.js.map +1 -1
  37. package/dist/drivers/ses.d.ts +77 -0
  38. package/dist/drivers/ses.js +181 -0
  39. package/dist/drivers/ses.js.map +1 -0
  40. package/dist/drivers/sqs.d.ts +11 -0
  41. package/dist/drivers/sqs.js +67 -1
  42. package/dist/drivers/sqs.js.map +1 -1
  43. package/dist/drivers/ssm.d.ts +1 -0
  44. package/dist/drivers/ssm.js +23 -3
  45. package/dist/drivers/ssm.js.map +1 -1
  46. package/dist/drivers/web-function.d.ts +41 -11
  47. package/dist/drivers/web-function.js +62 -8
  48. package/dist/drivers/web-function.js.map +1 -1
  49. package/dist/emulator.js.map +1 -1
  50. package/dist/images.d.ts +104 -0
  51. package/dist/images.js +182 -0
  52. package/dist/images.js.map +1 -0
  53. package/dist/index.d.ts +132 -7
  54. package/dist/index.js +11 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/local.js +222 -7
  57. package/dist/local.js.map +1 -1
  58. package/dist/policy.d.ts +47 -4
  59. package/dist/policy.js +369 -15
  60. package/dist/policy.js.map +1 -1
  61. package/dist/services.d.ts +155 -0
  62. package/dist/services.js +464 -0
  63. package/dist/services.js.map +1 -0
  64. package/dist/stage.d.ts +44 -4
  65. package/dist/stage.js +681 -138
  66. package/dist/stage.js.map +1 -1
  67. package/dist/static.d.ts +1 -1
  68. package/dist/static.js +2 -36
  69. package/dist/static.js.map +1 -1
  70. package/dist/util.d.ts +22 -0
  71. package/dist/util.js +18 -2
  72. package/dist/util.js.map +1 -1
  73. package/package.json +20 -14
  74. package/src/clients.ts +25 -1
  75. package/src/compat.ts +34 -11
  76. package/src/drivers/appsync.ts +220 -0
  77. package/src/drivers/ecr.ts +457 -0
  78. package/src/drivers/ecs.ts +661 -0
  79. package/src/drivers/events.ts +29 -2
  80. package/src/drivers/index.ts +5 -0
  81. package/src/drivers/kvs.ts +21 -12
  82. package/src/drivers/lambda.ts +103 -2
  83. package/src/drivers/request-function.ts +295 -0
  84. package/src/drivers/s3.ts +46 -0
  85. package/src/drivers/scheduler.ts +88 -5
  86. package/src/drivers/ses.ts +267 -0
  87. package/src/drivers/sqs.ts +95 -0
  88. package/src/drivers/ssm.ts +23 -2
  89. package/src/drivers/web-function.ts +108 -17
  90. package/src/emulator.ts +3 -3
  91. package/src/images.ts +254 -0
  92. package/src/index.ts +131 -8
  93. package/src/local.ts +251 -7
  94. package/src/policy.ts +450 -26
  95. package/src/services.ts +663 -0
  96. package/src/stage.ts +839 -153
  97. package/src/static.ts +2 -37
  98. package/src/util.ts +38 -4
package/src/index.ts CHANGED
@@ -18,19 +18,25 @@ import { GetCallerIdentityCommand } from '@aws-sdk/client-sts';
18
18
  import type {
19
19
  Bindings,
20
20
  PlatformRuntimeConfig,
21
+ RealtimeEdgeEntry,
21
22
  ResolvedManifest,
22
23
  RouteRecord,
24
+ WebCompute,
23
25
  } from '@ericminassian/platform-core';
24
26
  import { createClients } from './clients.ts';
27
+ import { ensureRealtimePlatform } from './drivers/appsync.ts';
25
28
  import { putObject } from './drivers/s3.ts';
26
29
  import { ensureLocal } from './local.ts';
27
- import { deployStage, destroyStage, listStageResources, rollbackStage } from './stage.ts';
30
+ import { controlService, describeServices } from './services.ts';
31
+ import { deployStage, destroyStage, expireStorage, listStageResources, rollbackStage } from './stage.ts';
28
32
  import type { EngineContext } from './util.ts';
29
33
 
30
34
  export type { AwsClients } from './clients.ts';
31
35
  export * from './drivers/index.ts';
32
36
  export * from './emulator.ts';
37
+ export * as images from './images.ts';
33
38
  export * as policies from './policy.ts';
39
+ export { ServiceNotFoundError } from './services.ts';
34
40
  export { hostFor } from './stage.ts';
35
41
  export { cacheControlFor, contentTypeFor } from './static.ts';
36
42
  export type { EngineContext, PolicyDocument, PolicyStatement } from './util.ts';
@@ -67,14 +73,31 @@ export interface DeployStageInput {
67
73
  stage: string;
68
74
  deploymentId: string;
69
75
  platform: PlatformRuntimeConfig;
70
- /** Uploaded build artifacts (zips) in the artifacts bucket. */
71
- artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location };
76
+ /**
77
+ * Uploaded build artifacts (zips) in the artifacts bucket. `services` is
78
+ * `services.zip`: `<service>/index.mjs` (+ `.map`) for each declared service.
79
+ */
80
+ artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location; services?: S3Location };
72
81
  /**
73
82
  * `function`: create/update the Lambda Web Function + route record (AWS).
74
83
  * `external`: skip both; `plat dev` runs the server process itself because
75
84
  * the emulator does not serve Web Function endpoints yet.
76
85
  */
77
86
  webMode?: 'function' | 'external';
87
+ /**
88
+ * How the server runs with `webMode: 'function'` (core `webComputeFor`
89
+ * decides it): `instance`, a Lambda Web Function (the default), or
90
+ * `request`, a Lambda function per request behind function URLs. A deploy
91
+ * builds only this one; the stage keeps the other mode's (it costs nothing
92
+ * idle) until the manifest drops `web.server` or the stage is destroyed.
93
+ */
94
+ webCompute?: WebCompute;
95
+ /**
96
+ * `ecs`: build each service's image and run it on ECS (AWS; the default).
97
+ * `external`: skip images and ECS; `plat dev` runs services as local
98
+ * processes. Their log groups are created either way.
99
+ */
100
+ servicesMode?: 'ecs' | 'external';
78
101
  /** Use this role instead of creating the per-stage role (the control plane runs privileged). */
79
102
  roleArn?: string;
80
103
  /** Extra environment variables for web + worker (merged over manifest `env`). */
@@ -83,7 +106,7 @@ export interface DeployStageInput {
83
106
  }
84
107
 
85
108
  export interface ResourceRef {
86
- /** `role`, `table`, `queue`, `bus`, `rule`, `schedule-group`, `schedule`, `log-group`, `web-function`, `function`, `esm`, `user-pool-client`, `route`, `static` */
109
+ /** `role`, `table`, `queue`, `bus`, `rule`, `schedule-group`, `schedule`, `log-group`, `web-function`, `function` (worker, a handler's own, or the request-mode server), `esm`, `user-pool-client`, `channel-namespace`, `email-tenant`, `configuration-set`, `route`, `static`, `image`, `task-definition`, `ecs-service` */
87
110
  type: string;
88
111
  name: string;
89
112
  arn?: string;
@@ -94,19 +117,86 @@ export interface DeployStageResult {
94
117
  host: string;
95
118
  url: string;
96
119
  route?: RouteRecord;
120
+ /** How the server runs, when the stage has one. */
121
+ compute?: WebCompute;
122
+ /** The server in instance mode. */
97
123
  webFunction?: { name: string; endpointDomain: string; revisionId: string };
124
+ /** The server in request mode: the version this deploy published, behind `urlDomain`. */
125
+ requestFunction?: { name: string; urlDomain: string; version: string };
98
126
  workerFunction?: { name: string; arn: string };
127
+ /** Services the deploy rolled out (`servicesMode: 'ecs'`). */
128
+ services?: DeployedService[];
99
129
  resources: ResourceRef[];
100
130
  }
101
131
 
132
+ export interface DeployedService {
133
+ /** The key in plat.config.ts (`ais`). */
134
+ name: string;
135
+ /** `<repositoryUri>@sha256:…`. */
136
+ image: string;
137
+ taskDefinitionArn: string;
138
+ /** 1 running, 0 when a preview doesn't run it. */
139
+ desired: number;
140
+ /** A preview's stop schedule. */
141
+ stopsAt?: string;
142
+ }
143
+
102
144
  export interface RollbackStageInput {
103
145
  app: string;
104
146
  stage: string;
105
147
  platform: PlatformRuntimeConfig;
106
- /** Route record of the deployment to go back to (its static prefix + endpoint). */
148
+ /**
149
+ * Route record of the deployment to go back to, in its compute mode. The
150
+ * engine picks the endpoint or function URL (`o`) itself.
151
+ */
107
152
  route: RouteRecord;
108
- /** Web Function revision to route 100% of traffic to. */
153
+ /** That deployment's Web Function revision (instance mode). */
109
154
  revisionId?: string;
155
+ /** That deployment's function version (request mode). */
156
+ version?: string;
157
+ /**
158
+ * Services that deployment declared. Each one the stage still runs is
159
+ * pointed back at that deployment's build; the rollback is refused if a
160
+ * build was cleaned up since.
161
+ */
162
+ services?: readonly string[];
163
+ }
164
+
165
+ export interface StageServicesInput {
166
+ app: string;
167
+ stage: string;
168
+ platform: PlatformRuntimeConfig;
169
+ }
170
+
171
+ /** One service as ECS reports it right now. */
172
+ export interface ServiceRuntimeState {
173
+ name: string;
174
+ desired: number;
175
+ running: number;
176
+ pending: number;
177
+ /** The newest ECS deployment's rollout (`COMPLETED`, `IN_PROGRESS`, `FAILED`). */
178
+ rollout?: 'completed' | 'in_progress' | 'failed';
179
+ /** Deployment whose build the newest ECS deployment runs (its task definition's tag). */
180
+ deploymentId?: string;
181
+ /** When the current task started. */
182
+ startedAt?: string;
183
+ /** When a stop schedule scales it to zero. */
184
+ stopsAt?: string;
185
+ /** The task that stopped most recently. */
186
+ lastStop?: { at: string; reason: string; exitCode?: number };
187
+ /** Recent ECS service events, newest first (at most 10). */
188
+ events: Array<{ at: string; message: string }>;
189
+ }
190
+
191
+ export interface ControlServiceInput extends StageServicesInput {
192
+ name: string;
193
+ /**
194
+ * `start`: desired 1, stopping again after `minutes` when given (replacing
195
+ * any stop schedule). `stop`: desired 0 (and no stop schedule). `restart`:
196
+ * a fresh task on the same build.
197
+ */
198
+ action: 'start' | 'stop' | 'restart';
199
+ minutes?: number;
110
200
  }
111
201
 
112
202
  export interface DestroyStageInput {
@@ -117,17 +207,45 @@ export interface DestroyStageInput {
117
207
  keepData?: boolean;
118
208
  }
119
209
 
210
+ export interface ExpireStorageInput {
211
+ app: string;
212
+ stage: string;
213
+ platform: PlatformRuntimeConfig;
214
+ /** The live deployment's: its stores' `expireAfterDays` and where their files are. */
215
+ manifest: Pick<ResolvedManifest, 'storage' | 'storageOptions'>;
216
+ /** Default: the current time. */
217
+ now?: Date;
218
+ }
219
+
120
220
  export interface Engine {
121
221
  readonly region: string;
122
222
  readonly target: 'aws' | 'emulator';
123
223
  accountId(): Promise<string>;
124
224
  deployStage(input: DeployStageInput): Promise<DeployStageResult>;
125
- rollbackStage(input: RollbackStageInput): Promise<void>;
225
+ /** Returns the route record it wrote. */
226
+ rollbackStage(input: RollbackStageInput): Promise<RouteRecord>;
126
227
  destroyStage(input: DestroyStageInput): Promise<void>;
228
+ /**
229
+ * Delete the files of the stage's stores that set `expireAfterDays` and
230
+ * weren't written for that many days. Answers how many, by store. The
231
+ * control plane runs it daily for every live stage.
232
+ */
233
+ expireStorage(input: ExpireStorageInput): Promise<Record<string, number>>;
127
234
  /** Everything the engine owns for a stage (found by name + tags). */
128
235
  listStageResources(app: string, stage: string): Promise<ResourceRef[]>;
129
236
  /** Upload a local file/buffer into the artifacts bucket (used by `plat dev`). */
130
237
  putArtifact(platform: PlatformRuntimeConfig, key: string, body: Uint8Array): Promise<S3Location>;
238
+ /**
239
+ * Keep realtime usable platform-wide: the public subscribe key exists and is far from expiry,
240
+ * and the router's realtime entry is current (written only when the platform has a route
241
+ * store). Returns that entry, or undefined when the platform has no realtime API. The control
242
+ * plane runs it nightly; `plat dev` serves the entry from its local router.
243
+ */
244
+ ensureRealtimePlatform(platform: PlatformRuntimeConfig): Promise<RealtimeEdgeEntry | undefined>;
245
+ /** The stage's long-running services as ECS runs them now (none without container compute). */
246
+ describeServices(input: StageServicesInput): Promise<ServiceRuntimeState[]>;
247
+ /** Start, stop or restart one of the stage's services. */
248
+ controlService(input: ControlServiceInput): Promise<{ desired: number; stopsAt?: string }>;
131
249
  }
132
250
 
133
251
  export function createEngine(opts: EngineOptions): Engine {
@@ -139,8 +257,12 @@ export function createEngine(opts: EngineOptions): Engine {
139
257
  deployStage: (input) => deployStage(ctx, input),
140
258
  rollbackStage: (input) => rollbackStage(ctx, input),
141
259
  destroyStage: (input) => destroyStage(ctx, input),
260
+ expireStorage: (input) => expireStorage(ctx, input),
142
261
  listStageResources: (app, stage) => listStageResources(ctx, app, stage),
143
262
  putArtifact: (platform, key, body) => putObject(ctx, { bucket: platform.artifactsBucket, key, body }),
263
+ ensureRealtimePlatform: (platform) => ensureRealtimePlatform(ctx, platform),
264
+ describeServices: (input) => describeServices(ctx, input),
265
+ controlService: (input) => controlService(ctx, input),
144
266
  };
145
267
  contexts.set(engine, ctx);
146
268
  return engine;
@@ -173,7 +295,8 @@ function createContext(opts: EngineOptions): EngineContext {
173
295
 
174
296
  /**
175
297
  * Shared resources `plat dev` needs inside a fresh emulator (buckets, tables,
176
- * user pool) and the matching runtime config (`target: 'emulator'`).
298
+ * user pool, realtime API, mail domain) and the matching runtime config
299
+ * (`target: 'emulator'`).
177
300
  */
178
301
  export async function ensureLocalPlatform(
179
302
  engine: Engine,
package/src/local.ts CHANGED
@@ -1,8 +1,26 @@
1
- import { type PlatformRuntimeConfig, platformNames } from '@ericminassian/platform-core';
1
+ import { CreateApiCommand } from '@aws-sdk/client-appsync';
2
+ import { CreateFunctionCommand, GetFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
3
+ import {
4
+ emailDomain,
5
+ type ContainersRuntimeConfig,
6
+ NODE_RUNTIME,
7
+ type PlatformRuntimeConfig,
8
+ platformNames,
9
+ type RealtimeRuntimeConfig,
10
+ } from '@ericminassian/platform-core';
11
+ import { Hash } from '@smithy/hash-node';
12
+ import { SignatureV4 } from '@smithy/signature-v4';
13
+ import { strToU8, zipSync } from 'fflate';
14
+ import { findEventApi } from './drivers/appsync.ts';
2
15
  import { ensureUserPool } from './drivers/cognito.ts';
3
16
  import { ensureTable } from './drivers/dynamodb.ts';
17
+ import { ensureRepository } from './drivers/ecr.ts';
18
+ import { ensureCluster } from './drivers/ecs.ts';
19
+ import { ensureRole } from './drivers/iam.ts';
4
20
  import { ensureBucket } from './drivers/s3.ts';
5
- import { type EngineContext, platformTags } from './util.ts';
21
+ import { ensureEmailIdentity } from './drivers/ses.ts';
22
+ import { containerExecutionPolicy, containerSchedulerPolicy, serviceTrustPolicy } from './policy.ts';
23
+ import { type EngineContext, ignoreNotFound, platformTags, sendRaw, waitFor } from './util.ts';
6
24
 
7
25
  /**
8
26
  * Inside a fresh AWS Emulator, create the shared resources a stage deploy
@@ -20,6 +38,7 @@ export async function ensureLocal(
20
38
  const artifactsBucket = platformNames.artifactsBucket(accountId, region);
21
39
  const sitesBucket = platformNames.sitesBucket(accountId, region);
22
40
  const storageBucket = platformNames.storageBucket(accountId, region);
41
+ const domain = opts.domain ?? 'localhost';
23
42
 
24
43
  await ensureBucket(ctx, { name: artifactsBucket, versioned: true, tags });
25
44
  await ensureBucket(ctx, { name: sitesBucket, tags });
@@ -28,10 +47,7 @@ export async function ensureLocal(
28
47
  tags,
29
48
  cors: [
30
49
  {
31
- AllowedOrigins: [
32
- `http://*.${opts.domain ?? 'localhost'}:${opts.port}`,
33
- `http://localhost:${opts.port}`,
34
- ],
50
+ AllowedOrigins: [`http://*.${domain}:${opts.port}`, `http://localhost:${opts.port}`],
35
51
  AllowedMethods: ['GET', 'PUT', 'POST', 'HEAD'],
36
52
  AllowedHeaders: ['*'],
37
53
  ExposeHeaders: ['ETag'],
@@ -54,13 +70,19 @@ export async function ensureLocal(
54
70
  tags,
55
71
  });
56
72
  const userPoolId = await ensureUserPool(ctx, { name: platformNames.userPool, tags });
73
+ const realtime = await ensureLocalRealtime(ctx, tags);
74
+ // Stages get real tenants and configuration sets in the emulator, so the domain they're
75
+ // associated with must exist. It never verifies and nothing is sent: local stages hand
76
+ // their mail to the CLI (`email.mode: 'local'`).
77
+ const mail = await ensureEmailIdentity(ctx, { domain: emailDomain(domain), tags });
78
+ const containers = await ensureLocalContainers(ctx, tags);
57
79
 
58
80
  return {
59
81
  v: 1,
60
82
  target: 'emulator',
61
83
  accountId,
62
84
  region,
63
- domain: opts.domain ?? 'localhost',
85
+ domain,
64
86
  publicScheme: 'http',
65
87
  publicPort: opts.port,
66
88
  artifactsBucket,
@@ -71,5 +93,227 @@ export async function ensureLocal(
71
93
  userPoolId,
72
94
  loginUrl: `http://localhost:${opts.port}`,
73
95
  jwksBaseUrl: opts.jwksBaseUrl,
96
+ realtime,
97
+ email: { domain: mail.domain, identityArn: mail.arn },
98
+ containers,
74
99
  };
75
100
  }
101
+
102
+ /**
103
+ * Container compute inside the emulator, like the foundation's: a Fargate
104
+ * cluster, the image repository, public subnets with a security group, and
105
+ * the execution and scheduler roles. The emulator's ECS runs tasks
106
+ * (simulated: it pulls nothing and runs no code) only when their subnet
107
+ * routes to an internet gateway, which its default VPC lacks; this adds one.
108
+ */
109
+ async function ensureLocalContainers(
110
+ ctx: EngineContext,
111
+ tags: Record<string, string>,
112
+ ): Promise<ContainersRuntimeConfig> {
113
+ const accountId = await ctx.accountId();
114
+ const cluster = platformNames.containerCluster;
115
+ await ensureCluster(ctx, { name: cluster, tags });
116
+ const repository = await ensureRepository(ctx, { name: platformNames.containerRepository, tags });
117
+ const execution = await ensureRole(ctx, {
118
+ name: platformNames.containerExecutionRole,
119
+ trust: serviceTrustPolicy('ecs-tasks.amazonaws.com'),
120
+ description: 'plat dev: pulls platform container images and writes their logs',
121
+ inlinePolicies: {
122
+ execution: containerExecutionPolicy({ region: ctx.region, accountId, repository: repository.name }),
123
+ },
124
+ tags,
125
+ });
126
+ const scheduler = await ensureRole(ctx, {
127
+ name: platformNames.containerSchedulerRole,
128
+ trust: serviceTrustPolicy('scheduler.amazonaws.com'),
129
+ description: "plat dev: scales stages' containers (preview stop schedules)",
130
+ inlinePolicies: { scale: containerSchedulerPolicy({ region: ctx.region, accountId, cluster }) },
131
+ tags,
132
+ });
133
+ const network = await ensureLocalNetwork(ctx);
134
+ return {
135
+ cluster,
136
+ subnets: network.subnets,
137
+ securityGroups: [network.securityGroup],
138
+ repository: repository.name,
139
+ // The emulator's CreateRepository answers with its own host and port, but its ECS only
140
+ // resolves images named the way AWS names them.
141
+ repositoryUri: `${repository.registryId}.dkr.ecr.${ctx.region}.amazonaws.com/${repository.name}`,
142
+ executionRoleArn: execution.arn,
143
+ schedulerRoleArn: scheduler.arn,
144
+ };
145
+ }
146
+
147
+ /**
148
+ * The default VPC's subnets, made public (an internet gateway and a default
149
+ * route, which AWS's default VPCs come with), and the containers' security
150
+ * group in it.
151
+ */
152
+ async function ensureLocalNetwork(ctx: EngineContext): Promise<{ subnets: string[]; securityGroup: string }> {
153
+ const vpcs = await ec2(ctx, 'DescribeVpcs', { 'Filter.1.Name': 'is-default', 'Filter.1.Value.1': 'true' });
154
+ const vpcId = xmlValues(vpcs, 'vpcId')[0];
155
+ if (!vpcId) throw new Error('the AWS Emulator has no default VPC');
156
+ const inVpc = { 'Filter.1.Name': 'vpc-id', 'Filter.1.Value.1': vpcId };
157
+ const subnets = [...new Set(xmlValues(await ec2(ctx, 'DescribeSubnets', inVpc), 'subnetId'))].toSorted();
158
+ if (!subnets.length) throw new Error(`the AWS Emulator's default VPC ${vpcId} has no subnets`);
159
+
160
+ const gateways = await ec2(ctx, 'DescribeInternetGateways', {
161
+ 'Filter.1.Name': 'attachment.vpc-id',
162
+ 'Filter.1.Value.1': vpcId,
163
+ });
164
+ let gateway = xmlValues(gateways, 'internetGatewayId')[0];
165
+ if (!gateway) {
166
+ gateway = xmlValues(await ec2(ctx, 'CreateInternetGateway', {}), 'internetGatewayId')[0]!;
167
+ await ec2(ctx, 'AttachInternetGateway', { InternetGatewayId: gateway, VpcId: vpcId });
168
+ }
169
+ const tables = await ec2(ctx, 'DescribeRouteTables', {
170
+ ...inVpc,
171
+ 'Filter.2.Name': 'association.main',
172
+ 'Filter.2.Value.1': 'true',
173
+ });
174
+ const table = xmlValues(tables, 'routeTableId')[0];
175
+ if (table && !xmlValues(tables, 'destinationCidrBlock').includes('0.0.0.0/0')) {
176
+ await ec2(ctx, 'CreateRoute', {
177
+ RouteTableId: table,
178
+ DestinationCidrBlock: '0.0.0.0/0',
179
+ GatewayId: gateway,
180
+ });
181
+ }
182
+
183
+ const groups = await ec2(ctx, 'DescribeSecurityGroups', {
184
+ ...inVpc,
185
+ 'Filter.2.Name': 'group-name',
186
+ 'Filter.2.Value.1': platformNames.containerNetwork,
187
+ });
188
+ const securityGroup =
189
+ xmlValues(groups, 'groupId')[0] ??
190
+ xmlValues(
191
+ await ec2(ctx, 'CreateSecurityGroup', {
192
+ GroupName: platformNames.containerNetwork,
193
+ GroupDescription: 'Platform containers: no inbound traffic, all outbound',
194
+ VpcId: vpcId,
195
+ }),
196
+ 'groupId',
197
+ )[0]!;
198
+ return { subnets, securityGroup };
199
+ }
200
+
201
+ /**
202
+ * One EC2 Query API call against the emulator, signed with the SDK's SigV4
203
+ * signer and sent through an SDK client's endpoint, credentials and HTTP
204
+ * handler. These few VPC calls are the engine's only EC2 calls, which
205
+ * doesn't warrant the SDK's EC2 client, one of its largest.
206
+ */
207
+ async function ec2(ctx: EngineContext, action: string, params: Record<string, string>): Promise<string> {
208
+ const client = ctx.clients.sts;
209
+ const endpoint = await client.config.endpoint!();
210
+ const body = new URLSearchParams({ Action: action, Version: '2016-11-15', ...params }).toString();
211
+ const signer = new SignatureV4({
212
+ service: 'ec2',
213
+ region: ctx.region,
214
+ credentials: client.config.credentials,
215
+ sha256: Hash.bind(null, 'sha256'),
216
+ });
217
+ const request = await signer.sign({
218
+ method: 'POST',
219
+ protocol: endpoint.protocol,
220
+ hostname: endpoint.hostname,
221
+ ...(endpoint.port ? { port: endpoint.port } : {}),
222
+ path: '/',
223
+ query: {},
224
+ headers: {
225
+ 'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
226
+ host: endpoint.port ? `${endpoint.hostname}:${endpoint.port}` : endpoint.hostname,
227
+ 'content-length': String(Buffer.byteLength(body)),
228
+ },
229
+ body,
230
+ });
231
+ const res = await sendRaw(client, request as Parameters<typeof sendRaw>[1]);
232
+ const xml = new TextDecoder().decode(res.body);
233
+ if (res.statusCode !== 200) {
234
+ const [code] = xmlValues(xml, 'Code');
235
+ const [message] = xmlValues(xml, 'Message');
236
+ throw new Error(`EC2 ${action} failed in the AWS Emulator: ${code ?? res.statusCode} ${message ?? xml}`);
237
+ }
238
+ return xml;
239
+ }
240
+
241
+ function xmlValues(xml: string, element: string): string[] {
242
+ return [...xml.matchAll(new RegExp(`<${element}>([^<]*)</${element}>`, 'g'))].map((m) => m[1]!);
243
+ }
244
+
245
+ /**
246
+ * The emulator never invokes an Event API's Lambda authorizer (it accepts any
247
+ * token), but the API still needs one to accept the AWS_LAMBDA mode signed-in
248
+ * namespaces use. So this one only satisfies the API's configuration.
249
+ */
250
+ const STUB_AUTHORIZER = `// plat dev: the AWS Emulator doesn't invoke Event API authorizers, so subscribe tokens
251
+ // aren't checked locally. The platform's real authorizer runs in AWS.
252
+ export const handler = async () => ({ isAuthorized: true });
253
+ `;
254
+
255
+ /**
256
+ * The platform's Event API inside the emulator, configured like the
257
+ * foundation's (same auth providers and defaults). The emulator serves its
258
+ * HTTP and realtime endpoints on local ports (`dns` is `127.0.0.1:<port>`).
259
+ */
260
+ async function ensureLocalRealtime(
261
+ ctx: EngineContext,
262
+ tags: Record<string, string>,
263
+ ): Promise<RealtimeRuntimeConfig> {
264
+ let api = await findEventApi(ctx, platformNames.realtimeApi);
265
+ if (!api) {
266
+ const authorizerArn = await ensureStubAuthorizer(ctx, tags);
267
+ const res = await ctx.clients.appsync.send(
268
+ new CreateApiCommand({
269
+ name: platformNames.realtimeApi,
270
+ tags,
271
+ eventConfig: {
272
+ authProviders: [
273
+ { authType: 'API_KEY' },
274
+ { authType: 'AWS_IAM' },
275
+ { authType: 'AWS_LAMBDA', lambdaAuthorizerConfig: { authorizerUri: authorizerArn } },
276
+ ],
277
+ connectionAuthModes: [{ authType: 'API_KEY' }, { authType: 'AWS_LAMBDA' }],
278
+ defaultPublishAuthModes: [{ authType: 'AWS_IAM' }],
279
+ defaultSubscribeAuthModes: [{ authType: 'AWS_LAMBDA' }],
280
+ },
281
+ }),
282
+ );
283
+ api = res.api;
284
+ }
285
+ const httpDomain = api?.dns?.HTTP;
286
+ const realtimeDomain = api?.dns?.REALTIME;
287
+ if (!api?.apiId || !httpDomain || !realtimeDomain)
288
+ throw new Error('the AWS Emulator returned an Event API without endpoints');
289
+ return { apiId: api.apiId, httpDomain, realtimeDomain };
290
+ }
291
+
292
+ async function ensureStubAuthorizer(ctx: EngineContext, tags: Record<string, string>): Promise<string> {
293
+ const name = platformNames.realtimeAuthorizer;
294
+ const existing = await ignoreNotFound(
295
+ ctx.clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: name })),
296
+ );
297
+ if (existing?.FunctionArn) return existing.FunctionArn;
298
+ const role = await ensureRole(ctx, {
299
+ name,
300
+ trust: serviceTrustPolicy('lambda.amazonaws.com'),
301
+ description: 'plat dev stub realtime authorizer',
302
+ tags,
303
+ });
304
+ const res = await ctx.clients.lambda.send(
305
+ new CreateFunctionCommand({
306
+ FunctionName: name,
307
+ Role: role.arn,
308
+ Runtime: NODE_RUNTIME,
309
+ Handler: 'index.handler',
310
+ Code: { ZipFile: zipSync({ 'index.mjs': strToU8(STUB_AUTHORIZER) }) },
311
+ Tags: tags,
312
+ }),
313
+ );
314
+ await waitFor(`${name} to become active`, async () => {
315
+ const c = await ctx.clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: name }));
316
+ return c.State === 'Active';
317
+ });
318
+ return res.FunctionArn!;
319
+ }