@ericminassian/platform-engine 0.0.0-stage → 0.1.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 (106) hide show
  1. package/dist/clients.d.ts +61 -0
  2. package/dist/clients.js +122 -0
  3. package/dist/clients.js.map +1 -0
  4. package/dist/compat.d.ts +19 -0
  5. package/dist/compat.js +63 -0
  6. package/dist/compat.js.map +1 -0
  7. package/dist/drivers/acm.d.ts +20 -0
  8. package/dist/drivers/acm.js +62 -0
  9. package/dist/drivers/acm.js.map +1 -0
  10. package/dist/drivers/cloudfront.d.ts +52 -0
  11. package/dist/drivers/cloudfront.js +223 -0
  12. package/dist/drivers/cloudfront.js.map +1 -0
  13. package/dist/drivers/cognito.d.ts +27 -0
  14. package/dist/drivers/cognito.js +151 -0
  15. package/dist/drivers/cognito.js.map +1 -0
  16. package/dist/drivers/dynamodb.d.ts +26 -0
  17. package/dist/drivers/dynamodb.js +151 -0
  18. package/dist/drivers/dynamodb.js.map +1 -0
  19. package/dist/drivers/events.d.ts +21 -0
  20. package/dist/drivers/events.js +62 -0
  21. package/dist/drivers/events.js.map +1 -0
  22. package/dist/drivers/iam.d.ts +29 -0
  23. package/dist/drivers/iam.js +137 -0
  24. package/dist/drivers/iam.js.map +1 -0
  25. package/dist/drivers/index.d.ts +16 -0
  26. package/dist/drivers/index.js +17 -0
  27. package/dist/drivers/index.js.map +1 -0
  28. package/dist/drivers/kvs.d.ts +5 -0
  29. package/dist/drivers/kvs.js +28 -0
  30. package/dist/drivers/kvs.js.map +1 -0
  31. package/dist/drivers/lambda.d.ts +48 -0
  32. package/dist/drivers/lambda.js +158 -0
  33. package/dist/drivers/lambda.js.map +1 -0
  34. package/dist/drivers/logs.d.ts +20 -0
  35. package/dist/drivers/logs.js +62 -0
  36. package/dist/drivers/logs.js.map +1 -0
  37. package/dist/drivers/route53.d.ts +30 -0
  38. package/dist/drivers/route53.js +96 -0
  39. package/dist/drivers/route53.js.map +1 -0
  40. package/dist/drivers/s3.d.ts +30 -0
  41. package/dist/drivers/s3.js +126 -0
  42. package/dist/drivers/s3.js.map +1 -0
  43. package/dist/drivers/scheduler.d.ts +21 -0
  44. package/dist/drivers/scheduler.js +59 -0
  45. package/dist/drivers/scheduler.js.map +1 -0
  46. package/dist/drivers/sns.d.ts +7 -0
  47. package/dist/drivers/sns.js +20 -0
  48. package/dist/drivers/sns.js.map +1 -0
  49. package/dist/drivers/sqs.d.ts +18 -0
  50. package/dist/drivers/sqs.js +46 -0
  51. package/dist/drivers/sqs.js.map +1 -0
  52. package/dist/drivers/ssm.d.ts +16 -0
  53. package/dist/drivers/ssm.js +45 -0
  54. package/dist/drivers/ssm.js.map +1 -0
  55. package/dist/drivers/web-function.d.ts +71 -0
  56. package/dist/drivers/web-function.js +227 -0
  57. package/dist/drivers/web-function.js.map +1 -0
  58. package/dist/emulator.d.ts +51 -0
  59. package/dist/emulator.js +142 -0
  60. package/dist/emulator.js.map +1 -0
  61. package/dist/index.d.ts +139 -0
  62. package/dist/index.js +71 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/local.d.ts +12 -0
  65. package/dist/local.js +71 -0
  66. package/dist/local.js.map +1 -0
  67. package/dist/policy.d.ts +47 -0
  68. package/dist/policy.js +332 -0
  69. package/dist/policy.js.map +1 -0
  70. package/dist/stage.d.ts +19 -0
  71. package/dist/stage.js +479 -0
  72. package/dist/stage.js.map +1 -0
  73. package/dist/static.d.ts +9 -0
  74. package/dist/static.js +55 -0
  75. package/dist/static.js.map +1 -0
  76. package/dist/util.d.ts +56 -0
  77. package/dist/util.js +127 -0
  78. package/dist/util.js.map +1 -0
  79. package/package.json +52 -3
  80. package/src/clients.ts +166 -0
  81. package/src/compat.ts +63 -0
  82. package/src/drivers/acm.ts +88 -0
  83. package/src/drivers/cloudfront.ts +291 -0
  84. package/src/drivers/cognito.ts +199 -0
  85. package/src/drivers/dynamodb.ts +206 -0
  86. package/src/drivers/events.ts +92 -0
  87. package/src/drivers/iam.ts +195 -0
  88. package/src/drivers/index.ts +16 -0
  89. package/src/drivers/kvs.ts +55 -0
  90. package/src/drivers/lambda.ts +283 -0
  91. package/src/drivers/logs.ts +81 -0
  92. package/src/drivers/route53.ts +129 -0
  93. package/src/drivers/s3.ts +196 -0
  94. package/src/drivers/scheduler.ts +90 -0
  95. package/src/drivers/sns.ts +33 -0
  96. package/src/drivers/sqs.ts +70 -0
  97. package/src/drivers/ssm.ts +65 -0
  98. package/src/drivers/web-function.ts +352 -0
  99. package/src/emulator.ts +203 -0
  100. package/src/index.ts +182 -0
  101. package/src/local.ts +75 -0
  102. package/src/policy.ts +398 -0
  103. package/src/stage.ts +568 -0
  104. package/src/static.ts +56 -0
  105. package/src/util.ts +175 -0
  106. package/README.md +0 -3
@@ -0,0 +1,92 @@
1
+ import {
2
+ CreateEventBusCommand,
3
+ DeleteEventBusCommand,
4
+ DeleteRuleCommand,
5
+ DescribeEventBusCommand,
6
+ ListRulesCommand,
7
+ ListTargetsByRuleCommand,
8
+ PutRuleCommand,
9
+ PutTargetsCommand,
10
+ RemoveTargetsCommand,
11
+ } from '@aws-sdk/client-eventbridge';
12
+ import { type EngineContext, ignoreNotFound, tagList } from '../util.ts';
13
+
14
+ export async function ensureEventBus(
15
+ ctx: EngineContext,
16
+ spec: { name: string; tags?: Record<string, string> },
17
+ ): Promise<string> {
18
+ const ev = ctx.clients.events;
19
+ const existing = await ignoreNotFound(ev.send(new DescribeEventBusCommand({ Name: spec.name })));
20
+ if (existing?.Arn) return existing.Arn;
21
+ const res = await ev.send(
22
+ new CreateEventBusCommand({ Name: spec.name, Tags: spec.tags ? tagList(spec.tags) : undefined }),
23
+ );
24
+ ctx.log('info', 'created event bus', `bus ${spec.name}`);
25
+ return res.EventBusArn!;
26
+ }
27
+
28
+ export interface RuleSpec {
29
+ bus: string;
30
+ name: string;
31
+ pattern: unknown;
32
+ targets: Array<{ id: string; arn: string; input?: string; roleArn?: string }>;
33
+ tags?: Record<string, string>;
34
+ }
35
+
36
+ export async function ensureRule(ctx: EngineContext, spec: RuleSpec): Promise<string> {
37
+ const ev = ctx.clients.events;
38
+ const rule = await ev.send(
39
+ new PutRuleCommand({
40
+ Name: spec.name,
41
+ EventBusName: spec.bus,
42
+ EventPattern: JSON.stringify(spec.pattern),
43
+ State: 'ENABLED',
44
+ Tags: spec.tags ? tagList(spec.tags) : undefined,
45
+ }),
46
+ );
47
+ await ev.send(
48
+ new PutTargetsCommand({
49
+ Rule: spec.name,
50
+ EventBusName: spec.bus,
51
+ Targets: spec.targets.map((t) => ({ Id: t.id, Arn: t.arn, Input: t.input, RoleArn: t.roleArn })),
52
+ }),
53
+ );
54
+ const existing = await ev.send(new ListTargetsByRuleCommand({ Rule: spec.name, EventBusName: spec.bus }));
55
+ const wanted = new Set(spec.targets.map((t) => t.id));
56
+ const stale = (existing.Targets ?? []).map((t) => t.Id!).filter((id) => !wanted.has(id));
57
+ if (stale.length)
58
+ await ev.send(new RemoveTargetsCommand({ Rule: spec.name, EventBusName: spec.bus, Ids: stale }));
59
+ return rule.RuleArn!;
60
+ }
61
+
62
+ export async function listRules(ctx: EngineContext, bus: string, prefix?: string): Promise<string[]> {
63
+ const out: string[] = [];
64
+ let NextToken: string | undefined;
65
+ do {
66
+ const res = await ignoreNotFound(
67
+ ctx.clients.events.send(new ListRulesCommand({ EventBusName: bus, NamePrefix: prefix, NextToken })),
68
+ );
69
+ if (!res) return out;
70
+ for (const r of res.Rules ?? []) if (r.Name) out.push(r.Name);
71
+ NextToken = res.NextToken;
72
+ } while (NextToken);
73
+ return out;
74
+ }
75
+
76
+ export async function deleteRule(ctx: EngineContext, bus: string, name: string): Promise<void> {
77
+ const ev = ctx.clients.events;
78
+ const targets = await ignoreNotFound(
79
+ ev.send(new ListTargetsByRuleCommand({ Rule: name, EventBusName: bus })),
80
+ );
81
+ const ids = (targets?.Targets ?? []).map((t) => t.Id!);
82
+ if (ids.length)
83
+ await ev.send(new RemoveTargetsCommand({ Rule: name, EventBusName: bus, Ids: ids, Force: true }));
84
+ await ignoreNotFound(ev.send(new DeleteRuleCommand({ Name: name, EventBusName: bus, Force: true })));
85
+ ctx.log('info', 'deleted rule', `rule ${name}`);
86
+ }
87
+
88
+ export async function deleteEventBus(ctx: EngineContext, name: string): Promise<void> {
89
+ for (const rule of await listRules(ctx, name)) await deleteRule(ctx, name, rule);
90
+ await ignoreNotFound(ctx.clients.events.send(new DeleteEventBusCommand({ Name: name })));
91
+ ctx.log('info', 'deleted event bus', `bus ${name}`);
92
+ }
@@ -0,0 +1,195 @@
1
+ import {
2
+ AttachRolePolicyCommand,
3
+ CreateOpenIDConnectProviderCommand,
4
+ CreatePolicyCommand,
5
+ CreatePolicyVersionCommand,
6
+ CreateRoleCommand,
7
+ DeletePolicyVersionCommand,
8
+ DeleteRoleCommand,
9
+ DeleteRolePermissionsBoundaryCommand,
10
+ DeleteRolePolicyCommand,
11
+ DetachRolePolicyCommand,
12
+ GetPolicyCommand,
13
+ GetPolicyVersionCommand,
14
+ GetRoleCommand,
15
+ ListAttachedRolePoliciesCommand,
16
+ ListOpenIDConnectProvidersCommand,
17
+ ListPolicyVersionsCommand,
18
+ ListRolePoliciesCommand,
19
+ PutRolePermissionsBoundaryCommand,
20
+ PutRolePolicyCommand,
21
+ TagRoleCommand,
22
+ UpdateAssumeRolePolicyCommand,
23
+ } from '@aws-sdk/client-iam';
24
+ import { type EngineContext, ignoreNotFound, type PolicyDocument, samePolicy, tagList } from '../util.ts';
25
+
26
+ export interface RoleSpec {
27
+ name: string;
28
+ path?: string;
29
+ description?: string;
30
+ trust: PolicyDocument;
31
+ /** Inline policies by name; inline policies not listed are removed. */
32
+ inlinePolicies?: Record<string, PolicyDocument>;
33
+ managedPolicyArns?: string[];
34
+ boundaryArn?: string;
35
+ tags?: Record<string, string>;
36
+ maxSessionDurationSeconds?: number;
37
+ }
38
+
39
+ export interface RoleState {
40
+ arn: string;
41
+ name: string;
42
+ created: boolean;
43
+ }
44
+
45
+ export async function ensureRole(ctx: EngineContext, spec: RoleSpec): Promise<RoleState> {
46
+ const iam = ctx.clients.iam;
47
+ const existing = await ignoreNotFound(iam.send(new GetRoleCommand({ RoleName: spec.name })));
48
+ let arn: string;
49
+ let created = false;
50
+ if (!existing?.Role) {
51
+ const res = await iam.send(
52
+ new CreateRoleCommand({
53
+ RoleName: spec.name,
54
+ Path: spec.path ?? '/',
55
+ Description: spec.description,
56
+ AssumeRolePolicyDocument: JSON.stringify(spec.trust),
57
+ PermissionsBoundary: spec.boundaryArn,
58
+ MaxSessionDuration: spec.maxSessionDurationSeconds,
59
+ Tags: spec.tags ? tagList(spec.tags) : undefined,
60
+ }),
61
+ );
62
+ arn = res.Role!.Arn!;
63
+ created = true;
64
+ ctx.log('info', 'created role', `role ${spec.name}`);
65
+ } else {
66
+ const role = existing.Role;
67
+ arn = role.Arn!;
68
+ if (!samePolicy(role.AssumeRolePolicyDocument, spec.trust)) {
69
+ await iam.send(
70
+ new UpdateAssumeRolePolicyCommand({
71
+ RoleName: spec.name,
72
+ PolicyDocument: JSON.stringify(spec.trust),
73
+ }),
74
+ );
75
+ }
76
+ const currentBoundary = role.PermissionsBoundary?.PermissionsBoundaryArn;
77
+ if (spec.boundaryArn && currentBoundary !== spec.boundaryArn) {
78
+ await iam.send(
79
+ new PutRolePermissionsBoundaryCommand({ RoleName: spec.name, PermissionsBoundary: spec.boundaryArn }),
80
+ );
81
+ } else if (!spec.boundaryArn && currentBoundary) {
82
+ await iam.send(new DeleteRolePermissionsBoundaryCommand({ RoleName: spec.name }));
83
+ }
84
+ if (spec.tags) await iam.send(new TagRoleCommand({ RoleName: spec.name, Tags: tagList(spec.tags) }));
85
+ }
86
+
87
+ const wanted = spec.inlinePolicies ?? {};
88
+ for (const [policyName, doc] of Object.entries(wanted)) {
89
+ await iam.send(
90
+ new PutRolePolicyCommand({
91
+ RoleName: spec.name,
92
+ PolicyName: policyName,
93
+ PolicyDocument: JSON.stringify(doc),
94
+ }),
95
+ );
96
+ }
97
+ const listed = await iam.send(new ListRolePoliciesCommand({ RoleName: spec.name }));
98
+ for (const name of listed.PolicyNames ?? []) {
99
+ if (!(name in wanted))
100
+ await iam.send(new DeleteRolePolicyCommand({ RoleName: spec.name, PolicyName: name }));
101
+ }
102
+
103
+ if (spec.managedPolicyArns) {
104
+ const attached = await iam.send(new ListAttachedRolePoliciesCommand({ RoleName: spec.name }));
105
+ const have = new Set((attached.AttachedPolicies ?? []).map((p) => p.PolicyArn!));
106
+ for (const p of spec.managedPolicyArns) {
107
+ if (!have.has(p)) await iam.send(new AttachRolePolicyCommand({ RoleName: spec.name, PolicyArn: p }));
108
+ }
109
+ for (const p of have) {
110
+ if (!spec.managedPolicyArns.includes(p)) {
111
+ await iam.send(new DetachRolePolicyCommand({ RoleName: spec.name, PolicyArn: p }));
112
+ }
113
+ }
114
+ }
115
+ return { arn, name: spec.name, created };
116
+ }
117
+
118
+ export async function deleteRole(ctx: EngineContext, name: string): Promise<boolean> {
119
+ const iam = ctx.clients.iam;
120
+ const existing = await ignoreNotFound(iam.send(new GetRoleCommand({ RoleName: name })));
121
+ if (!existing?.Role) return false;
122
+ const inline = await iam.send(new ListRolePoliciesCommand({ RoleName: name }));
123
+ for (const p of inline.PolicyNames ?? []) {
124
+ await ignoreNotFound(iam.send(new DeleteRolePolicyCommand({ RoleName: name, PolicyName: p })));
125
+ }
126
+ const attached = await iam.send(new ListAttachedRolePoliciesCommand({ RoleName: name }));
127
+ for (const p of attached.AttachedPolicies ?? []) {
128
+ await ignoreNotFound(iam.send(new DetachRolePolicyCommand({ RoleName: name, PolicyArn: p.PolicyArn })));
129
+ }
130
+ await ignoreNotFound(iam.send(new DeleteRoleCommand({ RoleName: name })));
131
+ ctx.log('info', 'deleted role', `role ${name}`);
132
+ return true;
133
+ }
134
+
135
+ /** Customer managed policy kept at `document` (new default version when it changes). */
136
+ export async function ensureManagedPolicy(
137
+ ctx: EngineContext,
138
+ spec: { name: string; path?: string; description?: string; document: PolicyDocument },
139
+ ): Promise<string> {
140
+ const iam = ctx.clients.iam;
141
+ const acct = await ctx.accountId();
142
+ const path = spec.path ?? '/';
143
+ const arn = `arn:aws:iam::${acct}:policy${path}${spec.name}`;
144
+ const existing = await ignoreNotFound(iam.send(new GetPolicyCommand({ PolicyArn: arn })));
145
+ if (!existing?.Policy) {
146
+ await iam.send(
147
+ new CreatePolicyCommand({
148
+ PolicyName: spec.name,
149
+ Path: path,
150
+ Description: spec.description,
151
+ PolicyDocument: JSON.stringify(spec.document),
152
+ }),
153
+ );
154
+ ctx.log('info', 'created managed policy', `policy ${spec.name}`);
155
+ return arn;
156
+ }
157
+ const version = await iam.send(
158
+ new GetPolicyVersionCommand({ PolicyArn: arn, VersionId: existing.Policy.DefaultVersionId }),
159
+ );
160
+ if (samePolicy(version.PolicyVersion?.Document, spec.document)) return arn;
161
+ const versions = await iam.send(new ListPolicyVersionsCommand({ PolicyArn: arn }));
162
+ const old = (versions.Versions ?? []).filter((v) => !v.IsDefaultVersion);
163
+ if ((versions.Versions ?? []).length >= 5 && old.length > 0) {
164
+ const oldest = old.sort((a, b) => (a.CreateDate?.getTime() ?? 0) - (b.CreateDate?.getTime() ?? 0))[0]!;
165
+ await iam.send(new DeletePolicyVersionCommand({ PolicyArn: arn, VersionId: oldest.VersionId }));
166
+ }
167
+ await iam.send(
168
+ new CreatePolicyVersionCommand({
169
+ PolicyArn: arn,
170
+ PolicyDocument: JSON.stringify(spec.document),
171
+ SetAsDefault: true,
172
+ }),
173
+ );
174
+ ctx.log('info', 'updated managed policy', `policy ${spec.name}`);
175
+ return arn;
176
+ }
177
+
178
+ /** GitHub Actions OIDC identity provider (one per account). */
179
+ export async function ensureGithubOidcProvider(ctx: EngineContext): Promise<string> {
180
+ const iam = ctx.clients.iam;
181
+ const url = 'token.actions.githubusercontent.com';
182
+ const list = await iam.send(new ListOpenIDConnectProvidersCommand({}));
183
+ const found = (list.OpenIDConnectProviderList ?? []).find((p) => p.Arn?.endsWith(`/${url}`));
184
+ if (found?.Arn) return found.Arn;
185
+ const res = await iam.send(
186
+ new CreateOpenIDConnectProviderCommand({
187
+ Url: `https://${url}`,
188
+ ClientIDList: ['sts.amazonaws.com'],
189
+ // IAM no longer validates thumbprints for GitHub's well-known issuer, but the field is required.
190
+ ThumbprintList: ['6938fd4d98bab03faadb97b34396831e3780aea1'],
191
+ }),
192
+ );
193
+ ctx.log('info', 'created GitHub OIDC provider', `oidc ${url}`);
194
+ return res.OpenIDConnectProviderArn!;
195
+ }
@@ -0,0 +1,16 @@
1
+ export * from './acm.ts';
2
+ export * from './cloudfront.ts';
3
+ export * from './cognito.ts';
4
+ export * from './dynamodb.ts';
5
+ export * from './events.ts';
6
+ export * from './iam.ts';
7
+ export * from './kvs.ts';
8
+ export * from './lambda.ts';
9
+ export * from './logs.ts';
10
+ export * from './route53.ts';
11
+ export * from './s3.ts';
12
+ export * from './scheduler.ts';
13
+ export * from './sns.ts';
14
+ export * from './sqs.ts';
15
+ export * from './ssm.ts';
16
+ export * from './web-function.ts';
@@ -0,0 +1,55 @@
1
+ import {
2
+ DeleteKeyCommand,
3
+ DescribeKeyValueStoreCommand,
4
+ GetKeyCommand,
5
+ PutKeyCommand,
6
+ } from '@aws-sdk/client-cloudfront-keyvaluestore';
7
+ import { encodeRouteRecord, type RouteRecord } from '@ericminassian/platform-core';
8
+ import { type EngineContext, errorName, ignoreNotFound, retry } from '../util.ts';
9
+
10
+ /**
11
+ * Host → route records in the CloudFront KeyValueStore read by the router
12
+ * function. Writes are optimistic (ETag); concurrent deploys retry.
13
+ */
14
+ const isConflict = (e: unknown) => /Conflict|PreconditionFailed|ValidationException/.test(errorName(e));
15
+
16
+ export async function putRoute(
17
+ ctx: EngineContext,
18
+ kvsArn: string,
19
+ host: string,
20
+ record: RouteRecord,
21
+ ): Promise<void> {
22
+ const value = encodeRouteRecord(record);
23
+ await retry(
24
+ async () => {
25
+ const d = await ctx.clients.kvs.send(new DescribeKeyValueStoreCommand({ KvsARN: kvsArn }));
26
+ await ctx.clients.kvs.send(
27
+ new PutKeyCommand({ KvsARN: kvsArn, Key: host, Value: value, IfMatch: d.ETag }),
28
+ );
29
+ },
30
+ { when: isConflict, attempts: 8, delayMs: 300 },
31
+ );
32
+ ctx.log('info', `route ${host} → ${record.d}`, `route ${host}`);
33
+ }
34
+
35
+ export async function getRoute(
36
+ ctx: EngineContext,
37
+ kvsArn: string,
38
+ host: string,
39
+ ): Promise<RouteRecord | undefined> {
40
+ const res = await ignoreNotFound(ctx.clients.kvs.send(new GetKeyCommand({ KvsARN: kvsArn, Key: host })));
41
+ return res?.Value ? (JSON.parse(res.Value) as RouteRecord) : undefined;
42
+ }
43
+
44
+ export async function deleteRoute(ctx: EngineContext, kvsArn: string, host: string): Promise<void> {
45
+ await retry(
46
+ async () => {
47
+ const d = await ctx.clients.kvs.send(new DescribeKeyValueStoreCommand({ KvsARN: kvsArn }));
48
+ await ignoreNotFound(
49
+ ctx.clients.kvs.send(new DeleteKeyCommand({ KvsARN: kvsArn, Key: host, IfMatch: d.ETag })),
50
+ );
51
+ },
52
+ { when: isConflict, attempts: 8, delayMs: 300 },
53
+ );
54
+ ctx.log('info', 'deleted route', `route ${host}`);
55
+ }
@@ -0,0 +1,283 @@
1
+ import {
2
+ AddPermissionCommand,
3
+ CreateEventSourceMappingCommand,
4
+ CreateFunctionCommand,
5
+ DeleteEventSourceMappingCommand,
6
+ DeleteFunctionCommand,
7
+ GetFunctionConfigurationCommand,
8
+ GetPolicyCommand,
9
+ ListEventSourceMappingsCommand,
10
+ RemovePermissionCommand,
11
+ TagResourceCommand,
12
+ UpdateEventSourceMappingCommand,
13
+ UpdateFunctionCodeCommand,
14
+ UpdateFunctionConfigurationCommand,
15
+ } from '@aws-sdk/client-lambda';
16
+ import type { S3Location } from '../index.ts';
17
+ import { type EngineContext, errorMessage, errorName, ignoreNotFound, retry, waitFor } from '../util.ts';
18
+
19
+ export interface FunctionSpec {
20
+ name: string;
21
+ roleArn: string;
22
+ runtime: string;
23
+ handler: string;
24
+ architecture: 'arm64' | 'x86_64';
25
+ memoryMb: number;
26
+ timeoutSeconds: number;
27
+ code: S3Location;
28
+ env: Record<string, string>;
29
+ logGroup?: string;
30
+ description?: string;
31
+ tags?: Record<string, string>;
32
+ }
33
+
34
+ export interface FunctionState {
35
+ name: string;
36
+ arn: string;
37
+ created: boolean;
38
+ }
39
+
40
+ /** IAM is eventually consistent: a new role can take seconds to be assumable by Lambda. */
41
+ const isRolePropagation = (e: unknown) =>
42
+ errorName(e) === 'InvalidParameterValueException' && /role|assume/i.test(errorMessage(e));
43
+ const isUpdateInProgress = (e: unknown) => errorName(e) === 'ResourceConflictException';
44
+
45
+ export async function ensureFunction(ctx: EngineContext, spec: FunctionSpec): Promise<FunctionState> {
46
+ const lambda = ctx.clients.lambda;
47
+ const existing = await ignoreNotFound(
48
+ lambda.send(new GetFunctionConfigurationCommand({ FunctionName: spec.name })),
49
+ );
50
+ const config = {
51
+ Role: spec.roleArn,
52
+ Runtime: spec.runtime as never,
53
+ Handler: spec.handler,
54
+ MemorySize: spec.memoryMb,
55
+ Timeout: spec.timeoutSeconds,
56
+ Description: spec.description,
57
+ Environment: { Variables: spec.env },
58
+ LoggingConfig: spec.logGroup ? { LogFormat: 'JSON' as const, LogGroup: spec.logGroup } : undefined,
59
+ };
60
+
61
+ if (!existing) {
62
+ const res = await retry(
63
+ () =>
64
+ lambda.send(
65
+ new CreateFunctionCommand({
66
+ FunctionName: spec.name,
67
+ ...config,
68
+ Architectures: [spec.architecture],
69
+ Code: { S3Bucket: spec.code.bucket, S3Key: spec.code.key, S3ObjectVersion: spec.code.versionId },
70
+ Tags: spec.tags,
71
+ }),
72
+ ),
73
+ { when: isRolePropagation, attempts: 15, delayMs: 2_000 },
74
+ );
75
+ ctx.log('info', 'created function', `function ${spec.name}`);
76
+ await waitReady(ctx, spec.name);
77
+ return { name: spec.name, arn: res.FunctionArn!, created: true };
78
+ }
79
+
80
+ await waitReady(ctx, spec.name);
81
+ await retry(
82
+ () =>
83
+ lambda.send(
84
+ new UpdateFunctionCodeCommand({
85
+ FunctionName: spec.name,
86
+ S3Bucket: spec.code.bucket,
87
+ S3Key: spec.code.key,
88
+ S3ObjectVersion: spec.code.versionId,
89
+ Architectures: [spec.architecture],
90
+ }),
91
+ ),
92
+ { when: isUpdateInProgress },
93
+ );
94
+ await waitReady(ctx, spec.name);
95
+ await retry(
96
+ () => lambda.send(new UpdateFunctionConfigurationCommand({ FunctionName: spec.name, ...config })),
97
+ {
98
+ when: (e) => isUpdateInProgress(e) || isRolePropagation(e),
99
+ },
100
+ );
101
+ await waitReady(ctx, spec.name);
102
+ if (spec.tags)
103
+ await lambda.send(new TagResourceCommand({ Resource: existing.FunctionArn, Tags: spec.tags }));
104
+ ctx.log('info', 'updated function', `function ${spec.name}`);
105
+ return { name: spec.name, arn: existing.FunctionArn!, created: false };
106
+ }
107
+
108
+ /** Wait until the function is Active and no update is in progress. */
109
+ export async function waitReady(ctx: EngineContext, name: string): Promise<void> {
110
+ await waitFor(
111
+ `function ${name} ready`,
112
+ async () => {
113
+ const c = await ctx.clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: name }));
114
+ if (c.State === 'Failed') throw new Error(`function ${name} failed: ${c.StateReason}`);
115
+ if (c.LastUpdateStatus === 'Failed')
116
+ throw new Error(`function ${name} update failed: ${c.LastUpdateStatusReason}`);
117
+ return c.State === 'Active' && c.LastUpdateStatus !== 'InProgress';
118
+ },
119
+ { timeoutMs: 300_000 },
120
+ );
121
+ }
122
+
123
+ export async function deleteFunction(ctx: EngineContext, name: string): Promise<boolean> {
124
+ const res = await ignoreNotFound(
125
+ ctx.clients.lambda.send(new DeleteFunctionCommand({ FunctionName: name })),
126
+ );
127
+ if (res) ctx.log('info', 'deleted function', `function ${name}`);
128
+ return res !== undefined;
129
+ }
130
+
131
+ // ------------------------------------------------------------------ event source mappings
132
+
133
+ export interface EventSourceMappingSpec {
134
+ functionName: string;
135
+ sourceArn: string;
136
+ batchSize: number;
137
+ maxConcurrency?: number;
138
+ }
139
+
140
+ export async function ensureEventSourceMapping(
141
+ ctx: EngineContext,
142
+ spec: EventSourceMappingSpec,
143
+ ): Promise<string> {
144
+ const lambda = ctx.clients.lambda;
145
+ const list = await lambda.send(
146
+ new ListEventSourceMappingsCommand({ FunctionName: spec.functionName, EventSourceArn: spec.sourceArn }),
147
+ );
148
+ const existing = list.EventSourceMappings?.[0];
149
+ const common = {
150
+ BatchSize: spec.batchSize,
151
+ FunctionResponseTypes: ['ReportBatchItemFailures' as const],
152
+ ScalingConfig: spec.maxConcurrency ? { MaximumConcurrency: spec.maxConcurrency } : undefined,
153
+ Enabled: true,
154
+ };
155
+ if (existing?.UUID) {
156
+ await retry(() => lambda.send(new UpdateEventSourceMappingCommand({ UUID: existing.UUID, ...common })), {
157
+ when: isUpdateInProgress,
158
+ });
159
+ return existing.UUID;
160
+ }
161
+ // The role's sqs:ReceiveMessage grant must be visible before Lambda accepts the mapping.
162
+ const res = await retry(
163
+ () =>
164
+ lambda.send(
165
+ new CreateEventSourceMappingCommand({
166
+ FunctionName: spec.functionName,
167
+ EventSourceArn: spec.sourceArn,
168
+ ...common,
169
+ }),
170
+ ),
171
+ {
172
+ when: (e) =>
173
+ errorName(e) === 'InvalidParameterValueException' && /permission|role/i.test(errorMessage(e)),
174
+ attempts: 15,
175
+ delayMs: 2_000,
176
+ },
177
+ );
178
+ ctx.log('info', 'created event source mapping', `esm ${spec.sourceArn.split(':').pop()}`);
179
+ return res.UUID!;
180
+ }
181
+
182
+ export async function listEventSourceMappings(
183
+ ctx: EngineContext,
184
+ functionName: string,
185
+ ): Promise<Array<{ uuid: string; sourceArn: string }>> {
186
+ const out: Array<{ uuid: string; sourceArn: string }> = [];
187
+ let Marker: string | undefined;
188
+ do {
189
+ const res = await ignoreNotFound(
190
+ ctx.clients.lambda.send(new ListEventSourceMappingsCommand({ FunctionName: functionName, Marker })),
191
+ );
192
+ if (!res) return out;
193
+ for (const m of res.EventSourceMappings ?? []) {
194
+ if (m.UUID && m.EventSourceArn) out.push({ uuid: m.UUID, sourceArn: m.EventSourceArn });
195
+ }
196
+ Marker = res.NextMarker;
197
+ } while (Marker);
198
+ return out;
199
+ }
200
+
201
+ export async function deleteEventSourceMapping(ctx: EngineContext, uuid: string): Promise<void> {
202
+ // A mapping that is still Creating/Updating refuses deletion with ResourceInUseException.
203
+ await ignoreNotFound(
204
+ retry(() => ctx.clients.lambda.send(new DeleteEventSourceMappingCommand({ UUID: uuid })), {
205
+ when: (e) => isUpdateInProgress(e) || errorName(e) === 'ResourceInUseException',
206
+ attempts: 30,
207
+ delayMs: 1_000,
208
+ }),
209
+ );
210
+ }
211
+
212
+ // ------------------------------------------------------------------ resource policy
213
+
214
+ export interface PermissionSpec {
215
+ functionName: string;
216
+ statementId: string;
217
+ principal: string;
218
+ action: string;
219
+ sourceArn?: string;
220
+ }
221
+
222
+ /** Add a resource-policy statement; replaces a same-id statement that differs. */
223
+ export async function ensurePermission(ctx: EngineContext, spec: PermissionSpec): Promise<void> {
224
+ const lambda = ctx.clients.lambda;
225
+ const current = await ignoreNotFound(
226
+ lambda.send(new GetPolicyCommand({ FunctionName: spec.functionName })),
227
+ );
228
+ if (current?.Policy) {
229
+ const doc = JSON.parse(current.Policy) as {
230
+ Statement: Array<{
231
+ Sid: string;
232
+ Principal?: { Service?: string };
233
+ Action?: string;
234
+ Condition?: { ArnLike?: { 'AWS:SourceArn'?: string } };
235
+ }>;
236
+ };
237
+ const st = doc.Statement.find((s) => s.Sid === spec.statementId);
238
+ if (st) {
239
+ const same =
240
+ st.Principal?.Service === spec.principal &&
241
+ st.Action === spec.action &&
242
+ (st.Condition?.ArnLike?.['AWS:SourceArn'] ?? undefined) === spec.sourceArn;
243
+ if (same) return;
244
+ await lambda.send(
245
+ new RemovePermissionCommand({ FunctionName: spec.functionName, StatementId: spec.statementId }),
246
+ );
247
+ }
248
+ }
249
+ try {
250
+ await lambda.send(
251
+ new AddPermissionCommand({
252
+ FunctionName: spec.functionName,
253
+ StatementId: spec.statementId,
254
+ Principal: spec.principal,
255
+ Action: spec.action,
256
+ SourceArn: spec.sourceArn,
257
+ }),
258
+ );
259
+ } catch (e) {
260
+ // Statement already present (e.g. GetPolicy returned a stale view).
261
+ if (errorName(e) !== 'ResourceConflictException') throw e;
262
+ }
263
+ }
264
+
265
+ export async function removePermission(
266
+ ctx: EngineContext,
267
+ functionName: string,
268
+ statementId: string,
269
+ ): Promise<void> {
270
+ await ignoreNotFound(
271
+ ctx.clients.lambda.send(
272
+ new RemovePermissionCommand({ FunctionName: functionName, StatementId: statementId }),
273
+ ),
274
+ );
275
+ }
276
+
277
+ export async function listPermissionIds(ctx: EngineContext, functionName: string): Promise<string[]> {
278
+ const current = await ignoreNotFound(
279
+ ctx.clients.lambda.send(new GetPolicyCommand({ FunctionName: functionName })),
280
+ );
281
+ if (!current?.Policy) return [];
282
+ return (JSON.parse(current.Policy) as { Statement: Array<{ Sid: string }> }).Statement.map((s) => s.Sid);
283
+ }