@ericminassian/platform-engine 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/ecr.d.ts +109 -0
  11. package/dist/drivers/ecr.js +303 -0
  12. package/dist/drivers/ecr.js.map +1 -0
  13. package/dist/drivers/ecs.d.ts +163 -0
  14. package/dist/drivers/ecs.js +447 -0
  15. package/dist/drivers/ecs.js.map +1 -0
  16. package/dist/drivers/events.d.ts +10 -0
  17. package/dist/drivers/events.js +13 -1
  18. package/dist/drivers/events.js.map +1 -1
  19. package/dist/drivers/index.d.ts +5 -0
  20. package/dist/drivers/index.js +5 -0
  21. package/dist/drivers/index.js.map +1 -1
  22. package/dist/drivers/kvs.d.ts +3 -0
  23. package/dist/drivers/kvs.js +14 -7
  24. package/dist/drivers/kvs.js.map +1 -1
  25. package/dist/drivers/lambda.d.ts +22 -0
  26. package/dist/drivers/lambda.js +74 -3
  27. package/dist/drivers/lambda.js.map +1 -1
  28. package/dist/drivers/request-function.d.ts +60 -0
  29. package/dist/drivers/request-function.js +167 -0
  30. package/dist/drivers/request-function.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +7 -0
  32. package/dist/drivers/s3.js +31 -0
  33. package/dist/drivers/s3.js.map +1 -1
  34. package/dist/drivers/scheduler.d.ts +24 -0
  35. package/dist/drivers/scheduler.js +60 -5
  36. package/dist/drivers/scheduler.js.map +1 -1
  37. package/dist/drivers/ses.d.ts +77 -0
  38. package/dist/drivers/ses.js +181 -0
  39. package/dist/drivers/ses.js.map +1 -0
  40. package/dist/drivers/sqs.d.ts +11 -0
  41. package/dist/drivers/sqs.js +67 -1
  42. package/dist/drivers/sqs.js.map +1 -1
  43. package/dist/drivers/ssm.d.ts +1 -0
  44. package/dist/drivers/ssm.js +23 -3
  45. package/dist/drivers/ssm.js.map +1 -1
  46. package/dist/drivers/web-function.d.ts +41 -11
  47. package/dist/drivers/web-function.js +62 -8
  48. package/dist/drivers/web-function.js.map +1 -1
  49. package/dist/emulator.js.map +1 -1
  50. package/dist/images.d.ts +104 -0
  51. package/dist/images.js +182 -0
  52. package/dist/images.js.map +1 -0
  53. package/dist/index.d.ts +132 -7
  54. package/dist/index.js +11 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/local.js +222 -7
  57. package/dist/local.js.map +1 -1
  58. package/dist/policy.d.ts +47 -4
  59. package/dist/policy.js +369 -15
  60. package/dist/policy.js.map +1 -1
  61. package/dist/services.d.ts +155 -0
  62. package/dist/services.js +464 -0
  63. package/dist/services.js.map +1 -0
  64. package/dist/stage.d.ts +44 -4
  65. package/dist/stage.js +681 -138
  66. package/dist/stage.js.map +1 -1
  67. package/dist/static.d.ts +1 -1
  68. package/dist/static.js +2 -36
  69. package/dist/static.js.map +1 -1
  70. package/dist/util.d.ts +22 -0
  71. package/dist/util.js +18 -2
  72. package/dist/util.js.map +1 -1
  73. package/package.json +20 -14
  74. package/src/clients.ts +25 -1
  75. package/src/compat.ts +34 -11
  76. package/src/drivers/appsync.ts +220 -0
  77. package/src/drivers/ecr.ts +457 -0
  78. package/src/drivers/ecs.ts +661 -0
  79. package/src/drivers/events.ts +29 -2
  80. package/src/drivers/index.ts +5 -0
  81. package/src/drivers/kvs.ts +21 -12
  82. package/src/drivers/lambda.ts +103 -2
  83. package/src/drivers/request-function.ts +295 -0
  84. package/src/drivers/s3.ts +46 -0
  85. package/src/drivers/scheduler.ts +88 -5
  86. package/src/drivers/ses.ts +267 -0
  87. package/src/drivers/sqs.ts +95 -0
  88. package/src/drivers/ssm.ts +23 -2
  89. package/src/drivers/web-function.ts +108 -17
  90. package/src/emulator.ts +3 -3
  91. package/src/images.ts +254 -0
  92. package/src/index.ts +131 -8
  93. package/src/local.ts +251 -7
  94. package/src/policy.ts +450 -26
  95. package/src/services.ts +663 -0
  96. package/src/stage.ts +839 -153
  97. package/src/static.ts +2 -37
  98. package/src/util.ts +38 -4
package/src/stage.ts CHANGED
@@ -1,6 +1,6 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { DescribeEventBusCommand } from '@aws-sdk/client-eventbridge';
2
3
  import { GetRoleCommand } from '@aws-sdk/client-iam';
3
- import { GetFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
4
4
  import { GetWebFunctionCommand } from '@aws-sdk/client-lambda-web';
5
5
  import {
6
6
  AUTH_ROUTES,
@@ -8,67 +8,149 @@ import {
8
8
  type Bindings,
9
9
  cognitoIssuer,
10
10
  cognitoJwksUri,
11
+ DEFAULT_ATTEMPTS,
12
+ type DeadLetter,
13
+ type EmailBindings,
14
+ emailDailyLimit,
15
+ emailFromAddress,
11
16
  encodeBindings,
17
+ type HandlerKind,
18
+ handlerFunctionName,
19
+ handlerKey,
20
+ handlerSettings,
12
21
  IAM_APP_PATH,
22
+ isJobSchedule,
23
+ JOB_MARKER,
13
24
  LOCAL_STAGE,
14
25
  NODE_RUNTIME,
15
26
  names,
27
+ newId,
28
+ originSecret,
29
+ ownFunctionHandlers,
16
30
  type PlatformRuntimeConfig,
17
31
  PROD_STAGE,
32
+ platformNames,
33
+ publicStores,
18
34
  publicUrl,
35
+ RESOURCE_KEY_PATTERN,
19
36
  type ResolvedManifest,
20
37
  type RouteRecord,
38
+ realtimeEndpoints,
21
39
  stageHost,
22
40
  toSchedulerExpression,
23
41
  validateStageName,
42
+ workerHandlers,
43
+ webMaxEnvironments,
24
44
  } from '@ericminassian/platform-core';
45
+ import {
46
+ deleteChannelNamespace,
47
+ ensureChannelNamespace,
48
+ ensureRealtimePlatform,
49
+ findEventApi,
50
+ getChannelNamespace,
51
+ } from './drivers/appsync.ts';
25
52
  import { deleteUserPoolClient, ensureUserPoolClient } from './drivers/cognito.ts';
26
53
  import { deleteTable, describeTable, ensureTable, stageTableSpec } from './drivers/dynamodb.ts';
27
54
  import { deleteEventBus, deleteRule, ensureEventBus, ensureRule, listRules } from './drivers/events.ts';
28
55
  import { deleteRole, ensureRole } from './drivers/iam.ts';
29
- import { deleteRoute, putRoute } from './drivers/kvs.ts';
56
+ import { deleteRoute, getRoute, putRoute } from './drivers/kvs.ts';
30
57
  import {
31
58
  deleteEventSourceMapping,
32
59
  deleteFunction,
60
+ ensureAsyncConfig,
33
61
  ensureEventSourceMapping,
34
62
  ensureFunction,
35
63
  ensurePermission,
64
+ type FunctionState,
36
65
  listEventSourceMappings,
66
+ listFunctions,
67
+ ensureReservedConcurrency,
68
+ listPermissionIds,
37
69
  removePermission,
38
70
  } from './drivers/lambda.ts';
39
71
  import { deleteLogGroup, ensureLogGroup, listLogGroups } from './drivers/logs.ts';
40
- import { deletePrefix, 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';
41
85
  import {
42
86
  deleteSchedule,
43
87
  deleteScheduleGroup,
88
+ deleteScheduleGroupIfEmpty,
44
89
  ensureSchedule,
45
90
  ensureScheduleGroup,
46
91
  listSchedules,
47
92
  } from './drivers/scheduler.ts';
48
- import { deleteQueue, ensureQueue, listQueues } from './drivers/sqs.ts';
49
- import { deleteParametersByPath } from './drivers/ssm.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';
110
+ import { deleteParameter, deleteParametersByPath, ensureParameterOnce } from './drivers/ssm.ts';
50
111
  import {
51
112
  createRevision,
52
113
  deleteWebFunction,
53
- ensureEndpoint,
54
- ensureRouterAccess,
114
+ endpointForRevision,
55
115
  ensureWebFunction,
56
- getEndpoint,
116
+ getRevisionState,
57
117
  pruneRevisions,
58
- setEndpointRevision,
59
118
  } from './drivers/web-function.ts';
60
119
  import type {
61
120
  DeployStageInput,
62
121
  DeployStageResult,
63
122
  DestroyStageInput,
123
+ ExpireStorageInput,
64
124
  ResourceRef,
65
125
  RollbackStageInput,
66
126
  } from './index.ts';
67
- 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';
68
139
  import { type EngineContext, ignoreNotFound, stageTags } from './util.ts';
69
140
 
70
- /** Static deployments kept per stage (current + previous ones for rollback). */
71
- const STATIC_DEPLOYMENTS_KEPT = 3;
141
+ /**
142
+ * Deployments whose static files and server revision are kept per stage (the
143
+ * newest ones, plus whatever the routes still use), so rollback can reach them.
144
+ */
145
+ const DEPLOYMENTS_KEPT = 3;
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);
72
154
 
73
155
  /**
74
156
  * Public host of a stage. Under `plat dev` the `local` stage is simply
@@ -86,7 +168,8 @@ function statementId(prefix: string, name: string): string {
86
168
  /**
87
169
  * Reconcile one stage with its manifest, then flip the route. Ordering keeps
88
170
  * the old deployment serving until everything for the new one is ready:
89
- * 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.
90
173
  */
91
174
  export async function deployStage(ctx: EngineContext, input: DeployStageInput): Promise<DeployStageResult> {
92
175
  const { manifest: m, stage, platform, deploymentId } = input;
@@ -102,24 +185,65 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
102
185
  const host = hostFor(platform, app, stage);
103
186
  const url = publicUrl(platform, host);
104
187
  const retention = input.logRetentionDays ?? (prod ? 30 : 7);
105
- const base = names.base(app, stage);
106
188
  const hasWeb = Boolean(m.web?.server) && webMode === 'function';
107
189
  const hasWorker = Boolean(m.worker);
190
+ const serviceKeys = Object.keys(m.services);
191
+ const servicesOnEcs = (input.servicesMode ?? 'ecs') === 'ecs';
108
192
  const resources: ResourceRef[] = [];
109
193
  const workerName = names.workerFunction(app, stage);
194
+ const servedStores = publicStores(m);
110
195
 
111
196
  if (hasWorker && !input.artifacts.worker)
112
197
  throw new Error('manifest declares a worker but no worker artifact was provided');
113
198
  if (hasWeb && !input.artifacts.server)
114
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
+ }
115
216
 
116
217
  ctx.log('info', `deploying ${app}/${stage} (${deploymentId})`);
117
218
 
118
- // 1. Log groups (retention set before anything writes to them).
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
+
228
+ // 1. Log groups (retention set before anything writes to them). These are all of them: the stage
229
+ // role can't create log groups (see stageRolePolicy).
119
230
  const webLogGroup = names.logGroup(app, stage, 'web');
120
231
  const workerLogGroup = names.logGroup(app, stage, 'worker');
121
- if (hasWeb) await ensureLogGroup(ctx, { name: webLogGroup, retentionDays: retention, tags });
232
+ if (hasWeb) {
233
+ await ensureLogGroup(ctx, { name: webLogGroup, retentionDays: retention, tags });
234
+ await ensureLogGroup(ctx, {
235
+ name: names.logGroup(app, stage, 'web.local'),
236
+ retentionDays: retention,
237
+ tags,
238
+ });
239
+ }
122
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
+ });
123
247
 
124
248
  // 2. Data.
125
249
  let table: string | undefined;
@@ -135,34 +259,13 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
135
259
  );
136
260
  }
137
261
 
138
- // 3. Queues (dead-letter queue first).
139
- const queues: Bindings['queues'] = {};
140
- const workerTimeout = m.worker?.timeoutSeconds ?? 60;
141
- for (const [key, q] of Object.entries(m.queues)) {
142
- const dlq = await ensureQueue(ctx, {
143
- name: names.deadLetterQueue(app, stage, key),
144
- attributes: { MessageRetentionPeriod: String(14 * 24 * 3600) },
145
- tags,
146
- });
147
- let visibility = q.visibilityTimeoutSeconds;
148
- if (visibility < workerTimeout) {
149
- ctx.log('warn', `visibility timeout raised to the worker timeout (${workerTimeout}s)`, `queue ${key}`);
150
- visibility = workerTimeout;
151
- }
152
- const main = await ensureQueue(ctx, {
153
- name: names.queue(app, stage, key),
154
- attributes: {
155
- VisibilityTimeout: String(visibility),
156
- MessageRetentionPeriod: String(4 * 24 * 3600),
157
- RedrivePolicy: JSON.stringify({ deadLetterTargetArn: dlq.arn, maxReceiveCount: q.maxReceiveCount }),
158
- },
159
- tags,
160
- });
161
- queues[key] = { url: main.url, arn: main.arn };
162
- resources.push(
163
- { type: 'queue', name: main.name, arn: main.arn },
164
- { type: 'queue', name: dlq.name, arn: dlq.arn },
165
- );
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 });
166
269
  }
167
270
 
168
271
  // 4. Event bus (always: anything may be published, subscriptions are optional).
@@ -213,17 +316,74 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
213
316
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
214
317
  }
215
318
 
216
- // 7. Bindings.
319
+ // 7. Stage key. Created once and kept for the stage's life, so db cursors
320
+ // survive redeploys. It goes in the bindings instead of being read from SSM
321
+ // at runtime (no extra call or IAM grant) because it only guards SDK-issued
322
+ // tokens: a leaked key lets someone read or forge cursors, not read data.
323
+ const stageKey = await ensureParameterOnce(ctx, {
324
+ name: names.stageKeyParameter(app, stage),
325
+ secure: true,
326
+ description: `Stage key for ${app}/${stage} (SDK-sealed tokens such as db cursors)`,
327
+ generate: () => randomBytes(32).toString('base64url'),
328
+ });
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
+
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;
217
376
  const bindings: Bindings = {
218
- v: 1,
377
+ v: 2,
219
378
  app,
220
379
  stage,
221
380
  host,
222
381
  url,
223
382
  revision: deploymentId,
224
383
  region,
384
+ account: acct,
225
385
  ...(table ? { table } : {}),
226
- queues,
386
+ ...(jobs ? { jobs } : {}),
227
387
  bus: { name: busName, arn: busArn },
228
388
  ...(m.storage.length
229
389
  ? {
@@ -231,6 +391,9 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
231
391
  bucket: platform.storageBucket,
232
392
  prefix: names.storagePrefix(app, stage),
233
393
  stores: m.storage,
394
+ ...(servedStores.length
395
+ ? { public: servedStores, publicPrefix: names.publicStoragePrefix(app, stage) }
396
+ : {}),
234
397
  },
235
398
  }
236
399
  : {}),
@@ -240,7 +403,10 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
240
403
  names: m.secrets,
241
404
  },
242
405
  ...(auth ? { auth } : {}),
406
+ ...(realtime ? { realtime } : {}),
407
+ ...(email ? { email } : {}),
243
408
  ...(hasWorker ? { worker: workerName } : {}),
409
+ stageKey,
244
410
  };
245
411
  const env = {
246
412
  [BINDINGS_ENV]: encodeBindings(bindings),
@@ -249,42 +415,94 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
249
415
  ...input.extraEnv,
250
416
  };
251
417
 
252
- // 8. 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).
253
421
  let workerFunction: DeployStageResult['workerFunction'];
254
- if (hasWorker && m.worker && input.artifacts.worker) {
255
- const fn = await ensureFunction(ctx, {
256
- name: workerName,
257
- roleArn,
258
- runtime: NODE_RUNTIME,
259
- handler: 'index.handler',
260
- architecture: 'arm64',
261
- memoryMb: m.worker.memoryMb,
262
- timeoutSeconds: m.worker.timeoutSeconds,
263
- code: input.artifacts.worker,
264
- env,
265
- logGroup: workerLogGroup,
266
- description: `${app}/${stage} worker (${deploymentId})`,
267
- tags,
268
- });
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]!;
269
454
  workerFunction = { name: fn.name, arn: fn.arn };
270
- 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
+ );
271
467
  await reconcileWorkerTriggers(ctx, {
272
468
  app,
273
469
  stage,
274
470
  manifest: m,
275
- workerName,
276
- workerArn: fn.arn,
471
+ functions,
277
472
  roleArn,
278
473
  busName,
279
- queues,
474
+ deadLetterArn: deadLetters.arn,
475
+ draining: legacy.draining,
280
476
  tags,
281
477
  resources,
282
478
  });
283
479
  } else {
284
480
  await removeWorker(ctx, app, stage);
285
481
  }
482
+ await retireLegacyQueues(ctx, { app, stage, legacy, deadLetters });
286
483
 
287
- // 9. Static files (new prefix per deployment; the old one keeps serving until the route flips).
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
+ }
505
+ // 10. Static files (new prefix per deployment; the old one keeps serving until the route flips).
288
506
  let staticPrefix: string | undefined;
289
507
  if (input.artifacts.static) {
290
508
  staticPrefix = names.sitePrefix(app, stage, deploymentId);
@@ -296,9 +514,36 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
296
514
  resources.push({ type: 'static', name: staticPrefix });
297
515
  }
298
516
 
299
- // 10. Web Function revision → endpoint.
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';
300
521
  let webFunction: DeployStageResult['webFunction'];
301
- 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) {
302
547
  const fnName = names.webFunction(app, stage);
303
548
  const revision = {
304
549
  functionName: fnName,
@@ -311,46 +556,62 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
311
556
  logGroup: webLogGroup,
312
557
  description: deploymentId,
313
558
  };
314
- const before = await getEndpoint(ctx, fnName, names.webEndpoint());
315
- const previous = (before?.revisionWeights ?? []).map((w) => w.revisionId!).filter(Boolean);
559
+ const maxEnvironments = webMaxEnvironments(m.web, stage);
316
560
  const fn = await ensureWebFunction(ctx, {
317
561
  name: fnName,
318
562
  tags,
319
- initial: { revision, endpointName: names.webEndpoint() },
563
+ initial: { revision, endpointName: names.webEndpoints()[0], maxEnvironments },
320
564
  });
321
565
  const fnArn = fn.arn;
322
566
  const revisionId = fn.initialRevisionId ?? (await createRevision(ctx, revision));
323
- const endpoint = await ensureEndpoint(ctx, {
567
+ const endpoint = await endpointForRevision(ctx, {
324
568
  functionName: fnName,
325
- endpointName: names.webEndpoint(),
569
+ functionArn: fnArn,
570
+ endpointNames: names.webEndpoints(),
326
571
  revisionId,
572
+ maxEnvironments,
573
+ ...(liveRoute?.o && liveRoute.c !== 'r' ? { liveDomain: liveRoute.o } : {}),
574
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
327
575
  });
328
- if (platform.distributionArn) {
329
- await ensureRouterAccess(ctx, {
330
- functionArn: fnArn,
331
- endpointArn: endpoint.arn,
332
- distributionArn: platform.distributionArn,
333
- });
334
- }
335
- await pruneRevisions(ctx, fnName, { keepNewest: 2, keep: [revisionId, ...previous] });
576
+ await pruneRevisions(ctx, fnName, { keepNewest: DEPLOYMENTS_KEPT, keep: endpoint.pinned });
336
577
  webFunction = { name: fnName, endpointDomain: endpoint.domainName, revisionId };
337
578
  resources.push({ type: 'web-function', name: fnName, arn: fnArn });
338
579
  } else if (webMode === 'function') {
339
580
  await deleteWebFunction(ctx, names.webFunction(app, stage));
581
+ await deleteFunction(ctx, names.requestFunction(app, stage));
340
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;
341
588
 
342
- // 11. 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.
343
595
  let route: RouteRecord | undefined;
344
- if (webMode === 'function' && (webFunction || staticPrefix)) {
596
+ if (webMode === 'function' && (server || staticPrefix || servedStores.length)) {
345
597
  route = {
346
598
  v: 1,
347
599
  app,
348
600
  stage,
349
601
  d: deploymentId,
350
- ...(webFunction ? { o: webFunction.endpointDomain } : {}),
602
+ ...server,
351
603
  ...(staticPrefix ? { s: staticPrefix } : {}),
352
- ...(webFunction && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
604
+ ...(server && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
353
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 } : {}),
354
615
  };
355
616
  if (platform.kvsArn) {
356
617
  await putRoute(ctx, platform.kvsArn, host, route);
@@ -358,25 +619,41 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
358
619
  } else {
359
620
  ctx.log('warn', 'platform has no route store; skipping route flip', `route ${host}`);
360
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}`);
361
626
  }
362
627
 
363
- // 12. Garbage-collect old static deployments.
628
+ // 13. Garbage-collect old static deployments.
364
629
  if (staticPrefix) {
365
- const prefixes = (await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`))
366
- .sort()
367
- .reverse();
368
- for (const p of prefixes.slice(STATIC_DEPLOYMENTS_KEPT)) {
369
- if (p.startsWith(staticPrefix)) continue;
630
+ const prefixes = await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`);
631
+ for (const p of staleStaticPrefixes(prefixes, [staticPrefix, liveRoute?.s])) {
370
632
  await deletePrefix(ctx, platform.sitesBucket, p);
371
633
  }
372
634
  }
373
635
 
374
- // 13. Queues removed from the manifest.
375
- const wantedQueues = new Set(
376
- Object.keys(m.queues).flatMap((k) => [names.queue(app, stage, k), names.deadLetterQueue(app, stage, k)]),
377
- );
378
- for (const q of await listQueues(ctx, `${base}--`)) {
379
- 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));
380
657
  }
381
658
 
382
659
  ctx.log('info', `deployed ${app}/${stage} → ${url}`);
@@ -385,78 +662,233 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
385
662
  host,
386
663
  url,
387
664
  ...(route ? { route } : {}),
665
+ ...(server ? { compute } : {}),
388
666
  ...(webFunction ? { webFunction } : {}),
667
+ ...(requestFunction ? { requestFunction } : {}),
389
668
  ...(workerFunction ? { workerFunction } : {}),
669
+ ...(services ? { services } : {}),
390
670
  resources,
391
671
  };
392
672
  }
393
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
+ */
394
805
  async function reconcileWorkerTriggers(
395
806
  ctx: EngineContext,
396
807
  p: {
397
808
  app: string;
398
809
  stage: string;
399
810
  manifest: ResolvedManifest;
400
- workerName: string;
401
- workerArn: string;
811
+ /** The worker's function, then each handler's own. */
812
+ functions: FunctionState[];
402
813
  roleArn: string;
403
814
  busName: string;
404
- 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 }>;
405
819
  tags: Record<string, string>;
406
820
  resources: ResourceRef[];
407
821
  },
408
822
  ): Promise<void> {
409
823
  const { app, stage, manifest: m } = p;
410
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));
411
831
 
412
- // Queue → worker mappings.
413
- const wantedSources = new Set<string>();
414
- for (const [key, q] of Object.entries(m.queues)) {
415
- const source = p.queues[key]!.arn;
416
- wantedSources.add(source);
417
- await ensureEventSourceMapping(ctx, {
418
- functionName: p.workerName,
419
- sourceArn: source,
420
- batchSize: q.batchSize,
421
- ...(q.concurrency ? { maxConcurrency: q.concurrency } : {}),
422
- });
423
- 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)` });
424
843
  }
425
- for (const esm of await listEventSourceMappings(ctx, p.workerName)) {
426
- 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
+ }
427
848
  }
428
849
 
429
850
  // Event subscriptions → rules on the stage bus.
430
851
  const wantedRules = new Set<string>();
852
+ const wantedGrants = new Set<string>();
431
853
  for (const type of m.events) {
854
+ const fn = target('event', type);
432
855
  const ruleName = names.eventRule(app, stage, type);
433
856
  wantedRules.add(ruleName);
857
+ const sid = statementId('events', ruleName);
858
+ wantedGrants.add(`${fn.name} ${sid}`);
434
859
  const ruleArn = await ensureRule(ctx, {
435
860
  bus: p.busName,
436
861
  name: ruleName,
437
862
  pattern: { 'detail-type': [type] },
438
- targets: [{ id: 'worker', arn: p.workerArn }],
863
+ targets: [{ id: 'worker', arn: fn.arn, deadLetterArn: p.deadLetterArn }],
439
864
  tags: p.tags,
440
- });
441
- await ensurePermission(ctx, {
442
- functionName: p.workerName,
443
- statementId: statementId('events', ruleName),
444
- principal: 'events.amazonaws.com',
445
- action: 'lambda:InvokeFunction',
446
- 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
+ }),
447
873
  });
448
874
  p.resources.push({ type: 'rule', name: ruleName, arn: ruleArn });
449
875
  }
450
876
  for (const rule of await listRules(ctx, p.busName, `${base}--`)) {
451
- if (wantedRules.has(rule)) continue;
452
- await deleteRule(ctx, p.busName, rule);
453
- 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
+ }
454
885
  }
455
886
 
456
- // 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.
457
889
  const group = names.scheduleGroup(app, stage);
458
890
  const cronKeys = Object.keys(m.crons);
459
- if (cronKeys.length) await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
891
+ await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
460
892
  for (const [key, cron] of Object.entries(m.crons)) {
461
893
  await ensureSchedule(ctx, {
462
894
  group,
@@ -464,41 +896,269 @@ async function reconcileWorkerTriggers(
464
896
  expression: toSchedulerExpression(cron.schedule),
465
897
  ...(cron.timezone ? { timezone: cron.timezone } : {}),
466
898
  target: {
467
- arn: p.workerArn,
899
+ arn: target('cron', key).arn,
468
900
  roleArn: p.roleArn,
469
901
  input: JSON.stringify({ __platform: 'cron', name: key }),
470
902
  },
903
+ deadLetterArn: p.deadLetterArn,
471
904
  });
472
905
  p.resources.push({ type: 'schedule', name: `${group}/${key}` });
473
906
  }
474
- const existing = await listSchedules(ctx, group);
475
- for (const s of existing) if (!cronKeys.includes(s)) await deleteSchedule(ctx, group, s);
476
- 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);
477
912
  }
478
913
 
479
- /** 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
+ */
480
919
  async function removeWorker(ctx: EngineContext, app: string, stage: string): Promise<void> {
481
- const workerName = names.workerFunction(app, stage);
482
- 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);
483
924
  const bus = names.eventBus(app, stage);
484
925
  for (const rule of await listRules(ctx, bus, `${names.base(app, stage)}--`))
485
926
  await deleteRule(ctx, bus, rule);
486
- for (const esm of await listEventSourceMappings(ctx, workerName))
487
- await deleteEventSourceMapping(ctx, esm.uuid);
488
- await deleteFunction(ctx, workerName);
927
+ for (const fn of await listWorkerFunctions(ctx, app, stage)) await deleteWorkerFunction(ctx, fn.name);
489
928
  }
490
929
 
491
- export async function rollbackStage(ctx: EngineContext, input: RollbackStageInput): Promise<void> {
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);
1076
+ }
1077
+
1078
+ /**
1079
+ * Static prefixes (`<app>/<stage>/<deployment>/`) to delete after a deploy:
1080
+ * all but the newest few, never one in `keep`. That includes the prefix the
1081
+ * previous route pointed at: edges that haven't picked up the new route
1082
+ * still serve it, and it is what a rollback returns to. After a rollback to
1083
+ * an earlier deployment it can be older than the newest few.
1084
+ */
1085
+ export function staleStaticPrefixes(prefixes: string[], keep: Array<string | undefined>): string[] {
1086
+ const kept = new Set(keep.filter(Boolean).map((k) => `${k}/`));
1087
+ // Deployment ids sort by creation time.
1088
+ return prefixes
1089
+ .toSorted()
1090
+ .toReversed()
1091
+ .slice(DEPLOYMENTS_KEPT)
1092
+ .filter((p) => !kept.has(p));
1093
+ }
1094
+
1095
+ /**
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.
1100
+ */
1101
+ async function assertCanRollBack(
1102
+ ctx: EngineContext,
1103
+ input: RollbackStageInput,
1104
+ ): Promise<ServicesRollback | undefined> {
1105
+ const { app, stage, platform, route } = input;
1106
+ const gone = (what: string) => new Error(`deployment ${route.d} can't be rolled back to: ${what}`);
1107
+ if (route.s && !(await hasObjects(ctx, platform.sitesBucket, `${route.s}/`))) {
1108
+ throw gone('its static files have been cleaned up');
1109
+ }
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) {
1116
+ const state = await getRevisionState(ctx, names.webFunction(app, stage), input.revisionId);
1117
+ if (!state) throw gone('its server revision has been cleaned up');
1118
+ if (state !== 'Active') throw gone(`its server revision is ${state}`);
1119
+ }
1120
+ return planServicesRollback(ctx, input, gone);
1121
+ }
1122
+
1123
+ /**
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.
1130
+ */
1131
+ export async function rollbackStage(ctx: EngineContext, input: RollbackStageInput): Promise<RouteRecord> {
492
1132
  const { app, stage, platform } = input;
493
- if (input.revisionId) {
494
- await setEndpointRevision(ctx, {
495
- functionName: names.webFunction(app, stage),
496
- endpointName: names.webEndpoint(),
1133
+ const services = await assertCanRollBack(ctx, input);
1134
+ await applyServicesRollback(ctx, services);
1135
+ const host = hostFor(platform, app, stage);
1136
+ let route = input.route;
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) {
1147
+ const functionName = names.webFunction(app, stage);
1148
+ const fn = await ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName }));
1149
+ const endpoint = await endpointForRevision(ctx, {
1150
+ functionName,
1151
+ functionArn: fn.functionArn!,
1152
+ endpointNames: names.webEndpoints(),
497
1153
  revisionId: input.revisionId,
1154
+ ...(live?.o && live.c !== 'r' ? { liveDomain: live.o } : {}),
1155
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
498
1156
  });
1157
+ route = { ...route, o: endpoint.domainName };
499
1158
  }
500
- if (platform.kvsArn) await putRoute(ctx, platform.kvsArn, hostFor(platform, app, stage), input.route);
501
- ctx.log('info', `rolled back ${app}/${stage} to ${input.route.d}`);
1159
+ if (platform.kvsArn) await putRoute(ctx, platform.kvsArn, host, route);
1160
+ ctx.log('info', `rolled back ${app}/${stage} to ${route.d}`);
1161
+ return route;
502
1162
  }
503
1163
 
504
1164
  /** Remove a stage. Order: stop traffic, stop triggers, compute, messaging, identity, then (optionally) data. */
@@ -510,17 +1170,26 @@ export async function destroyStage(ctx: EngineContext, input: DestroyStageInput)
510
1170
  if (platform.kvsArn) await ignoreNotFound(deleteRoute(ctx, platform.kvsArn, host));
511
1171
  await removeWorker(ctx, app, stage);
512
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));
513
1177
  for (const q of await listQueues(ctx, `${names.base(app, stage)}--`)) await deleteQueue(ctx, q.name);
514
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));
515
1182
  if (platform.userPoolId)
516
1183
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
517
1184
  await deleteRole(ctx, names.role(app, stage));
1185
+ await deleteParameter(ctx, names.stageKeyParameter(app, stage));
518
1186
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage))) await deleteLogGroup(ctx, g);
519
1187
  await deletePrefix(ctx, platform.sitesBucket, `${app}/${stage}/`);
520
1188
  await deletePrefix(ctx, platform.artifactsBucket, `${app}/${stage}/`);
521
1189
  if (!input.keepData) {
522
1190
  await deleteTable(ctx, names.table(app, stage));
523
1191
  await deletePrefix(ctx, platform.storageBucket, names.storagePrefix(app, stage));
1192
+ await deletePrefix(ctx, platform.storageBucket, names.publicStoragePrefix(app, stage));
524
1193
  await deleteParametersByPath(ctx, names.secretsPath(app, stage));
525
1194
  }
526
1195
  ctx.log('info', `destroyed ${app}/${stage}`);
@@ -539,13 +1208,9 @@ export async function listStageResources(
539
1208
  if (role?.Role) out.push({ type: 'role', name: role.Role.RoleName!, arn: role.Role.Arn! });
540
1209
  const table = await describeTable(ctx, names.table(app, stage));
541
1210
  if (table) out.push({ type: 'table', name: table.TableName!, arn: table.TableArn! });
542
- const worker = await ignoreNotFound(
543
- ctx.clients.lambda.send(
544
- new GetFunctionConfigurationCommand({ FunctionName: names.workerFunction(app, stage) }),
545
- ),
546
- );
547
- if (worker?.FunctionArn)
548
- 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 });
549
1214
  const web = await ignoreNotFound(
550
1215
  ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName: names.webFunction(app, stage) })),
551
1216
  );
@@ -564,5 +1229,26 @@ export async function listStageResources(
564
1229
  for (const s of await listSchedules(ctx, group)) out.push({ type: 'schedule', name: `${group}/${s}` });
565
1230
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage)))
566
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)));
567
1253
  return out;
568
1254
  }