@ericminassian/platform-engine 0.3.0 → 0.4.1

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