@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
@@ -8,14 +8,23 @@ import {
8
8
  ListSchedulesCommand,
9
9
  UpdateScheduleCommand,
10
10
  } from '@aws-sdk/client-scheduler';
11
- import { type EngineContext, ignoreNotFound, retry, tagList } from '../util.ts';
11
+ import { atExpression } from '@ericminassian/platform-core';
12
+ import { type EngineContext, ignoreNotFound, retry, tagList, waitFor } from '../util.ts';
13
+
14
+ export { atExpression };
12
15
 
13
16
  export async function ensureScheduleGroup(
14
17
  ctx: EngineContext,
15
18
  spec: { name: string; tags?: Record<string, string> },
16
19
  ): Promise<string> {
17
20
  const sch = ctx.clients.scheduler;
18
- const existing = await ignoreNotFound(sch.send(new GetScheduleGroupCommand({ Name: spec.name })));
21
+ const get = () => ignoreNotFound(sch.send(new GetScheduleGroupCommand({ Name: spec.name })));
22
+ let existing = await get();
23
+ if (existing?.State === 'DELETING') {
24
+ // Groups are deleted asynchronously; one deleted by the previous deploy may still be going.
25
+ await waitFor(`schedule group ${spec.name} to finish deleting`, async () => !(await get()));
26
+ existing = undefined;
27
+ }
19
28
  if (existing?.Arn) return existing.Arn;
20
29
  const res = await sch.send(
21
30
  new CreateScheduleGroupCommand({ Name: spec.name, Tags: spec.tags ? tagList(spec.tags) : undefined }),
@@ -31,6 +40,8 @@ export interface ScheduleSpec {
31
40
  expression: string;
32
41
  timezone?: string;
33
42
  target: { arn: string; roleArn: string; input: string };
43
+ /** Where a firing Scheduler couldn't deliver goes (the stage's dead-letter queue). */
44
+ deadLetterArn?: string;
34
45
  }
35
46
 
36
47
  export async function ensureSchedule(ctx: EngineContext, spec: ScheduleSpec): Promise<void> {
@@ -47,6 +58,7 @@ export async function ensureSchedule(ctx: EngineContext, spec: ScheduleSpec): Pr
47
58
  RoleArn: spec.target.roleArn,
48
59
  Input: spec.target.input,
49
60
  RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 },
61
+ ...(spec.deadLetterArn ? { DeadLetterConfig: { Arn: spec.deadLetterArn } } : {}),
50
62
  },
51
63
  };
52
64
  const existing = await ignoreNotFound(
@@ -58,11 +70,68 @@ export async function ensureSchedule(ctx: EngineContext, spec: ScheduleSpec): Pr
58
70
  existing
59
71
  ? sch.send(new UpdateScheduleCommand(definition))
60
72
  : sch.send(new CreateScheduleCommand(definition)),
61
- { when: (e) => /assume the role|execution role/i.test(String((e as Error).message)), attempts: 12 },
73
+ { when: (e) => /assume the role|execution role/i.test((e as Error).message), attempts: 12 },
62
74
  );
63
75
  if (!existing) ctx.log('info', 'created schedule', `schedule ${spec.group}/${spec.name}`);
64
76
  }
65
77
 
78
+ export interface OneShotScheduleSpec {
79
+ group: string;
80
+ name: string;
81
+ /** When it fires (to the second, UTC). The schedule deletes itself afterwards. */
82
+ at: Date;
83
+ target: { arn: string; roleArn: string; input: string };
84
+ }
85
+
86
+ /** Inverse of {@link atExpression}. */
87
+ export function parseAtExpression(expression: string | undefined): Date | undefined {
88
+ const m = /^at\((\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\)$/.exec(expression ?? '');
89
+ return m ? new Date(`${m[1]}Z`) : undefined;
90
+ }
91
+
92
+ /** Create or move a schedule that fires once, then deletes itself. */
93
+ export async function ensureOneShotSchedule(ctx: EngineContext, spec: OneShotScheduleSpec): Promise<void> {
94
+ const sch = ctx.clients.scheduler;
95
+ const definition = {
96
+ Name: spec.name,
97
+ GroupName: spec.group,
98
+ ScheduleExpression: atExpression(spec.at),
99
+ ScheduleExpressionTimezone: 'UTC',
100
+ ActionAfterCompletion: 'DELETE' as const,
101
+ FlexibleTimeWindow: { Mode: 'OFF' as const },
102
+ State: 'ENABLED' as const,
103
+ Target: {
104
+ Arn: spec.target.arn,
105
+ RoleArn: spec.target.roleArn,
106
+ Input: spec.target.input,
107
+ RetryPolicy: { MaximumRetryAttempts: 5, MaximumEventAgeInSeconds: 3600 },
108
+ },
109
+ };
110
+ const existing = await ignoreNotFound(
111
+ sch.send(new GetScheduleCommand({ Name: spec.name, GroupName: spec.group })),
112
+ );
113
+ await retry(
114
+ () =>
115
+ existing
116
+ ? sch.send(new UpdateScheduleCommand(definition))
117
+ : sch.send(new CreateScheduleCommand(definition)),
118
+ { when: (e) => /assume the role|execution role/i.test((e as Error).message), attempts: 12 },
119
+ );
120
+ ctx.log('info', `fires at ${spec.at.toISOString()}`, `schedule ${spec.group}/${spec.name}`);
121
+ }
122
+
123
+ /** When a one-shot schedule fires, or undefined when there is none (or it isn't one-shot). */
124
+ export async function getOneShotScheduleTime(
125
+ ctx: EngineContext,
126
+ group: string,
127
+ name: string,
128
+ ): Promise<Date | undefined> {
129
+ const s = await ignoreNotFound(
130
+ ctx.clients.scheduler.send(new GetScheduleCommand({ Name: name, GroupName: group })),
131
+ );
132
+ return parseAtExpression(s?.ScheduleExpression);
133
+ }
134
+
66
135
  export async function listSchedules(ctx: EngineContext, group: string): Promise<string[]> {
67
136
  const out: string[] = [];
68
137
  let NextToken: string | undefined;
@@ -78,13 +147,27 @@ export async function listSchedules(ctx: EngineContext, group: string): Promise<
78
147
  }
79
148
 
80
149
  export async function deleteSchedule(ctx: EngineContext, group: string, name: string): Promise<void> {
81
- await ignoreNotFound(
150
+ const res = await ignoreNotFound(
82
151
  ctx.clients.scheduler.send(new DeleteScheduleCommand({ Name: name, GroupName: group })),
83
152
  );
84
- ctx.log('info', 'deleted schedule', `schedule ${group}/${name}`);
153
+ if (res) ctx.log('info', 'deleted schedule', `schedule ${group}/${name}`);
85
154
  }
86
155
 
156
+ /** Delete the group and every schedule in it. */
87
157
  export async function deleteScheduleGroup(ctx: EngineContext, group: string): Promise<void> {
88
158
  for (const s of await listSchedules(ctx, group)) await deleteSchedule(ctx, group, s);
159
+ const exists = await ignoreNotFound(
160
+ ctx.clients.scheduler.send(new GetScheduleGroupCommand({ Name: group })),
161
+ );
162
+ if (!exists || exists.State === 'DELETING') return;
163
+ await ignoreNotFound(ctx.clients.scheduler.send(new DeleteScheduleGroupCommand({ Name: group })));
164
+ }
165
+
166
+ /** Delete the group if no schedule is left in it. */
167
+ export async function deleteScheduleGroupIfEmpty(ctx: EngineContext, group: string): Promise<void> {
168
+ const exists = await ignoreNotFound(
169
+ ctx.clients.scheduler.send(new GetScheduleGroupCommand({ Name: group })),
170
+ );
171
+ if (!exists || exists.State === 'DELETING' || (await listSchedules(ctx, group)).length) return;
89
172
  await ignoreNotFound(ctx.clients.scheduler.send(new DeleteScheduleGroupCommand({ Name: group })));
90
173
  }
@@ -0,0 +1,267 @@
1
+ import {
2
+ CreateConfigurationSetCommand,
3
+ CreateEmailIdentityCommand,
4
+ CreateTenantCommand,
5
+ CreateTenantResourceAssociationCommand,
6
+ DeleteConfigurationSetCommand,
7
+ DeleteTenantCommand,
8
+ DeleteTenantResourceAssociationCommand,
9
+ GetConfigurationSetCommand,
10
+ type GetConfigurationSetCommandOutput,
11
+ GetEmailIdentityCommand,
12
+ GetTenantCommand,
13
+ ListTenantResourcesCommand,
14
+ PutConfigurationSetReputationOptionsCommand,
15
+ PutTenantSuppressionAttributesCommand,
16
+ type Tag,
17
+ TagResourceCommand,
18
+ type Tenant,
19
+ type TenantSuppressionAttributes,
20
+ } from '@aws-sdk/client-sesv2';
21
+ import { configurationSetArn, emailIdentityArn } from '../policy.ts';
22
+ import { type EngineContext, ignoreNotFound, tagList } from '../util.ts';
23
+
24
+ /**
25
+ * Amazon SES: each stage that declares `email` is a tenant plus a
26
+ * configuration set, both named `names.emailTenant`, associated with the
27
+ * platform's one domain identity (the foundation stack verifies it; the
28
+ * emulator's comes from `ensureLocal`). Found by name, like everything else
29
+ * the engine owns.
30
+ *
31
+ * The tenant is what isolates apps from each other: SES keeps its own
32
+ * suppression list, reports its metrics, and pauses only it when its
33
+ * reputation policy (SES's default, `standard`) sees too many bounces or
34
+ * complaints.
35
+ */
36
+
37
+ /** Every stage tenant keeps its own list, fed by hard bounces and complaints. */
38
+ export const TENANT_SUPPRESSION = {
39
+ SuppressedReasons: ['BOUNCE', 'COMPLAINT'],
40
+ SuppressionScope: 'TENANT',
41
+ } as const satisfies TenantSuppressionAttributes;
42
+
43
+ export interface TenantState {
44
+ name: string;
45
+ id: string;
46
+ arn: string;
47
+ }
48
+
49
+ // ---------------------------------------------------------------- configuration sets
50
+
51
+ export async function getConfigurationSet(
52
+ ctx: EngineContext,
53
+ name: string,
54
+ ): Promise<GetConfigurationSetCommandOutput | undefined> {
55
+ return ignoreNotFound(ctx.clients.ses.send(new GetConfigurationSetCommand({ ConfigurationSetName: name })));
56
+ }
57
+
58
+ /**
59
+ * The stage's configuration set, with reputation metrics on (they feed the
60
+ * console's bounce and complaint rates). Sends name it with the tenant, which
61
+ * is also what the stage role's grant covers.
62
+ */
63
+ export async function ensureConfigurationSet(
64
+ ctx: EngineContext,
65
+ spec: { name: string; tags: Record<string, string> },
66
+ ): Promise<{ name: string; arn: string }> {
67
+ const arn = configurationSetArn(ctx.region, await ctx.accountId(), spec.name);
68
+ const existing = await getConfigurationSet(ctx, spec.name);
69
+ if (!existing) {
70
+ await ctx.clients.ses.send(
71
+ new CreateConfigurationSetCommand({
72
+ ConfigurationSetName: spec.name,
73
+ ReputationOptions: { ReputationMetricsEnabled: true },
74
+ Tags: tagList(spec.tags),
75
+ }),
76
+ );
77
+ ctx.log('info', 'created configuration set', `configuration-set ${spec.name}`);
78
+ return { name: spec.name, arn };
79
+ }
80
+ if (!existing.ReputationOptions?.ReputationMetricsEnabled) {
81
+ await ctx.clients.ses.send(
82
+ new PutConfigurationSetReputationOptionsCommand({
83
+ ConfigurationSetName: spec.name,
84
+ ReputationMetricsEnabled: true,
85
+ }),
86
+ );
87
+ ctx.log('info', 'turned on reputation metrics', `configuration-set ${spec.name}`);
88
+ }
89
+ await ensureTags(ctx, arn, existing.Tags, spec.tags);
90
+ return { name: spec.name, arn };
91
+ }
92
+
93
+ export async function deleteConfigurationSet(ctx: EngineContext, name: string): Promise<boolean> {
94
+ const res = await ignoreNotFound(
95
+ ctx.clients.ses.send(new DeleteConfigurationSetCommand({ ConfigurationSetName: name })),
96
+ );
97
+ if (res === undefined) return false;
98
+ ctx.log('info', 'deleted configuration set', `configuration-set ${name}`);
99
+ return true;
100
+ }
101
+
102
+ // ---------------------------------------------------------------- tenants
103
+
104
+ export async function getTenant(ctx: EngineContext, name: string): Promise<TenantState | undefined> {
105
+ const res = await ignoreNotFound(ctx.clients.ses.send(new GetTenantCommand({ TenantName: name })));
106
+ return res?.Tenant ? tenantState(res.Tenant) : undefined;
107
+ }
108
+
109
+ /**
110
+ * The stage's tenant, created with the platform's suppression settings. An
111
+ * existing one keeps its id (and so its suppression list, metrics and any
112
+ * pause); only its tags and suppression settings are brought in line.
113
+ */
114
+ export async function ensureTenant(
115
+ ctx: EngineContext,
116
+ spec: { name: string; tags: Record<string, string> },
117
+ ): Promise<TenantState> {
118
+ const existing = await ignoreNotFound(
119
+ ctx.clients.ses.send(new GetTenantCommand({ TenantName: spec.name })),
120
+ );
121
+ if (!existing?.Tenant) {
122
+ const created = await ctx.clients.ses.send(
123
+ new CreateTenantCommand({
124
+ TenantName: spec.name,
125
+ Tags: tagList(spec.tags),
126
+ SuppressionAttributes: TENANT_SUPPRESSION,
127
+ }),
128
+ );
129
+ ctx.log('info', 'created tenant', `email-tenant ${spec.name}`);
130
+ // Checked rather than assumed: a tenant left on the account's list would share
131
+ // suppressions (and their reputation cost) with every other app.
132
+ if (!sameSuppression(created.SuppressionAttributes)) await putTenantSuppression(ctx, spec.name);
133
+ return tenantState(created);
134
+ }
135
+ const state = tenantState(existing.Tenant);
136
+ await ensureTags(ctx, state.arn, existing.Tenant.Tags, spec.tags);
137
+ if (!sameSuppression(existing.Tenant.SuppressionAttributes)) await putTenantSuppression(ctx, spec.name);
138
+ return state;
139
+ }
140
+
141
+ /** Point the tenant at its own suppression list (`TENANT_SUPPRESSION`). */
142
+ export async function putTenantSuppression(ctx: EngineContext, name: string): Promise<void> {
143
+ await ctx.clients.ses.send(
144
+ new PutTenantSuppressionAttributesCommand({ TenantName: name, ...TENANT_SUPPRESSION }),
145
+ );
146
+ ctx.log('info', 'tenant keeps its own suppression list', `email-tenant ${name}`);
147
+ }
148
+
149
+ /** ARNs of everything associated with the tenant (identities, configuration sets, templates). */
150
+ export async function listTenantResources(ctx: EngineContext, name: string): Promise<string[]> {
151
+ const out: string[] = [];
152
+ let NextToken: string | undefined;
153
+ do {
154
+ const res = await ctx.clients.ses.send(
155
+ new ListTenantResourcesCommand({ TenantName: name, ...(NextToken ? { NextToken } : {}) }),
156
+ );
157
+ for (const r of res.TenantResources ?? []) if (r.ResourceArn) out.push(r.ResourceArn);
158
+ NextToken = res.NextToken;
159
+ } while (NextToken);
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * Associate exactly `resourceArns` (the domain identity and the stage's
165
+ * configuration set) with the tenant: a send that names the tenant may only
166
+ * use resources associated with it. SES refuses a second association of the
167
+ * same resource (AlreadyExists), so this lists first.
168
+ */
169
+ export async function ensureTenantResources(
170
+ ctx: EngineContext,
171
+ name: string,
172
+ resourceArns: readonly string[],
173
+ ): Promise<void> {
174
+ const current = new Set(await listTenantResources(ctx, name));
175
+ for (const arn of resourceArns) {
176
+ if (current.has(arn)) continue;
177
+ await ctx.clients.ses.send(
178
+ new CreateTenantResourceAssociationCommand({ TenantName: name, ResourceArn: arn }),
179
+ );
180
+ ctx.log('info', `associated ${arn.slice(arn.lastIndexOf(':') + 1)}`, `email-tenant ${name}`);
181
+ }
182
+ for (const arn of current) {
183
+ if (resourceArns.includes(arn)) continue;
184
+ await ignoreNotFound(
185
+ ctx.clients.ses.send(
186
+ new DeleteTenantResourceAssociationCommand({ TenantName: name, ResourceArn: arn }),
187
+ ),
188
+ );
189
+ ctx.log('info', `dissociated ${arn.slice(arn.lastIndexOf(':') + 1)}`, `email-tenant ${name}`);
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Delete the tenant (its suppression list and metrics go with it). Its
195
+ * associations are removed first so the identity and configuration set are
196
+ * free of it whatever SES does with them on delete.
197
+ */
198
+ export async function deleteTenant(ctx: EngineContext, name: string): Promise<boolean> {
199
+ const resources = await ignoreNotFound(listTenantResources(ctx, name));
200
+ if (resources === undefined) return false;
201
+ for (const arn of resources) {
202
+ await ignoreNotFound(
203
+ ctx.clients.ses.send(
204
+ new DeleteTenantResourceAssociationCommand({ TenantName: name, ResourceArn: arn }),
205
+ ),
206
+ );
207
+ }
208
+ const res = await ignoreNotFound(ctx.clients.ses.send(new DeleteTenantCommand({ TenantName: name })));
209
+ if (res === undefined) return false;
210
+ ctx.log('info', 'deleted tenant', `email-tenant ${name}`);
211
+ return true;
212
+ }
213
+
214
+ // ---------------------------------------------------------------- identities
215
+
216
+ /**
217
+ * A domain identity, created when missing. Only `ensureLocal` uses this: in
218
+ * AWS the foundation stack owns the identity and its DNS records. Returns its
219
+ * ARN (SES doesn't report one).
220
+ */
221
+ export async function ensureEmailIdentity(
222
+ ctx: EngineContext,
223
+ spec: { domain: string; tags: Record<string, string> },
224
+ ): Promise<{ domain: string; arn: string }> {
225
+ const arn = emailIdentityArn(ctx.region, await ctx.accountId(), spec.domain);
226
+ const existing = await ignoreNotFound(
227
+ ctx.clients.ses.send(new GetEmailIdentityCommand({ EmailIdentity: spec.domain })),
228
+ );
229
+ if (!existing) {
230
+ await ctx.clients.ses.send(
231
+ new CreateEmailIdentityCommand({ EmailIdentity: spec.domain, Tags: tagList(spec.tags) }),
232
+ );
233
+ ctx.log('info', 'created domain identity', `email-identity ${spec.domain}`);
234
+ }
235
+ return { domain: spec.domain, arn };
236
+ }
237
+
238
+ // ---------------------------------------------------------------- helpers
239
+
240
+ function tenantState(t: Pick<Tenant, 'TenantName' | 'TenantId' | 'TenantArn'>): TenantState {
241
+ if (!t.TenantName || !t.TenantId || !t.TenantArn)
242
+ throw new Error('SES returned a tenant without its name, id or ARN');
243
+ return { name: t.TenantName, id: t.TenantId, arn: t.TenantArn };
244
+ }
245
+
246
+ function sameSuppression(a: TenantSuppressionAttributes | undefined): boolean {
247
+ const reasons = (a?.SuppressedReasons ?? []).toSorted().join(',');
248
+ return (
249
+ a?.SuppressionScope === TENANT_SUPPRESSION.SuppressionScope &&
250
+ reasons === TENANT_SUPPRESSION.SuppressedReasons.toSorted().join(',')
251
+ );
252
+ }
253
+
254
+ /** Add or correct the platform's tags; tags someone else added stay. */
255
+ async function ensureTags(
256
+ ctx: EngineContext,
257
+ arn: string,
258
+ current: Tag[] | undefined,
259
+ wanted: Record<string, string>,
260
+ ): Promise<void> {
261
+ const have = new Map((current ?? []).map((t) => [t.Key, t.Value]));
262
+ const missing = Object.entries(wanted).filter(([k, v]) => have.get(k) !== v);
263
+ if (!missing.length) return;
264
+ await ctx.clients.ses.send(
265
+ new TagResourceCommand({ ResourceArn: arn, Tags: missing.map(([Key, Value]) => ({ Key, Value })) }),
266
+ );
267
+ }
@@ -1,9 +1,12 @@
1
1
  import {
2
2
  CreateQueueCommand,
3
+ DeleteMessageBatchCommand,
3
4
  DeleteQueueCommand,
4
5
  GetQueueAttributesCommand,
5
6
  GetQueueUrlCommand,
6
7
  ListQueuesCommand,
8
+ ReceiveMessageCommand,
9
+ SendMessageBatchCommand,
7
10
  SetQueueAttributesCommand,
8
11
  TagQueueCommand,
9
12
  } from '@aws-sdk/client-sqs';
@@ -21,6 +24,27 @@ export async function getQueueUrl(ctx: EngineContext, name: string): Promise<str
21
24
  return res?.QueueUrl;
22
25
  }
23
26
 
27
+ /** A queue's visibility timeout in seconds; undefined when the queue doesn't exist. */
28
+ export async function getQueueVisibility(ctx: EngineContext, name: string): Promise<number | undefined> {
29
+ const url = await getQueueUrl(ctx, name);
30
+ if (!url) return undefined;
31
+ const res = await ignoreNotFound(
32
+ ctx.clients.sqs.send(
33
+ new GetQueueAttributesCommand({ QueueUrl: url, AttributeNames: ['VisibilityTimeout'] }),
34
+ ),
35
+ );
36
+ const value = res?.Attributes?.VisibilityTimeout;
37
+ return value === undefined ? undefined : Number(value);
38
+ }
39
+
40
+ export async function setQueueAttributes(
41
+ ctx: EngineContext,
42
+ url: string,
43
+ attributes: Record<string, string>,
44
+ ): Promise<void> {
45
+ await ctx.clients.sqs.send(new SetQueueAttributesCommand({ QueueUrl: url, Attributes: attributes }));
46
+ }
47
+
24
48
  export async function ensureQueue(
25
49
  ctx: EngineContext,
26
50
  spec: { name: string; attributes?: Record<string, string>; tags?: Record<string, string> },
@@ -68,3 +92,74 @@ export async function listQueues(
68
92
  } while (NextToken);
69
93
  return out;
70
94
  }
95
+
96
+ /** Messages a queue holds (visible, in flight and delayed); undefined when it doesn't exist. */
97
+ export async function queueDepth(ctx: EngineContext, url: string): Promise<number | undefined> {
98
+ const res = await ignoreNotFound(
99
+ ctx.clients.sqs.send(
100
+ new GetQueueAttributesCommand({
101
+ QueueUrl: url,
102
+ AttributeNames: [
103
+ 'ApproximateNumberOfMessages',
104
+ 'ApproximateNumberOfMessagesNotVisible',
105
+ 'ApproximateNumberOfMessagesDelayed',
106
+ ],
107
+ }),
108
+ ),
109
+ );
110
+ if (!res) return undefined;
111
+ const a = res.Attributes ?? {};
112
+ return (
113
+ Number(a.ApproximateNumberOfMessages ?? 0) +
114
+ Number(a.ApproximateNumberOfMessagesNotVisible ?? 0) +
115
+ Number(a.ApproximateNumberOfMessagesDelayed ?? 0)
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Moves every message visible on `from` to `to`, rewritten by `transform`,
121
+ * deleting each once it's sent. Answers how many moved. Messages in flight
122
+ * elsewhere stay where they are.
123
+ */
124
+ export async function moveMessages(
125
+ ctx: EngineContext,
126
+ from: string,
127
+ to: string,
128
+ transform: (body: string, receiveCount: number) => string,
129
+ ): Promise<number> {
130
+ const sqs = ctx.clients.sqs;
131
+ let moved = 0;
132
+ for (;;) {
133
+ const res = await sqs.send(
134
+ new ReceiveMessageCommand({
135
+ QueueUrl: from,
136
+ MaxNumberOfMessages: 10,
137
+ VisibilityTimeout: 60,
138
+ MessageSystemAttributeNames: ['ApproximateReceiveCount'],
139
+ }),
140
+ );
141
+ const messages = res.Messages ?? [];
142
+ if (messages.length === 0) return moved;
143
+ const sent = await sqs.send(
144
+ new SendMessageBatchCommand({
145
+ QueueUrl: to,
146
+ Entries: messages.map((m, i) => ({
147
+ Id: String(i),
148
+ MessageBody: transform(m.Body ?? '', Number(m.Attributes?.ApproximateReceiveCount ?? '1')),
149
+ })),
150
+ }),
151
+ );
152
+ const ok = new Set((sent.Successful ?? []).map((e) => e.Id));
153
+ const done = messages.filter((_, i) => ok.has(String(i)));
154
+ if (done.length)
155
+ await sqs.send(
156
+ new DeleteMessageBatchCommand({
157
+ QueueUrl: from,
158
+ Entries: done.map((m, i) => ({ Id: String(i), ReceiptHandle: m.ReceiptHandle! })),
159
+ }),
160
+ );
161
+ moved += done.length;
162
+ if (done.length < messages.length)
163
+ throw new Error(`could not move ${messages.length - done.length} messages from ${from}`);
164
+ }
165
+ }
@@ -1,10 +1,11 @@
1
1
  import {
2
+ DeleteParameterCommand,
2
3
  DeleteParametersCommand,
3
4
  GetParameterCommand,
4
5
  GetParametersByPathCommand,
5
6
  PutParameterCommand,
6
7
  } from '@aws-sdk/client-ssm';
7
- import { type EngineContext, ignoreNotFound } from '../util.ts';
8
+ import { type EngineContext, errorName, ignoreNotFound } from '../util.ts';
8
9
 
9
10
  export async function getParameter(
10
11
  ctx: EngineContext,
@@ -41,11 +42,31 @@ export async function ensureParameterOnce(
41
42
  const current = await getParameter(ctx, spec.name);
42
43
  if (current !== undefined) return current;
43
44
  const value = spec.generate();
44
- await putParameter(ctx, { name: spec.name, value, secure: spec.secure, description: spec.description });
45
+ try {
46
+ await ctx.clients.ssm.send(
47
+ new PutParameterCommand({
48
+ Name: spec.name,
49
+ Value: value,
50
+ Type: spec.secure ? 'SecureString' : 'String',
51
+ Description: spec.description,
52
+ // Never overwrite: a concurrent creator may have won, and its value is the one in use.
53
+ Overwrite: false,
54
+ }),
55
+ );
56
+ } catch (e) {
57
+ if (errorName(e) !== 'ParameterAlreadyExists') throw e;
58
+ const winner = await getParameter(ctx, spec.name);
59
+ if (winner === undefined) throw e;
60
+ return winner;
61
+ }
45
62
  ctx.log('info', 'created parameter', `parameter ${spec.name}`);
46
63
  return value;
47
64
  }
48
65
 
66
+ export async function deleteParameter(ctx: EngineContext, name: string): Promise<void> {
67
+ await ignoreNotFound(ctx.clients.ssm.send(new DeleteParameterCommand({ Name: name })));
68
+ }
69
+
49
70
  export async function deleteParametersByPath(ctx: EngineContext, path: string): Promise<number> {
50
71
  const ssm = ctx.clients.ssm;
51
72
  const names: string[] = [];