@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/dist/stage.js CHANGED
@@ -1,24 +1,38 @@
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
- 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';
6
7
  import { deleteUserPoolClient, ensureUserPoolClient } from './drivers/cognito.js';
7
8
  import { deleteTable, describeTable, ensureTable, stageTableSpec } from './drivers/dynamodb.js';
8
9
  import { deleteEventBus, deleteRule, ensureEventBus, ensureRule, listRules } from './drivers/events.js';
9
10
  import { deleteRole, ensureRole } from './drivers/iam.js';
10
- import { deleteRoute, putRoute } from './drivers/kvs.js';
11
- import { deleteEventSourceMapping, deleteFunction, ensureEventSourceMapping, ensureFunction, ensurePermission, listEventSourceMappings, removePermission, } from './drivers/lambda.js';
11
+ import { deleteRoute, getRoute, putRoute } from './drivers/kvs.js';
12
+ import { deleteEventSourceMapping, deleteFunction, ensureAsyncConfig, ensureEventSourceMapping, ensureFunction, ensurePermission, listEventSourceMappings, listFunctions, ensureReservedConcurrency, listPermissionIds, removePermission, } from './drivers/lambda.js';
12
13
  import { deleteLogGroup, ensureLogGroup, listLogGroups } from './drivers/logs.js';
13
- import { deletePrefix, listChildPrefixes, publishStaticZip } from './drivers/s3.js';
14
- import { deleteSchedule, deleteScheduleGroup, ensureSchedule, ensureScheduleGroup, listSchedules, } from './drivers/scheduler.js';
15
- import { deleteQueue, ensureQueue, listQueues } from './drivers/sqs.js';
16
- import { deleteParametersByPath } from './drivers/ssm.js';
17
- import { createRevision, deleteWebFunction, ensureEndpoint, ensureRouterAccess, ensureWebFunction, getEndpoint, pruneRevisions, setEndpointRevision, } from './drivers/web-function.js';
18
- import { stageRolePolicy, stageTrustPolicy } from './policy.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';
19
+ import { deleteParameter, deleteParametersByPath, ensureParameterOnce } from './drivers/ssm.js';
20
+ import { createRevision, deleteWebFunction, endpointForRevision, ensureWebFunction, getRevisionState, pruneRevisions, } from './drivers/web-function.js';
21
+ import { configurationSetArn, stageRolePolicy, stageTrustPolicy } from './policy.js';
22
+ import { applyServicesRollback, awaitServiceRollouts, destroyServices, listServiceResources, planServicesRollback, pruneServices, startServices, } from './services.js';
19
23
  import { ignoreNotFound, stageTags } from './util.js';
20
- /** Static deployments kept per stage (current + previous ones for rollback). */
21
- const STATIC_DEPLOYMENTS_KEPT = 3;
24
+ /**
25
+ * Deployments whose static files and server revision are kept per stage (the
26
+ * newest ones, plus whatever the routes still use), so rollback can reach them.
27
+ */
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);
22
36
  /**
23
37
  * Public host of a stage. Under `plat dev` the `local` stage is simply
24
38
  * `<app>.localhost`; everything else follows `stageHost`.
@@ -34,7 +48,8 @@ function statementId(prefix, name) {
34
48
  /**
35
49
  * Reconcile one stage with its manifest, then flip the route. Ordering keeps
36
50
  * the old deployment serving until everything for the new one is ready:
37
- * 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.
38
53
  */
39
54
  export async function deployStage(ctx, input) {
40
55
  const { manifest: m, stage, platform, deploymentId } = input;
@@ -50,23 +65,54 @@ export async function deployStage(ctx, input) {
50
65
  const host = hostFor(platform, app, stage);
51
66
  const url = publicUrl(platform, host);
52
67
  const retention = input.logRetentionDays ?? (prod ? 30 : 7);
53
- const base = names.base(app, stage);
54
68
  const hasWeb = Boolean(m.web?.server) && webMode === 'function';
55
69
  const hasWorker = Boolean(m.worker);
70
+ const serviceKeys = Object.keys(m.services);
71
+ const servicesOnEcs = (input.servicesMode ?? 'ecs') === 'ecs';
56
72
  const resources = [];
57
73
  const workerName = names.workerFunction(app, stage);
74
+ const servedStores = publicStores(m);
58
75
  if (hasWorker && !input.artifacts.worker)
59
76
  throw new Error('manifest declares a worker but no worker artifact was provided');
60
77
  if (hasWeb && !input.artifacts.server)
61
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
+ }
62
89
  ctx.log('info', `deploying ${app}/${stage} (${deploymentId})`);
63
- // 1. Log groups (retention set before anything writes to them).
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 });
96
+ // 1. Log groups (retention set before anything writes to them). These are all of them: the stage
97
+ // role can't create log groups (see stageRolePolicy).
64
98
  const webLogGroup = names.logGroup(app, stage, 'web');
65
99
  const workerLogGroup = names.logGroup(app, stage, 'worker');
66
- if (hasWeb)
100
+ if (hasWeb) {
67
101
  await ensureLogGroup(ctx, { name: webLogGroup, retentionDays: retention, tags });
102
+ await ensureLogGroup(ctx, {
103
+ name: names.logGroup(app, stage, 'web.local'),
104
+ retentionDays: retention,
105
+ tags,
106
+ });
107
+ }
68
108
  if (hasWorker)
69
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
+ });
70
116
  // 2. Data.
71
117
  let table;
72
118
  if (m.db) {
@@ -77,31 +123,13 @@ export async function deployStage(ctx, input) {
77
123
  else if (await describeTable(ctx, names.table(app, stage))) {
78
124
  ctx.log('warn', 'db is off in plat.config.ts but the table still exists; keeping it (data)', `table ${names.table(app, stage)}`);
79
125
  }
80
- // 3. Queues (dead-letter queue first).
81
- const queues = {};
82
- const workerTimeout = m.worker?.timeoutSeconds ?? 60;
83
- for (const [key, q] of Object.entries(m.queues)) {
84
- const dlq = await ensureQueue(ctx, {
85
- name: names.deadLetterQueue(app, stage, key),
86
- attributes: { MessageRetentionPeriod: String(14 * 24 * 3600) },
87
- tags,
88
- });
89
- let visibility = q.visibilityTimeoutSeconds;
90
- if (visibility < workerTimeout) {
91
- ctx.log('warn', `visibility timeout raised to the worker timeout (${workerTimeout}s)`, `queue ${key}`);
92
- visibility = workerTimeout;
93
- }
94
- const main = await ensureQueue(ctx, {
95
- name: names.queue(app, stage, key),
96
- attributes: {
97
- VisibilityTimeout: String(visibility),
98
- MessageRetentionPeriod: String(4 * 24 * 3600),
99
- RedrivePolicy: JSON.stringify({ deadLetterTargetArn: dlq.arn, maxReceiveCount: q.maxReceiveCount }),
100
- },
101
- tags,
102
- });
103
- queues[key] = { url: main.url, arn: main.arn };
104
- 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 });
105
133
  }
106
134
  // 4. Event bus (always: anything may be published, subscriptions are optional).
107
135
  const busName = names.eventBus(app, stage);
@@ -150,17 +178,67 @@ export async function deployStage(ctx, input) {
150
178
  else if (platform.userPoolId) {
151
179
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
152
180
  }
153
- // 7. Bindings.
181
+ // 7. Stage key. Created once and kept for the stage's life, so db cursors
182
+ // survive redeploys. It goes in the bindings instead of being read from SSM
183
+ // at runtime (no extra call or IAM grant) because it only guards SDK-issued
184
+ // tokens: a leaked key lets someone read or forge cursors, not read data.
185
+ const stageKey = await ensureParameterOnce(ctx, {
186
+ name: names.stageKeyParameter(app, stage),
187
+ secure: true,
188
+ description: `Stage key for ${app}/${stage} (SDK-sealed tokens such as db cursors)`,
189
+ generate: () => randomBytes(32).toString('base64url'),
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 });
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;
154
231
  const bindings = {
155
- v: 1,
232
+ v: 2,
156
233
  app,
157
234
  stage,
158
235
  host,
159
236
  url,
160
237
  revision: deploymentId,
161
238
  region,
239
+ account: acct,
162
240
  ...(table ? { table } : {}),
163
- queues,
241
+ ...(jobs ? { jobs } : {}),
164
242
  bus: { name: busName, arn: busArn },
165
243
  ...(m.storage.length
166
244
  ? {
@@ -168,6 +246,9 @@ export async function deployStage(ctx, input) {
168
246
  bucket: platform.storageBucket,
169
247
  prefix: names.storagePrefix(app, stage),
170
248
  stores: m.storage,
249
+ ...(servedStores.length
250
+ ? { public: servedStores, publicPrefix: names.publicStoragePrefix(app, stage) }
251
+ : {}),
171
252
  },
172
253
  }
173
254
  : {}),
@@ -177,7 +258,10 @@ export async function deployStage(ctx, input) {
177
258
  names: m.secrets,
178
259
  },
179
260
  ...(auth ? { auth } : {}),
261
+ ...(realtime ? { realtime } : {}),
262
+ ...(email ? { email } : {}),
180
263
  ...(hasWorker ? { worker: workerName } : {}),
264
+ stageKey,
181
265
  };
182
266
  const env = {
183
267
  [BINDINGS_ENV]: encodeBindings(bindings),
@@ -185,34 +269,54 @@ export async function deployStage(ctx, input) {
185
269
  ...m.env,
186
270
  ...input.extraEnv,
187
271
  };
188
- // 8. 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).
189
275
  let workerFunction;
190
- if (hasWorker && m.worker && input.artifacts.worker) {
191
- const fn = await ensureFunction(ctx, {
192
- 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,
193
283
  roleArn,
194
284
  runtime: NODE_RUNTIME,
195
285
  handler: 'index.handler',
196
286
  architecture: 'arm64',
197
- memoryMb: m.worker.memoryMb,
198
- timeoutSeconds: m.worker.timeoutSeconds,
199
- code: input.artifacts.worker,
287
+ memoryMb: settings.memoryMb,
288
+ timeoutSeconds: settings.timeoutSeconds,
289
+ code,
200
290
  env,
201
291
  logGroup: workerLogGroup,
202
- description: `${app}/${stage} worker (${deploymentId})`,
292
+ description: `${app}/${stage} ${of} (${deploymentId})`,
203
293
  tags,
204
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];
205
301
  workerFunction = { name: fn.name, arn: fn.arn };
206
- 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
+ }));
207
311
  await reconcileWorkerTriggers(ctx, {
208
312
  app,
209
313
  stage,
210
314
  manifest: m,
211
- workerName,
212
- workerArn: fn.arn,
315
+ functions,
213
316
  roleArn,
214
317
  busName,
215
- queues,
318
+ deadLetterArn: deadLetters.arn,
319
+ draining: legacy.draining,
216
320
  tags,
217
321
  resources,
218
322
  });
@@ -220,7 +324,29 @@ export async function deployStage(ctx, input) {
220
324
  else {
221
325
  await removeWorker(ctx, app, stage);
222
326
  }
223
- // 9. Static files (new prefix per deployment; the old one keeps serving until the route flips).
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
+ }
349
+ // 10. Static files (new prefix per deployment; the old one keeps serving until the route flips).
224
350
  let staticPrefix;
225
351
  if (input.artifacts.static) {
226
352
  staticPrefix = names.sitePrefix(app, stage, deploymentId);
@@ -231,9 +357,37 @@ export async function deployStage(ctx, input) {
231
357
  });
232
358
  resources.push({ type: 'static', name: staticPrefix });
233
359
  }
234
- // 10. Web Function revision → endpoint.
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';
235
364
  let webFunction;
236
- 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) {
237
391
  const fnName = names.webFunction(app, stage);
238
392
  const revision = {
239
393
  functionName: fnName,
@@ -246,46 +400,61 @@ export async function deployStage(ctx, input) {
246
400
  logGroup: webLogGroup,
247
401
  description: deploymentId,
248
402
  };
249
- const before = await getEndpoint(ctx, fnName, names.webEndpoint());
250
- const previous = (before?.revisionWeights ?? []).map((w) => w.revisionId).filter(Boolean);
403
+ const maxEnvironments = webMaxEnvironments(m.web, stage);
251
404
  const fn = await ensureWebFunction(ctx, {
252
405
  name: fnName,
253
406
  tags,
254
- initial: { revision, endpointName: names.webEndpoint() },
407
+ initial: { revision, endpointName: names.webEndpoints()[0], maxEnvironments },
255
408
  });
256
409
  const fnArn = fn.arn;
257
410
  const revisionId = fn.initialRevisionId ?? (await createRevision(ctx, revision));
258
- const endpoint = await ensureEndpoint(ctx, {
411
+ const endpoint = await endpointForRevision(ctx, {
259
412
  functionName: fnName,
260
- endpointName: names.webEndpoint(),
413
+ functionArn: fnArn,
414
+ endpointNames: names.webEndpoints(),
261
415
  revisionId,
416
+ maxEnvironments,
417
+ ...(liveRoute?.o && liveRoute.c !== 'r' ? { liveDomain: liveRoute.o } : {}),
418
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
262
419
  });
263
- if (platform.distributionArn) {
264
- await ensureRouterAccess(ctx, {
265
- functionArn: fnArn,
266
- endpointArn: endpoint.arn,
267
- distributionArn: platform.distributionArn,
268
- });
269
- }
270
- await pruneRevisions(ctx, fnName, { keepNewest: 2, keep: [revisionId, ...previous] });
420
+ await pruneRevisions(ctx, fnName, { keepNewest: DEPLOYMENTS_KEPT, keep: endpoint.pinned });
271
421
  webFunction = { name: fnName, endpointDomain: endpoint.domainName, revisionId };
272
422
  resources.push({ type: 'web-function', name: fnName, arn: fnArn });
273
423
  }
274
424
  else if (webMode === 'function') {
275
425
  await deleteWebFunction(ctx, names.webFunction(app, stage));
426
+ await deleteFunction(ctx, names.requestFunction(app, stage));
276
427
  }
277
- // 11. 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.
278
438
  let route;
279
- if (webMode === 'function' && (webFunction || staticPrefix)) {
439
+ if (webMode === 'function' && (server || staticPrefix || servedStores.length)) {
280
440
  route = {
281
441
  v: 1,
282
442
  app,
283
443
  stage,
284
444
  d: deploymentId,
285
- ...(webFunction ? { o: webFunction.endpointDomain } : {}),
445
+ ...server,
286
446
  ...(staticPrefix ? { s: staticPrefix } : {}),
287
- ...(webFunction && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
447
+ ...(server && staticPrefix ? { r: m.web?.serverRoutes ?? ['/api/'] } : {}),
288
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 } : {}),
289
458
  };
290
459
  if (platform.kvsArn) {
291
460
  await putRoute(ctx, platform.kvsArn, host, route);
@@ -295,22 +464,39 @@ export async function deployStage(ctx, input) {
295
464
  ctx.log('warn', 'platform has no route store; skipping route flip', `route ${host}`);
296
465
  }
297
466
  }
298
- // 12. Garbage-collect old static deployments.
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
+ }
472
+ // 13. Garbage-collect old static deployments.
299
473
  if (staticPrefix) {
300
- const prefixes = (await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`))
301
- .sort()
302
- .reverse();
303
- for (const p of prefixes.slice(STATIC_DEPLOYMENTS_KEPT)) {
304
- if (p.startsWith(staticPrefix))
305
- continue;
474
+ const prefixes = await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`);
475
+ for (const p of staleStaticPrefixes(prefixes, [staticPrefix, liveRoute?.s])) {
306
476
  await deletePrefix(ctx, platform.sitesBucket, p);
307
477
  }
308
478
  }
309
- // 13. Queues removed from the manifest.
310
- const wantedQueues = new Set(Object.keys(m.queues).flatMap((k) => [names.queue(app, stage, k), names.deadLetterQueue(app, stage, k)]));
311
- for (const q of await listQueues(ctx, `${base}--`)) {
312
- if (!wantedQueues.has(q.name))
313
- 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));
314
500
  }
315
501
  ctx.log('info', `deployed ${app}/${stage} → ${url}`);
316
502
  return {
@@ -318,63 +504,183 @@ export async function deployStage(ctx, input) {
318
504
  host,
319
505
  url,
320
506
  ...(route ? { route } : {}),
507
+ ...(server ? { compute } : {}),
321
508
  ...(webFunction ? { webFunction } : {}),
509
+ ...(requestFunction ? { requestFunction } : {}),
322
510
  ...(workerFunction ? { workerFunction } : {}),
511
+ ...(services ? { services } : {}),
323
512
  resources,
324
513
  };
325
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
+ */
326
616
  async function reconcileWorkerTriggers(ctx, p) {
327
617
  const { app, stage, manifest: m } = p;
328
618
  const base = names.base(app, stage);
329
- // Queue → worker mappings.
330
- const wantedSources = new Set();
331
- for (const [key, q] of Object.entries(m.queues)) {
332
- const source = p.queues[key].arn;
333
- wantedSources.add(source);
334
- await ensureEventSourceMapping(ctx, {
335
- functionName: p.workerName,
336
- sourceArn: source,
337
- batchSize: q.batchSize,
338
- ...(q.concurrency ? { maxConcurrency: q.concurrency } : {}),
339
- });
340
- 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)` });
341
636
  }
342
- for (const esm of await listEventSourceMappings(ctx, p.workerName)) {
343
- if (!wantedSources.has(esm.sourceArn))
344
- 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
+ }
345
642
  }
346
643
  // Event subscriptions → rules on the stage bus.
347
644
  const wantedRules = new Set();
645
+ const wantedGrants = new Set();
348
646
  for (const type of m.events) {
647
+ const fn = target('event', type);
349
648
  const ruleName = names.eventRule(app, stage, type);
350
649
  wantedRules.add(ruleName);
650
+ const sid = statementId('events', ruleName);
651
+ wantedGrants.add(`${fn.name} ${sid}`);
351
652
  const ruleArn = await ensureRule(ctx, {
352
653
  bus: p.busName,
353
654
  name: ruleName,
354
655
  pattern: { 'detail-type': [type] },
355
- targets: [{ id: 'worker', arn: p.workerArn }],
656
+ targets: [{ id: 'worker', arn: fn.arn, deadLetterArn: p.deadLetterArn }],
356
657
  tags: p.tags,
357
- });
358
- await ensurePermission(ctx, {
359
- functionName: p.workerName,
360
- statementId: statementId('events', ruleName),
361
- principal: 'events.amazonaws.com',
362
- action: 'lambda:InvokeFunction',
363
- 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
+ }),
364
665
  });
365
666
  p.resources.push({ type: 'rule', name: ruleName, arn: ruleArn });
366
667
  }
367
668
  for (const rule of await listRules(ctx, p.busName, `${base}--`)) {
368
- if (wantedRules.has(rule))
369
- continue;
370
- await deleteRule(ctx, p.busName, rule);
371
- 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
+ }
372
678
  }
373
- // 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.
374
681
  const group = names.scheduleGroup(app, stage);
375
682
  const cronKeys = Object.keys(m.crons);
376
- if (cronKeys.length)
377
- await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
683
+ await ensureScheduleGroup(ctx, { name: group, tags: p.tags });
378
684
  for (const [key, cron] of Object.entries(m.crons)) {
379
685
  await ensureSchedule(ctx, {
380
686
  group,
@@ -382,43 +688,247 @@ async function reconcileWorkerTriggers(ctx, p) {
382
688
  expression: toSchedulerExpression(cron.schedule),
383
689
  ...(cron.timezone ? { timezone: cron.timezone } : {}),
384
690
  target: {
385
- arn: p.workerArn,
691
+ arn: target('cron', key).arn,
386
692
  roleArn: p.roleArn,
387
693
  input: JSON.stringify({ __platform: 'cron', name: key }),
388
694
  },
695
+ deadLetterArn: p.deadLetterArn,
389
696
  });
390
697
  p.resources.push({ type: 'schedule', name: `${group}/${key}` });
391
698
  }
392
- const existing = await listSchedules(ctx, group);
393
- for (const s of existing)
394
- if (!cronKeys.includes(s))
699
+ for (const s of await listSchedules(ctx, group))
700
+ if (isCronSchedule(s) && !cronKeys.includes(s))
395
701
  await deleteSchedule(ctx, group, s);
396
- if (!cronKeys.length && existing.length)
397
- await deleteScheduleGroup(ctx, group);
702
+ // Nothing triggers these any more.
703
+ for (const fn of stale)
704
+ await deleteWorkerFunction(ctx, fn.name);
398
705
  }
399
- /** 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
+ */
400
711
  async function removeWorker(ctx, app, stage) {
401
- const workerName = names.workerFunction(app, stage);
402
- 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);
403
718
  const bus = names.eventBus(app, stage);
404
719
  for (const rule of await listRules(ctx, bus, `${names.base(app, stage)}--`))
405
720
  await deleteRule(ctx, bus, rule);
406
- 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))
407
842
  await deleteEventSourceMapping(ctx, esm.uuid);
408
- await deleteFunction(ctx, workerName);
843
+ await deleteFunction(ctx, name);
409
844
  }
845
+ /**
846
+ * Static prefixes (`<app>/<stage>/<deployment>/`) to delete after a deploy:
847
+ * all but the newest few, never one in `keep`. That includes the prefix the
848
+ * previous route pointed at: edges that haven't picked up the new route
849
+ * still serve it, and it is what a rollback returns to. After a rollback to
850
+ * an earlier deployment it can be older than the newest few.
851
+ */
852
+ export function staleStaticPrefixes(prefixes, keep) {
853
+ const kept = new Set(keep.filter(Boolean).map((k) => `${k}/`));
854
+ // Deployment ids sort by creation time.
855
+ return prefixes
856
+ .toSorted()
857
+ .toReversed()
858
+ .slice(DEPLOYMENTS_KEPT)
859
+ .filter((p) => !kept.has(p));
860
+ }
861
+ /**
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.
866
+ */
867
+ async function assertCanRollBack(ctx, input) {
868
+ const { app, stage, platform, route } = input;
869
+ const gone = (what) => new Error(`deployment ${route.d} can't be rolled back to: ${what}`);
870
+ if (route.s && !(await hasObjects(ctx, platform.sitesBucket, `${route.s}/`))) {
871
+ throw gone('its static files have been cleaned up');
872
+ }
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) {
883
+ const state = await getRevisionState(ctx, names.webFunction(app, stage), input.revisionId);
884
+ if (!state)
885
+ throw gone('its server revision has been cleaned up');
886
+ if (state !== 'Active')
887
+ throw gone(`its server revision is ${state}`);
888
+ }
889
+ return planServicesRollback(ctx, input, gone);
890
+ }
891
+ /**
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.
898
+ */
410
899
  export async function rollbackStage(ctx, input) {
411
900
  const { app, stage, platform } = input;
412
- if (input.revisionId) {
413
- await setEndpointRevision(ctx, {
414
- functionName: names.webFunction(app, stage),
415
- endpointName: names.webEndpoint(),
901
+ const services = await assertCanRollBack(ctx, input);
902
+ await applyServicesRollback(ctx, services);
903
+ const host = hostFor(platform, app, stage);
904
+ let route = input.route;
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) {
916
+ const functionName = names.webFunction(app, stage);
917
+ const fn = await ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName }));
918
+ const endpoint = await endpointForRevision(ctx, {
919
+ functionName,
920
+ functionArn: fn.functionArn,
921
+ endpointNames: names.webEndpoints(),
416
922
  revisionId: input.revisionId,
923
+ ...(live?.o && live.c !== 'r' ? { liveDomain: live.o } : {}),
924
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
417
925
  });
926
+ route = { ...route, o: endpoint.domainName };
418
927
  }
419
928
  if (platform.kvsArn)
420
- await putRoute(ctx, platform.kvsArn, hostFor(platform, app, stage), input.route);
421
- ctx.log('info', `rolled back ${app}/${stage} to ${input.route.d}`);
929
+ await putRoute(ctx, platform.kvsArn, host, route);
930
+ ctx.log('info', `rolled back ${app}/${stage} to ${route.d}`);
931
+ return route;
422
932
  }
423
933
  /** Remove a stage. Order: stop traffic, stop triggers, compute, messaging, identity, then (optionally) data. */
424
934
  export async function destroyStage(ctx, input) {
@@ -429,12 +939,22 @@ export async function destroyStage(ctx, input) {
429
939
  await ignoreNotFound(deleteRoute(ctx, platform.kvsArn, host));
430
940
  await removeWorker(ctx, app, stage);
431
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));
432
947
  for (const q of await listQueues(ctx, `${names.base(app, stage)}--`))
433
948
  await deleteQueue(ctx, q.name);
434
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));
435
954
  if (platform.userPoolId)
436
955
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
437
956
  await deleteRole(ctx, names.role(app, stage));
957
+ await deleteParameter(ctx, names.stageKeyParameter(app, stage));
438
958
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage)))
439
959
  await deleteLogGroup(ctx, g);
440
960
  await deletePrefix(ctx, platform.sitesBucket, `${app}/${stage}/`);
@@ -442,6 +962,7 @@ export async function destroyStage(ctx, input) {
442
962
  if (!input.keepData) {
443
963
  await deleteTable(ctx, names.table(app, stage));
444
964
  await deletePrefix(ctx, platform.storageBucket, names.storagePrefix(app, stage));
965
+ await deletePrefix(ctx, platform.storageBucket, names.publicStoragePrefix(app, stage));
445
966
  await deleteParametersByPath(ctx, names.secretsPath(app, stage));
446
967
  }
447
968
  ctx.log('info', `destroyed ${app}/${stage}`);
@@ -455,9 +976,9 @@ export async function listStageResources(ctx, app, stage) {
455
976
  const table = await describeTable(ctx, names.table(app, stage));
456
977
  if (table)
457
978
  out.push({ type: 'table', name: table.TableName, arn: table.TableArn });
458
- const worker = await ignoreNotFound(ctx.clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: names.workerFunction(app, stage) })));
459
- if (worker?.FunctionArn)
460
- 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 });
461
982
  const web = await ignoreNotFound(ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName: names.webFunction(app, stage) })));
462
983
  if (web?.functionArn)
463
984
  out.push({ type: 'web-function', name: web.functionName, arn: web.functionArn });
@@ -474,6 +995,28 @@ export async function listStageResources(ctx, app, stage) {
474
995
  out.push({ type: 'schedule', name: `${group}/${s}` });
475
996
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage)))
476
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)));
477
1020
  return out;
478
1021
  }
479
1022
  //# sourceMappingURL=stage.js.map