@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.
Files changed (68) hide show
  1. package/dist/clients.d.ts +0 -4
  2. package/dist/clients.js +1 -14
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +9 -21
  5. package/dist/compat.js +6 -26
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/cognito.d.ts +27 -3
  8. package/dist/drivers/cognito.js +76 -24
  9. package/dist/drivers/cognito.js.map +1 -1
  10. package/dist/drivers/index.d.ts +0 -2
  11. package/dist/drivers/index.js +0 -2
  12. package/dist/drivers/index.js.map +1 -1
  13. package/dist/drivers/logs.d.ts +11 -0
  14. package/dist/drivers/logs.js +15 -1
  15. package/dist/drivers/logs.js.map +1 -1
  16. package/dist/drivers/scheduler.d.ts +0 -21
  17. package/dist/drivers/scheduler.js +0 -43
  18. package/dist/drivers/scheduler.js.map +1 -1
  19. package/dist/index.d.ts +2 -81
  20. package/dist/index.js +0 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/local.js +2 -140
  23. package/dist/local.js.map +1 -1
  24. package/dist/login-branding.d.ts +27 -0
  25. package/dist/login-branding.js +329 -0
  26. package/dist/login-branding.js.map +1 -0
  27. package/dist/login-glyphs.d.ts +12 -0
  28. package/dist/login-glyphs.js +903 -0
  29. package/dist/login-glyphs.js.map +1 -0
  30. package/dist/policy.d.ts +2 -26
  31. package/dist/policy.js +2 -107
  32. package/dist/policy.js.map +1 -1
  33. package/dist/stage.d.ts +1 -2
  34. package/dist/stage.js +16 -87
  35. package/dist/stage.js.map +1 -1
  36. package/dist/util.d.ts +0 -22
  37. package/dist/util.js +0 -16
  38. package/dist/util.js.map +1 -1
  39. package/package.json +10 -7
  40. package/src/clients.ts +1 -15
  41. package/src/compat.ts +9 -32
  42. package/src/drivers/cognito.ts +98 -23
  43. package/src/drivers/index.ts +0 -2
  44. package/src/drivers/logs.ts +21 -0
  45. package/src/drivers/scheduler.ts +0 -69
  46. package/src/index.ts +3 -78
  47. package/src/local.ts +2 -152
  48. package/src/login-branding.ts +407 -0
  49. package/src/login-glyphs.ts +911 -0
  50. package/src/policy.ts +2 -132
  51. package/src/stage.ts +16 -102
  52. package/src/util.ts +0 -34
  53. package/dist/drivers/ecr.d.ts +0 -109
  54. package/dist/drivers/ecr.js +0 -303
  55. package/dist/drivers/ecr.js.map +0 -1
  56. package/dist/drivers/ecs.d.ts +0 -163
  57. package/dist/drivers/ecs.js +0 -447
  58. package/dist/drivers/ecs.js.map +0 -1
  59. package/dist/images.d.ts +0 -104
  60. package/dist/images.js +0 -182
  61. package/dist/images.js.map +0 -1
  62. package/dist/services.d.ts +0 -155
  63. package/dist/services.js +0 -464
  64. package/dist/services.js.map +0 -1
  65. package/src/drivers/ecr.ts +0 -457
  66. package/src/drivers/ecs.ts +0 -661
  67. package/src/images.ts +0 -254
  68. package/src/services.ts +0 -663
package/src/services.ts DELETED
@@ -1,663 +0,0 @@
1
- import {
2
- CONTAINER_BASE_IMAGE,
3
- type ContainersRuntimeConfig,
4
- isPreviewStage,
5
- names,
6
- platformNames,
7
- type ResolvedManifest,
8
- SERVICE_ENV,
9
- TAGS,
10
- } from '@ericminassian/platform-core';
11
- import { unzipSync } from 'fflate';
12
- import { deleteImages, ensureBaseImage, listImages, pushImage } from './drivers/ecr.ts';
13
- import {
14
- deleteService,
15
- deleteTaskDefinitions,
16
- describeTaskDefinition,
17
- ensureService,
18
- getService,
19
- listServices,
20
- listTaskDefinitionArns,
21
- listTaskDefinitionFamilies,
22
- listTaskDefinitions,
23
- listTasks,
24
- newestDeployment,
25
- RolloutError,
26
- type RolloutFailure,
27
- registerTaskDefinition,
28
- restartService,
29
- setDesiredCount,
30
- setTaskDefinition,
31
- shortTaskDefinition,
32
- waitForRollout,
33
- } from './drivers/ecs.ts';
34
- import { getObjectBytes } from './drivers/s3.ts';
35
- import {
36
- deleteSchedule,
37
- ensureOneShotSchedule,
38
- ensureScheduleGroup,
39
- getOneShotScheduleTime,
40
- } from './drivers/scheduler.ts';
41
- import type {
42
- ControlServiceInput,
43
- DeployedService,
44
- ResourceRef,
45
- RollbackStageInput,
46
- S3Location,
47
- ServiceRuntimeState,
48
- StageServicesInput,
49
- } from './index.ts';
50
- import { type EngineContext, mapLimit, stageTags } from './util.ts';
51
-
52
- /**
53
- * A stage's long-running services: one ECS service per declared service,
54
- * running the image built from the deployment's `services.zip` with the
55
- * stage's bindings and role. Built on the generic image, ECS and scheduler
56
- * drivers; `stage.ts` calls these at the right points of a deploy.
57
- */
58
-
59
- type ServiceConfig = ResolvedManifest['services'][string];
60
-
61
- /** How long a deploy waits for every service's rollout. */
62
- export const ROLLOUT_TIMEOUT_MS = 6 * 60_000;
63
-
64
- /** EventBridge Scheduler's universal target for ECS UpdateService (a preview's stop schedule). */
65
- const UPDATE_SERVICE_TARGET = 'arn:aws:scheduler:::aws-sdk:ecs:updateService';
66
-
67
- /** The stage has no service by that name (the control plane answers 404). */
68
- export class ServiceNotFoundError extends Error {
69
- override readonly name = 'ServiceNotFoundError';
70
- readonly service: string;
71
- constructor(service: string, app: string, stage: string) {
72
- super(`${app}/${stage} has no service ${service}`);
73
- this.service = service;
74
- }
75
- }
76
-
77
- /** A preview runs a service for `previewMinutes` after each deploy (never when 0); other stages always. */
78
- export function deployDesiredCount(stage: string, service: Pick<ServiceConfig, 'previewMinutes'>): number {
79
- return isPreviewStage(stage) && service.previewMinutes <= 0 ? 0 : 1;
80
- }
81
-
82
- /** When a deploy's stop schedule scales the service to zero: previews with minutes only. */
83
- export function deployStopTime(
84
- stage: string,
85
- service: Pick<ServiceConfig, 'previewMinutes'>,
86
- now: Date,
87
- ): Date | undefined {
88
- if (!isPreviewStage(stage) || service.previewMinutes <= 0) return undefined;
89
- return minutesFrom(now, service.previewMinutes);
90
- }
91
-
92
- /** `now + minutes`, to the second (Scheduler's one-shot resolution). */
93
- function minutesFrom(now: Date, minutes: number): Date {
94
- return new Date(Math.floor((now.getTime() + minutes * 60_000) / 1000) * 1000);
95
- }
96
-
97
- function stagePrefix(app: string, stage: string): string {
98
- return `${names.base(app, stage)}--`;
99
- }
100
-
101
- /** The manifest key of a stage's ECS service or task definition family, or undefined if it isn't one. */
102
- function serviceKey(prefix: string, name: string | undefined): string | undefined {
103
- if (!name?.startsWith(prefix)) return undefined;
104
- const key = name.slice(prefix.length);
105
- // Keys can't contain `--`, so anything that does isn't a service's.
106
- return key && !key.includes('--') ? key : undefined;
107
- }
108
-
109
- function stopTarget(containers: ContainersRuntimeConfig, service: string) {
110
- return {
111
- arn: UPDATE_SERVICE_TARGET,
112
- roleArn: containers.schedulerRoleArn,
113
- input: JSON.stringify({ Cluster: containers.cluster, Service: service, DesiredCount: 0 }),
114
- };
115
- }
116
-
117
- // ------------------------------------------------------------------ deploy
118
-
119
- export interface ServiceRollout {
120
- /** Manifest key. */
121
- name: string;
122
- /** ECS service name. */
123
- service: string;
124
- taskDefinition: string;
125
- /** What the service ran before this deploy (none for a new service). */
126
- previousTaskDefinition?: string;
127
- desired: number;
128
- logGroup: string;
129
- }
130
-
131
- export interface StartServicesInput {
132
- app: string;
133
- stage: string;
134
- deploymentId: string;
135
- services: ResolvedManifest['services'];
136
- containers: ContainersRuntimeConfig;
137
- region: string;
138
- /** The stage role, which the code runs as. */
139
- roleArn: string;
140
- /** What the worker gets (bindings, NODE_OPTIONS, manifest env, extra env). */
141
- env: Record<string, string>;
142
- tags: Record<string, string>;
143
- artifact: S3Location;
144
- resources: ResourceRef[];
145
- }
146
-
147
- /**
148
- * Build and roll out every declared service without waiting: push its
149
- * image, register a task definition, point the ECS service at it and set a
150
- * preview's stop schedule. {@link awaitServiceRollouts} waits afterwards.
151
- */
152
- export async function startServices(
153
- ctx: EngineContext,
154
- input: StartServicesInput,
155
- ): Promise<{ deployed: DeployedService[]; rollouts: ServiceRollout[] }> {
156
- const { app, stage, deploymentId, containers: c } = input;
157
- const keys = Object.keys(input.services).toSorted();
158
- const zip = unzipSync(await getObjectBytes(ctx, input.artifact));
159
- for (const key of keys)
160
- if (!zip[`${key}/index.mjs`]) throw new Error(`services.zip has no ${key}/index.mjs`);
161
-
162
- const base = await ensureBaseImage(ctx, { repository: c.repository, base: CONTAINER_BASE_IMAGE });
163
- const group = names.scheduleGroup(app, stage);
164
- const now = new Date();
165
- const deployed: DeployedService[] = [];
166
- const rollouts: ServiceRollout[] = [];
167
- for (const key of keys) {
168
- const svc = input.services[key]!;
169
- const map = zip[`${key}/index.mjs.map`];
170
- const tag = names.serviceImageTag(app, stage, key, deploymentId);
171
- const { image } = await pushImage(ctx, {
172
- repository: c.repository,
173
- repositoryUri: c.repositoryUri,
174
- base,
175
- files: [
176
- { path: '/app/index.mjs', content: zip[`${key}/index.mjs`]! },
177
- ...(map ? [{ path: '/app/index.mjs.map', content: map }] : []),
178
- ],
179
- entrypoint: ['node', '/app/index.mjs'],
180
- workingDir: '/app',
181
- user: 'node',
182
- tag,
183
- });
184
- const name = names.service(app, stage, key);
185
- const logGroup = names.serviceLogGroup(app, stage, key);
186
- const taskDefinition = await registerTaskDefinition(ctx, {
187
- family: name,
188
- cpu: svc.cpu,
189
- memoryMb: svc.memoryMb,
190
- taskRoleArn: input.roleArn,
191
- executionRoleArn: c.executionRoleArn,
192
- image,
193
- environment: { ...input.env, [SERVICE_ENV]: key },
194
- logGroup,
195
- region: input.region,
196
- tags: { ...input.tags, [TAGS.deployment]: deploymentId },
197
- });
198
- const desired = deployDesiredCount(stage, svc);
199
- const state = await ensureService(ctx, {
200
- cluster: c.cluster,
201
- name,
202
- taskDefinition,
203
- desiredCount: desired,
204
- spot: svc.spot,
205
- subnets: c.subnets,
206
- securityGroups: c.securityGroups,
207
- tags: input.tags,
208
- });
209
- const stopsAt = deployStopTime(stage, svc, now);
210
- const schedule = names.serviceStopSchedule(key);
211
- if (stopsAt) {
212
- await ensureScheduleGroup(ctx, { name: group, tags: input.tags });
213
- await ensureOneShotSchedule(ctx, { group, name: schedule, at: stopsAt, target: stopTarget(c, name) });
214
- input.resources.push({ type: 'schedule', name: `${group}/${schedule}` });
215
- } else {
216
- await deleteSchedule(ctx, group, schedule);
217
- }
218
- if (desired === 0)
219
- ctx.log(
220
- 'info',
221
- 'not running it: previewMinutes is 0 (start it from the console or CLI)',
222
- `ecs-service ${name}`,
223
- );
224
- deployed.push({
225
- name: key,
226
- image,
227
- taskDefinitionArn: taskDefinition,
228
- desired,
229
- ...(stopsAt ? { stopsAt: stopsAt.toISOString() } : {}),
230
- });
231
- rollouts.push({
232
- name: key,
233
- service: name,
234
- taskDefinition,
235
- ...(state.previousTaskDefinition ? { previousTaskDefinition: state.previousTaskDefinition } : {}),
236
- desired,
237
- logGroup,
238
- });
239
- input.resources.push(
240
- { type: 'image', name: `${c.repository}:${tag}` },
241
- { type: 'task-definition', name: shortTaskDefinition(taskDefinition), arn: taskDefinition },
242
- { type: 'ecs-service', name, arn: state.arn },
243
- );
244
- }
245
- return { deployed, rollouts };
246
- }
247
-
248
- /**
249
- * Wait for every rollout that starts a task, together, within one deadline.
250
- * A failed rollout fails the deploy with what ECS and the container said.
251
- * ECS's circuit breaker takes a service it gave up on back to its previous
252
- * build; when the wait gives up first, this does the same (or stops a
253
- * service that has no previous build).
254
- */
255
- export async function awaitServiceRollouts(
256
- ctx: EngineContext,
257
- input: { cluster: string; rollouts: readonly ServiceRollout[]; timeoutMs?: number; intervalMs?: number },
258
- ): Promise<void> {
259
- const deadline = Date.now() + (input.timeoutMs ?? ROLLOUT_TIMEOUT_MS);
260
- const waiting = input.rollouts.filter((r) => r.desired > 0);
261
- if (!waiting.length) return;
262
- ctx.log('info', `waiting for ${waiting.map((r) => r.name).join(', ')} to start`);
263
- const results = await Promise.allSettled(
264
- waiting.map(async (r) => {
265
- await waitForRollout(ctx, {
266
- cluster: input.cluster,
267
- service: r.service,
268
- taskDefinition: r.taskDefinition,
269
- logGroup: r.logGroup,
270
- deadline,
271
- ...(input.intervalMs !== undefined ? { intervalMs: input.intervalMs } : {}),
272
- });
273
- ctx.log('info', 'running', `ecs-service ${r.service}`);
274
- }),
275
- );
276
- const errors: string[] = [];
277
- for (const [i, result] of results.entries()) {
278
- if (result.status === 'fulfilled') continue;
279
- const e = result.reason as unknown;
280
- if (!(e instanceof RolloutError)) throw e;
281
- await recoverFailedRollout(ctx, input.cluster, waiting[i]!, e.failure);
282
- errors.push(e.message);
283
- }
284
- if (errors.length) throw new Error(errors.join('\n'));
285
- }
286
-
287
- /** What a failed rollout leaves behind. Exported for tests. */
288
- export function recoveryFor(
289
- failure: RolloutFailure,
290
- rollout: Pick<ServiceRollout, 'previousTaskDefinition'>,
291
- ): { taskDefinition: string } | 'stop' | 'none' {
292
- if (failure === 'replaced') return 'none';
293
- if (!rollout.previousTaskDefinition) return 'stop';
294
- // ECS's circuit breaker already rolls back a deployment it marked FAILED.
295
- return failure === 'failed' ? 'none' : { taskDefinition: rollout.previousTaskDefinition };
296
- }
297
-
298
- async function recoverFailedRollout(
299
- ctx: EngineContext,
300
- cluster: string,
301
- rollout: ServiceRollout,
302
- failure: RolloutFailure,
303
- ): Promise<void> {
304
- const action = recoveryFor(failure, rollout);
305
- const resource = `ecs-service ${rollout.service}`;
306
- if (action === 'stop') {
307
- ctx.log('warn', 'stopping it: it has no earlier build to go back to', resource);
308
- await setDesiredCount(ctx, cluster, rollout.service, 0);
309
- } else if (action !== 'none') {
310
- ctx.log('warn', `going back to ${shortTaskDefinition(action.taskDefinition)}`, resource);
311
- await setTaskDefinition(ctx, cluster, rollout.service, action.taskDefinition);
312
- }
313
- }
314
-
315
- /**
316
- * Builds to delete for one service: everything but the newest `kept`
317
- * deployments, the ones in `keep` (the previous and the new deployment) and
318
- * whatever an ECS deployment of the service still runs. Exported for tests.
319
- */
320
- export function staleServiceBuilds(input: {
321
- taskDefinitions: ReadonlyArray<{ arn: string; revision: number; deploymentId?: string }>;
322
- images: ReadonlyArray<{ tag: string; deploymentId: string }>;
323
- inUse: readonly string[];
324
- keep: ReadonlyArray<string | undefined>;
325
- kept: number;
326
- }): { taskDefinitions: string[]; imageTags: string[] } {
327
- const inUse = new Set(input.inUse);
328
- const ids = [
329
- ...new Set([
330
- ...input.taskDefinitions.flatMap((t) => (t.deploymentId ? [t.deploymentId] : [])),
331
- ...input.images.map((i) => i.deploymentId),
332
- ]),
333
- ]
334
- .toSorted()
335
- .toReversed();
336
- const keepIds = new Set([
337
- ...ids.slice(0, input.kept),
338
- ...input.keep.filter((k): k is string => Boolean(k)),
339
- ...input.taskDefinitions.filter((t) => inUse.has(t.arn) && t.deploymentId).map((t) => t.deploymentId!),
340
- ]);
341
- // A retried deploy registers its deployment twice: keep that deployment's newest revision.
342
- const newestPerDeployment = new Map<string, string>();
343
- for (const t of input.taskDefinitions.toSorted((a, b) => b.revision - a.revision))
344
- if (t.deploymentId && !newestPerDeployment.has(t.deploymentId))
345
- newestPerDeployment.set(t.deploymentId, t.arn);
346
- return {
347
- taskDefinitions: input.taskDefinitions
348
- .filter(
349
- (t) =>
350
- !inUse.has(t.arn) &&
351
- !(
352
- t.deploymentId &&
353
- keepIds.has(t.deploymentId) &&
354
- newestPerDeployment.get(t.deploymentId) === t.arn
355
- ),
356
- )
357
- .map((t) => t.arn),
358
- imageTags: input.images.filter((i) => !keepIds.has(i.deploymentId)).map((i) => i.tag),
359
- };
360
- }
361
-
362
- /**
363
- * After the route flip: delete services the manifest no longer declares
364
- * (ECS service, stop schedule, task definitions, images) and old builds of
365
- * the ones it does.
366
- */
367
- export async function pruneServices(
368
- ctx: EngineContext,
369
- input: {
370
- app: string;
371
- stage: string;
372
- services: ResolvedManifest['services'];
373
- containers: ContainersRuntimeConfig;
374
- /** Deployments whose builds stay whatever their age. */
375
- keep: ReadonlyArray<string | undefined>;
376
- /** Task definitions that stay whatever their age (what each service ran before the deploy). */
377
- keepTaskDefinitions?: readonly string[];
378
- kept: number;
379
- },
380
- ): Promise<void> {
381
- const { app, stage, containers: c } = input;
382
- const prefix = stagePrefix(app, stage);
383
- const group = names.scheduleGroup(app, stage);
384
- const declared = new Set(Object.keys(input.services));
385
-
386
- const live = await listServices(ctx, c.cluster, prefix);
387
- for (const svc of live) {
388
- const key = serviceKey(prefix, svc.serviceName);
389
- if (!key || declared.has(key)) continue;
390
- await deleteService(ctx, c.cluster, svc.serviceName!);
391
- await deleteSchedule(ctx, group, names.serviceStopSchedule(key));
392
- }
393
-
394
- const images = new Map<string, Array<{ tag: string; deploymentId: string }>>();
395
- for (const image of await listImages(ctx, c.repository, prefix)) {
396
- const [key, deploymentId, ...rest] = image.tag.slice(prefix.length).split('--');
397
- if (!key || !deploymentId || rest.length) continue;
398
- images.set(key, [...(images.get(key) ?? []), { tag: image.tag, deploymentId }]);
399
- }
400
- const families = new Map<string, string>();
401
- for (const family of await listTaskDefinitionFamilies(ctx, prefix, 'ALL')) {
402
- const key = serviceKey(prefix, family);
403
- if (key) families.set(key, family);
404
- }
405
-
406
- for (const key of new Set([...images.keys(), ...families.keys()])) {
407
- const family = names.service(app, stage, key);
408
- const tags = images.get(key) ?? [];
409
- if (!declared.has(key)) {
410
- await deleteTaskDefinitions(ctx, await allRevisions(ctx, family));
411
- await deleteImages(
412
- ctx,
413
- c.repository,
414
- tags.map((t) => ({ tag: t.tag })),
415
- );
416
- continue;
417
- }
418
- const revisions = await listTaskDefinitions(ctx, family);
419
- const svc = live.find((s) => s.serviceName === family);
420
- const stale = staleServiceBuilds({
421
- taskDefinitions: revisions.map((t) => ({
422
- arn: t.arn,
423
- revision: t.revision,
424
- ...(t.tags[TAGS.deployment] ? { deploymentId: t.tags[TAGS.deployment] } : {}),
425
- })),
426
- images: tags,
427
- inUse: [
428
- ...(svc?.deployments ?? []).flatMap((d) => (d.taskDefinition ? [d.taskDefinition] : [])),
429
- ...(input.keepTaskDefinitions ?? []),
430
- ],
431
- keep: input.keep,
432
- kept: input.kept,
433
- });
434
- // Deregistered revisions can't be run or rolled back to: those an earlier cleanup left go too.
435
- const inactive = await listTaskDefinitionArns(ctx, family, 'INACTIVE');
436
- await deleteTaskDefinitions(ctx, [...stale.taskDefinitions, ...inactive]);
437
- await deleteImages(
438
- ctx,
439
- c.repository,
440
- stale.imageTags.map((tag) => ({ tag })),
441
- );
442
- }
443
- }
444
-
445
- async function allRevisions(ctx: EngineContext, family: string): Promise<string[]> {
446
- const [active, inactive] = await Promise.all([
447
- listTaskDefinitionArns(ctx, family, 'ACTIVE'),
448
- listTaskDefinitionArns(ctx, family, 'INACTIVE'),
449
- ]);
450
- return [...active, ...inactive];
451
- }
452
-
453
- /** The deployment a service's ECS deployment (or task definition) belongs to. */
454
- export async function deploymentOf(
455
- ctx: EngineContext,
456
- taskDefinition: string | undefined,
457
- ): Promise<string | undefined> {
458
- if (!taskDefinition) return undefined;
459
- return (await describeTaskDefinition(ctx, taskDefinition))?.tags[TAGS.deployment];
460
- }
461
-
462
- // ------------------------------------------------------------------ rollback
463
-
464
- /** Which services a rollback repoints, keeps or can't bring back. Exported for tests. */
465
- export function rollbackSelection(
466
- target: readonly string[],
467
- live: readonly string[],
468
- ): { repoint: string[]; keep: string[]; missing: string[] } {
469
- const t = new Set(target);
470
- const l = new Set(live);
471
- return {
472
- repoint: live.filter((k) => t.has(k)).toSorted(),
473
- keep: live.filter((k) => !t.has(k)).toSorted(),
474
- missing: target.filter((k) => !l.has(k)).toSorted(),
475
- };
476
- }
477
-
478
- /** The newest revision built by `deploymentId`. Exported for tests. */
479
- export function buildOf<T extends { revision: number; tags: Record<string, string> }>(
480
- revisions: readonly T[],
481
- deploymentId: string,
482
- ): T | undefined {
483
- return revisions
484
- .filter((t) => t.tags[TAGS.deployment] === deploymentId)
485
- .toSorted((a, b) => b.revision - a.revision)[0];
486
- }
487
-
488
- export interface ServicesRollback {
489
- cluster: string;
490
- updates: Array<{ service: string; taskDefinition: string }>;
491
- }
492
-
493
- /**
494
- * Before a rollback changes anything: find the build of `route.d` for every
495
- * service that deployment declared and the stage still runs. Refuses
496
- * (through `gone`) when one has been cleaned up.
497
- */
498
- export async function planServicesRollback(
499
- ctx: EngineContext,
500
- input: RollbackStageInput,
501
- gone: (what: string) => Error,
502
- ): Promise<ServicesRollback | undefined> {
503
- const c = input.platform.containers;
504
- if (!c || !input.services) return undefined;
505
- const { app, stage, route } = input;
506
- const prefix = stagePrefix(app, stage);
507
- const live = await listServices(ctx, c.cluster, prefix);
508
- const liveKeys = live.flatMap((s) => serviceKey(prefix, s.serviceName) ?? []);
509
- const selection = rollbackSelection(input.services, liveKeys);
510
- for (const key of selection.keep)
511
- ctx.log(
512
- 'warn',
513
- `deployment ${route.d} has no service ${key}; it keeps running its current build`,
514
- `ecs-service ${names.service(app, stage, key)}`,
515
- );
516
- for (const key of selection.missing)
517
- ctx.log(
518
- 'warn',
519
- `deployment ${route.d} had service ${key}, which the stage no longer runs: redeploy that commit to bring it back`,
520
- );
521
- const updates: ServicesRollback['updates'] = [];
522
- for (const key of selection.repoint) {
523
- const service = names.service(app, stage, key);
524
- const build = buildOf(await listTaskDefinitions(ctx, service), route.d);
525
- if (!build) throw gone(`the build of service ${key} has been cleaned up`);
526
- if (live.find((s) => s.serviceName === service)?.taskDefinition !== build.arn)
527
- updates.push({ service, taskDefinition: build.arn });
528
- }
529
- return { cluster: c.cluster, updates };
530
- }
531
-
532
- /** Point each service at its build from the rollback's deployment (ECS rolls it out; no wait). */
533
- export async function applyServicesRollback(
534
- ctx: EngineContext,
535
- plan: ServicesRollback | undefined,
536
- ): Promise<void> {
537
- for (const u of plan?.updates ?? [])
538
- await setTaskDefinition(ctx, plan!.cluster, u.service, u.taskDefinition);
539
- }
540
-
541
- // ------------------------------------------------------------------ destroy / list
542
-
543
- /** Delete the stage's services, task definitions and images (stop schedules go with the schedule group). */
544
- export async function destroyServices(
545
- ctx: EngineContext,
546
- input: { app: string; stage: string; containers: ContainersRuntimeConfig },
547
- ): Promise<void> {
548
- const { app, stage, containers: c } = input;
549
- const prefix = stagePrefix(app, stage);
550
- for (const svc of await listServices(ctx, c.cluster, prefix))
551
- await deleteService(ctx, c.cluster, svc.serviceName!);
552
- for (const family of await listTaskDefinitionFamilies(ctx, prefix, 'ALL')) {
553
- if (serviceKey(prefix, family)) await deleteTaskDefinitions(ctx, await allRevisions(ctx, family));
554
- }
555
- const images = await listImages(ctx, c.repository, prefix);
556
- await deleteImages(
557
- ctx,
558
- c.repository,
559
- images.map((i) => ({ tag: i.tag })),
560
- );
561
- }
562
-
563
- /** The stage's ECS services and task definition families, found by name (no runtime config needed). */
564
- export async function listServiceResources(
565
- ctx: EngineContext,
566
- app: string,
567
- stage: string,
568
- ): Promise<ResourceRef[]> {
569
- const prefix = stagePrefix(app, stage);
570
- const out: ResourceRef[] = [];
571
- for (const svc of await listServices(ctx, platformNames.containerCluster, prefix))
572
- out.push({ type: 'ecs-service', name: svc.serviceName!, arn: svc.serviceArn! });
573
- for (const family of await listTaskDefinitionFamilies(ctx, prefix, 'ACTIVE'))
574
- if (serviceKey(prefix, family)) out.push({ type: 'task-definition', name: family });
575
- return out;
576
- }
577
-
578
- // ------------------------------------------------------------------ runtime state and control
579
-
580
- export async function describeServices(
581
- ctx: EngineContext,
582
- input: StageServicesInput,
583
- ): Promise<ServiceRuntimeState[]> {
584
- const c = input.platform.containers;
585
- if (!c) return [];
586
- const { app, stage } = input;
587
- const prefix = stagePrefix(app, stage);
588
- const group = names.scheduleGroup(app, stage);
589
- const services = (await listServices(ctx, c.cluster, prefix)).filter((s) =>
590
- serviceKey(prefix, s.serviceName),
591
- );
592
- return mapLimit(services, 4, async (svc) => {
593
- const name = serviceKey(prefix, svc.serviceName)!;
594
- const newest = newestDeployment(svc.deployments);
595
- const [deploymentId, running, stopped, stopsAt] = await Promise.all([
596
- deploymentOf(ctx, newest?.taskDefinition),
597
- listTasks(ctx, c.cluster, svc.serviceName!, 'RUNNING'),
598
- listTasks(ctx, c.cluster, svc.serviceName!, 'STOPPED'),
599
- getOneShotScheduleTime(ctx, group, names.serviceStopSchedule(name)),
600
- ]);
601
- const current = running.find((t) => t.lastStatus === 'RUNNING' && t.startedAt);
602
- const last = stopped.find((t) => t.stoppedAt);
603
- const container = last?.containers?.find((x) => x.name === 'app');
604
- const rollout = newest?.rolloutState?.toLowerCase() as ServiceRuntimeState['rollout'];
605
- return {
606
- name,
607
- desired: svc.desiredCount ?? 0,
608
- running: svc.runningCount ?? 0,
609
- pending: svc.pendingCount ?? 0,
610
- ...(rollout ? { rollout } : {}),
611
- ...(deploymentId ? { deploymentId } : {}),
612
- ...(current?.startedAt ? { startedAt: current.startedAt.toISOString() } : {}),
613
- ...(stopsAt ? { stopsAt: stopsAt.toISOString() } : {}),
614
- ...(last?.stoppedAt
615
- ? {
616
- lastStop: {
617
- at: last.stoppedAt.toISOString(),
618
- reason: [last.stoppedReason, container?.reason].filter(Boolean).join(': ') || 'unknown',
619
- ...(container?.exitCode !== undefined ? { exitCode: container.exitCode } : {}),
620
- },
621
- }
622
- : {}),
623
- events: (svc.events ?? []).slice(0, 10).map((e) => ({
624
- at: e.createdAt?.toISOString() ?? '',
625
- message: e.message ?? '',
626
- })),
627
- };
628
- });
629
- }
630
-
631
- export async function controlService(
632
- ctx: EngineContext,
633
- input: ControlServiceInput,
634
- ): Promise<{ desired: number; stopsAt?: string }> {
635
- const { app, stage, platform } = input;
636
- const c = platform.containers;
637
- const service = names.service(app, stage, input.name);
638
- const svc = c ? await getService(ctx, c.cluster, service) : undefined;
639
- if (!c || svc?.status !== 'ACTIVE') throw new ServiceNotFoundError(input.name, app, stage);
640
- const group = names.scheduleGroup(app, stage);
641
- const schedule = names.serviceStopSchedule(input.name);
642
- if (input.action === 'restart') {
643
- await restartService(ctx, c.cluster, service);
644
- const stopsAt = await getOneShotScheduleTime(ctx, group, schedule);
645
- return { desired: svc.desiredCount ?? 0, ...(stopsAt ? { stopsAt: stopsAt.toISOString() } : {}) };
646
- }
647
- if (input.action === 'stop') {
648
- await setDesiredCount(ctx, c.cluster, service, 0);
649
- await deleteSchedule(ctx, group, schedule);
650
- return { desired: 0 };
651
- }
652
- if (input.minutes !== undefined && !(Number.isInteger(input.minutes) && input.minutes > 0))
653
- throw new Error('minutes must be a positive whole number');
654
- await setDesiredCount(ctx, c.cluster, service, 1);
655
- if (input.minutes === undefined) {
656
- await deleteSchedule(ctx, group, schedule);
657
- return { desired: 1 };
658
- }
659
- const at = minutesFrom(new Date(), input.minutes);
660
- await ensureScheduleGroup(ctx, { name: group, tags: stageTags(app, stage) });
661
- await ensureOneShotSchedule(ctx, { group, name: schedule, at, target: stopTarget(c, service) });
662
- return { desired: 1, stopsAt: at.toISOString() };
663
- }