@ericminassian/platform-engine 0.3.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 (94) 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 +5 -0
  32. package/dist/drivers/s3.js +26 -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/web-function.d.ts +11 -3
  44. package/dist/drivers/web-function.js +22 -5
  45. package/dist/drivers/web-function.js.map +1 -1
  46. package/dist/emulator.js.map +1 -1
  47. package/dist/images.d.ts +104 -0
  48. package/dist/images.js +182 -0
  49. package/dist/images.js.map +1 -0
  50. package/dist/index.d.ts +130 -6
  51. package/dist/index.js +11 -2
  52. package/dist/index.js.map +1 -1
  53. package/dist/local.js +222 -7
  54. package/dist/local.js.map +1 -1
  55. package/dist/policy.d.ts +47 -4
  56. package/dist/policy.js +365 -13
  57. package/dist/policy.js.map +1 -1
  58. package/dist/services.d.ts +155 -0
  59. package/dist/services.js +464 -0
  60. package/dist/services.js.map +1 -0
  61. package/dist/stage.d.ts +33 -8
  62. package/dist/stage.js +598 -124
  63. package/dist/stage.js.map +1 -1
  64. package/dist/static.d.ts +1 -1
  65. package/dist/static.js +2 -36
  66. package/dist/static.js.map +1 -1
  67. package/dist/util.d.ts +22 -0
  68. package/dist/util.js +18 -2
  69. package/dist/util.js.map +1 -1
  70. package/package.json +20 -14
  71. package/src/clients.ts +25 -1
  72. package/src/compat.ts +34 -11
  73. package/src/drivers/appsync.ts +220 -0
  74. package/src/drivers/ecr.ts +457 -0
  75. package/src/drivers/ecs.ts +661 -0
  76. package/src/drivers/events.ts +29 -2
  77. package/src/drivers/index.ts +5 -0
  78. package/src/drivers/kvs.ts +21 -12
  79. package/src/drivers/lambda.ts +103 -2
  80. package/src/drivers/request-function.ts +295 -0
  81. package/src/drivers/s3.ts +38 -0
  82. package/src/drivers/scheduler.ts +88 -5
  83. package/src/drivers/ses.ts +267 -0
  84. package/src/drivers/sqs.ts +95 -0
  85. package/src/drivers/web-function.ts +29 -9
  86. package/src/emulator.ts +3 -3
  87. package/src/images.ts +254 -0
  88. package/src/index.ts +129 -7
  89. package/src/local.ts +251 -7
  90. package/src/policy.ts +446 -24
  91. package/src/services.ts +663 -0
  92. package/src/stage.ts +753 -139
  93. package/src/static.ts +2 -37
  94. package/src/util.ts +38 -4
package/src/stage.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { DescribeEventBusCommand } from '@aws-sdk/client-eventbridge';
3
3
  import { GetRoleCommand } from '@aws-sdk/client-iam';
4
- import { GetFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
5
4
  import { GetWebFunctionCommand } from '@aws-sdk/client-lambda-web';
6
5
  import {
7
6
  AUTH_ROUTES,
@@ -9,20 +8,47 @@ import {
9
8
  type Bindings,
10
9
  cognitoIssuer,
11
10
  cognitoJwksUri,
11
+ DEFAULT_ATTEMPTS,
12
+ type DeadLetter,
13
+ type EmailBindings,
14
+ emailDailyLimit,
15
+ emailFromAddress,
12
16
  encodeBindings,
17
+ type HandlerKind,
18
+ handlerFunctionName,
19
+ handlerKey,
20
+ handlerSettings,
13
21
  IAM_APP_PATH,
22
+ isJobSchedule,
23
+ JOB_MARKER,
14
24
  LOCAL_STAGE,
15
25
  NODE_RUNTIME,
16
26
  names,
27
+ newId,
28
+ originSecret,
29
+ ownFunctionHandlers,
17
30
  type PlatformRuntimeConfig,
18
31
  PROD_STAGE,
32
+ platformNames,
33
+ publicStores,
19
34
  publicUrl,
35
+ RESOURCE_KEY_PATTERN,
20
36
  type ResolvedManifest,
21
37
  type RouteRecord,
38
+ realtimeEndpoints,
22
39
  stageHost,
23
40
  toSchedulerExpression,
24
41
  validateStageName,
42
+ workerHandlers,
43
+ webMaxEnvironments,
25
44
  } from '@ericminassian/platform-core';
45
+ import {
46
+ deleteChannelNamespace,
47
+ ensureChannelNamespace,
48
+ ensureRealtimePlatform,
49
+ findEventApi,
50
+ getChannelNamespace,
51
+ } from './drivers/appsync.ts';
26
52
  import { deleteUserPoolClient, ensureUserPoolClient } from './drivers/cognito.ts';
27
53
  import { deleteTable, describeTable, ensureTable, stageTableSpec } from './drivers/dynamodb.ts';
28
54
  import { deleteEventBus, deleteRule, ensureEventBus, ensureRule, listRules } from './drivers/events.ts';
@@ -31,22 +57,56 @@ import { deleteRoute, getRoute, putRoute } from './drivers/kvs.ts';
31
57
  import {
32
58
  deleteEventSourceMapping,
33
59
  deleteFunction,
60
+ ensureAsyncConfig,
34
61
  ensureEventSourceMapping,
35
62
  ensureFunction,
36
63
  ensurePermission,
64
+ type FunctionState,
37
65
  listEventSourceMappings,
66
+ listFunctions,
67
+ ensureReservedConcurrency,
68
+ listPermissionIds,
38
69
  removePermission,
39
70
  } from './drivers/lambda.ts';
40
71
  import { deleteLogGroup, ensureLogGroup, listLogGroups } from './drivers/logs.ts';
41
- import { deletePrefix, hasObjects, listChildPrefixes, publishStaticZip } from './drivers/s3.ts';
72
+ import {
73
+ aliasForVersion,
74
+ getVersionState,
75
+ publishRequestFunction,
76
+ pruneVersions,
77
+ } from './drivers/request-function.ts';
78
+ import {
79
+ deleteObjectsOlderThan,
80
+ deletePrefix,
81
+ hasObjects,
82
+ listChildPrefixes,
83
+ publishStaticZip,
84
+ } from './drivers/s3.ts';
42
85
  import {
43
86
  deleteSchedule,
44
87
  deleteScheduleGroup,
88
+ deleteScheduleGroupIfEmpty,
45
89
  ensureSchedule,
46
90
  ensureScheduleGroup,
47
91
  listSchedules,
48
92
  } from './drivers/scheduler.ts';
49
- import { deleteQueue, ensureQueue, listQueues } from './drivers/sqs.ts';
93
+ import {
94
+ deleteConfigurationSet,
95
+ deleteTenant,
96
+ ensureConfigurationSet,
97
+ ensureTenant,
98
+ ensureTenantResources,
99
+ getConfigurationSet,
100
+ getTenant,
101
+ } from './drivers/ses.ts';
102
+ import {
103
+ deleteQueue,
104
+ ensureQueue,
105
+ listQueues,
106
+ moveMessages,
107
+ queueDepth,
108
+ setQueueAttributes,
109
+ } from './drivers/sqs.ts';
50
110
  import { deleteParameter, deleteParametersByPath, ensureParameterOnce } from './drivers/ssm.ts';
51
111
  import {
52
112
  createRevision,
@@ -60,10 +120,22 @@ import type {
60
120
  DeployStageInput,
61
121
  DeployStageResult,
62
122
  DestroyStageInput,
123
+ ExpireStorageInput,
63
124
  ResourceRef,
64
125
  RollbackStageInput,
65
126
  } from './index.ts';
66
- import { stageRolePolicy, stageTrustPolicy } from './policy.ts';
127
+ import { configurationSetArn, stageRolePolicy, stageTrustPolicy } from './policy.ts';
128
+ import {
129
+ applyServicesRollback,
130
+ awaitServiceRollouts,
131
+ destroyServices,
132
+ listServiceResources,
133
+ planServicesRollback,
134
+ pruneServices,
135
+ type ServiceRollout,
136
+ type ServicesRollback,
137
+ startServices,
138
+ } from './services.ts';
67
139
  import { type EngineContext, ignoreNotFound, stageTags } from './util.ts';
68
140
 
69
141
  /**
@@ -72,6 +144,14 @@ import { type EngineContext, ignoreNotFound, stageTags } from './util.ts';
72
144
  */
73
145
  const DEPLOYMENTS_KEPT = 3;
74
146
 
147
+ /**
148
+ * Crons, jobs' retries and delayed sends, and preview stop schedules share the
149
+ * stage's schedule group. Cron keys start with a letter and can't contain
150
+ * `--`; a job's schedule starts with `_` and a service's stop schedule is
151
+ * `<key>--stop`.
152
+ */
153
+ const isCronSchedule = (name: string) => !name.includes('--') && !isJobSchedule(name);
154
+
75
155
  /**
76
156
  * Public host of a stage. Under `plat dev` the `local` stage is simply
77
157
  * `<app>.localhost`; everything else follows `stageHost`.
@@ -88,7 +168,8 @@ function statementId(prefix: string, name: string): string {
88
168
  /**
89
169
  * Reconcile one stage with its manifest, then flip the route. Ordering keeps
90
170
  * the old deployment serving until everything for the new one is ready:
91
- * data/messaging → role → worker → static → web revision → route (last) → GC.
171
+ * data/messaging → role → worker → services (started) → static → server
172
+ * build → services (running) → route (last) → GC.
92
173
  */
93
174
  export async function deployStage(ctx: EngineContext, input: DeployStageInput): Promise<DeployStageResult> {
94
175
  const { manifest: m, stage, platform, deploymentId } = input;
@@ -104,19 +185,46 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
104
185
  const host = hostFor(platform, app, stage);
105
186
  const url = publicUrl(platform, host);
106
187
  const retention = input.logRetentionDays ?? (prod ? 30 : 7);
107
- const base = names.base(app, stage);
108
188
  const hasWeb = Boolean(m.web?.server) && webMode === 'function';
109
189
  const hasWorker = Boolean(m.worker);
190
+ const serviceKeys = Object.keys(m.services);
191
+ const servicesOnEcs = (input.servicesMode ?? 'ecs') === 'ecs';
110
192
  const resources: ResourceRef[] = [];
111
193
  const workerName = names.workerFunction(app, stage);
194
+ const servedStores = publicStores(m);
112
195
 
113
196
  if (hasWorker && !input.artifacts.worker)
114
197
  throw new Error('manifest declares a worker but no worker artifact was provided');
115
198
  if (hasWeb && !input.artifacts.server)
116
199
  throw new Error('manifest declares web.server but no server artifact was provided');
200
+ if (m.realtime && !platform.realtime)
201
+ throw new Error(
202
+ "plat.config.ts declares realtime, but this platform has no realtime API yet (its foundation predates it): deploy the platform's foundation first",
203
+ );
204
+ if (m.email && !platform.email)
205
+ throw new Error(
206
+ "plat.config.ts declares email, but this platform has no mail domain yet (its foundation predates it): deploy the platform's foundation first",
207
+ );
208
+ if (serviceKeys.length && servicesOnEcs) {
209
+ if (!platform.containers)
210
+ throw new Error(
211
+ "plat.config.ts declares services, but this platform has no container compute yet (its foundation predates it): deploy the platform's foundation first",
212
+ );
213
+ if (!input.artifacts.services)
214
+ throw new Error('manifest declares services but no services artifact was provided');
215
+ }
117
216
 
118
217
  ctx.log('info', `deploying ${app}/${stage} (${deploymentId})`);
119
218
 
219
+ // The route the edge serves now. The new revision goes on the endpoint it doesn't use, GC keeps
220
+ // its static files (edges keep serving it until they pick up the new route), and its public
221
+ // stores are the ones whose files live under the public prefix.
222
+ const liveRoute =
223
+ webMode === 'function' && platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
224
+
225
+ // 0. Checked before anything changes.
226
+ await assertStoreVisibility(ctx, { app, stage, manifest: m, platform, liveRoute });
227
+
120
228
  // 1. Log groups (retention set before anything writes to them). These are all of them: the stage
121
229
  // role can't create log groups (see stageRolePolicy).
122
230
  const webLogGroup = names.logGroup(app, stage, 'web');
@@ -130,6 +238,12 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
130
238
  });
131
239
  }
132
240
  if (hasWorker) await ensureLogGroup(ctx, { name: workerLogGroup, retentionDays: retention, tags });
241
+ for (const key of serviceKeys)
242
+ await ensureLogGroup(ctx, {
243
+ name: names.serviceLogGroup(app, stage, key),
244
+ retentionDays: retention,
245
+ tags,
246
+ });
133
247
 
134
248
  // 2. Data.
135
249
  let table: string | undefined;
@@ -145,34 +259,13 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
145
259
  );
146
260
  }
147
261
 
148
- // 3. Queues (dead-letter queue first).
149
- const queues: Bindings['queues'] = {};
150
- const workerTimeout = m.worker?.timeoutSeconds ?? 60;
151
- for (const [key, q] of Object.entries(m.queues)) {
152
- const dlq = await ensureQueue(ctx, {
153
- name: names.deadLetterQueue(app, stage, key),
154
- attributes: { MessageRetentionPeriod: String(14 * 24 * 3600) },
155
- tags,
156
- });
157
- let visibility = q.visibilityTimeoutSeconds;
158
- if (visibility < workerTimeout) {
159
- ctx.log('warn', `visibility timeout raised to the worker timeout (${workerTimeout}s)`, `queue ${key}`);
160
- visibility = workerTimeout;
161
- }
162
- const main = await ensureQueue(ctx, {
163
- name: names.queue(app, stage, key),
164
- attributes: {
165
- VisibilityTimeout: String(visibility),
166
- MessageRetentionPeriod: String(4 * 24 * 3600),
167
- RedrivePolicy: JSON.stringify({ deadLetterTargetArn: dlq.arn, maxReceiveCount: q.maxReceiveCount }),
168
- },
169
- tags,
170
- });
171
- queues[key] = { url: main.url, arn: main.arn };
172
- resources.push(
173
- { type: 'queue', name: main.name, arn: main.arn },
174
- { type: 'queue', name: dlq.name, arn: dlq.arn },
175
- );
262
+ // 3. Jobs: the stage's dead-letter queue. Queues have no SQS queue of their own (they're async
263
+ // invokes, core jobs.ts); queues from before that drain first (step 9).
264
+ let deadLetters: { url: string; arn: string } | undefined;
265
+ if (hasWorker) {
266
+ const dead = await ensureDeadLetterQueue(ctx, { app, stage, region, accountId: acct, tags });
267
+ deadLetters = { url: dead.url, arn: dead.arn };
268
+ resources.push({ type: 'queue', name: dead.name, arn: dead.arn });
176
269
  }
177
270
 
178
271
  // 4. Event bus (always: anything may be published, subscriptions are optional).
@@ -234,17 +327,63 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
234
327
  generate: () => randomBytes(32).toString('base64url'),
235
328
  });
236
329
 
330
+ // 7b. Realtime: the stage's channel namespace, ready before any code that
331
+ // publishes to it (worker, web revision) and before the route advertises it.
332
+ let realtime: Bindings['realtime'];
333
+ if (m.realtime && platform.realtime) {
334
+ const namespace = names.realtimeNamespace(app, stage);
335
+ const ns = await ensureChannelNamespace(ctx, {
336
+ apiId: platform.realtime.apiId,
337
+ name: namespace,
338
+ subscribe: m.realtime.subscribe,
339
+ tags,
340
+ });
341
+ // The key and the router's entry normally exist (foundation deploy, nightly job); this makes
342
+ // a first realtime deploy work regardless.
343
+ await ensureRealtimePlatform(ctx, platform);
344
+ realtime = {
345
+ namespace,
346
+ publishUrl: realtimeEndpoints(platform, platform.realtime).publishUrl,
347
+ subscribe: m.realtime.subscribe,
348
+ channels: m.realtime.channels,
349
+ };
350
+ resources.push({ type: 'channel-namespace', name: namespace, ...(ns.arn ? { arn: ns.arn } : {}) });
351
+ }
352
+
353
+ // 7c. Email: the stage's SES tenant, ready before any code that sends with it.
354
+ const email = await reconcileStageEmail(ctx, { app, stage, manifest: m, platform, tags, resources });
355
+
237
356
  // 8. Bindings.
357
+ const jobs: Bindings['jobs'] = deadLetters
358
+ ? {
359
+ queues: Object.keys(m.queues),
360
+ fns: Object.fromEntries(
361
+ ownFunctionHandlers(m).map((h) => [
362
+ handlerKey(h.kind, h.name),
363
+ names.handlerFunction(app, stage, h.kind, h.name),
364
+ ]),
365
+ ),
366
+ attempts: Object.fromEntries(
367
+ workerHandlers(m)
368
+ .filter((h) => h.maxAttempts !== DEFAULT_ATTEMPTS[h.kind])
369
+ .map((h) => [handlerKey(h.kind, h.name), h.maxAttempts]),
370
+ ),
371
+ dead: deadLetters.url,
372
+ group: names.scheduleGroup(app, stage),
373
+ role: roleArn,
374
+ }
375
+ : undefined;
238
376
  const bindings: Bindings = {
239
- v: 1,
377
+ v: 2,
240
378
  app,
241
379
  stage,
242
380
  host,
243
381
  url,
244
382
  revision: deploymentId,
245
383
  region,
384
+ account: acct,
246
385
  ...(table ? { table } : {}),
247
- queues,
386
+ ...(jobs ? { jobs } : {}),
248
387
  bus: { name: busName, arn: busArn },
249
388
  ...(m.storage.length
250
389
  ? {
@@ -252,6 +391,9 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
252
391
  bucket: platform.storageBucket,
253
392
  prefix: names.storagePrefix(app, stage),
254
393
  stores: m.storage,
394
+ ...(servedStores.length
395
+ ? { public: servedStores, publicPrefix: names.publicStoragePrefix(app, stage) }
396
+ : {}),
255
397
  },
256
398
  }
257
399
  : {}),
@@ -261,6 +403,8 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
261
403
  names: m.secrets,
262
404
  },
263
405
  ...(auth ? { auth } : {}),
406
+ ...(realtime ? { realtime } : {}),
407
+ ...(email ? { email } : {}),
264
408
  ...(hasWorker ? { worker: workerName } : {}),
265
409
  stageKey,
266
410
  };
@@ -271,46 +415,93 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
271
415
  ...input.extraEnv,
272
416
  };
273
417
 
274
- // 9. Worker + its triggers.
418
+ // 9. Worker + its triggers. A handler that sets its own memory, timeout or concurrency runs in a
419
+ // function of its own: same bundle, environment and log group, other settings (Lambda sets them
420
+ // per function).
275
421
  let workerFunction: DeployStageResult['workerFunction'];
276
- if (hasWorker && m.worker && input.artifacts.worker) {
277
- const fn = await ensureFunction(ctx, {
278
- name: workerName,
279
- roleArn,
280
- runtime: NODE_RUNTIME,
281
- handler: 'index.handler',
282
- architecture: 'arm64',
283
- memoryMb: m.worker.memoryMb,
284
- timeoutSeconds: m.worker.timeoutSeconds,
285
- code: input.artifacts.worker,
286
- env,
287
- logGroup: workerLogGroup,
288
- description: `${app}/${stage} worker (${deploymentId})`,
289
- tags,
290
- });
422
+ // Queues from before jobs were pushed: the ones that still hold messages drain through their
423
+ // event source mappings (the SDK still reads SQS batches); the rest go after the triggers move.
424
+ const legacy = await listLegacyQueues(ctx, { app, stage, manifest: m, region, accountId: acct });
425
+ if (hasWorker && m.worker && input.artifacts.worker && deadLetters) {
426
+ const code = input.artifacts.worker;
427
+ const deployFunction = (
428
+ name: string,
429
+ settings: { memoryMb: number; timeoutSeconds: number },
430
+ of: string,
431
+ ) =>
432
+ ensureFunction(ctx, {
433
+ name,
434
+ roleArn,
435
+ runtime: NODE_RUNTIME,
436
+ handler: 'index.handler',
437
+ architecture: 'arm64',
438
+ memoryMb: settings.memoryMb,
439
+ timeoutSeconds: settings.timeoutSeconds,
440
+ code,
441
+ env,
442
+ logGroup: workerLogGroup,
443
+ description: `${app}/${stage} ${of} (${deploymentId})`,
444
+ tags,
445
+ });
446
+ // Each takes seconds of updates and waits, and none depends on another.
447
+ const functions = await settleAll([
448
+ deployFunction(workerName, m.worker, 'worker'),
449
+ ...ownFunctionHandlers(m).map((h) =>
450
+ deployFunction(names.handlerFunction(app, stage, h.kind, h.name), h, `worker, ${h.kind} ${h.name}`),
451
+ ),
452
+ ]);
453
+ const fn = functions[0]!;
291
454
  workerFunction = { name: fn.name, arn: fn.arn };
292
- resources.push({ type: 'function', name: fn.name, arn: fn.arn });
455
+ for (const f of functions) resources.push({ type: 'function', name: f.name, arn: f.arn });
456
+ // Crashes and timeouts (Lambda's retries) end in the dead-letter queue too; a queue's
457
+ // concurrency is its own function's reserved concurrency, and a cap no longer declared goes.
458
+ const concurrency = new Map(
459
+ ownFunctionHandlers(m).map((h) => [names.handlerFunction(app, stage, h.kind, h.name), h.concurrency]),
460
+ );
461
+ await settleAll(
462
+ functions.map(async (f) => {
463
+ await ensureAsyncConfig(ctx, { functionName: f.name, deadLetterArn: deadLetters.arn });
464
+ await ensureReservedConcurrency(ctx, f.name, concurrency.get(f.name));
465
+ }),
466
+ );
293
467
  await reconcileWorkerTriggers(ctx, {
294
468
  app,
295
469
  stage,
296
470
  manifest: m,
297
- workerName,
298
- workerArn: fn.arn,
471
+ functions,
299
472
  roleArn,
300
473
  busName,
301
- queues,
474
+ deadLetterArn: deadLetters.arn,
475
+ draining: legacy.draining,
302
476
  tags,
303
477
  resources,
304
478
  });
305
479
  } else {
306
480
  await removeWorker(ctx, app, stage);
307
481
  }
482
+ await retireLegacyQueues(ctx, { app, stage, legacy, deadLetters });
308
483
 
309
- // The route the edge serves now. The new revision goes on the endpoint it doesn't use, and GC keeps
310
- // its static files: edges keep serving it until they pick up the new route.
311
- const liveRoute =
312
- webMode === 'function' && platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
313
-
484
+ // 9b. Services: images, task definitions and ECS services. Their rollouts run while the static
485
+ // files and the web revision go up, and must finish before the route flips.
486
+ let services: DeployStageResult['services'];
487
+ let rollouts: ServiceRollout[] = [];
488
+ if (servicesOnEcs && serviceKeys.length && platform.containers && input.artifacts.services) {
489
+ const started = await startServices(ctx, {
490
+ app,
491
+ stage,
492
+ deploymentId,
493
+ services: m.services,
494
+ containers: platform.containers,
495
+ region,
496
+ roleArn,
497
+ env,
498
+ tags,
499
+ artifact: input.artifacts.services,
500
+ resources,
501
+ });
502
+ services = started.deployed;
503
+ rollouts = started.rollouts;
504
+ }
314
505
  // 10. Static files (new prefix per deployment; the old one keeps serving until the route flips).
315
506
  let staticPrefix: string | undefined;
316
507
  if (input.artifacts.static) {
@@ -323,9 +514,36 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
323
514
  resources.push({ type: 'static', name: staticPrefix });
324
515
  }
325
516
 
326
- // 11. Web Function revision → an endpoint the live route doesn't use.
517
+ // 11. The server, in its compute mode, on the endpoint or function URL the live route doesn't
518
+ // use. The other mode's server stays as it is (both cost nothing idle), so switching back or
519
+ // rolling back to a deployment in the other mode finds it.
520
+ const compute = input.webCompute ?? 'instance';
327
521
  let webFunction: DeployStageResult['webFunction'];
328
- if (hasWeb && m.web && input.artifacts.server) {
522
+ let requestFunction: DeployStageResult['requestFunction'];
523
+ if (hasWeb && m.web && input.artifacts.server && compute === 'request') {
524
+ const fnName = names.requestFunction(app, stage);
525
+ const fn = await publishRequestFunction(ctx, {
526
+ name: fnName,
527
+ roleArn,
528
+ code: input.artifacts.server,
529
+ env,
530
+ memoryMb: m.web.memoryMb,
531
+ timeoutSeconds: m.web.timeoutSeconds,
532
+ logGroup: webLogGroup,
533
+ deploymentId,
534
+ description: `${app}/${stage} server (${deploymentId})`,
535
+ tags,
536
+ });
537
+ const alias = await aliasForVersion(ctx, {
538
+ functionName: fnName,
539
+ aliasNames: names.webEndpoints(),
540
+ version: fn.version,
541
+ ...(liveRoute?.c === 'r' && liveRoute.o ? { liveDomain: liveRoute.o } : {}),
542
+ });
543
+ await pruneVersions(ctx, fnName, { keepNewest: DEPLOYMENTS_KEPT, keep: alias.pinned });
544
+ requestFunction = { name: fnName, urlDomain: alias.domainName, version: fn.version };
545
+ resources.push({ type: 'function', name: fnName, arn: fn.arn });
546
+ } else if (hasWeb && m.web && input.artifacts.server) {
329
547
  const fnName = names.webFunction(app, stage);
330
548
  const revision = {
331
549
  functionName: fnName,
@@ -338,10 +556,11 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
338
556
  logGroup: webLogGroup,
339
557
  description: deploymentId,
340
558
  };
559
+ const maxEnvironments = webMaxEnvironments(m.web, stage);
341
560
  const fn = await ensureWebFunction(ctx, {
342
561
  name: fnName,
343
562
  tags,
344
- initial: { revision, endpointName: names.webEndpoints()[0] },
563
+ initial: { revision, endpointName: names.webEndpoints()[0], maxEnvironments },
345
564
  });
346
565
  const fnArn = fn.arn;
347
566
  const revisionId = fn.initialRevisionId ?? (await createRevision(ctx, revision));
@@ -350,7 +569,8 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
350
569
  functionArn: fnArn,
351
570
  endpointNames: names.webEndpoints(),
352
571
  revisionId,
353
- ...(liveRoute?.o ? { liveDomain: liveRoute.o } : {}),
572
+ maxEnvironments,
573
+ ...(liveRoute?.o && liveRoute.c !== 'r' ? { liveDomain: liveRoute.o } : {}),
354
574
  ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
355
575
  });
356
576
  await pruneRevisions(ctx, fnName, { keepNewest: DEPLOYMENTS_KEPT, keep: endpoint.pinned });
@@ -358,20 +578,40 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
358
578
  resources.push({ type: 'web-function', name: fnName, arn: fnArn });
359
579
  } else if (webMode === 'function') {
360
580
  await deleteWebFunction(ctx, names.webFunction(app, stage));
581
+ await deleteFunction(ctx, names.requestFunction(app, stage));
361
582
  }
583
+ const server = webFunction
584
+ ? { o: webFunction.endpointDomain }
585
+ : requestFunction
586
+ ? { o: requestFunction.urlDomain, c: 'r' as const, k: await originSecret(stageKey) }
587
+ : undefined;
362
588
 
363
- // 12. Route flip — the only step that changes what users see.
589
+ // 11b. Every service that should run is running (a failed rollout fails the deploy here).
590
+ if (platform.containers && rollouts.length)
591
+ await awaitServiceRollouts(ctx, { cluster: platform.containers.cluster, rollouts });
592
+
593
+ // 12. Route flip — the only step that changes what users see. A stage with public stores is
594
+ // routed even without web, so its files have a host.
364
595
  let route: RouteRecord | undefined;
365
- if (webMode === 'function' && (webFunction || staticPrefix)) {
596
+ if (webMode === 'function' && (server || staticPrefix || servedStores.length)) {
366
597
  route = {
367
598
  v: 1,
368
599
  app,
369
600
  stage,
370
601
  d: deploymentId,
371
- ...(webFunction ? { o: webFunction.endpointDomain } : {}),
602
+ ...server,
372
603
  ...(staticPrefix ? { s: staticPrefix } : {}),
373
- ...(webFunction && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
604
+ ...(server && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
374
605
  ...(staticPrefix ? { spa: m.web?.spa === false ? (0 as const) : (1 as const) } : {}),
606
+ ...(realtime
607
+ ? {
608
+ rt: {
609
+ n: realtime.namespace,
610
+ m: realtime.subscribe === 'signed-in' ? ('s' as const) : ('p' as const),
611
+ },
612
+ }
613
+ : {}),
614
+ ...(servedStores.length ? { p: servedStores } : {}),
375
615
  };
376
616
  if (platform.kvsArn) {
377
617
  await putRoute(ctx, platform.kvsArn, host, route);
@@ -379,6 +619,10 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
379
619
  } else {
380
620
  ctx.log('warn', 'platform has no route store; skipping route flip', `route ${host}`);
381
621
  }
622
+ } else if (liveRoute && platform.kvsArn) {
623
+ // Nothing left to serve (no server, files or public stores): the host stops answering.
624
+ await deleteRoute(ctx, platform.kvsArn, host);
625
+ ctx.log('info', 'nothing to serve; removed the route', `route ${host}`);
382
626
  }
383
627
 
384
628
  // 13. Garbage-collect old static deployments.
@@ -389,12 +633,27 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
389
633
  }
390
634
  }
391
635
 
392
- // 14. Queues removed from the manifest.
393
- const wantedQueues = new Set(
394
- Object.keys(m.queues).flatMap((k) => [names.queue(app, stage, k), names.deadLetterQueue(app, stage, k)]),
395
- );
396
- for (const q of await listQueues(ctx, `${base}--`)) {
397
- if (!wantedQueues.has(q.name)) await deleteQueue(ctx, q.name);
636
+ // 13b. Services removed from the manifest, and old builds of the rest. Kept: the newest few
637
+ // deployments' builds, the one each service ran before this deploy and the previously live one
638
+ // (rollback targets).
639
+ if (servicesOnEcs && platform.containers) {
640
+ await pruneServices(ctx, {
641
+ app,
642
+ stage,
643
+ services: m.services,
644
+ containers: platform.containers,
645
+ keep: [deploymentId, liveRoute?.d],
646
+ keepTaskDefinitions: rollouts.flatMap((r) => r.previousTaskDefinition ?? []),
647
+ kept: DEPLOYMENTS_KEPT,
648
+ });
649
+ // The group holds crons and jobs' retries and delayed sends while there's a worker.
650
+ if (!hasWorker) await deleteScheduleGroupIfEmpty(ctx, names.scheduleGroup(app, stage));
651
+ }
652
+
653
+ // 14. Realtime removed from the manifest: the route no longer advertises it, so the namespace
654
+ // can go (open connections to it are dropped by AppSync).
655
+ if (!m.realtime && platform.realtime) {
656
+ await deleteChannelNamespace(ctx, platform.realtime.apiId, names.realtimeNamespace(app, stage));
398
657
  }
399
658
 
400
659
  ctx.log('info', `deployed ${app}/${stage} → ${url}`);
@@ -403,78 +662,233 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
403
662
  host,
404
663
  url,
405
664
  ...(route ? { route } : {}),
665
+ ...(server ? { compute } : {}),
406
666
  ...(webFunction ? { webFunction } : {}),
667
+ ...(requestFunction ? { requestFunction } : {}),
407
668
  ...(workerFunction ? { workerFunction } : {}),
669
+ ...(services ? { services } : {}),
408
670
  resources,
409
671
  };
410
672
  }
411
673
 
674
+ /**
675
+ * A stage's SES tenant and configuration set (both `names.emailTenant`),
676
+ * associated with the platform's domain, and the bindings the SDK sends
677
+ * with. Under `plat dev` and `plat test` the same resources exist in the
678
+ * emulator, but the SDK hands mail to the CLI instead of sending (`local`).
679
+ *
680
+ * When `email` leaves the manifest the role loses its grant
681
+ * (stageRolePolicy), but the tenant and its configuration set stay, like a
682
+ * table when `db` goes: the tenant holds the stage's suppression list and any
683
+ * pause SES put on it, and recreating it later would start both over.
684
+ */
685
+ export async function reconcileStageEmail(
686
+ ctx: EngineContext,
687
+ p: {
688
+ app: string;
689
+ stage: string;
690
+ manifest: Pick<ResolvedManifest, 'email'>;
691
+ platform: Pick<PlatformRuntimeConfig, 'target' | 'telemetryTable' | 'email'>;
692
+ tags: Record<string, string>;
693
+ resources: ResourceRef[];
694
+ },
695
+ ): Promise<EmailBindings | undefined> {
696
+ const { app, stage, platform } = p;
697
+ const declared = p.manifest.email;
698
+ const name = names.emailTenant(app, stage);
699
+ // A platform without a mail domain can't have created a tenant (deployStage refuses `email`
700
+ // there), and its control plane may not call SES at all.
701
+ if (!platform.email) return undefined;
702
+ if (!declared) {
703
+ if (await getTenant(ctx, name))
704
+ ctx.log(
705
+ 'warn',
706
+ 'email is off in plat.config.ts but the SES tenant still exists; keeping it (suppression list, sending status)',
707
+ `email-tenant ${name}`,
708
+ );
709
+ return undefined;
710
+ }
711
+ const configurationSet = await ensureConfigurationSet(ctx, { name, tags: p.tags });
712
+ const tenant = await ensureTenant(ctx, { name, tags: p.tags });
713
+ await ensureTenantResources(ctx, name, [platform.email.identityArn, configurationSet.arn]);
714
+ p.resources.push(
715
+ { type: 'email-tenant', name, arn: tenant.arn },
716
+ { type: 'configuration-set', name, arn: configurationSet.arn },
717
+ );
718
+ return {
719
+ mode: platform.target === 'emulator' ? 'local' : 'ses',
720
+ from: emailFromAddress(app, stage, platform.email.domain),
721
+ ...(declared.name ? { name: declared.name } : {}),
722
+ tenant: name,
723
+ dailyLimit: emailDailyLimit(stage, declared.dailyLimit),
724
+ usageTable: platform.telemetryTable,
725
+ };
726
+ }
727
+
728
+ /** Destroy: the tenant (associations first), then its configuration set. */
729
+ async function deleteStageEmail(ctx: EngineContext, name: string): Promise<void> {
730
+ await deleteTenant(ctx, name);
731
+ await deleteConfigurationSet(ctx, name);
732
+ }
733
+
734
+ /**
735
+ * A public store's files live under the public prefix and a private one's
736
+ * don't (see core `storage.ts`), so a store can't switch once it has files:
737
+ * the files would stay where the other kind is read, and moving them while
738
+ * the live deployment still writes there could lose some. Whether a store is
739
+ * public now is what the live route serves; without one, nothing is.
740
+ */
741
+ async function assertStoreVisibility(
742
+ ctx: EngineContext,
743
+ p: {
744
+ app: string;
745
+ stage: string;
746
+ manifest: ResolvedManifest;
747
+ platform: PlatformRuntimeConfig;
748
+ liveRoute: RouteRecord | undefined;
749
+ },
750
+ ): Promise<void> {
751
+ const served = new Set(p.liveRoute?.p ?? []);
752
+ const wanted = new Set(publicStores(p.manifest));
753
+ for (const store of p.manifest.storage) {
754
+ const wasPublic = served.has(store);
755
+ if (wasPublic === wanted.has(store)) continue;
756
+ const prefix = wasPublic
757
+ ? names.publicStoragePrefix(p.app, p.stage, store)
758
+ : names.storagePrefix(p.app, p.stage, store);
759
+ if (!(await hasObjects(ctx, p.platform.storageBucket, prefix))) continue;
760
+ const was = wasPublic ? 'public' : 'private';
761
+ const now = wasPublic ? 'private' : 'public';
762
+ throw new Error(
763
+ `store "${store}" has files from when it was ${was}, and a store with files can't become ${now}: ` +
764
+ `declare a new store in plat.config.ts for the ${now} files`,
765
+ );
766
+ }
767
+ }
768
+
769
+ /** Delete files not written for their store's `expireAfterDays`; answers how many, by store. */
770
+ export async function expireStorage(
771
+ ctx: EngineContext,
772
+ input: ExpireStorageInput,
773
+ ): Promise<Record<string, number>> {
774
+ const { app, stage, platform, manifest: m } = input;
775
+ const now = input.now ?? new Date();
776
+ const deleted: Record<string, number> = {};
777
+ for (const store of m.storage) {
778
+ const options = m.storageOptions[store];
779
+ if (!options?.expireAfterDays) continue;
780
+ const prefix = options.public
781
+ ? names.publicStoragePrefix(app, stage, store)
782
+ : names.storagePrefix(app, stage, store);
783
+ const cutoff = new Date(now.getTime() - options.expireAfterDays * 86_400_000);
784
+ deleted[store] = await deleteObjectsOlderThan(ctx, platform.storageBucket, prefix, cutoff);
785
+ if (deleted[store]) ctx.log('info', `deleted ${deleted[store]} expired files`, `store ${prefix}`);
786
+ }
787
+ return deleted;
788
+ }
789
+
790
+ /** Waits for every promise, then fails with the first failure, so nothing runs on after a deploy fails. */
791
+ async function settleAll<T>(promises: Array<Promise<T>>): Promise<T[]> {
792
+ const results = await Promise.allSettled(promises);
793
+ const failed = results.find((r) => r.status === 'rejected');
794
+ if (failed) throw failed.reason;
795
+ return results.map((r) => (r as PromiseFulfilledResult<T>).value);
796
+ }
797
+
798
+ /**
799
+ * Points each event subscription and cron at the function its handler runs
800
+ * in, keeps draining pre-0.4.0 queues that still hold messages, then removes
801
+ * handler functions no longer declared. A trigger reaches its new function
802
+ * before it leaves the old one. Queue messages need no trigger: the SDK
803
+ * invokes the function directly.
804
+ */
412
805
  async function reconcileWorkerTriggers(
413
806
  ctx: EngineContext,
414
807
  p: {
415
808
  app: string;
416
809
  stage: string;
417
810
  manifest: ResolvedManifest;
418
- workerName: string;
419
- workerArn: string;
811
+ /** The worker's function, then each handler's own. */
812
+ functions: FunctionState[];
420
813
  roleArn: string;
421
814
  busName: string;
422
- queues: Bindings['queues'];
815
+ /** The stage's dead-letter queue: where triggers send what they couldn't deliver. */
816
+ deadLetterArn: string;
817
+ /** Pre-0.4.0 queues still holding messages, by key. */
818
+ draining: ReadonlyArray<{ key: string; url: string; arn: string }>;
423
819
  tags: Record<string, string>;
424
820
  resources: ResourceRef[];
425
821
  },
426
822
  ): Promise<void> {
427
823
  const { app, stage, manifest: m } = p;
428
824
  const base = names.base(app, stage);
825
+ const arns = new Map(p.functions.map((f) => [f.name, f.arn]));
826
+ const target = (kind: HandlerKind, name: string) => {
827
+ const fn = handlerFunctionName(app, stage, m, kind, name);
828
+ return { name: fn, arn: arns.get(fn)! };
829
+ };
830
+ const stale = (await listWorkerFunctions(ctx, app, stage)).filter((f) => !arns.has(f.name));
429
831
 
430
- // Queue → worker mappings.
431
- const wantedSources = new Set<string>();
432
- for (const [key, q] of Object.entries(m.queues)) {
433
- const source = p.queues[key]!.arn;
434
- wantedSources.add(source);
435
- await ensureEventSourceMapping(ctx, {
436
- functionName: p.workerName,
437
- sourceArn: source,
438
- batchSize: q.batchSize,
439
- ...(q.concurrency ? { maxConcurrency: q.concurrency } : {}),
440
- });
441
- p.resources.push({ type: 'esm', name: `${key} → worker` });
832
+ // Pre-0.4.0 queue → function mappings, while their queues drain.
833
+ const wantedMappings = new Set<string>();
834
+ for (const q of p.draining) {
835
+ const fn = target('queue', q.key);
836
+ wantedMappings.add(`${fn.name} ${q.arn}`);
837
+ // Lambda refuses a mapping whose queue hides a message for less than the function may run; the
838
+ // handler's timeout can have grown since the queue was made. 6× is AWS's advice.
839
+ const timeout = handlerSettings(m, 'queue', q.key).timeoutSeconds;
840
+ await setQueueAttributes(ctx, q.url, { VisibilityTimeout: String(Math.min(timeout * 6, 43_200)) });
841
+ await ensureEventSourceMapping(ctx, { functionName: fn.name, sourceArn: q.arn, batchSize: 10 });
842
+ p.resources.push({ type: 'esm', name: `${q.key} → ${fn.name} (draining)` });
442
843
  }
443
- for (const esm of await listEventSourceMappings(ctx, p.workerName)) {
444
- if (!wantedSources.has(esm.sourceArn)) await deleteEventSourceMapping(ctx, esm.uuid);
844
+ for (const fn of [...p.functions, ...stale]) {
845
+ for (const esm of await listEventSourceMappings(ctx, fn.name)) {
846
+ if (!wantedMappings.has(`${fn.name} ${esm.sourceArn}`)) await deleteEventSourceMapping(ctx, esm.uuid);
847
+ }
445
848
  }
446
849
 
447
850
  // Event subscriptions → rules on the stage bus.
448
851
  const wantedRules = new Set<string>();
852
+ const wantedGrants = new Set<string>();
449
853
  for (const type of m.events) {
854
+ const fn = target('event', type);
450
855
  const ruleName = names.eventRule(app, stage, type);
451
856
  wantedRules.add(ruleName);
857
+ const sid = statementId('events', ruleName);
858
+ wantedGrants.add(`${fn.name} ${sid}`);
452
859
  const ruleArn = await ensureRule(ctx, {
453
860
  bus: p.busName,
454
861
  name: ruleName,
455
862
  pattern: { 'detail-type': [type] },
456
- targets: [{ id: 'worker', arn: p.workerArn }],
863
+ targets: [{ id: 'worker', arn: fn.arn, deadLetterArn: p.deadLetterArn }],
457
864
  tags: p.tags,
458
- });
459
- await ensurePermission(ctx, {
460
- functionName: p.workerName,
461
- statementId: statementId('events', ruleName),
462
- principal: 'events.amazonaws.com',
463
- action: 'lambda:InvokeFunction',
464
- sourceArn: ruleArn,
865
+ beforeTargets: (arn) =>
866
+ ensurePermission(ctx, {
867
+ functionName: fn.name,
868
+ statementId: sid,
869
+ principal: 'events.amazonaws.com',
870
+ action: 'lambda:InvokeFunction',
871
+ sourceArn: arn,
872
+ }),
465
873
  });
466
874
  p.resources.push({ type: 'rule', name: ruleName, arn: ruleArn });
467
875
  }
468
876
  for (const rule of await listRules(ctx, p.busName, `${base}--`)) {
469
- if (wantedRules.has(rule)) continue;
470
- await deleteRule(ctx, p.busName, rule);
471
- await removePermission(ctx, p.workerName, statementId('events', rule));
877
+ if (!wantedRules.has(rule)) await deleteRule(ctx, p.busName, rule);
878
+ }
879
+ // Grants for rules that are gone or now target another function.
880
+ for (const fn of p.functions) {
881
+ for (const sid of await listPermissionIds(ctx, fn.name)) {
882
+ if (sid.startsWith('events-') && !wantedGrants.has(`${fn.name} ${sid}`))
883
+ await removePermission(ctx, fn.name, sid);
884
+ }
472
885
  }
473
886
 
474
- // Crons → schedules (EventBridge Scheduler invokes the worker with the stage role).
887
+ // Crons → schedules (EventBridge Scheduler invokes the function with the stage role).
888
+ // The group also holds jobs' retries and delayed sends, so it exists whenever there's a worker.
475
889
  const group = names.scheduleGroup(app, stage);
476
890
  const cronKeys = Object.keys(m.crons);
477
- if (cronKeys.length) await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
891
+ await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
478
892
  for (const [key, cron] of Object.entries(m.crons)) {
479
893
  await ensureSchedule(ctx, {
480
894
  group,
@@ -482,28 +896,183 @@ async function reconcileWorkerTriggers(
482
896
  expression: toSchedulerExpression(cron.schedule),
483
897
  ...(cron.timezone ? { timezone: cron.timezone } : {}),
484
898
  target: {
485
- arn: p.workerArn,
899
+ arn: target('cron', key).arn,
486
900
  roleArn: p.roleArn,
487
901
  input: JSON.stringify({ __platform: 'cron', name: key }),
488
902
  },
903
+ deadLetterArn: p.deadLetterArn,
489
904
  });
490
905
  p.resources.push({ type: 'schedule', name: `${group}/${key}` });
491
906
  }
492
- const existing = await listSchedules(ctx, group);
493
- for (const s of existing) if (!cronKeys.includes(s)) await deleteSchedule(ctx, group, s);
494
- if (!cronKeys.length && existing.length) await deleteScheduleGroup(ctx, group);
907
+ for (const s of await listSchedules(ctx, group))
908
+ if (isCronSchedule(s) && !cronKeys.includes(s)) await deleteSchedule(ctx, group, s);
909
+
910
+ // Nothing triggers these any more.
911
+ for (const fn of stale) await deleteWorkerFunction(ctx, fn.name);
495
912
  }
496
913
 
497
- /** The manifest no longer has a worker: remove it and everything that targets it. */
914
+ /**
915
+ * The manifest no longer has a worker: remove its functions, everything that
916
+ * targets them, and jobs waiting for them. Services' stop schedules stay (and
917
+ * with them the group).
918
+ */
498
919
  async function removeWorker(ctx: EngineContext, app: string, stage: string): Promise<void> {
499
- const workerName = names.workerFunction(app, stage);
500
- await deleteScheduleGroup(ctx, names.scheduleGroup(app, stage));
920
+ const group = names.scheduleGroup(app, stage);
921
+ const schedules = await listSchedules(ctx, group);
922
+ for (const s of schedules) if (isCronSchedule(s) || isJobSchedule(s)) await deleteSchedule(ctx, group, s);
923
+ await deleteScheduleGroupIfEmpty(ctx, group);
501
924
  const bus = names.eventBus(app, stage);
502
925
  for (const rule of await listRules(ctx, bus, `${names.base(app, stage)}--`))
503
926
  await deleteRule(ctx, bus, rule);
504
- for (const esm of await listEventSourceMappings(ctx, workerName))
505
- await deleteEventSourceMapping(ctx, esm.uuid);
506
- await deleteFunction(ctx, workerName);
927
+ for (const fn of await listWorkerFunctions(ctx, app, stage)) await deleteWorkerFunction(ctx, fn.name);
928
+ }
929
+
930
+ /**
931
+ * The worker's function and its handlers' own: every function under the
932
+ * stage's base but the request-mode server (`names.requestFunction`).
933
+ */
934
+ async function listWorkerFunctions(ctx: EngineContext, app: string, stage: string) {
935
+ const server = names.requestFunction(app, stage);
936
+ return (await listFunctions(ctx, `${names.base(app, stage)}--`)).filter((f) => f.name !== server);
937
+ }
938
+
939
+ /**
940
+ * The stage's dead-letter queue: kept 14 days, never polled. Lambda's
941
+ * on-failure destination and Scheduler send to it as the stage role;
942
+ * EventBridge, which has no role here, needs the queue's policy, scoped to
943
+ * this stage's rules.
944
+ */
945
+ async function ensureDeadLetterQueue(
946
+ ctx: EngineContext,
947
+ p: { app: string; stage: string; region: string; accountId: string; tags: Record<string, string> },
948
+ ) {
949
+ const name = names.deadLetters(p.app, p.stage);
950
+ const arn = `arn:aws:sqs:${p.region}:${p.accountId}:${name}`;
951
+ return ensureQueue(ctx, {
952
+ name,
953
+ attributes: {
954
+ MessageRetentionPeriod: String(14 * 24 * 3600),
955
+ Policy: JSON.stringify({
956
+ Version: '2012-10-17',
957
+ Statement: [
958
+ {
959
+ Sid: 'StageRules',
960
+ Effect: 'Allow',
961
+ Principal: { Service: 'events.amazonaws.com' },
962
+ Action: 'sqs:SendMessage',
963
+ Resource: arn,
964
+ Condition: {
965
+ ArnLike: {
966
+ 'aws:SourceArn': `arn:aws:events:${p.region}:${p.accountId}:rule/${names.eventBus(p.app, p.stage)}/${names.base(p.app, p.stage)}--*`,
967
+ },
968
+ },
969
+ },
970
+ ],
971
+ }),
972
+ },
973
+ tags: p.tags,
974
+ });
975
+ }
976
+
977
+ interface LegacyQueues {
978
+ /** Queues whose handler is still declared and that still hold messages: they keep their mapping. */
979
+ draining: Array<{ key: string; name: string; url: string; arn: string }>;
980
+ /** Every other pre-0.4.0 queue and dead-letter queue of the stage. */
981
+ rest: Array<{ name: string; url: string; deadLetters: boolean }>;
982
+ }
983
+
984
+ /**
985
+ * The stage's queues from before jobs were pushed (0.4.0): `<base>--<key>`
986
+ * and `<base>--<key>--dlq`. Everything else under the base is the stage's
987
+ * dead-letter queue or `plat dev`'s event tap.
988
+ */
989
+ async function listLegacyQueues(
990
+ ctx: EngineContext,
991
+ p: { app: string; stage: string; manifest: ResolvedManifest; region: string; accountId: string },
992
+ ): Promise<LegacyQueues> {
993
+ const { app, stage, manifest: m } = p;
994
+ const base = names.base(app, stage);
995
+ const out: LegacyQueues = { draining: [], rest: [] };
996
+ for (const q of await listQueues(ctx, `${base}--`)) {
997
+ if (q.name === names.deadLetters(app, stage) || q.name === names.devEventTap(app, stage)) continue;
998
+ const suffix = q.name.slice(base.length + 2);
999
+ const deadLetters = suffix.endsWith('--dlq');
1000
+ const key = deadLetters ? suffix.slice(0, -5) : suffix;
1001
+ if (!RESOURCE_KEY_PATTERN.test(key)) continue;
1002
+ if (!deadLetters && m.worker && m.queues[key] && ((await queueDepth(ctx, q.url)) ?? 0) > 0) {
1003
+ const arn = `arn:aws:sqs:${p.region}:${p.accountId}:${q.name}`;
1004
+ out.draining.push({ key, name: q.name, url: q.url, arn });
1005
+ continue;
1006
+ }
1007
+ out.rest.push({ name: q.name, url: q.url, deadLetters });
1008
+ }
1009
+ return out;
1010
+ }
1011
+
1012
+ /**
1013
+ * After the triggers moved: pre-0.4.0 dead-letter queues' messages move into
1014
+ * the stage's dead-letter queue (where the console redrives them), and every
1015
+ * old queue no longer draining is deleted. Without a worker there's nothing to
1016
+ * redrive to, so the stage's dead-letter queue goes too.
1017
+ */
1018
+ async function retireLegacyQueues(
1019
+ ctx: EngineContext,
1020
+ p: {
1021
+ app: string;
1022
+ stage: string;
1023
+ legacy: LegacyQueues;
1024
+ deadLetters: { url: string; arn: string } | undefined;
1025
+ },
1026
+ ): Promise<void> {
1027
+ for (const q of p.legacy.rest) {
1028
+ if (q.deadLetters && p.deadLetters) {
1029
+ const key = q.name.slice(names.base(p.app, p.stage).length + 2, -5);
1030
+ const moved = await moveMessages(ctx, q.url, p.deadLetters.url, (body, receives) =>
1031
+ legacyDeadLetter(key, body, receives),
1032
+ );
1033
+ if (moved)
1034
+ ctx.log(
1035
+ 'info',
1036
+ `moved ${moved} dead letters to ${names.deadLetters(p.app, p.stage)}`,
1037
+ `queue ${q.name}`,
1038
+ );
1039
+ // Messages in flight (someone reading the queue) keep it for the next deploy.
1040
+ if (((await queueDepth(ctx, q.url)) ?? 0) > 0) continue;
1041
+ }
1042
+ await deleteQueue(ctx, q.name);
1043
+ }
1044
+ if (!p.deadLetters) await deleteQueue(ctx, names.deadLetters(p.app, p.stage));
1045
+ }
1046
+
1047
+ /** A pre-0.4.0 dead-lettered message, as the SDK would have dead-lettered it. */
1048
+ export function legacyDeadLetter(queue: string, body: string, receives: number): string {
1049
+ let parsed: unknown = body;
1050
+ try {
1051
+ parsed = JSON.parse(body);
1052
+ } catch {
1053
+ // A body the SDK didn't encode stays a string.
1054
+ }
1055
+ const letter: DeadLetter = {
1056
+ v: 1,
1057
+ job: {
1058
+ __platform: JOB_MARKER,
1059
+ kind: 'queue',
1060
+ name: queue,
1061
+ id: newId('m'),
1062
+ attempt: receives,
1063
+ sentAt: Date.now(),
1064
+ body: parsed,
1065
+ },
1066
+ failedAt: Date.now(),
1067
+ error: { name: 'Unknown', message: 'dead-lettered by the queue this stage had before 0.4.0' },
1068
+ };
1069
+ return JSON.stringify(letter);
1070
+ }
1071
+
1072
+ /** Lambda keeps a function's event source mappings when it deletes the function, so they go first. */
1073
+ async function deleteWorkerFunction(ctx: EngineContext, name: string): Promise<void> {
1074
+ for (const esm of await listEventSourceMappings(ctx, name)) await deleteEventSourceMapping(ctx, esm.uuid);
1075
+ await deleteFunction(ctx, name);
507
1076
  }
508
1077
 
509
1078
  /**
@@ -516,53 +1085,73 @@ async function removeWorker(ctx: EngineContext, app: string, stage: string): Pro
516
1085
  export function staleStaticPrefixes(prefixes: string[], keep: Array<string | undefined>): string[] {
517
1086
  const kept = new Set(keep.filter(Boolean).map((k) => `${k}/`));
518
1087
  // Deployment ids sort by creation time.
519
- return [...prefixes]
520
- .sort()
521
- .reverse()
1088
+ return prefixes
1089
+ .toSorted()
1090
+ .toReversed()
522
1091
  .slice(DEPLOYMENTS_KEPT)
523
1092
  .filter((p) => !kept.has(p));
524
1093
  }
525
1094
 
526
1095
  /**
527
- * Rollback targets lose their files to garbage collection after enough
528
- * deploys. Check before changing anything, so a stage is never pointed at a
529
- * deployment that can no longer serve.
1096
+ * Rollback targets lose their files and builds to garbage collection after
1097
+ * enough deploys. Check before changing anything, so a stage is never
1098
+ * pointed at a deployment that can no longer serve. Returns what the
1099
+ * services go back to.
530
1100
  */
531
- async function assertCanRollBack(ctx: EngineContext, input: RollbackStageInput): Promise<void> {
1101
+ async function assertCanRollBack(
1102
+ ctx: EngineContext,
1103
+ input: RollbackStageInput,
1104
+ ): Promise<ServicesRollback | undefined> {
532
1105
  const { app, stage, platform, route } = input;
533
1106
  const gone = (what: string) => new Error(`deployment ${route.d} can't be rolled back to: ${what}`);
534
1107
  if (route.s && !(await hasObjects(ctx, platform.sitesBucket, `${route.s}/`))) {
535
1108
  throw gone('its static files have been cleaned up');
536
1109
  }
537
- if (input.revisionId) {
1110
+ if (route.o && route.c === 'r') {
1111
+ if (!input.version) throw gone('its server version was not recorded');
1112
+ const state = await getVersionState(ctx, names.requestFunction(app, stage), input.version);
1113
+ if (!state) throw gone('its server version has been cleaned up');
1114
+ if (state !== 'Active') throw gone(`its server version is ${state}`);
1115
+ } else if (input.revisionId) {
538
1116
  const state = await getRevisionState(ctx, names.webFunction(app, stage), input.revisionId);
539
1117
  if (!state) throw gone('its server revision has been cleaned up');
540
1118
  if (state !== 'Active') throw gone(`its server revision is ${state}`);
541
1119
  }
1120
+ return planServicesRollback(ctx, input, gone);
542
1121
  }
543
1122
 
544
1123
  /**
545
- * Point the stage back at an earlier deployment. Its revision usually still
546
- * has an endpoint pinned to it (always for the previous deployment), so the
547
- * route write is the whole switch; otherwise the endpoint the live route
548
- * doesn't use is pointed at it first. Returns the route written: its
549
- * endpoint can differ from the one recorded at deploy time.
1124
+ * Point the stage back at an earlier deployment, in the compute mode it ran
1125
+ * in. Its server build usually still has an endpoint or alias pinned to it
1126
+ * (always for the previous deployment in the same mode), so the route write
1127
+ * is the whole switch; otherwise the one the live route doesn't use is
1128
+ * pointed at it first. Returns the route written: its endpoint or function
1129
+ * URL can differ from the one recorded at deploy time.
550
1130
  */
551
1131
  export async function rollbackStage(ctx: EngineContext, input: RollbackStageInput): Promise<RouteRecord> {
552
1132
  const { app, stage, platform } = input;
553
- await assertCanRollBack(ctx, input);
1133
+ const services = await assertCanRollBack(ctx, input);
1134
+ await applyServicesRollback(ctx, services);
554
1135
  const host = hostFor(platform, app, stage);
555
1136
  let route = input.route;
556
- if (input.revisionId && route.o) {
1137
+ const live = route.o && platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
1138
+ if (route.o && route.c === 'r' && input.version) {
1139
+ const url = await aliasForVersion(ctx, {
1140
+ functionName: names.requestFunction(app, stage),
1141
+ aliasNames: names.webEndpoints(),
1142
+ version: input.version,
1143
+ ...(live?.c === 'r' && live.o ? { liveDomain: live.o } : {}),
1144
+ });
1145
+ route = { ...route, o: url.domainName };
1146
+ } else if (route.o && input.revisionId) {
557
1147
  const functionName = names.webFunction(app, stage);
558
1148
  const fn = await ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName }));
559
- const live = platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
560
1149
  const endpoint = await endpointForRevision(ctx, {
561
1150
  functionName,
562
1151
  functionArn: fn.functionArn!,
563
1152
  endpointNames: names.webEndpoints(),
564
1153
  revisionId: input.revisionId,
565
- ...(live?.o ? { liveDomain: live.o } : {}),
1154
+ ...(live?.o && live.c !== 'r' ? { liveDomain: live.o } : {}),
566
1155
  ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
567
1156
  });
568
1157
  route = { ...route, o: endpoint.domainName };
@@ -581,8 +1170,15 @@ export async function destroyStage(ctx: EngineContext, input: DestroyStageInput)
581
1170
  if (platform.kvsArn) await ignoreNotFound(deleteRoute(ctx, platform.kvsArn, host));
582
1171
  await removeWorker(ctx, app, stage);
583
1172
  await deleteWebFunction(ctx, names.webFunction(app, stage));
1173
+ // Its versions, aliases and function URLs go with it.
1174
+ await deleteFunction(ctx, names.requestFunction(app, stage));
1175
+ if (platform.containers) await destroyServices(ctx, { app, stage, containers: platform.containers });
1176
+ await deleteScheduleGroup(ctx, names.scheduleGroup(app, stage));
584
1177
  for (const q of await listQueues(ctx, `${names.base(app, stage)}--`)) await deleteQueue(ctx, q.name);
585
1178
  await deleteEventBus(ctx, names.eventBus(app, stage));
1179
+ if (platform.realtime)
1180
+ await deleteChannelNamespace(ctx, platform.realtime.apiId, names.realtimeNamespace(app, stage));
1181
+ if (platform.email) await deleteStageEmail(ctx, names.emailTenant(app, stage));
586
1182
  if (platform.userPoolId)
587
1183
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
588
1184
  await deleteRole(ctx, names.role(app, stage));
@@ -593,6 +1189,7 @@ export async function destroyStage(ctx: EngineContext, input: DestroyStageInput)
593
1189
  if (!input.keepData) {
594
1190
  await deleteTable(ctx, names.table(app, stage));
595
1191
  await deletePrefix(ctx, platform.storageBucket, names.storagePrefix(app, stage));
1192
+ await deletePrefix(ctx, platform.storageBucket, names.publicStoragePrefix(app, stage));
596
1193
  await deleteParametersByPath(ctx, names.secretsPath(app, stage));
597
1194
  }
598
1195
  ctx.log('info', `destroyed ${app}/${stage}`);
@@ -611,13 +1208,9 @@ export async function listStageResources(
611
1208
  if (role?.Role) out.push({ type: 'role', name: role.Role.RoleName!, arn: role.Role.Arn! });
612
1209
  const table = await describeTable(ctx, names.table(app, stage));
613
1210
  if (table) out.push({ type: 'table', name: table.TableName!, arn: table.TableArn! });
614
- const worker = await ignoreNotFound(
615
- ctx.clients.lambda.send(
616
- new GetFunctionConfigurationCommand({ FunctionName: names.workerFunction(app, stage) }),
617
- ),
618
- );
619
- if (worker?.FunctionArn)
620
- out.push({ type: 'function', name: worker.FunctionName!, arn: worker.FunctionArn });
1211
+ // The worker's function, its handlers' own and the request-mode server.
1212
+ for (const fn of await listFunctions(ctx, `${names.base(app, stage)}--`))
1213
+ out.push({ type: 'function', name: fn.name, arn: fn.arn });
621
1214
  const web = await ignoreNotFound(
622
1215
  ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName: names.webFunction(app, stage) })),
623
1216
  );
@@ -636,5 +1229,26 @@ export async function listStageResources(
636
1229
  for (const s of await listSchedules(ctx, group)) out.push({ type: 'schedule', name: `${group}/${s}` });
637
1230
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage)))
638
1231
  out.push({ type: 'log-group', name: g });
1232
+ // Found by name like everything else, so this needs no runtime config.
1233
+ const api = await findEventApi(ctx, platformNames.realtimeApi);
1234
+ const ns = api?.apiId
1235
+ ? await getChannelNamespace(ctx, api.apiId, names.realtimeNamespace(app, stage))
1236
+ : undefined;
1237
+ if (ns?.name)
1238
+ out.push({
1239
+ type: 'channel-namespace',
1240
+ name: ns.name,
1241
+ ...(ns.channelNamespaceArn ? { arn: ns.channelNamespaceArn } : {}),
1242
+ });
1243
+ const tenantName = names.emailTenant(app, stage);
1244
+ const tenant = await getTenant(ctx, tenantName);
1245
+ if (tenant) out.push({ type: 'email-tenant', name: tenant.name, arn: tenant.arn });
1246
+ if (await getConfigurationSet(ctx, tenantName))
1247
+ out.push({
1248
+ type: 'configuration-set',
1249
+ name: tenantName,
1250
+ arn: configurationSetArn(ctx.region, await ctx.accountId(), tenantName),
1251
+ });
1252
+ out.push(...(await listServiceResources(ctx, app, stage)));
639
1253
  return out;
640
1254
  }