@ericminassian/platform-engine 0.4.0 → 0.5.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/dist/clients.d.ts +0 -4
- package/dist/clients.js +1 -14
- package/dist/clients.js.map +1 -1
- package/dist/compat.d.ts +9 -21
- package/dist/compat.js +6 -26
- package/dist/compat.js.map +1 -1
- package/dist/drivers/cognito.d.ts +27 -3
- package/dist/drivers/cognito.js +76 -24
- package/dist/drivers/cognito.js.map +1 -1
- package/dist/drivers/index.d.ts +0 -2
- package/dist/drivers/index.js +0 -2
- package/dist/drivers/index.js.map +1 -1
- package/dist/drivers/logs.d.ts +11 -0
- package/dist/drivers/logs.js +15 -1
- package/dist/drivers/logs.js.map +1 -1
- package/dist/drivers/scheduler.d.ts +0 -21
- package/dist/drivers/scheduler.js +0 -43
- package/dist/drivers/scheduler.js.map +1 -1
- package/dist/index.d.ts +2 -81
- package/dist/index.js +0 -5
- package/dist/index.js.map +1 -1
- package/dist/local.js +2 -140
- package/dist/local.js.map +1 -1
- package/dist/login-branding.d.ts +27 -0
- package/dist/login-branding.js +329 -0
- package/dist/login-branding.js.map +1 -0
- package/dist/login-glyphs.d.ts +12 -0
- package/dist/login-glyphs.js +903 -0
- package/dist/login-glyphs.js.map +1 -0
- package/dist/policy.d.ts +2 -26
- package/dist/policy.js +2 -107
- package/dist/policy.js.map +1 -1
- package/dist/stage.d.ts +1 -2
- package/dist/stage.js +16 -87
- package/dist/stage.js.map +1 -1
- package/dist/util.d.ts +0 -22
- package/dist/util.js +0 -16
- package/dist/util.js.map +1 -1
- package/package.json +10 -7
- package/src/clients.ts +1 -15
- package/src/compat.ts +9 -32
- package/src/drivers/cognito.ts +98 -23
- package/src/drivers/index.ts +0 -2
- package/src/drivers/logs.ts +21 -0
- package/src/drivers/scheduler.ts +0 -69
- package/src/index.ts +3 -78
- package/src/local.ts +2 -152
- package/src/login-branding.ts +407 -0
- package/src/login-glyphs.ts +911 -0
- package/src/policy.ts +2 -132
- package/src/stage.ts +16 -102
- package/src/util.ts +0 -34
- package/dist/drivers/ecr.d.ts +0 -109
- package/dist/drivers/ecr.js +0 -303
- package/dist/drivers/ecr.js.map +0 -1
- package/dist/drivers/ecs.d.ts +0 -163
- package/dist/drivers/ecs.js +0 -447
- package/dist/drivers/ecs.js.map +0 -1
- package/dist/images.d.ts +0 -104
- package/dist/images.js +0 -182
- package/dist/images.js.map +0 -1
- package/dist/services.d.ts +0 -155
- package/dist/services.js +0 -464
- package/dist/services.js.map +0 -1
- package/src/drivers/ecr.ts +0 -457
- package/src/drivers/ecs.ts +0 -661
- package/src/images.ts +0 -254
- package/src/services.ts +0 -663
package/src/drivers/logs.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
DescribeLogGroupsCommand,
|
|
5
5
|
PutAccountPolicyCommand,
|
|
6
6
|
PutRetentionPolicyCommand,
|
|
7
|
+
PutSubscriptionFilterCommand,
|
|
7
8
|
} from '@aws-sdk/client-cloudwatch-logs';
|
|
8
9
|
import { type EngineContext, errorName, ignoreNotFound } from '../util.ts';
|
|
9
10
|
|
|
@@ -79,3 +80,23 @@ export async function ensureAccountSubscriptionFilter(
|
|
|
79
80
|
);
|
|
80
81
|
ctx.log('info', 'put account subscription filter', `account-policy ${spec.name}`);
|
|
81
82
|
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A subscription filter on one log group, for lines the account-level one
|
|
86
|
+
* can't match (it takes a single pattern): every line of `logGroup` matching
|
|
87
|
+
* `filterPattern` (empty: all of them) streams to `destinationArn`.
|
|
88
|
+
*/
|
|
89
|
+
export async function ensureSubscriptionFilter(
|
|
90
|
+
ctx: EngineContext,
|
|
91
|
+
spec: { name: string; logGroup: string; destinationArn: string; filterPattern: string },
|
|
92
|
+
): Promise<void> {
|
|
93
|
+
await ctx.clients.logs.send(
|
|
94
|
+
new PutSubscriptionFilterCommand({
|
|
95
|
+
filterName: spec.name,
|
|
96
|
+
logGroupName: spec.logGroup,
|
|
97
|
+
destinationArn: spec.destinationArn,
|
|
98
|
+
filterPattern: spec.filterPattern,
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
ctx.log('info', 'put subscription filter', `log-group ${spec.logGroup}`);
|
|
102
|
+
}
|
package/src/drivers/scheduler.ts
CHANGED
|
@@ -8,11 +8,8 @@ import {
|
|
|
8
8
|
ListSchedulesCommand,
|
|
9
9
|
UpdateScheduleCommand,
|
|
10
10
|
} from '@aws-sdk/client-scheduler';
|
|
11
|
-
import { atExpression } from '@ericminassian/platform-core';
|
|
12
11
|
import { type EngineContext, ignoreNotFound, retry, tagList, waitFor } from '../util.ts';
|
|
13
12
|
|
|
14
|
-
export { atExpression };
|
|
15
|
-
|
|
16
13
|
export async function ensureScheduleGroup(
|
|
17
14
|
ctx: EngineContext,
|
|
18
15
|
spec: { name: string; tags?: Record<string, string> },
|
|
@@ -75,63 +72,6 @@ export async function ensureSchedule(ctx: EngineContext, spec: ScheduleSpec): Pr
|
|
|
75
72
|
if (!existing) ctx.log('info', 'created schedule', `schedule ${spec.group}/${spec.name}`);
|
|
76
73
|
}
|
|
77
74
|
|
|
78
|
-
export interface OneShotScheduleSpec {
|
|
79
|
-
group: string;
|
|
80
|
-
name: string;
|
|
81
|
-
/** When it fires (to the second, UTC). The schedule deletes itself afterwards. */
|
|
82
|
-
at: Date;
|
|
83
|
-
target: { arn: string; roleArn: string; input: string };
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Inverse of {@link atExpression}. */
|
|
87
|
-
export function parseAtExpression(expression: string | undefined): Date | undefined {
|
|
88
|
-
const m = /^at\((\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\)$/.exec(expression ?? '');
|
|
89
|
-
return m ? new Date(`${m[1]}Z`) : undefined;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Create or move a schedule that fires once, then deletes itself. */
|
|
93
|
-
export async function ensureOneShotSchedule(ctx: EngineContext, spec: OneShotScheduleSpec): Promise<void> {
|
|
94
|
-
const sch = ctx.clients.scheduler;
|
|
95
|
-
const definition = {
|
|
96
|
-
Name: spec.name,
|
|
97
|
-
GroupName: spec.group,
|
|
98
|
-
ScheduleExpression: atExpression(spec.at),
|
|
99
|
-
ScheduleExpressionTimezone: 'UTC',
|
|
100
|
-
ActionAfterCompletion: 'DELETE' as const,
|
|
101
|
-
FlexibleTimeWindow: { Mode: 'OFF' as const },
|
|
102
|
-
State: 'ENABLED' as const,
|
|
103
|
-
Target: {
|
|
104
|
-
Arn: spec.target.arn,
|
|
105
|
-
RoleArn: spec.target.roleArn,
|
|
106
|
-
Input: spec.target.input,
|
|
107
|
-
RetryPolicy: { MaximumRetryAttempts: 5, MaximumEventAgeInSeconds: 3600 },
|
|
108
|
-
},
|
|
109
|
-
};
|
|
110
|
-
const existing = await ignoreNotFound(
|
|
111
|
-
sch.send(new GetScheduleCommand({ Name: spec.name, GroupName: spec.group })),
|
|
112
|
-
);
|
|
113
|
-
await retry(
|
|
114
|
-
() =>
|
|
115
|
-
existing
|
|
116
|
-
? sch.send(new UpdateScheduleCommand(definition))
|
|
117
|
-
: sch.send(new CreateScheduleCommand(definition)),
|
|
118
|
-
{ when: (e) => /assume the role|execution role/i.test((e as Error).message), attempts: 12 },
|
|
119
|
-
);
|
|
120
|
-
ctx.log('info', `fires at ${spec.at.toISOString()}`, `schedule ${spec.group}/${spec.name}`);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/** When a one-shot schedule fires, or undefined when there is none (or it isn't one-shot). */
|
|
124
|
-
export async function getOneShotScheduleTime(
|
|
125
|
-
ctx: EngineContext,
|
|
126
|
-
group: string,
|
|
127
|
-
name: string,
|
|
128
|
-
): Promise<Date | undefined> {
|
|
129
|
-
const s = await ignoreNotFound(
|
|
130
|
-
ctx.clients.scheduler.send(new GetScheduleCommand({ Name: name, GroupName: group })),
|
|
131
|
-
);
|
|
132
|
-
return parseAtExpression(s?.ScheduleExpression);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
75
|
export async function listSchedules(ctx: EngineContext, group: string): Promise<string[]> {
|
|
136
76
|
const out: string[] = [];
|
|
137
77
|
let NextToken: string | undefined;
|
|
@@ -162,12 +102,3 @@ export async function deleteScheduleGroup(ctx: EngineContext, group: string): Pr
|
|
|
162
102
|
if (!exists || exists.State === 'DELETING') return;
|
|
163
103
|
await ignoreNotFound(ctx.clients.scheduler.send(new DeleteScheduleGroupCommand({ Name: group })));
|
|
164
104
|
}
|
|
165
|
-
|
|
166
|
-
/** Delete the group if no schedule is left in it. */
|
|
167
|
-
export async function deleteScheduleGroupIfEmpty(ctx: EngineContext, group: string): Promise<void> {
|
|
168
|
-
const exists = await ignoreNotFound(
|
|
169
|
-
ctx.clients.scheduler.send(new GetScheduleGroupCommand({ Name: group })),
|
|
170
|
-
);
|
|
171
|
-
if (!exists || exists.State === 'DELETING' || (await listSchedules(ctx, group)).length) return;
|
|
172
|
-
await ignoreNotFound(ctx.clients.scheduler.send(new DeleteScheduleGroupCommand({ Name: group })));
|
|
173
|
-
}
|
package/src/index.ts
CHANGED
|
@@ -27,16 +27,13 @@ import { createClients } from './clients.ts';
|
|
|
27
27
|
import { ensureRealtimePlatform } from './drivers/appsync.ts';
|
|
28
28
|
import { putObject } from './drivers/s3.ts';
|
|
29
29
|
import { ensureLocal } from './local.ts';
|
|
30
|
-
import { controlService, describeServices } from './services.ts';
|
|
31
30
|
import { deployStage, destroyStage, expireStorage, listStageResources, rollbackStage } from './stage.ts';
|
|
32
31
|
import type { EngineContext } from './util.ts';
|
|
33
32
|
|
|
34
33
|
export type { AwsClients } from './clients.ts';
|
|
35
34
|
export * from './drivers/index.ts';
|
|
36
35
|
export * from './emulator.ts';
|
|
37
|
-
export * as images from './images.ts';
|
|
38
36
|
export * as policies from './policy.ts';
|
|
39
|
-
export { ServiceNotFoundError } from './services.ts';
|
|
40
37
|
export { hostFor } from './stage.ts';
|
|
41
38
|
export { cacheControlFor, contentTypeFor } from './static.ts';
|
|
42
39
|
export type { EngineContext, PolicyDocument, PolicyStatement } from './util.ts';
|
|
@@ -73,11 +70,8 @@ export interface DeployStageInput {
|
|
|
73
70
|
stage: string;
|
|
74
71
|
deploymentId: string;
|
|
75
72
|
platform: PlatformRuntimeConfig;
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
* `services.zip`: `<service>/index.mjs` (+ `.map`) for each declared service.
|
|
79
|
-
*/
|
|
80
|
-
artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location; services?: S3Location };
|
|
73
|
+
/** Uploaded build artifacts (zips) in the artifacts bucket. */
|
|
74
|
+
artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location };
|
|
81
75
|
/**
|
|
82
76
|
* `function`: create/update the Lambda Web Function + route record (AWS).
|
|
83
77
|
* `external`: skip both; `plat dev` runs the server process itself because
|
|
@@ -92,12 +86,6 @@ export interface DeployStageInput {
|
|
|
92
86
|
* idle) until the manifest drops `web.server` or the stage is destroyed.
|
|
93
87
|
*/
|
|
94
88
|
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';
|
|
101
89
|
/** Use this role instead of creating the per-stage role (the control plane runs privileged). */
|
|
102
90
|
roleArn?: string;
|
|
103
91
|
/** Extra environment variables for web + worker (merged over manifest `env`). */
|
|
@@ -106,7 +94,7 @@ export interface DeployStageInput {
|
|
|
106
94
|
}
|
|
107
95
|
|
|
108
96
|
export interface ResourceRef {
|
|
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
|
|
97
|
+
/** `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` */
|
|
110
98
|
type: string;
|
|
111
99
|
name: string;
|
|
112
100
|
arn?: string;
|
|
@@ -124,23 +112,9 @@ export interface DeployStageResult {
|
|
|
124
112
|
/** The server in request mode: the version this deploy published, behind `urlDomain`. */
|
|
125
113
|
requestFunction?: { name: string; urlDomain: string; version: string };
|
|
126
114
|
workerFunction?: { name: string; arn: string };
|
|
127
|
-
/** Services the deploy rolled out (`servicesMode: 'ecs'`). */
|
|
128
|
-
services?: DeployedService[];
|
|
129
115
|
resources: ResourceRef[];
|
|
130
116
|
}
|
|
131
117
|
|
|
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
|
-
|
|
144
118
|
export interface RollbackStageInput {
|
|
145
119
|
app: string;
|
|
146
120
|
stage: string;
|
|
@@ -154,49 +128,6 @@ export interface RollbackStageInput {
|
|
|
154
128
|
revisionId?: string;
|
|
155
129
|
/** That deployment's function version (request mode). */
|
|
156
130
|
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;
|
|
200
131
|
}
|
|
201
132
|
|
|
202
133
|
export interface DestroyStageInput {
|
|
@@ -242,10 +173,6 @@ export interface Engine {
|
|
|
242
173
|
* plane runs it nightly; `plat dev` serves the entry from its local router.
|
|
243
174
|
*/
|
|
244
175
|
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 }>;
|
|
249
176
|
}
|
|
250
177
|
|
|
251
178
|
export function createEngine(opts: EngineOptions): Engine {
|
|
@@ -261,8 +188,6 @@ export function createEngine(opts: EngineOptions): Engine {
|
|
|
261
188
|
listStageResources: (app, stage) => listStageResources(ctx, app, stage),
|
|
262
189
|
putArtifact: (platform, key, body) => putObject(ctx, { bucket: platform.artifactsBucket, key, body }),
|
|
263
190
|
ensureRealtimePlatform: (platform) => ensureRealtimePlatform(ctx, platform),
|
|
264
|
-
describeServices: (input) => describeServices(ctx, input),
|
|
265
|
-
controlService: (input) => controlService(ctx, input),
|
|
266
191
|
};
|
|
267
192
|
contexts.set(engine, ctx);
|
|
268
193
|
return engine;
|
package/src/local.ts
CHANGED
|
@@ -2,25 +2,20 @@ import { CreateApiCommand } from '@aws-sdk/client-appsync';
|
|
|
2
2
|
import { CreateFunctionCommand, GetFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
|
|
3
3
|
import {
|
|
4
4
|
emailDomain,
|
|
5
|
-
type ContainersRuntimeConfig,
|
|
6
5
|
NODE_RUNTIME,
|
|
7
6
|
type PlatformRuntimeConfig,
|
|
8
7
|
platformNames,
|
|
9
8
|
type RealtimeRuntimeConfig,
|
|
10
9
|
} from '@ericminassian/platform-core';
|
|
11
|
-
import { Hash } from '@smithy/hash-node';
|
|
12
|
-
import { SignatureV4 } from '@smithy/signature-v4';
|
|
13
10
|
import { strToU8, zipSync } from 'fflate';
|
|
14
11
|
import { findEventApi } from './drivers/appsync.ts';
|
|
15
12
|
import { ensureUserPool } from './drivers/cognito.ts';
|
|
16
13
|
import { ensureTable } from './drivers/dynamodb.ts';
|
|
17
|
-
import { ensureRepository } from './drivers/ecr.ts';
|
|
18
|
-
import { ensureCluster } from './drivers/ecs.ts';
|
|
19
14
|
import { ensureRole } from './drivers/iam.ts';
|
|
20
15
|
import { ensureBucket } from './drivers/s3.ts';
|
|
21
16
|
import { ensureEmailIdentity } from './drivers/ses.ts';
|
|
22
|
-
import {
|
|
23
|
-
import { type EngineContext, ignoreNotFound, platformTags,
|
|
17
|
+
import { serviceTrustPolicy } from './policy.ts';
|
|
18
|
+
import { type EngineContext, ignoreNotFound, platformTags, waitFor } from './util.ts';
|
|
24
19
|
|
|
25
20
|
/**
|
|
26
21
|
* Inside a fresh AWS Emulator, create the shared resources a stage deploy
|
|
@@ -75,7 +70,6 @@ export async function ensureLocal(
|
|
|
75
70
|
// associated with must exist. It never verifies and nothing is sent: local stages hand
|
|
76
71
|
// their mail to the CLI (`email.mode: 'local'`).
|
|
77
72
|
const mail = await ensureEmailIdentity(ctx, { domain: emailDomain(domain), tags });
|
|
78
|
-
const containers = await ensureLocalContainers(ctx, tags);
|
|
79
73
|
|
|
80
74
|
return {
|
|
81
75
|
v: 1,
|
|
@@ -95,153 +89,9 @@ export async function ensureLocal(
|
|
|
95
89
|
jwksBaseUrl: opts.jwksBaseUrl,
|
|
96
90
|
realtime,
|
|
97
91
|
email: { domain: mail.domain, identityArn: mail.arn },
|
|
98
|
-
containers,
|
|
99
92
|
};
|
|
100
93
|
}
|
|
101
94
|
|
|
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
95
|
/**
|
|
246
96
|
* The emulator never invokes an Event API's Lambda authorizer (it accepts any
|
|
247
97
|
* token), but the API still needs one to accept the AWS_LAMBDA mode signed-in
|