@ericminassian/platform-engine 0.3.0 → 0.4.0

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