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