@kensio/yulin 1.20.15 → 1.20.16

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 (95) hide show
  1. package/README.md +13 -0
  2. package/dist/sdk/module/sim-sdk-module-client-interceptor.d.ts +5 -0
  3. package/dist/sdk/module/sim-sdk-module-client-interceptor.js +14 -0
  4. package/dist/sdk/module/sim-sdk-static-client-factory.d.ts +26 -0
  5. package/dist/sdk/module/sim-sdk-static-client-factory.js +59 -0
  6. package/dist/sdk/send-patch.d.ts +8 -0
  7. package/dist/sdk/send-patch.js +11 -0
  8. package/dist/service/aws/caller/sim-aws-caller-resolver.d.ts +28 -6
  9. package/dist/service/aws/caller/sim-aws-caller-resolver.js +18 -11
  10. package/dist/service/aws/caller/sim-aws-caller.d.ts +9 -0
  11. package/dist/service/aws/caller/sim-aws-resolved-caller.d.ts +19 -0
  12. package/dist/service/aws/caller/sim-aws-resolved-caller.js +26 -0
  13. package/dist/service/aws/factory/sim-aws-account-region-service-builder.d.ts +6 -0
  14. package/dist/service/aws/factory/sim-aws-account-region-service-builder.js +3 -0
  15. package/dist/service/aws/factory/sim-aws-account-service-cache.d.ts +6 -0
  16. package/dist/service/aws/factory/sim-aws-account-service-cache.js +5 -0
  17. package/dist/service/aws/factory/sim-aws-service-factory.d.ts +5 -0
  18. package/dist/service/aws/factory/sim-aws-service-factory.js +6 -0
  19. package/dist/service/aws/sim-aws-properties.d.ts +15 -0
  20. package/dist/service/aws/sim-aws.js +2 -1
  21. package/dist/service/iam/authorize/context/sim-iam-auth-z-caller-context-builder.d.ts +30 -7
  22. package/dist/service/iam/authorize/context/sim-iam-auth-z-caller-context-builder.js +20 -11
  23. package/dist/service/iam/authorize/context/sim-iam-auth-z-context-builder.d.ts +2 -1
  24. package/dist/service/iam/authorize/context/sim-iam-auth-z-context-builder.js +5 -1
  25. package/dist/service/iam/authorize/match/sim-iam-policy-principal-matcher.d.ts +10 -0
  26. package/dist/service/iam/authorize/match/sim-iam-policy-principal-matcher.js +15 -3
  27. package/dist/service/iam/authorize/sim-iam-account-auth-z.d.ts +11 -4
  28. package/dist/service/iam/authorize/sim-iam-account-auth-z.js +5 -3
  29. package/dist/service/iam/authorize/sim-iam-authorizer.d.ts +2 -1
  30. package/dist/service/iam/authorize/sim-iam-authorizer.js +1 -0
  31. package/dist/service/iam/role/sim-iam-role-with-policy.factory.d.ts +9 -0
  32. package/dist/service/iam/role/sim-iam-role-with-policy.factory.js +4 -2
  33. package/dist/service/iam/sim-iam-account-parts.d.ts +8 -0
  34. package/dist/service/iam/sim-iam-account-parts.js +1 -0
  35. package/dist/service/sts/auth-z/assume-role-auth-z-coordinator.d.ts +9 -2
  36. package/dist/service/sts/auth-z/assume-role-auth-z-coordinator.js +2 -2
  37. package/dist/service/sts/auth-z/assume-role-source-account-auth-z.d.ts +10 -4
  38. package/dist/service/sts/auth-z/assume-role-source-account-auth-z.js +8 -7
  39. package/dist/service/sts/auth-z/assume-role-target-auth-z.d.ts +2 -2
  40. package/dist/service/sts/auth-z/assume-role-trust-policy-authorizer.d.ts +6 -2
  41. package/dist/service/sts/auth-z/assume-role-trust-policy-authorizer.js +14 -11
  42. package/dist/service/sts/command/assume-role/assume-role.handler.d.ts +5 -1
  43. package/dist/service/sts/command/assume-role/assume-role.handler.js +5 -2
  44. package/dist/service/sts/command/get-caller-identity/get-caller-identity.handler.d.ts +5 -1
  45. package/dist/service/sts/command/get-caller-identity/get-caller-identity.handler.js +4 -1
  46. package/dist/service/sts/service-role/sim-service-role.js +5 -1
  47. package/dist/service/sts/sim-sts.d.ts +9 -1
  48. package/dist/service/sts/sim-sts.js +4 -0
  49. package/docs/README.md +54 -0
  50. package/docs/ai-skill/README.md +69 -0
  51. package/docs/cli/README.md +284 -0
  52. package/docs/factories/README.md +140 -0
  53. package/docs/lint/README.md +176 -0
  54. package/docs/non-aws-dependencies/README.md +261 -0
  55. package/docs/sdk/README.md +272 -0
  56. package/docs/serve/README.md +1126 -0
  57. package/docs/services/acm/README.md +823 -0
  58. package/docs/services/apigateway/README.md +1919 -0
  59. package/docs/services/apigatewayv2/README.md +2678 -0
  60. package/docs/services/athena/README.md +1044 -0
  61. package/docs/services/bedrock/README.md +350 -0
  62. package/docs/services/cloudformation/README.md +3440 -0
  63. package/docs/services/cloudfront/README.md +2874 -0
  64. package/docs/services/cloudwatch/README.md +420 -0
  65. package/docs/services/cognito/README.md +4923 -0
  66. package/docs/services/dynamodb/README.md +3784 -0
  67. package/docs/services/ecr/README.md +302 -0
  68. package/docs/services/ecs/README.md +2010 -0
  69. package/docs/services/elbv2/README.md +1897 -0
  70. package/docs/services/eventbridge/README.md +1110 -0
  71. package/docs/services/firehose/README.md +805 -0
  72. package/docs/services/glue/README.md +501 -0
  73. package/docs/services/iam/README.md +1283 -0
  74. package/docs/services/kinesis/README.md +454 -0
  75. package/docs/services/kms/README.md +659 -0
  76. package/docs/services/lambda/README.md +3645 -0
  77. package/docs/services/logs/README.md +868 -0
  78. package/docs/services/organizations/README.md +574 -0
  79. package/docs/services/personalize/README.md +835 -0
  80. package/docs/services/rekognition/README.md +1070 -0
  81. package/docs/services/route53/README.md +1783 -0
  82. package/docs/services/s3/README.md +3024 -0
  83. package/docs/services/scheduler/README.md +806 -0
  84. package/docs/services/secretsmanager/README.md +667 -0
  85. package/docs/services/ses/README.md +1011 -0
  86. package/docs/services/sns/README.md +1904 -0
  87. package/docs/services/sqs/README.md +1185 -0
  88. package/docs/services/ssm/README.md +1072 -0
  89. package/docs/services/stepfunctions/README.md +1332 -0
  90. package/docs/services/sts/README.md +245 -0
  91. package/docs/services/wafv2/README.md +1378 -0
  92. package/docs/terraform/README.md +248 -0
  93. package/docs/time/README.md +284 -0
  94. package/llms.txt +59 -0
  95. package/package.json +7 -4
@@ -0,0 +1,3645 @@
1
+ # Simulated Lambda
2
+
3
+ Yulin includes a simulated AWS Lambda service for tests and local development. Functions are created
4
+ and invoked in-process and in memory, with no containers and no real AWS infrastructure.
5
+
6
+ Handlers run with their execution role as the simulated caller, so AWS calls made inside a handler
7
+ are authorized by simulated IAM, as on real Lambda.
8
+
9
+ Lambda-specific helpers are imported from the `@kensio/yulin/lambda` subpath. Real `LambdaClient`
10
+ instances can be routed into sim Lambda with
11
+ [SDK interception](https://yulinsim.dev/sdk/ "Simulated AWS SDK interception docs").
12
+
13
+ ## Creating and invoking a function
14
+
15
+ The quickest way to a working function is to pass a real in-process handler function through the
16
+ SDK-shaped `Code.ZipFile` input with `makeLambdaZipFileInput(...)`. The handler is an ordinary
17
+ function in your Node.js process. It can be stepped through in a debugger and can close over local
18
+ state.
19
+
20
+ ```typescript sim-lambda-create-and-invoke
21
+ /**
22
+ * Creating and invoking a simulated Lambda function backed by a real
23
+ * in-process handler function.
24
+ */
25
+
26
+ import {
27
+ CreateFunctionCommand,
28
+ GetFunctionCommand,
29
+ InvokeCommand,
30
+ } from "@aws-sdk/client-lambda";
31
+
32
+ import { SimAws } from "@kensio/yulin";
33
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
34
+
35
+ const simAws = new SimAws();
36
+ const lambda = simAws.lambda();
37
+
38
+ await lambda.createFunction(
39
+ new CreateFunctionCommand({
40
+ FunctionName: "greeter",
41
+ Role: "arn:aws:iam::111111111111:role/GreeterRole",
42
+ Code: {
43
+ ZipFile: makeLambdaZipFileInput(
44
+ (event: { name: string }) => `Hello ${event.name}`,
45
+ ),
46
+ },
47
+ }),
48
+ );
49
+
50
+ const invokeOutput = await lambda.invoke(
51
+ new InvokeCommand({
52
+ FunctionName: "greeter",
53
+ Payload: JSON.stringify({ name: "Yulin" }),
54
+ }),
55
+ );
56
+
57
+ if (invokeOutput.Payload === undefined) throw new Error("No invoke Payload");
58
+ console.log(invokeOutput.StatusCode);
59
+ console.log(Buffer.from(invokeOutput.Payload).toString());
60
+
61
+ await simAws.backgroundTasksComplete();
62
+
63
+ const fetched = await lambda.getFunction(
64
+ new GetFunctionCommand({ FunctionName: "greeter" }),
65
+ );
66
+ console.log(fetched.Configuration.State);
67
+ ```
68
+
69
+ Creating a function requires an execution `Role` ARN, as on real AWS. A new function starts in the
70
+ `Pending` state and becomes `Active` in the background. Wait with
71
+ `simAws.backgroundTasksComplete()` when a test asserts on the `Active` state.
72
+
73
+ Handlers use the same signature as real Node.js Lambda handlers, `(event, context, callback)`. All
74
+ the real completion styles work. Return a promise, return a plain value, call the callback, or use
75
+ the legacy context `done`/`fail`/`succeed` methods. Typed handlers written against the `aws-lambda`
76
+ typings package can be passed in unchanged.
77
+
78
+ A handler that throws is reported AWS-style. The invocation output has `FunctionError:
79
+ "Unhandled"` and the payload is an error document with `errorType`, `errorMessage`, and `trace`.
80
+ The invoke call itself returns normally.
81
+
82
+ ## Zip-packaged code and the vm runtime
83
+
84
+ Real Lambda receives function code as a zip archive. `makeLambdaCodeZip(...)` builds real zip
85
+ bytes from a source string (which becomes a single `index.js` module) or from a files map keyed by
86
+ archive path (like a bundled deployment package). The archive runs in a Node.js `vm` context with
87
+ real cold-start semantics. The module is imported once, on first invocation, and module state stays
88
+ warm across invocations.
89
+
90
+ ```typescript sim-lambda-zip-code-vm-runtime
91
+ /**
92
+ * Running zip-packaged function code in the simulated vm runtime.
93
+ */
94
+
95
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
96
+
97
+ import { SimAws } from "@kensio/yulin";
98
+ import { makeLambdaCodeZip } from "@kensio/yulin/lambda";
99
+
100
+ const simAws = new SimAws();
101
+ const lambda = simAws.lambda();
102
+
103
+ const codeZip = makeLambdaCodeZip(`
104
+ let invocations = 0;
105
+ exports.handler = async (event) => {
106
+ invocations += 1;
107
+ return { name: event.name, invocations };
108
+ };
109
+ `);
110
+
111
+ await lambda.createFunction(
112
+ new CreateFunctionCommand({
113
+ FunctionName: "warm-counter",
114
+ Role: "arn:aws:iam::111111111111:role/WarmCounterRole",
115
+ Handler: "index.handler",
116
+ Runtime: "nodejs22.x",
117
+ Code: { ZipFile: codeZip },
118
+ }),
119
+ );
120
+
121
+ const first = await lambda.invoke(
122
+ new InvokeCommand({
123
+ FunctionName: "warm-counter",
124
+ Payload: JSON.stringify({ name: "one" }),
125
+ }),
126
+ );
127
+ const second = await lambda.invoke(
128
+ new InvokeCommand({
129
+ FunctionName: "warm-counter",
130
+ Payload: JSON.stringify({ name: "two" }),
131
+ }),
132
+ );
133
+
134
+ if (first.Payload === undefined || second.Payload === undefined) {
135
+ throw new Error("No invoke Payload");
136
+ }
137
+ console.log(Buffer.from(first.Payload).toString());
138
+ console.log(Buffer.from(second.Payload).toString());
139
+
140
+ await simAws.backgroundTasksComplete();
141
+ ```
142
+
143
+ The vm runtime models the real Node.js runtime closely:
144
+
145
+ - The `Handler` string selects the module and export, e.g. `index.handler` or `src/app.handler`.
146
+ - Modules in the archive can `require` each other with relative paths, use Node.js built-in
147
+ modules, and use dependencies bundled under the archive's `node_modules/`.
148
+ - The sandbox provides an AWS-like `process.env` with the standard runtime variables
149
+ (`AWS_REGION`, `AWS_LAMBDA_FUNCTION_NAME`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE`, ...).
150
+ - The sandbox provides writable `process.stdout` and `process.stderr`, with its `console` built
151
+ over them, as the real runtime does. See [What a handler prints](#what-a-handler-prints).
152
+ - Import and handler problems surface as invocation errors, with the real runtime error types
153
+ (`Runtime.ImportModuleError`, `Runtime.HandlerNotFound`, `Runtime.UserCodeSyntaxError`,
154
+ `Runtime.MalformedHandlerName`). Creation succeeds either way.
155
+
156
+ Code is CommonJS, as zipped `.js` files are on the real `nodejs` runtimes. An ES module deployment
157
+ package is refused at cold start. A handler file ending in `.mjs` is reported as
158
+ `Runtime.ImportModuleError` naming the file. A `.js` file opening on `import` is reported as
159
+ `Runtime.UserCodeSyntaxError: Cannot use import statement outside a module`. The archive's root
160
+ `package.json` goes unread. Declaring `"type": "module"` in it makes no difference to either.
161
+ Real Lambda has run ES module packages since nodejs14.x, and `NodejsFunction` in CDK emits one
162
+ under `format: OutputFormat.ESM`.
163
+
164
+ There are two ways round that. An [executable binding](#executable-bindings) or
165
+ `makeLambdaZipFileInput(...)` backs the function with a real in-process handler. The test's own
166
+ module system loads that handler, and its format is whatever the test file's is. An ESM project
167
+ needs nothing further. Where the archive itself has to be the deployed artefact, compile a CommonJS
168
+ build of the same source and deploy that as the function's code.
169
+
170
+ `Code.ZipFile` bytes that fail to unzip are rejected at creation with the AWS-like
171
+ `InvalidParameterValueException: Could not unzip uploaded file`.
172
+
173
+ The archives are real zip files, and they interoperate with real tooling in both directions. A zip
174
+ built by any other tool works as `Code.ZipFile` input, and `makeLambdaCodeZip` output can be
175
+ unzipped normally.
176
+
177
+ ### What a handler prints
178
+
179
+ The sandbox has writable standard streams. `process.stdout.write(...)` and
180
+ `process.stderr.write(...)` work inside a handler, and its `console` is built over them as the real
181
+ runtime's is. A logging library that builds its own console over them works too:
182
+
183
+ ```javascript
184
+ const { Console } = require("node:console");
185
+ const logger = new Console({ stdout: process.stdout, stderr: process.stderr });
186
+ ```
187
+
188
+ That is what AWS Lambda Powertools' `Logger` does, at module scope, and a bundled Powertools handler
189
+ runs here. Its `Metrics` writes its embedded metric format document to standard output, where the
190
+ metrics a handler emitted can be read back the same way its log lines can.
191
+
192
+ What a handler prints is recorded into the function's log group in
193
+ [simulated CloudWatch Logs](https://yulinsim.dev/services/logs/ "Simulated CloudWatch Logs usage docs"), at
194
+ `/aws/lambda/<function name>`. A test asserts on it by searching that group:
195
+
196
+ ```typescript
197
+ const found = await simAws.logs().filterLogEvents(
198
+ new FilterLogEventsCommand({
199
+ logGroupName: "/aws/lambda/orders",
200
+ filterPattern: "ERROR",
201
+ }),
202
+ );
203
+ ```
204
+
205
+ One line becomes one log event, as it does in an account. A handler printing a multi-line object
206
+ gets several events, and a search for one of those lines finds it. EMF metric documents go to the
207
+ same place, since Powertools' `Metrics` writes them to standard output.
208
+
209
+ Each invocation also reaches the matching host stream, standard output to standard output and
210
+ standard error to standard error, where a test or a `pnpm run dev` session already sees output. That
211
+ is a tee rather than a redirect. Real Lambda sends output to CloudWatch Logs and nowhere else, and a
212
+ test tool that swallowed the output would make a failing test harder to debug than it is with none
213
+ of this.
214
+
215
+ `context.logGroupName` and `context.logStreamName` name the group and stream that were actually
216
+ written to, and stream names use the real `YYYY/MM/DD/[$LATEST]<hash>` format. The hash identifies
217
+ the execution environment rather than the request. Match the shape, and leave the value alone.
218
+
219
+ A function backed by a handler function reference is recorded too, whether the handler arrived
220
+ through `Code.ZipFile`, through a CloudFormation stack binding, or as the image of a simulated ECR
221
+ repository. Such a handler is a closure over your own module scope and prints through the same
222
+ console and standard streams as the rest of the test run, and both are bridged to the function's log
223
+ group for the length of an invocation, in the way `process.env` and `Date` are. `console.log`,
224
+ `console.info`, `console.debug`, `console.warn` and `console.error` all arrive, along with anything
225
+ written to `process.stdout` or `process.stderr`, so a logging library building its own console over
226
+ the process streams is recorded as well. Printing with no invocation running reaches the host
227
+ console alone.
228
+
229
+ A test that binds its handler for a breakpoint, or so the handler can close over its own state, can
230
+ still assert on the lines it logged:
231
+
232
+ ```typescript sim-lambda-bound-handler-output
233
+ /**
234
+ * Asserting on what a bound in-process Lambda handler printed.
235
+ */
236
+
237
+ import { FilterLogEventsCommand } from "@aws-sdk/client-cloudwatch-logs";
238
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
239
+
240
+ import { SimAws } from "@kensio/yulin";
241
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
242
+
243
+ const simAws = new SimAws();
244
+
245
+ await simAws.lambda().createFunction(
246
+ new CreateFunctionCommand({
247
+ FunctionName: "orders",
248
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
249
+ Code: {
250
+ ZipFile: makeLambdaZipFileInput((event: { orderId: string }) => {
251
+ console.log(`ERROR ${event.orderId} has no items`);
252
+
253
+ return "rejected";
254
+ }),
255
+ },
256
+ }),
257
+ );
258
+
259
+ await simAws.lambda().invoke(
260
+ new InvokeCommand({
261
+ FunctionName: "orders",
262
+ Payload: JSON.stringify({ orderId: "order-1" }),
263
+ }),
264
+ );
265
+
266
+ const logged = await simAws.logs().filterLogEvents(
267
+ new FilterLogEventsCommand({
268
+ logGroupName: "/aws/lambda/orders",
269
+ filterPattern: "ERROR",
270
+ }),
271
+ );
272
+
273
+ // [ 'ERROR order-1 has no items' ]
274
+ console.log(logged.events?.map((event) => event.message));
275
+
276
+ await simAws.backgroundTasksComplete();
277
+ ```
278
+
279
+ ## Function code from S3
280
+
281
+ Function code can also be fetched from a zip object stored in sim S3, as SAM and CDK deployments
282
+ do on real AWS. The code object is fetched once at creation time, as the creating caller, so
283
+ simulated IAM applies to the code object read.
284
+
285
+ ```typescript sim-lambda-s3-code
286
+ /**
287
+ * Creating a simulated Lambda function from a code zip stored in sim S3.
288
+ */
289
+
290
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
291
+ import { CreateBucketCommand, PutObjectCommand } from "@aws-sdk/client-s3";
292
+
293
+ import { SimAws } from "@kensio/yulin";
294
+ import { makeLambdaCodeZip } from "@kensio/yulin/lambda";
295
+
296
+ const simAws = new SimAws();
297
+
298
+ await simAws
299
+ .s3()
300
+ .createBucket(new CreateBucketCommand({ Bucket: "code-bucket" }));
301
+ await simAws.s3().putObject(
302
+ new PutObjectCommand({
303
+ Bucket: "code-bucket",
304
+ Key: "artifacts/greeter.zip",
305
+ Body: makeLambdaCodeZip(
306
+ "exports.handler = async (event) => 'Hello ' + event.name + ' from S3';",
307
+ ),
308
+ }),
309
+ );
310
+
311
+ await simAws.lambda().createFunction(
312
+ new CreateFunctionCommand({
313
+ FunctionName: "s3-greeter",
314
+ Role: "arn:aws:iam::111111111111:role/S3GreeterRole",
315
+ Handler: "index.handler",
316
+ Code: {
317
+ S3Bucket: "code-bucket",
318
+ S3Key: "artifacts/greeter.zip",
319
+ },
320
+ }),
321
+ );
322
+
323
+ const output = await simAws.lambda().invoke(
324
+ new InvokeCommand({
325
+ FunctionName: "s3-greeter",
326
+ Payload: JSON.stringify({ name: "Yulin" }),
327
+ }),
328
+ );
329
+
330
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
331
+ console.log(Buffer.from(output.Payload).toString());
332
+
333
+ await simAws.backgroundTasksComplete();
334
+ ```
335
+
336
+ S3 lookup failures are wrapped AWS-style, e.g. `Error occurred while GetObject. S3 Error Code:
337
+ NoSuchKey. ...`. `S3ObjectVersion` is accepted but ignored, as sim S3 has no object versioning
338
+ yet. A standalone `SimLambda` (constructed directly, outside `SimAws`) has no sim S3 to
339
+ fetch from. `SimAws`-created Lambda wires the same-scope sim S3 automatically, matching real
340
+ Lambda's requirement for a same-region code bucket.
341
+
342
+ ## Replacing a function's code
343
+
344
+ `UpdateFunctionCodeCommand` replaces the code `$LATEST` runs, taking the same four code shapes `CreateFunction` takes. It carries them at the top level of its input rather than under `Code`, as real Lambda does. A test that redeploys part-way through, or that wants a function to start failing after a few invocations, changes what runs without deleting the function.
345
+
346
+ The function keeps everything else it holds. Its name, ARN, execution Role, environment variables, timeout, memory, [resource-based policy](#resource-based-policies), [Function URL](#function-urls), published versions and aliases all survive, which is what separates this from deleting the function and creating it again.
347
+
348
+ ```typescript sim-lambda-update-function-code
349
+ /**
350
+ * Replacing the code a simulated Lambda function runs, part-way through.
351
+ */
352
+
353
+ import {
354
+ CreateFunctionCommand,
355
+ InvokeCommand,
356
+ UpdateFunctionCodeCommand,
357
+ } from "@aws-sdk/client-lambda";
358
+
359
+ import { SimAws } from "@kensio/yulin";
360
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
361
+
362
+ const simAws = new SimAws();
363
+ const lambda = simAws.lambda();
364
+
365
+ await lambda.createFunction(
366
+ new CreateFunctionCommand({
367
+ FunctionName: "orders",
368
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
369
+ Code: { ZipFile: makeLambdaZipFileInput(() => ({ ok: true })) },
370
+ }),
371
+ );
372
+
373
+ await lambda.updateFunctionCode(
374
+ new UpdateFunctionCodeCommand({
375
+ FunctionName: "orders",
376
+ ZipFile: makeLambdaZipFileInput(() => {
377
+ throw new Error("the order service is down");
378
+ }),
379
+ }),
380
+ );
381
+
382
+ const invoked = await lambda.invoke(
383
+ new InvokeCommand({ FunctionName: "orders" }),
384
+ );
385
+ console.log(invoked.FunctionError);
386
+
387
+ await simAws.backgroundTasksComplete();
388
+ ```
389
+
390
+ Zip code runs under the `Handler` the function already has, because `UpdateFunctionCode` carries none of its own. Replacing a handler-reference function's code with a zip archive is refused for that reason. Set a `Handler` with [`UpdateFunctionConfiguration`](#changing-a-functions-settings) first, then replace the code.
391
+
392
+ A published version keeps the code it was published with, so a version published before an update goes on running it while `$LATEST` runs the replacement. `Publish: true` publishes a version of the replacement code and answers with that version rather than with `$LATEST`. See [Versions and aliases](#versions-and-aliases).
393
+
394
+ ## Changing a function's settings
395
+
396
+ `UpdateFunctionConfigurationCommand` changes the settings simulated Lambda models: `Role`, `Handler`, `Runtime`, `Description`, `Timeout`, `MemorySize` and `Environment`. A member the request leaves out keeps the value the function has. Changing one setting says nothing about the rest.
397
+
398
+ `Environment` replaces the whole variable map rather than merging into it, as on real AWS. A variable the request leaves out is gone, and `Variables: {}` clears them all. The names are validated the way `CreateFunction` validates them, down to the reserved ones the runtime owns.
399
+
400
+ ```typescript sim-lambda-update-function-configuration
401
+ /**
402
+ * Changing a simulated Lambda function's timeout and environment variables.
403
+ */
404
+
405
+ import {
406
+ CreateFunctionCommand,
407
+ InvokeCommand,
408
+ UpdateFunctionConfigurationCommand,
409
+ } from "@aws-sdk/client-lambda";
410
+
411
+ import { SimAws } from "@kensio/yulin";
412
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
413
+
414
+ const simAws = new SimAws();
415
+ const lambda = simAws.lambda();
416
+
417
+ await lambda.createFunction(
418
+ new CreateFunctionCommand({
419
+ FunctionName: "orders",
420
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
421
+ Timeout: 30,
422
+ Environment: { Variables: { ORDERS_TABLE: "orders-v1" } },
423
+ Code: {
424
+ ZipFile: makeLambdaZipFileInput((_event, context) => ({
425
+ table: process.env["ORDERS_TABLE"],
426
+ remainingMs: context.getRemainingTimeInMillis(),
427
+ })),
428
+ },
429
+ }),
430
+ );
431
+
432
+ await lambda.updateFunctionConfiguration(
433
+ new UpdateFunctionConfigurationCommand({
434
+ FunctionName: "orders",
435
+ Timeout: 1,
436
+ Environment: { Variables: { ORDERS_TABLE: "orders-v2" } },
437
+ }),
438
+ );
439
+
440
+ const invoked = await lambda.invoke(
441
+ new InvokeCommand({ FunctionName: "orders" }),
442
+ );
443
+ console.log(Buffer.from(invoked.Payload ?? new Uint8Array()).toString());
444
+
445
+ await simAws.backgroundTasksComplete();
446
+ ```
447
+
448
+ The function keeps its name, ARN, code, [resource-based policy](#resource-based-policies), [Function URL](#function-urls), published versions and aliases. A version published beforehand keeps the settings it was published with, and one published afterwards carries the changed ones. See [Versions and aliases](#versions-and-aliases).
449
+
450
+ A changed `Environment`, `MemorySize` or `Handler` reaches the code itself. The next invocation of a [zip code function](#zip-packaged-code-and-the-vm-runtime) cold starts under the new settings. Whatever its module had in memory goes, the way it goes on real Lambda when the configuration changes. A `Handler` change picks a different export out of the archive already deployed, with no need to upload it again.
451
+
452
+ ## Listing the functions
453
+
454
+ `ListFunctionsCommand` reports every function in the Account and Region, each described as `GetFunction` describes it. `FunctionVersion: "ALL"` adds each function's published versions to the listing.
455
+
456
+ ```typescript sim-lambda-list-functions
457
+ /**
458
+ * Listing the simulated Lambda functions an Account and Region holds.
459
+ */
460
+
461
+ import {
462
+ CreateFunctionCommand,
463
+ ListFunctionsCommand,
464
+ } from "@aws-sdk/client-lambda";
465
+
466
+ import { SimAws } from "@kensio/yulin";
467
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
468
+
469
+ const simAws = new SimAws();
470
+ const lambda = simAws.lambda();
471
+
472
+ for (const functionName of ["orders", "invoices"]) {
473
+ await lambda.createFunction(
474
+ new CreateFunctionCommand({
475
+ FunctionName: functionName,
476
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
477
+ Code: { ZipFile: makeLambdaZipFileInput(() => functionName) },
478
+ }),
479
+ );
480
+ }
481
+
482
+ const listed = await lambda.listFunctions(new ListFunctionsCommand({}));
483
+ console.log(listed.Functions.map((simFunction) => simFunction.FunctionName));
484
+
485
+ await simAws.backgroundTasksComplete();
486
+ ```
487
+
488
+ The listing is authorized as a whole, against `lambda:ListFunctions` on `*`, the way AWS documents the permission. A caller without it is denied rather than given a filtered list.
489
+
490
+ ## The runtime-provided AWS SDK
491
+
492
+ Like the real Lambda Node.js runtime, the simulated runtime provides AWS SDK v3 packages without
493
+ them being bundled in the code archive. `require("@aws-sdk/client-s3")`, or any other `@aws-sdk/*`
494
+ package installed in the host project, resolves to the real package with its clients routed into
495
+ the owning simulated AWS environment. Calls the function code makes run as the function's
496
+ execution role, and simulated IAM authorizes them just like real Lambda execution roles.
497
+
498
+ ```typescript sim-lambda-runtime-provided-sdk
499
+ /**
500
+ * Simulated Lambda function code reading sim S3 through the
501
+ * runtime-provided AWS SDK, authorized as its execution role.
502
+ */
503
+
504
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
505
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
506
+ import { CreateBucketCommand, PutObjectCommand } from "@aws-sdk/client-s3";
507
+
508
+ import { SimAws } from "@kensio/yulin";
509
+ import { makeLambdaCodeZip } from "@kensio/yulin/lambda";
510
+
511
+ const simAws = new SimAws();
512
+
513
+ // An object for the function to read.
514
+ await simAws
515
+ .s3()
516
+ .createBucket(new CreateBucketCommand({ Bucket: "data-bucket" }));
517
+ await simAws.s3().putObject(
518
+ new PutObjectCommand({
519
+ Bucket: "data-bucket",
520
+ Key: "greeting.txt",
521
+ Body: "Hello from S3",
522
+ }),
523
+ );
524
+
525
+ // An execution role allowed to read it.
526
+ const roleCreation = await simAws.iam().createRole(
527
+ new CreateRoleCommand({
528
+ RoleName: "ReaderRole",
529
+ AssumeRolePolicyDocument: JSON.stringify({
530
+ Version: "2012-10-17",
531
+ Statement: {
532
+ Effect: "Allow",
533
+ Principal: { Service: "lambda.amazonaws.com" },
534
+ Action: "sts:AssumeRole",
535
+ },
536
+ }),
537
+ }),
538
+ );
539
+ await simAws.iam().putRolePolicy(
540
+ new PutRolePolicyCommand({
541
+ RoleName: "ReaderRole",
542
+ PolicyName: "ReadDataBucket",
543
+ PolicyDocument: JSON.stringify({
544
+ Version: "2012-10-17",
545
+ Statement: {
546
+ Effect: "Allow",
547
+ Action: "s3:GetObject",
548
+ Resource: "arn:aws:s3:::data-bucket/*",
549
+ },
550
+ }),
551
+ }),
552
+ );
553
+
554
+ // Function code using the runtime-provided AWS SDK.
555
+ await simAws.lambda().createFunction(
556
+ new CreateFunctionCommand({
557
+ FunctionName: "reader",
558
+ Role: roleCreation.Role.Arn,
559
+ Handler: "index.handler",
560
+ Code: {
561
+ ZipFile: makeLambdaCodeZip(`
562
+ const { S3Client, GetObjectCommand } = require("@aws-sdk/client-s3");
563
+ const s3Client = new S3Client({});
564
+ exports.handler = async (event) => {
565
+ const output = await s3Client.send(
566
+ new GetObjectCommand({
567
+ Bucket: "data-bucket",
568
+ Key: event.objectKey,
569
+ }),
570
+ );
571
+ return await output.Body.transformToString();
572
+ };
573
+ `),
574
+ },
575
+ }),
576
+ );
577
+
578
+ const output = await simAws.lambda().invoke(
579
+ new InvokeCommand({
580
+ FunctionName: "reader",
581
+ Payload: JSON.stringify({ objectKey: "greeting.txt" }),
582
+ }),
583
+ );
584
+
585
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
586
+ console.log(Buffer.from(output.Payload).toString());
587
+
588
+ await simAws.backgroundTasksComplete();
589
+ ```
590
+
591
+ If the execution role lacks permission for a call the handler makes, simulated IAM denies it and
592
+ the invocation reports the denial as an unhandled function error, just as a real execution-role
593
+ denial surfaces inside the handler.
594
+
595
+ A client constructed without a region defaults to the function's account and region scope, as the
596
+ real runtime's `AWS_REGION` provides. An explicit region on the client wins. The archive always
597
+ takes precedence. A package bundled under the archive's `node_modules/` is used as it stands, and
598
+ reaches the simulation through the transport below.
599
+
600
+ An `@aws-sdk/*` package the project has not installed is refused when the function code requires
601
+ it. The message names every other AWS SDK package the code imports and the project is missing too.
602
+ One install then covers the set. (The archive is the only place to read what a third-party function
603
+ imports.) Packages bundled under the archive's `node_modules/` are left out of that list, along with
604
+ anything only a bundled dependency imports.
605
+
606
+ ### Function code that bundles the SDK
607
+
608
+ Some deployment packages inline the SDK rather than relying on the runtime to provide it. CDK's
609
+ `NodejsFunction` does that when given `bundling: { externalModules: [] }`. There is then no
610
+ `@aws-sdk/*` module left for the runtime to provide, and nothing to intercept.
611
+
612
+ Those functions reach the simulation anyway. The runtime provides their HTTP transport, `node:http`
613
+ and `node:https`, and a request addressed to an AWS API endpoint is answered from the same
614
+ simulated services, as the same execution role, instead of going to the network. The execution
615
+ role credentials are in the function's environment, as real Lambda puts them there. The SDK resolves
616
+ credentials inside the sandbox, where it would otherwise fail with `CredentialsProviderError`.
617
+
618
+ A serialized request states which operation it is and carries its input for the services using the
619
+ AWS JSON protocol. Those are the ones that can be read back without the operation's schema:
620
+
621
+ ACM, CloudWatch Logs, Cognito Identity Provider, DynamoDB, DynamoDB Streams, ECS, EventBridge, KMS,
622
+ Rekognition, Secrets Manager, SQS and SSM.
623
+
624
+ A bundled call to any other simulated service, such as S3, SNS, SES or Lambda itself, fails with an
625
+ error naming the service. Leaving the SDK out of that archive puts it back
626
+ on the module interception path above, which every simulated service is reachable through.
627
+
628
+ Values the JSON protocols encode travel in their encoded form. A binary attribute written through a
629
+ bundled SDK is stored base64-encoded and decodes correctly when the same path reads it back, where
630
+ an in-process intercepted client reading it sees the encoded string.
631
+
632
+ Only service API endpoints are answered as Commands. The endpoint of one resource, such as a Lambda
633
+ Function URL or an API Gateway HTTP API, carries an ordinary HTTP request. Those are routed by
634
+ hostname, along with everything else a handler asks for over HTTP.
635
+
636
+ ## The HTTP requests function code makes
637
+
638
+ A request from a handler to a hostname the simulation serves is answered by the simulation. It
639
+ never leaves the process. `fetch`, `node:http` and `node:https` all reach it, so it makes no
640
+ difference which client the handler was written with.
641
+
642
+ Two kinds of hostname are served. Everything simulated Route53 resolves is answered over the same
643
+ in-process HTTP entry point a browser on localhost reaches. That covers a
644
+ [Cognito user pool domain](https://yulinsim.dev/services/cognito/ "Simulated Cognito usage docs") in both of its forms
645
+ (`<prefix>.auth.<region>.amazoncognito.com` and a custom domain such as `auth.example.com`), an
646
+ [API Gateway HTTP API](https://yulinsim.dev/services/apigatewayv2/ "Simulated API Gateway usage docs"), a
647
+ [load balancer](https://yulinsim.dev/services/elbv2/ "Simulated ELBv2 usage docs") and anything a hosted-zone record points at
648
+ one of those.
649
+
650
+ The AWS service API endpoints are the other kind, and a request to one is read for what it carries.
651
+ A serialized Command goes to the simulated operation it names (the section above). A request
652
+ carrying no operation header and no signature is an ordinary HTTP request, and the endpoint serves
653
+ it the way the local hostname does. That is how a pool's JWKS is read at
654
+ `cognito-idp.<region>.amazonaws.com` by a client holding no credentials.
655
+
656
+ A hostname the simulation serves nothing at goes where it was addressed. A handler calling a
657
+ payment API or a webhook reaches the network as it always did.
658
+
659
+ The authorization code grant is the request this exists for. Cognito issues an authorization code
660
+ to the browser and the application exchanges it for tokens from its own server, and there is no SDK
661
+ operation for that exchange. It is a POST to `/oauth2/token` on the pool's domain, which is a
662
+ hostname the simulation now serves:
663
+
664
+ ```typescript sim-lambda-outbound-token-exchange
665
+ /**
666
+ * A simulated Lambda exchanging an authorization code for tokens at the
667
+ * simulated Cognito user pool domain that issued it.
668
+ */
669
+
670
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
671
+
672
+ import { SimAws } from "@kensio/yulin";
673
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
674
+
675
+ const simAws = new SimAws({ defaultRegionName: "eu-west-2" });
676
+
677
+ // The pool's domain, the app client the callback authenticates as, and the
678
+ // code the browser carried to it.
679
+ declare const domainHost: string;
680
+ declare const clientId: string;
681
+ declare const clientSecret: string;
682
+ declare const callbackUrl: string;
683
+ declare const authorizationCode: string;
684
+
685
+ await simAws.lambda().createFunction(
686
+ new CreateFunctionCommand({
687
+ FunctionName: "user",
688
+ Role: "arn:aws:iam::111111111111:role/UserRole",
689
+ Code: {
690
+ ZipFile: makeLambdaZipFileInput(async (event: { code: string }) => {
691
+ const credentials = `${clientId}:${clientSecret}`;
692
+ const response = await fetch(`https://${domainHost}/oauth2/token`, {
693
+ method: "POST",
694
+ headers: {
695
+ "content-type": "application/x-www-form-urlencoded",
696
+ authorization: `Basic ${Buffer.from(credentials).toString("base64")}`,
697
+ },
698
+ body: new URLSearchParams({
699
+ grant_type: "authorization_code",
700
+ code: event.code,
701
+ redirect_uri: callbackUrl,
702
+ }).toString(),
703
+ });
704
+
705
+ return await response.json();
706
+ }),
707
+ },
708
+ }),
709
+ );
710
+
711
+ const output = await simAws.lambda().invoke(
712
+ new InvokeCommand({
713
+ FunctionName: "user",
714
+ Payload: JSON.stringify({ code: authorizationCode }),
715
+ }),
716
+ );
717
+
718
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
719
+
720
+ // The id, access and refresh tokens the pool issued.
721
+ console.log(Buffer.from(output.Payload).toString());
722
+
723
+ await simAws.backgroundTasksComplete();
724
+ ```
725
+
726
+ Zip-packaged code takes its three clients from the sandbox the vm runtime builds around it, and
727
+ nothing outside that sandbox is touched. A handler function reference is a closure over your own
728
+ module scope and reads the same globals as the rest of the test run, so those globals are bridged
729
+ for the length of an invocation, in the way `process.env` and `Date` are (see
730
+ [Read environment variables inside the handler](#read-environment-variables-inside-the-handler)).
731
+ With no invocation running they behave as they always did, which leaves a request a handler module
732
+ makes while it is being imported going to the network.
733
+
734
+ A response comes back from the simulation as it was answered. A redirect arrives as the `302` it
735
+ is, where the host `fetch` would have followed it.
736
+
737
+ ### Verifying a Cognito token in a handler
738
+
739
+ An API that takes a bearer token verifies it against the keys the pool publishes.
740
+ `CognitoJwtVerifier` from `aws-jwt-verify` builds the JWKS URL from the pool id
741
+ (`https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json`) and accepts no
742
+ other, and fetches it with `node:https` the first time it verifies anything. Both of those are the
743
+ simulation's to answer inside a handler, so the verifier in the deployed code verifies a simulated
744
+ pool's token with no cache primed and no setup around it:
745
+
746
+ ```typescript sim-lambda-verify-cognito-token
747
+ /**
748
+ * A simulated Lambda verifying a Cognito access token, with a verifier that
749
+ * goes and fetches the pool's JWKS for itself.
750
+ */
751
+
752
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
753
+ import { CognitoJwtVerifier } from "aws-jwt-verify";
754
+
755
+ import { SimAws } from "@kensio/yulin";
756
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
757
+
758
+ const simAws = new SimAws({ defaultRegionName: "eu-west-2" });
759
+
760
+ // The pool the API trusts, the app client its tokens are issued to, and the
761
+ // token a caller presented.
762
+ declare const userPoolId: string;
763
+ declare const clientId: string;
764
+ declare const accessToken: string;
765
+
766
+ await simAws.lambda().createFunction(
767
+ new CreateFunctionCommand({
768
+ FunctionName: "api",
769
+ Role: "arn:aws:iam::111111111111:role/ApiRole",
770
+ Code: {
771
+ ZipFile: makeLambdaZipFileInput(async (event: { token: string }) => {
772
+ const verifier = CognitoJwtVerifier.create({
773
+ userPoolId,
774
+ tokenUse: "access",
775
+ clientId,
776
+ });
777
+
778
+ return await verifier.verify(event.token);
779
+ }),
780
+ },
781
+ }),
782
+ );
783
+
784
+ const output = await simAws.lambda().invoke(
785
+ new InvokeCommand({
786
+ FunctionName: "api",
787
+ Payload: JSON.stringify({ token: accessToken }),
788
+ }),
789
+ );
790
+
791
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
792
+
793
+ // The claims of the access token, read by the verifier the API ships with.
794
+ console.log(Buffer.from(output.Payload).toString());
795
+
796
+ await simAws.backgroundTasksComplete();
797
+ ```
798
+
799
+ The pool's OpenID configuration is served at the same endpoint, at
800
+ `/<userPoolId>/.well-known/openid-configuration`. Its `issuer` and `jwks_uri` name the local
801
+ hostname the simulation answered on, and a handler that discovered the document can fetch the keys
802
+ it points at. See
803
+ [serving a pool's JWKS](https://yulinsim.dev/services/cognito/#serving-a-pools-jwks-on-localhost "Simulated Cognito usage docs").
804
+
805
+ A Command the same function sends still reaches simulated Cognito. An SDK bundled into the
806
+ deployment package addresses `cognito-idp.<region>.amazonaws.com` as well, and its requests carry
807
+ the operation header that says so.
808
+
809
+ ## Invocation types
810
+
811
+ `InvokeCommand` supports the three AWS invocation types. `RequestResponse` (the default) awaits
812
+ the handler and returns its JSON-serialised result as the response payload. `Event` returns `202`
813
+ immediately and runs the handler in the background. `DryRun` returns `204` without invoking the
814
+ handler at all.
815
+
816
+ ```typescript sim-lambda-invocation-types
817
+ /**
818
+ * Simulated Lambda Event and DryRun invocation types.
819
+ */
820
+
821
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
822
+
823
+ import { SimAws } from "@kensio/yulin";
824
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
825
+
826
+ const simAws = new SimAws();
827
+ const lambda = simAws.lambda();
828
+
829
+ const handledEvents: unknown[] = [];
830
+ await lambda.createFunction(
831
+ new CreateFunctionCommand({
832
+ FunctionName: "recorder",
833
+ Role: "arn:aws:iam::111111111111:role/RecorderRole",
834
+ Code: {
835
+ ZipFile: makeLambdaZipFileInput((event) => {
836
+ handledEvents.push(event);
837
+ return null;
838
+ }),
839
+ },
840
+ }),
841
+ );
842
+
843
+ // An Event invocation is accepted before the handler has run.
844
+ const eventOutput = await lambda.invoke(
845
+ new InvokeCommand({
846
+ FunctionName: "recorder",
847
+ InvocationType: "Event",
848
+ Payload: JSON.stringify({ recorded: true }),
849
+ }),
850
+ );
851
+ console.log(eventOutput.StatusCode);
852
+ console.log(handledEvents.length);
853
+
854
+ // The handler runs when simulator background tasks complete.
855
+ await simAws.backgroundTasksComplete();
856
+ console.log(handledEvents.length);
857
+
858
+ // A DryRun invocation never runs the handler.
859
+ const dryRunOutput = await lambda.invoke(
860
+ new InvokeCommand({
861
+ FunctionName: "recorder",
862
+ InvocationType: "DryRun",
863
+ }),
864
+ );
865
+ console.log(dryRunOutput.StatusCode);
866
+ ```
867
+
868
+ `Event` invocation handler errors never reach the caller, who has already been answered. Where the
869
+ handler keeps failing they reach the function's destinations instead, which is what the next section
870
+ covers.
871
+
872
+ ## Asynchronous retries and destinations
873
+
874
+ An `Event` invocation whose handler throws is retried twice, as real Lambda retries one. The retries
875
+ wait on the simulated clock, about a minute before the first and two before the second, so a test
876
+ reaches them by advancing time rather than by waiting for it.
877
+
878
+ `PutFunctionEventInvokeConfigCommand` changes how many retries a function makes and where its
879
+ results go. An invocation that fails its last attempt is sent to the `OnFailure` destination, and
880
+ one whose handler returns is sent to `OnSuccess`. A destination ARN can name a simulated SQS queue,
881
+ SNS topic, EventBridge event bus or Lambda function.
882
+
883
+ ```typescript sim-lambda-async-destinations
884
+ /**
885
+ * Asynchronous invocation retries and an OnFailure destination.
886
+ */
887
+
888
+ import {
889
+ CreateFunctionCommand,
890
+ InvokeCommand,
891
+ PutFunctionEventInvokeConfigCommand,
892
+ } from "@aws-sdk/client-lambda";
893
+ import { CreateQueueCommand, ReceiveMessageCommand } from "@aws-sdk/client-sqs";
894
+
895
+ import { SimAws } from "@kensio/yulin";
896
+ import {
897
+ makeLambdaZipFileInput,
898
+ type SimLambdaDestinationRecord,
899
+ } from "@kensio/yulin/lambda";
900
+
901
+ const simAws = new SimAws();
902
+ const lambda = simAws.lambda();
903
+ const sqs = simAws.sqs();
904
+
905
+ const created = await sqs.createQueue(
906
+ new CreateQueueCommand({ QueueName: "order-failures" }),
907
+ );
908
+
909
+ const attempts: string[] = [];
910
+ await lambda.createFunction(
911
+ new CreateFunctionCommand({
912
+ FunctionName: "orders",
913
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
914
+ Code: {
915
+ ZipFile: makeLambdaZipFileInput((event: { id: number }) => {
916
+ attempts.push(`tried order ${event.id}`);
917
+ throw new Error("orders handler failed");
918
+ }),
919
+ },
920
+ }),
921
+ );
922
+
923
+ await lambda.putFunctionEventInvokeConfig(
924
+ new PutFunctionEventInvokeConfigCommand({
925
+ FunctionName: "orders",
926
+ MaximumRetryAttempts: 1,
927
+ DestinationConfig: {
928
+ OnFailure: {
929
+ Destination: "arn:aws:sqs:us-east-1:888888888888:order-failures",
930
+ },
931
+ },
932
+ }),
933
+ );
934
+
935
+ await lambda.invoke(
936
+ new InvokeCommand({
937
+ FunctionName: "orders",
938
+ InvocationType: "Event",
939
+ Payload: JSON.stringify({ id: 7 }),
940
+ }),
941
+ );
942
+
943
+ // The first attempt runs behind the caller. The retry waits on the clock.
944
+ await simAws.backgroundTasksComplete();
945
+ console.log(attempts.length);
946
+
947
+ await simAws.clock().advanceBy({ minutes: 2 });
948
+ console.log(attempts.length);
949
+
950
+ const received = await sqs.receiveMessage(
951
+ new ReceiveMessageCommand({ QueueUrl: created.QueueUrl }),
952
+ );
953
+ const record = JSON.parse(
954
+ String(received.Messages?.[0]?.Body),
955
+ ) as SimLambdaDestinationRecord;
956
+ console.log(record.requestContext.condition);
957
+ console.log(record.requestContext.approximateInvokeCount);
958
+ console.log(record.requestPayload);
959
+ ```
960
+
961
+ The queue receives the record real Lambda sends, carrying the event that was invoked as
962
+ `requestPayload`, the handler error as `responsePayload`, how many attempts were made, and a
963
+ `condition` of `Success`, `RetriesExhausted` or `EventAgeExceeded`. An event that outlives
964
+ `MaximumEventAgeInSeconds` is given up on before its next attempt and reported under that last
965
+ condition.
966
+
967
+ `GetFunctionEventInvokeConfigCommand`, `UpdateFunctionEventInvokeConfigCommand`,
968
+ `DeleteFunctionEventInvokeConfigCommand` and `ListFunctionEventInvokeConfigsCommand` read and change
969
+ what was written. `Put` writes the whole config, returning a setting it leaves out to its default,
970
+ and `Update` changes only the settings it names. A `Qualifier` gives a published version or an alias
971
+ a config of its own, and an invocation of a qualifier with no config of its own uses the function's.
972
+
973
+ ### Dead-letter targets
974
+
975
+ `DeadLetterConfig` is the older way to keep a failed asynchronous invocation, and simulated Lambda
976
+ takes it on `CreateFunction` and `UpdateFunctionConfiguration`. Its `TargetArn` names a simulated
977
+ SQS queue or SNS topic, which receives the event as it was invoked rather than the destination
978
+ record around it.
979
+
980
+ ```typescript sim-lambda-dead-letter-queue
981
+ /**
982
+ * A simulated Lambda function with a dead-letter queue.
983
+ */
984
+
985
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
986
+ import { CreateQueueCommand, ReceiveMessageCommand } from "@aws-sdk/client-sqs";
987
+
988
+ import { SimAws } from "@kensio/yulin";
989
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
990
+
991
+ const simAws = new SimAws();
992
+ const lambda = simAws.lambda();
993
+ const sqs = simAws.sqs();
994
+
995
+ const created = await sqs.createQueue(
996
+ new CreateQueueCommand({ QueueName: "orders-dlq" }),
997
+ );
998
+
999
+ await lambda.createFunction(
1000
+ new CreateFunctionCommand({
1001
+ FunctionName: "orders",
1002
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
1003
+ DeadLetterConfig: {
1004
+ TargetArn: "arn:aws:sqs:us-east-1:888888888888:orders-dlq",
1005
+ },
1006
+ Code: {
1007
+ ZipFile: makeLambdaZipFileInput(() => {
1008
+ throw new Error("orders handler failed");
1009
+ }),
1010
+ },
1011
+ }),
1012
+ );
1013
+
1014
+ await lambda.invoke(
1015
+ new InvokeCommand({
1016
+ FunctionName: "orders",
1017
+ InvocationType: "Event",
1018
+ Payload: JSON.stringify({ id: 7 }),
1019
+ }),
1020
+ );
1021
+
1022
+ // Past both retries, so the invocation has been given up on.
1023
+ await simAws.backgroundTasksComplete();
1024
+ await simAws.clock().advanceBy({ minutes: 5 });
1025
+
1026
+ const received = await sqs.receiveMessage(
1027
+ new ReceiveMessageCommand({ QueueUrl: created.QueueUrl }),
1028
+ );
1029
+ console.log(received.Messages?.[0]?.Body);
1030
+ ```
1031
+
1032
+ A function carrying both a dead-letter target and an `OnFailure` destination sends to both.
1033
+
1034
+ ## Versions and aliases
1035
+
1036
+ `PublishVersionCommand` copies a function as it stands and numbers the copy. The first is version
1037
+ `1`, and each later one counts up. The copy keeps the code, handler, timeout, memory and
1038
+ environment it was published with. `CreateAliasCommand` gives one of those versions a name, and
1039
+ `UpdateAliasCommand` moves the name to another version, so a deployment can repoint what callers
1040
+ invoke.
1041
+
1042
+ `InvokeCommand` and `GetFunctionCommand` take a `Qualifier` naming a version number or an alias.
1043
+ The same qualifier can travel on the `FunctionName` instead, appended to the name (`orders:live`)
1044
+ or to a function ARN. `ExecutedVersion` on the invocation output is the version number that ran,
1045
+ and an invocation through an alias reports the version behind it. Inside the handler, `context`
1046
+ carries that number as `functionVersion` and the qualified ARN as `invokedFunctionArn`.
1047
+
1048
+ ```typescript sim-lambda-versions-and-aliases
1049
+ /**
1050
+ * Publishing a simulated Lambda function version, pointing an alias at it,
1051
+ * invoking through the alias, and granting a permission on the alias alone.
1052
+ */
1053
+
1054
+ import {
1055
+ AddPermissionCommand,
1056
+ CreateAliasCommand,
1057
+ CreateFunctionCommand,
1058
+ GetPolicyCommand,
1059
+ InvokeCommand,
1060
+ ListVersionsByFunctionCommand,
1061
+ PublishVersionCommand,
1062
+ } from "@aws-sdk/client-lambda";
1063
+
1064
+ import { SimAws } from "@kensio/yulin";
1065
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
1066
+
1067
+ const simAws = new SimAws();
1068
+ const lambda = simAws.lambda();
1069
+
1070
+ await lambda.createFunction(
1071
+ new CreateFunctionCommand({
1072
+ FunctionName: "orders",
1073
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
1074
+ Code: {
1075
+ ZipFile: makeLambdaZipFileInput((_event, context) => ({
1076
+ ranAs: context.functionVersion,
1077
+ })),
1078
+ },
1079
+ }),
1080
+ );
1081
+
1082
+ const published = await lambda.publishVersion(
1083
+ new PublishVersionCommand({ FunctionName: "orders" }),
1084
+ );
1085
+ console.log(published.Version);
1086
+ console.log(published.FunctionArn);
1087
+
1088
+ await lambda.createAlias(
1089
+ new CreateAliasCommand({
1090
+ FunctionName: "orders",
1091
+ Name: "live",
1092
+ FunctionVersion: published.Version,
1093
+ }),
1094
+ );
1095
+
1096
+ const invoked = await lambda.invoke(
1097
+ new InvokeCommand({ FunctionName: "orders", Qualifier: "live" }),
1098
+ );
1099
+ console.log(invoked.ExecutedVersion);
1100
+
1101
+ const versions = await lambda.listVersionsByFunction(
1102
+ new ListVersionsByFunctionCommand({ FunctionName: "orders" }),
1103
+ );
1104
+ console.log(versions.Versions.map((version) => version.Version));
1105
+
1106
+ await lambda.addPermission(
1107
+ new AddPermissionCommand({
1108
+ FunctionName: "orders",
1109
+ Qualifier: "live",
1110
+ StatementId: "AllowReporting",
1111
+ Action: "lambda:InvokeFunction",
1112
+ Principal: "222222222222",
1113
+ }),
1114
+ );
1115
+
1116
+ // The statements granted on the alias, and on nothing else.
1117
+ const aliasPolicy = await lambda.getPolicy(
1118
+ new GetPolicyCommand({ FunctionName: "orders", Qualifier: "live" }),
1119
+ );
1120
+ console.log(aliasPolicy.Policy);
1121
+ ```
1122
+
1123
+ A function with no qualifier is `$LATEST`, which is what every caller that passes none reaches, and
1124
+ what `ListVersionsByFunctionCommand` lists ahead of the published versions. An alias points at a
1125
+ published version, and `$LATEST` is refused with a `ValidationException` on the version pattern, as
1126
+ it is on real Lambda. A qualifier naming no version and no alias fails with
1127
+ `ResourceNotFoundException` against the qualified ARN.
1128
+
1129
+ `GetAliasCommand`, `ListAliasesCommand` and `DeleteAliasCommand` read and remove aliases.
1130
+ `ListAliasesCommand` takes a `FunctionVersion` to narrow the answer to the aliases on one version,
1131
+ and a version nothing published is reported as missing rather than answered with an empty listing.
1132
+ Deleting an alias leaves the version it pointed at invokable by its number. Deleting the function
1133
+ takes its versions and aliases with it.
1134
+
1135
+ `AddPermissionCommand`, `RemovePermissionCommand` and `GetPolicyCommand` take the same `Qualifier`.
1136
+ The statement is held against the version or the alias it names, and carries that qualified ARN as
1137
+ its `Resource`. `GetPolicy` reads back the statements of the one resource it was asked for, and a
1138
+ request with no qualifier reads the function's own. An `Invoke` is authorized against the resource
1139
+ it names. A grant on `live` admits a call through `live`, and a call on the function itself or on
1140
+ the version behind the alias needs a grant of its own. See
1141
+ [Resource-based policies](#resource-based-policies).
1142
+
1143
+ An alias keeps the grants made on it when `UpdateAliasCommand` moves it to another version. That is
1144
+ what makes an alias a stable thing for another Account or another service to be granted (the grant
1145
+ belongs to the name that was integrated against).
1146
+
1147
+ The version and alias commands act on the function itself, so they take its name or its unqualified
1148
+ ARN. A `FunctionName` carrying a qualifier (`orders:live`) is refused with an
1149
+ `InvalidParameterValueException` rather than acted on as though the qualifier were absent.
1150
+
1151
+ ## Triggering a function from an SQS queue
1152
+
1153
+ An event source mapping connects a [simulated queue](https://yulinsim.dev/services/sqs/ "Simulated SQS docs") to a function.
1154
+ Messages sent to the queue are delivered to the handler as an SQS event, with the `Records` shape
1155
+ real Lambda uses.
1156
+
1157
+ Polling runs on the simulation's background scheduler. A test awaits
1158
+ `simAws.backgroundTasksComplete()` and then asserts, without sleeping.
1159
+
1160
+ `BatchSize` says how many messages one invocation may be given, and defaults to 10. The queue and
1161
+ the function have to be in the same account and region, as they do on real AWS.
1162
+
1163
+ ```typescript sim-lambda-sqs-event-source
1164
+ /**
1165
+ * Delivering messages from a simulated queue to a simulated function.
1166
+ */
1167
+
1168
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
1169
+ import {
1170
+ CreateEventSourceMappingCommand,
1171
+ CreateFunctionCommand,
1172
+ } from "@aws-sdk/client-lambda";
1173
+ import { CreateQueueCommand, SendMessageCommand } from "@aws-sdk/client-sqs";
1174
+
1175
+ import { SimAws } from "@kensio/yulin";
1176
+ import {
1177
+ makeLambdaZipFileInput,
1178
+ type SimLambdaSqsEvent,
1179
+ } from "@kensio/yulin/lambda";
1180
+
1181
+ const simAws = new SimAws();
1182
+ const queueArn = `arn:aws:sqs:${simAws.defaultRegionName}:${simAws.defaultAccountId}:orders`;
1183
+
1184
+ const { QueueUrl } = await simAws
1185
+ .sqs()
1186
+ .createQueue(new CreateQueueCommand({ QueueName: "orders" }));
1187
+
1188
+ // The execution role needs the three SQS actions Lambda polls a queue with.
1189
+ const role = await simAws.iam().createRole(
1190
+ new CreateRoleCommand({
1191
+ RoleName: "OrderConsumerRole",
1192
+ AssumeRolePolicyDocument: JSON.stringify({
1193
+ Version: "2012-10-17",
1194
+ Statement: {
1195
+ Effect: "Allow",
1196
+ Principal: { Service: "lambda.amazonaws.com" },
1197
+ Action: "sts:AssumeRole",
1198
+ },
1199
+ }),
1200
+ }),
1201
+ );
1202
+
1203
+ await simAws.iam().putRolePolicy(
1204
+ new PutRolePolicyCommand({
1205
+ RoleName: "OrderConsumerRole",
1206
+ PolicyName: "ConsumeOrders",
1207
+ PolicyDocument: JSON.stringify({
1208
+ Version: "2012-10-17",
1209
+ Statement: {
1210
+ Effect: "Allow",
1211
+ Action: [
1212
+ "sqs:ReceiveMessage",
1213
+ "sqs:DeleteMessage",
1214
+ "sqs:GetQueueAttributes",
1215
+ ],
1216
+ Resource: queueArn,
1217
+ },
1218
+ }),
1219
+ }),
1220
+ );
1221
+
1222
+ const consumed: string[] = [];
1223
+
1224
+ await simAws.lambda().createFunction(
1225
+ new CreateFunctionCommand({
1226
+ FunctionName: "order-consumer",
1227
+ Role: role.Role.Arn,
1228
+ Code: {
1229
+ ZipFile: makeLambdaZipFileInput((event: SimLambdaSqsEvent) => {
1230
+ for (const record of event.Records) {
1231
+ consumed.push(record.body);
1232
+ }
1233
+ }),
1234
+ },
1235
+ }),
1236
+ );
1237
+
1238
+ await simAws.lambda().createEventSourceMapping(
1239
+ new CreateEventSourceMappingCommand({
1240
+ EventSourceArn: queueArn,
1241
+ FunctionName: "order-consumer",
1242
+ BatchSize: 5,
1243
+ }),
1244
+ );
1245
+
1246
+ await simAws
1247
+ .sqs()
1248
+ .sendMessage(new SendMessageCommand({ QueueUrl, MessageBody: "order-1" }));
1249
+
1250
+ // Delivery happens in the background, so wait for the simulation to settle.
1251
+ await simAws.backgroundTasksComplete();
1252
+
1253
+ console.log(consumed); // ["order-1"]
1254
+ ```
1255
+
1256
+ Each record carries `messageId`, `receiptHandle`, `body`, `md5OfBody`, `messageAttributes`,
1257
+ `eventSource`, `eventSourceARN`, `awsRegion`, and the `attributes` map holding `SentTimestamp`,
1258
+ `ApproximateReceiveCount` and `ApproximateFirstReceiveTimestamp`. `SimLambdaSqsEvent` and
1259
+ `SimLambdaSqsEventRecord` are exported from `@kensio/yulin/lambda` for typing a handler, and are
1260
+ minimal structural equivalents of the `SQSEvent` and `SQSRecord` types from the `aws-lambda` typings
1261
+ package, and a handler already written against those can be passed in unchanged. `SenderId` is left
1262
+ out, because a simulated caller has no user or role id to report it as.
1263
+
1264
+ Creating the mapping checks the two things real Lambda checks. The queue has to exist, and the
1265
+ function's execution role has to be allowed `sqs:ReceiveMessage`, `sqs:DeleteMessage` and
1266
+ `sqs:GetQueueAttributes` on it. A role missing one of them fails with
1267
+ `InvalidParameterValueException` naming the operation, before the mapping exists.
1268
+
1269
+ `GetEventSourceMappingCommand`, `ListEventSourceMappingsCommand` and
1270
+ `DeleteEventSourceMappingCommand` read and remove mappings. A mapping is `Creating` when the command
1271
+ returns and `Enabled` once the simulation has caught up, as on real Lambda. Deleting it stops the
1272
+ polling.
1273
+
1274
+ ### Mapping onto a version or an alias
1275
+
1276
+ A `FunctionName` can carry a version number or an alias name on the end, or be a qualified function
1277
+ ARN, and batches then go to the version that qualifier names. `FunctionArn` on the mapping is the
1278
+ alias, and the version behind it is what runs:
1279
+
1280
+ ```typescript sim-lambda-event-source-alias
1281
+ /**
1282
+ * An event source mapping onto an alias, polling for the version it points at.
1283
+ */
1284
+
1285
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
1286
+ import {
1287
+ CreateAliasCommand,
1288
+ CreateEventSourceMappingCommand,
1289
+ CreateFunctionCommand,
1290
+ PublishVersionCommand,
1291
+ } from "@aws-sdk/client-lambda";
1292
+ import { CreateQueueCommand, SendMessageCommand } from "@aws-sdk/client-sqs";
1293
+
1294
+ import { SimAws } from "@kensio/yulin";
1295
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
1296
+
1297
+ const simAws = new SimAws();
1298
+ const lambda = simAws.lambda();
1299
+ const queueArn = `arn:aws:sqs:${simAws.defaultRegionName}:${simAws.defaultAccountId}:orders`;
1300
+
1301
+ const { QueueUrl } = await simAws
1302
+ .sqs()
1303
+ .createQueue(new CreateQueueCommand({ QueueName: "orders" }));
1304
+
1305
+ const role = await simAws.iam().createRole(
1306
+ new CreateRoleCommand({
1307
+ RoleName: "OrderConsumerRole",
1308
+ AssumeRolePolicyDocument: JSON.stringify({
1309
+ Version: "2012-10-17",
1310
+ Statement: {
1311
+ Effect: "Allow",
1312
+ Principal: { Service: "lambda.amazonaws.com" },
1313
+ Action: "sts:AssumeRole",
1314
+ },
1315
+ }),
1316
+ }),
1317
+ );
1318
+
1319
+ await simAws.iam().putRolePolicy(
1320
+ new PutRolePolicyCommand({
1321
+ RoleName: "OrderConsumerRole",
1322
+ PolicyName: "ConsumeOrders",
1323
+ PolicyDocument: JSON.stringify({
1324
+ Version: "2012-10-17",
1325
+ Statement: {
1326
+ Effect: "Allow",
1327
+ Action: [
1328
+ "sqs:ReceiveMessage",
1329
+ "sqs:DeleteMessage",
1330
+ "sqs:GetQueueAttributes",
1331
+ ],
1332
+ Resource: queueArn,
1333
+ },
1334
+ }),
1335
+ }),
1336
+ );
1337
+
1338
+ await lambda.createFunction(
1339
+ new CreateFunctionCommand({
1340
+ FunctionName: "order-consumer",
1341
+ Role: role.Role.Arn,
1342
+ Code: {
1343
+ ZipFile: makeLambdaZipFileInput((_event, context) => {
1344
+ console.log(context.functionVersion); // "1", the version behind `live`
1345
+
1346
+ return "handled";
1347
+ }),
1348
+ },
1349
+ }),
1350
+ );
1351
+
1352
+ const published = await lambda.publishVersion(
1353
+ new PublishVersionCommand({ FunctionName: "order-consumer" }),
1354
+ );
1355
+
1356
+ await lambda.createAlias(
1357
+ new CreateAliasCommand({
1358
+ FunctionName: "order-consumer",
1359
+ Name: "live",
1360
+ FunctionVersion: published.Version,
1361
+ }),
1362
+ );
1363
+
1364
+ const mapping = await lambda.createEventSourceMapping(
1365
+ new CreateEventSourceMappingCommand({
1366
+ EventSourceArn: queueArn,
1367
+ FunctionName: "order-consumer:live",
1368
+ }),
1369
+ );
1370
+
1371
+ console.log(mapping.FunctionArn); // ...:function:order-consumer:live
1372
+
1373
+ await simAws
1374
+ .sqs()
1375
+ .sendMessage(new SendMessageCommand({ QueueUrl, MessageBody: "order-1" }));
1376
+ await simAws.backgroundTasksComplete();
1377
+ ```
1378
+
1379
+ The qualifier is resolved on every poll, so `UpdateAlias` moves what an existing mapping delivers to.
1380
+ The version has to be there when the mapping is made. A qualifier naming none fails with
1381
+ `ResourceNotFoundException`, the way a function that is not there does. Polling still runs as the
1382
+ function's execution role, which a published version carries over from the function it was published
1383
+ from.
1384
+
1385
+ ### When the handler fails
1386
+
1387
+ A handler that returns normally has handled the batch, and the messages are deleted from the queue.
1388
+ A handler that throws returns the whole batch. The messages stay on the queue, hidden until their
1389
+ visibility timeout lapses, and are delivered again after that. Advancing the simulation's clock is
1390
+ what brings them back:
1391
+
1392
+ ```typescript
1393
+ await simAws.clock().advanceBy({ seconds: 31 });
1394
+ ```
1395
+
1396
+ A queue with a `RedrivePolicy` eventually gives up on a message the handler keeps throwing on and
1397
+ moves it to the dead-letter queue, exactly as it would for any other failing consumer. See
1398
+ [dead-letter queues](https://yulinsim.dev/services/sqs/#dead-letter-queues "Simulated SQS dead-letter queue docs").
1399
+
1400
+ The handler error itself goes unreported to whoever sent the message, as it does on real AWS. What
1401
+ the sender sees is the message coming back.
1402
+
1403
+ ### Reporting individual message failures
1404
+
1405
+ A queue mapping created with `FunctionResponseTypes: ["ReportBatchItemFailures"]` takes the
1406
+ `batchItemFailures` list the handler returns. The message ids named in it go back to the queue, and
1407
+ the rest of the batch is deleted. A stream mapping takes the same list and does something else with
1408
+ it, under [reporting individual record failures](#reporting-individual-record-failures).
1409
+
1410
+ ```typescript
1411
+ await simAws.lambda().createEventSourceMapping(
1412
+ new CreateEventSourceMappingCommand({
1413
+ EventSourceArn: queueArn,
1414
+ FunctionName: "order-consumer",
1415
+ FunctionResponseTypes: ["ReportBatchItemFailures"],
1416
+ }),
1417
+ );
1418
+
1419
+ // The handler reports the message ids it could not handle.
1420
+ const handler = (event: SimLambdaSqsEvent) => ({
1421
+ batchItemFailures: event.Records.filter((record) => !canHandle(record)).map(
1422
+ (record) => ({ itemIdentifier: record.messageId }),
1423
+ ),
1424
+ });
1425
+ ```
1426
+
1427
+ A report naming an id that was not in the batch returns the whole batch, as real Lambda does with a
1428
+ report it cannot trust. So does an entry with no `itemIdentifier`. A handler that returns no list,
1429
+ or an empty `batchItemFailures` list, has handled the whole batch.
1430
+
1431
+ ### Making an SQS event without a queue
1432
+
1433
+ A test of the handler on its own, with no queue and no mapping, still has to pass it a whole event.
1434
+ `lambdaSqsEventFactory` makes one, and `lambdaSqsEventRecordFactory` makes the records in it. Such a
1435
+ test then says what the messages carry and leaves the rest to the factory:
1436
+
1437
+ ```typescript sim-lambda-sqs-event-factory
1438
+ /**
1439
+ * Making an SQS event to call a handler with.
1440
+ */
1441
+
1442
+ import {
1443
+ lambdaSqsEventFactory,
1444
+ lambdaSqsEventRecordFactory,
1445
+ type SimLambdaSqsEvent,
1446
+ } from "@kensio/yulin/lambda";
1447
+
1448
+ function ordersHandler(event: SimLambdaSqsEvent): readonly string[] {
1449
+ return event.Records.map(
1450
+ (record) => (JSON.parse(record.body) as { orderId: string }).orderId,
1451
+ );
1452
+ }
1453
+
1454
+ const batch = lambdaSqsEventFactory.make({
1455
+ Records: [{ body: '{"orderId":"YL-1"}' }, { body: '{"orderId":"YL-2"}' }],
1456
+ });
1457
+
1458
+ // [ 'YL-1', 'YL-2' ]
1459
+ console.log(ordersHandler(batch));
1460
+
1461
+ // The record factory makes one on its own, for a test about a single message.
1462
+ const record = lambdaSqsEventRecordFactory.make({
1463
+ body: '{"orderId":"YL-9"}',
1464
+ eventSourceARN: "arn:aws:sqs:eu-west-2:888888888888:orders",
1465
+ });
1466
+
1467
+ // eu-west-2
1468
+ console.log(record.awsRegion);
1469
+ ```
1470
+
1471
+ The default is the single-message batch a quiet queue delivers. Each record is completed as a
1472
+ delivered one is, including the message id, the receipt handle and the three system `attributes` a
1473
+ simulated mapping reports. Two fields a record repeats are computed from the rest. `md5OfBody` is
1474
+ the digest of the body given, which a handler checking the digest compares against, and `awsRegion`
1475
+ is the Region of the queue ARN given.
1476
+
1477
+ Reporting individual failures can be tested against a made event too. The handler's
1478
+ `batchItemFailures` name `messageId` values, and those are the ids of the records the factory made.
1479
+
1480
+ ### Event source mappings in templates
1481
+
1482
+ `AWS::Lambda::EventSourceMapping` deploys the same thing, and CDK's
1483
+ `fn.addEventSource(new SqsEventSource(queue))` emits one. `EventSourceArn` and `FunctionName` accept the
1484
+ `Fn::GetAtt` and `Ref` values a template gives them, `Ref` on the mapping returns its UUID, and
1485
+ `Fn::GetAtt` exposes `Id` and `EventSourceMappingArn`. A queue mapping has no `StartingPosition`, and
1486
+ a template naming one is refused. The same Resource deploys a
1487
+ [stream mapping](#stream-mappings-in-templates), which has to have one.
1488
+
1489
+ ## Triggering a function from a DynamoDB stream
1490
+
1491
+ An event source mapping also connects a [simulated table's stream](https://yulinsim.dev/services/dynamodb/#capturing-changes-with-a-stream "Simulated DynamoDB streams docs")
1492
+ to a function. Changes to the table are delivered to the handler as a DynamoDB stream event, with
1493
+ the `Records` shape real Lambda uses.
1494
+
1495
+ `StartingPosition` is required for a stream and is `TRIM_HORIZON` or `LATEST`. `TRIM_HORIZON` reads
1496
+ what the stream still holds, so changes made before the mapping existed are delivered too. `LATEST`
1497
+ reads only what the table changes from the moment the mapping starts reading. `AT_TIMESTAMP` is for
1498
+ [a Kinesis stream](#triggering-a-function-from-a-kinesis-stream) and is refused by name here.
1499
+
1500
+ `BatchSize` says how many records one invocation may be given, and defaults to 100, the number
1501
+ CDK's `DynamoEventSource` also asks for. The table and the function have to be in the same account
1502
+ and region, as they do on real AWS.
1503
+
1504
+ ```typescript sim-lambda-dynamodb-stream-event-source
1505
+ /**
1506
+ * Delivering a simulated table's changes to a simulated function.
1507
+ */
1508
+
1509
+ import {
1510
+ CreateTableCommand,
1511
+ GetItemCommand,
1512
+ PutItemCommand,
1513
+ } from "@aws-sdk/client-dynamodb";
1514
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
1515
+ import {
1516
+ CreateEventSourceMappingCommand,
1517
+ CreateFunctionCommand,
1518
+ } from "@aws-sdk/client-lambda";
1519
+
1520
+ import { SimAws } from "@kensio/yulin";
1521
+ import {
1522
+ makeLambdaZipFileInput,
1523
+ type SimLambdaDynamoDbStreamEvent,
1524
+ } from "@kensio/yulin/lambda";
1525
+
1526
+ const simAws = new SimAws();
1527
+
1528
+ const { TableDescription } = await simAws.dynamoDb().createTable(
1529
+ new CreateTableCommand({
1530
+ TableName: "orders",
1531
+ KeySchema: [{ AttributeName: "orderId", KeyType: "HASH" }],
1532
+ AttributeDefinitions: [{ AttributeName: "orderId", AttributeType: "S" }],
1533
+ BillingMode: "PAY_PER_REQUEST",
1534
+ StreamSpecification: {
1535
+ StreamEnabled: true,
1536
+ StreamViewType: "NEW_AND_OLD_IMAGES",
1537
+ },
1538
+ }),
1539
+ );
1540
+
1541
+ const streamArn = TableDescription?.LatestStreamArn;
1542
+
1543
+ // The projection goes into a second table. A function writing back into the
1544
+ // table whose stream invoked it would be delivered its own writes, which the
1545
+ // simulator refuses rather than looping on.
1546
+ await simAws.dynamoDb().createTable(
1547
+ new CreateTableCommand({
1548
+ TableName: "order-totals",
1549
+ KeySchema: [{ AttributeName: "orderId", KeyType: "HASH" }],
1550
+ AttributeDefinitions: [{ AttributeName: "orderId", AttributeType: "S" }],
1551
+ BillingMode: "PAY_PER_REQUEST",
1552
+ }),
1553
+ );
1554
+
1555
+ // The execution role needs the three stream actions Lambda reads a stream
1556
+ // with, plus ListStreams, which is on every stream rather than on one, and
1557
+ // whatever the function itself does.
1558
+ const role = await simAws.iam().createRole(
1559
+ new CreateRoleCommand({
1560
+ RoleName: "OrderProjectorRole",
1561
+ AssumeRolePolicyDocument: JSON.stringify({
1562
+ Version: "2012-10-17",
1563
+ Statement: {
1564
+ Effect: "Allow",
1565
+ Principal: { Service: "lambda.amazonaws.com" },
1566
+ Action: "sts:AssumeRole",
1567
+ },
1568
+ }),
1569
+ }),
1570
+ );
1571
+
1572
+ await simAws.iam().putRolePolicy(
1573
+ new PutRolePolicyCommand({
1574
+ RoleName: "OrderProjectorRole",
1575
+ PolicyName: "ProjectOrders",
1576
+ PolicyDocument: JSON.stringify({
1577
+ Version: "2012-10-17",
1578
+ Statement: [
1579
+ {
1580
+ Effect: "Allow",
1581
+ Action: [
1582
+ "dynamodb:DescribeStream",
1583
+ "dynamodb:GetRecords",
1584
+ "dynamodb:GetShardIterator",
1585
+ ],
1586
+ Resource: streamArn,
1587
+ },
1588
+ { Effect: "Allow", Action: "dynamodb:ListStreams", Resource: "*" },
1589
+ {
1590
+ Effect: "Allow",
1591
+ Action: "dynamodb:PutItem",
1592
+ Resource: `arn:aws:dynamodb:${simAws.defaultRegionName}:${simAws.defaultAccountId}:table/order-totals`,
1593
+ },
1594
+ ],
1595
+ }),
1596
+ }),
1597
+ );
1598
+
1599
+ await simAws.lambda().createFunction(
1600
+ new CreateFunctionCommand({
1601
+ FunctionName: "order-projector",
1602
+ Role: role.Role.Arn,
1603
+ Code: {
1604
+ ZipFile: makeLambdaZipFileInput(
1605
+ async (event: SimLambdaDynamoDbStreamEvent) => {
1606
+ await Promise.all(
1607
+ event.Records.map(async (record) =>
1608
+ simAws.dynamoDb().putItem(
1609
+ new PutItemCommand({
1610
+ TableName: "order-totals",
1611
+ Item: {
1612
+ orderId: { S: record.dynamodb.Keys?.["orderId"]?.S ?? "" },
1613
+ total: { N: record.dynamodb.NewImage?.["total"]?.N ?? "0" },
1614
+ },
1615
+ }),
1616
+ ),
1617
+ ),
1618
+ );
1619
+ },
1620
+ ),
1621
+ },
1622
+ }),
1623
+ );
1624
+
1625
+ await simAws.lambda().createEventSourceMapping(
1626
+ new CreateEventSourceMappingCommand({
1627
+ EventSourceArn: streamArn,
1628
+ FunctionName: "order-projector",
1629
+ StartingPosition: "TRIM_HORIZON",
1630
+ }),
1631
+ );
1632
+
1633
+ await simAws.dynamoDb().putItem(
1634
+ new PutItemCommand({
1635
+ TableName: "orders",
1636
+ Item: { orderId: { S: "order-1" }, total: { N: "42" } },
1637
+ }),
1638
+ );
1639
+
1640
+ // Delivery happens in the background, so wait for the simulation to settle.
1641
+ await simAws.backgroundTasksComplete();
1642
+
1643
+ const projected = await simAws.dynamoDb().getItem(
1644
+ new GetItemCommand({
1645
+ TableName: "order-totals",
1646
+ Key: { orderId: { S: "order-1" } },
1647
+ }),
1648
+ );
1649
+
1650
+ console.log(projected.Item?.["total"]?.N); // "42"
1651
+ ```
1652
+
1653
+ Each record carries `eventID`, `eventName`, `eventVersion`, `eventSource`, `awsRegion`,
1654
+ `eventSourceARN` and a `dynamodb` body holding `Keys`, the images the stream's view type selects,
1655
+ `SequenceNumber`, `SizeBytes`, `StreamViewType` and `ApproximateCreationDateTime` as whole seconds
1656
+ since the epoch. A time to live removal also carries
1657
+ `userIdentity: { type: "Service", principalId: "dynamodb.amazonaws.com" }`. A handler tells an
1658
+ expiry from a deletion the application asked for by that. The event lower-cases those two fields
1659
+ where [the Streams API capitalizes them](https://yulinsim.dev/services/dynamodb/#reading-a-streams-records "Simulated DynamoDB Streams docs").
1660
+
1661
+ `SimLambdaDynamoDbStreamEvent` and `SimLambdaDynamoDbStreamEventRecord` are exported from
1662
+ `@kensio/yulin/lambda` for typing a handler, and are minimal structural equivalents of the
1663
+ `DynamoDBStreamEvent` and `DynamoDBRecord` types from the `aws-lambda` typings package.
1664
+
1665
+ A binary attribute reaches the handler as a base64 string, as it does on AWS. The event arrives as
1666
+ JSON, and JSON has no bytes. `Buffer.from(value.B, "base64")`
1667
+ therefore reads the same here as it does deployed. The
1668
+ [Streams API](https://yulinsim.dev/services/dynamodb/#reading-a-streams-records "Simulated DynamoDB Streams docs") hands out
1669
+ bytes for the same attribute, because its client decodes them. Nesting makes no difference, and
1670
+ binary inside a list or a map is encoded too.
1671
+
1672
+ Creating the mapping checks what real Lambda checks. The stream has to exist, and the function's
1673
+ execution role has to be allowed `dynamodb:DescribeStream`, `dynamodb:GetRecords` and
1674
+ `dynamodb:GetShardIterator` on it, plus `dynamodb:ListStreams` on `*`. Those four are what both the
1675
+ AWS managed policy and CDK's own grant give a stream consumer. A role missing one of them fails with
1676
+ `InvalidParameterValueException` naming the operation.
1677
+
1678
+ ### When the handler fails
1679
+
1680
+ A stream behaves differently from a queue here. A queue hands a message out and hides it, and a
1681
+ batch the handler threw on becomes the queue's problem afterwards. A stream hands out a place, and
1682
+ the mapping is the only thing that remembers it. A batch the handler threw on is read again from
1683
+ exactly where it was, and everything behind it waits until it is through. That is what blocking a
1684
+ shard means.
1685
+
1686
+ Advancing the simulation's clock is what hands the batch over again:
1687
+
1688
+ ```typescript
1689
+ await simAws.clock().advanceBy({ seconds: 30 });
1690
+ ```
1691
+
1692
+ The batch is delivered again five times, after 1, 2, 4, 8 and 16 seconds, so six deliveries in all.
1693
+ Then it is discarded and the mapping carries on with the stream, as AWS does once a stream mapping's
1694
+ error handling has run out.
1695
+
1696
+ Both the cadence and the number of attempts are simulator constraints rather than AWS behaviour. AWS
1697
+ documents no delay between attempts and retries until the records age out of the stream, a day
1698
+ later. A delay of zero here would fall due at the instant the clock already reads. A handler that
1699
+ always throws would then leave `advanceBy` with work falling due forever, and waiting out a
1700
+ simulated day is the same problem with more steps.
1701
+
1702
+ ### Reporting individual record failures
1703
+
1704
+ A stream mapping created with `FunctionResponseTypes: ["ReportBatchItemFailures"]` takes the
1705
+ `batchItemFailures` list the handler returns. For a stream the identifier is the record's
1706
+ `SequenceNumber`:
1707
+
1708
+ ```typescript
1709
+ await simAws.lambda().createEventSourceMapping(
1710
+ new CreateEventSourceMappingCommand({
1711
+ EventSourceArn: streamArn,
1712
+ FunctionName: "order-projector",
1713
+ StartingPosition: "TRIM_HORIZON",
1714
+ FunctionResponseTypes: ["ReportBatchItemFailures"],
1715
+ }),
1716
+ );
1717
+
1718
+ // The handler reports the sequence numbers it could not handle.
1719
+ const handler = (event: SimLambdaDynamoDbStreamEvent) => ({
1720
+ batchItemFailures: event.Records.filter((record) => !canHandle(record)).map(
1721
+ (record) => ({ itemIdentifier: record.dynamodb.SequenceNumber }),
1722
+ ),
1723
+ });
1724
+ ```
1725
+
1726
+ A stream reads that report differently from a queue. A queue takes back the messages the report
1727
+ names and deletes the rest. A stream moves its checkpoint to the lowest sequence
1728
+ number the report names and delivers everything from there again, including the records after it
1729
+ that the handler did handle. That is real AWS behaviour rather than a simulation artifact, and it is
1730
+ why a stream consumer has to be idempotent.
1731
+
1732
+ So a report naming only the last record of a batch delivers that record again. A report naming the
1733
+ first record delivers the whole batch again. The redelivery is a retry like any other. It waits out
1734
+ the same backoff, counts against the same five attempts, and what is left is discarded when they run
1735
+ out.
1736
+
1737
+ A report naming a sequence number that was not in the batch delivers the whole batch again, as real
1738
+ Lambda does with a report it cannot trust. So does an entry with no `itemIdentifier`. A handler that
1739
+ returns no list, or an empty `batchItemFailures` list, has handled the whole batch. A mapping
1740
+ created without `FunctionResponseTypes` ignores a report entirely.
1741
+
1742
+ ### Writing back to the source table
1743
+
1744
+ A handler that writes into the table whose stream invoked it is delivered its own write, which
1745
+ writes again. Real Lambda runs that loop for as long as the account is willing to pay for it. The
1746
+ simulation refuses instead, with an error naming the function, the stream and the table, before the
1747
+ test times out.
1748
+
1749
+ The write itself succeeds. The refusal comes afterwards, from whatever is waiting for the simulation
1750
+ to settle:
1751
+
1752
+ ```typescript
1753
+ await simAws.backgroundTasksComplete(); // throws SimLambdaStreamCascadeError
1754
+ ```
1755
+
1756
+ Only the handler's own writes count. Items written at the same time by the test, or by anything else
1757
+ in the simulation, are an ordinary batch however many of them there are, because the guard tells them
1758
+ apart by where the write came from, and never by when it landed.
1759
+
1760
+ Writing the projection into a second table is what the guard is asking for, and is what a real
1761
+ aggregation or search index does anyway.
1762
+
1763
+ ### Making a stream event without a table
1764
+
1765
+ `lambdaDynamoDbStreamEventFactory` and `lambdaDynamoDbStreamEventRecordFactory` make the same events
1766
+ for a test that calls the handler directly, with no table and no mapping:
1767
+
1768
+ ```typescript sim-lambda-dynamodb-stream-event-factory
1769
+ /**
1770
+ * Making a DynamoDB stream event to call a handler with.
1771
+ */
1772
+
1773
+ import {
1774
+ lambdaDynamoDbStreamEventFactory,
1775
+ type SimLambdaDynamoDbStreamEvent,
1776
+ } from "@kensio/yulin/lambda";
1777
+
1778
+ function shippedOrders(event: SimLambdaDynamoDbStreamEvent): readonly string[] {
1779
+ return event.Records.filter(
1780
+ (record) => record.dynamodb.NewImage?.["status"]?.S === "shipped",
1781
+ ).map((record) => record.dynamodb.Keys?.["orderId"]?.S ?? "");
1782
+ }
1783
+
1784
+ const event = lambdaDynamoDbStreamEventFactory.make({
1785
+ Records: [
1786
+ {
1787
+ eventName: "MODIFY",
1788
+ dynamodb: {
1789
+ Keys: { orderId: { S: "YL-1" } },
1790
+ OldImage: { orderId: { S: "YL-1" }, status: { S: "placed" } },
1791
+ NewImage: { orderId: { S: "YL-1" }, status: { S: "shipped" } },
1792
+ },
1793
+ },
1794
+ { eventName: "INSERT" },
1795
+ ],
1796
+ });
1797
+
1798
+ // [ 'YL-1' ]
1799
+ console.log(shippedOrders(event));
1800
+
1801
+ // NEW_AND_OLD_IMAGES, because that is what this record carries
1802
+ console.log(event.Records[0]?.dynamodb.StreamViewType);
1803
+ ```
1804
+
1805
+ The default is the single-record batch one changed item produces. What a record says in more than
1806
+ one place is computed from the rest, and the result is a record a stream could have delivered. An
1807
+ `INSERT` carries a new image, a `REMOVE` an old one and a `MODIFY` both, `StreamViewType` names the
1808
+ images
1809
+ the record actually carries, and `awsRegion` is the Region of the stream ARN given. A record for a
1810
+ `KEYS_ONLY` stream is one with the images explicitly taken away, as in
1811
+ `make({ dynamodb: { NewImage: undefined, OldImage: undefined } })`.
1812
+
1813
+ `SizeBytes` is a plausible default, and measures nothing about the images given. A test asserting
1814
+ on it should say what it expects.
1815
+
1816
+ ### Stream mappings in templates
1817
+
1818
+ `AWS::Lambda::EventSourceMapping` deploys a stream mapping too. `EventSourceArn` takes the
1819
+ `Fn::GetAtt … StreamArn` of a
1820
+ [streamed table](https://yulinsim.dev/services/dynamodb/#deploying-a-table-with-a-stream "Simulated DynamoDB table stream in CloudFormation docs")
1821
+ in the same template. That reference is also what makes the mapping wait for the table.
1822
+ `StartingPosition` is required, as it is for an SDK caller, and the properties go to
1823
+ `CreateEventSourceMapping` unjudged. A template that gets one wrong is refused in the words the
1824
+ command refuses it in.
1825
+
1826
+ ```typescript sim-lambda-cloudformation-dynamodb-event-source
1827
+ /**
1828
+ * Deploying a table's stream, a function, and the mapping between them.
1829
+ */
1830
+
1831
+ import { PutItemCommand } from "@aws-sdk/client-dynamodb";
1832
+
1833
+ import { SimAws } from "@kensio/yulin";
1834
+ import type { SimLambdaDynamoDbStreamEvent } from "@kensio/yulin/lambda";
1835
+
1836
+ const simAws = new SimAws();
1837
+ const projected: string[] = [];
1838
+
1839
+ const stack = await simAws.cloudFormation().deployTemplate({
1840
+ stackName: "orders-stack",
1841
+ template: {
1842
+ Resources: {
1843
+ OrdersTable: {
1844
+ Type: "AWS::DynamoDB::Table",
1845
+ Properties: {
1846
+ TableName: "orders",
1847
+ KeySchema: [{ AttributeName: "orderId", KeyType: "HASH" }],
1848
+ AttributeDefinitions: [
1849
+ { AttributeName: "orderId", AttributeType: "S" },
1850
+ ],
1851
+ BillingMode: "PAY_PER_REQUEST",
1852
+ StreamSpecification: { StreamViewType: "NEW_AND_OLD_IMAGES" },
1853
+ },
1854
+ },
1855
+ ProjectorRole: {
1856
+ Type: "AWS::IAM::Role",
1857
+ Properties: {
1858
+ RoleName: "OrderProjectorRole",
1859
+ AssumeRolePolicyDocument: {
1860
+ Version: "2012-10-17",
1861
+ Statement: [
1862
+ {
1863
+ Effect: "Allow",
1864
+ Principal: { Service: "lambda.amazonaws.com" },
1865
+ Action: "sts:AssumeRole",
1866
+ },
1867
+ ],
1868
+ },
1869
+ Policies: [
1870
+ {
1871
+ PolicyName: "ReadOrdersStream",
1872
+ PolicyDocument: {
1873
+ Version: "2012-10-17",
1874
+ Statement: [
1875
+ {
1876
+ Effect: "Allow",
1877
+ Action: [
1878
+ "dynamodb:DescribeStream",
1879
+ "dynamodb:GetRecords",
1880
+ "dynamodb:GetShardIterator",
1881
+ ],
1882
+ Resource: { "Fn::GetAtt": ["OrdersTable", "StreamArn"] },
1883
+ },
1884
+ {
1885
+ Effect: "Allow",
1886
+ Action: "dynamodb:ListStreams",
1887
+ Resource: "*",
1888
+ },
1889
+ ],
1890
+ },
1891
+ },
1892
+ ],
1893
+ },
1894
+ },
1895
+ ProjectorFunction: {
1896
+ Type: "AWS::Lambda::Function",
1897
+ Properties: {
1898
+ FunctionName: "order-projector",
1899
+ Role: { "Fn::GetAtt": ["ProjectorRole", "Arn"] },
1900
+ },
1901
+ },
1902
+ OrderProjectorMapping: {
1903
+ Type: "AWS::Lambda::EventSourceMapping",
1904
+ Properties: {
1905
+ EventSourceArn: { "Fn::GetAtt": ["OrdersTable", "StreamArn"] },
1906
+ FunctionName: { Ref: "ProjectorFunction" },
1907
+ BatchSize: 100,
1908
+ StartingPosition: "TRIM_HORIZON",
1909
+ },
1910
+ },
1911
+ },
1912
+ },
1913
+ bindings: [
1914
+ {
1915
+ logicalId: "ProjectorFunction",
1916
+ handler: (event: SimLambdaDynamoDbStreamEvent): void => {
1917
+ for (const record of event.Records) {
1918
+ projected.push(record.dynamodb.Keys?.["orderId"]?.S ?? "");
1919
+ }
1920
+ },
1921
+ },
1922
+ ],
1923
+ });
1924
+ await stack.waitForDeployComplete();
1925
+
1926
+ await simAws.dynamoDb().putItem(
1927
+ new PutItemCommand({
1928
+ TableName: "orders",
1929
+ Item: { orderId: { S: "order-1" }, total: { N: "101" } },
1930
+ }),
1931
+ );
1932
+ await simAws.backgroundTasksComplete();
1933
+
1934
+ console.log(projected); // ["order-1"]
1935
+ ```
1936
+
1937
+ CDK's `fn.addEventSource(new DynamoEventSource(table, { startingPosition }))` synthesises exactly
1938
+ this, and deploys without hand-editing. The grant CDK writes alongside it is an inline policy with
1939
+ the three stream actions on the stream ARN and `dynamodb:ListStreams` on every stream, exactly what
1940
+ the mapping's execution-role check is looking for.
1941
+
1942
+ The properties a non-default `DynamoEventSource` adds are refused by name. Those are
1943
+ `FilterCriteria`, `ParallelizationFactor`, `BisectBatchOnFunctionError`, `TumblingWindowInSeconds`
1944
+ and `DestinationConfig`.
1945
+
1946
+ A hand-written template or a SAM application usually gives the function the AWS managed policy
1947
+ `AWSLambdaDynamoDBExecutionRole` instead. Simulated IAM has no model for managed policy ARNs, so
1948
+ that role reaches the mapping with no stream permissions and the mapping is refused when it is
1949
+ created.
1950
+ Write the grant as an inline policy, as the example above and CDK both do.
1951
+
1952
+ ## Triggering a function from a Kinesis stream
1953
+
1954
+ An event source mapping also connects a [simulated Kinesis stream](https://yulinsim.dev/services/kinesis/ "Simulated Kinesis Data Streams docs")
1955
+ to a function. Records put onto the stream are delivered to the handler as a Kinesis event, with the
1956
+ `Records` shape real Lambda uses.
1957
+
1958
+ A Kinesis stream has as many shards as it was created with, and every one of them is read. Real
1959
+ Lambda runs a processor per shard, and so does this: each shard keeps its own place on the stream,
1960
+ delivers its own batches and backs off on its own when a batch fails. One invocation is given
1961
+ records from one shard, so a handler that has to see records in order should put them under one
1962
+ partition key, which is what puts them on one shard.
1963
+
1964
+ `StartingPosition` is required for a stream. A Kinesis stream takes all three positions.
1965
+ `TRIM_HORIZON` reads what the stream still holds, `LATEST` reads only what arrives from the moment
1966
+ the mapping starts reading, and `AT_TIMESTAMP` reads from the instant `StartingPositionTimestamp`
1967
+ names.
1968
+
1969
+ `BatchSize` says how many records one invocation may be given, and defaults to 100, the number CDK's
1970
+ `KinesisEventSource` also asks for. The stream and the function have to be in the same account and
1971
+ region, as they do on real AWS.
1972
+
1973
+ ```typescript sim-lambda-kinesis-event-source
1974
+ /**
1975
+ * Delivering a simulated Kinesis stream's records to a simulated function.
1976
+ */
1977
+
1978
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
1979
+ import { CreateStreamCommand, PutRecordCommand } from "@aws-sdk/client-kinesis";
1980
+ import {
1981
+ CreateEventSourceMappingCommand,
1982
+ CreateFunctionCommand,
1983
+ } from "@aws-sdk/client-lambda";
1984
+
1985
+ import { SimAws } from "@kensio/yulin";
1986
+ import {
1987
+ makeLambdaZipFileInput,
1988
+ type SimLambdaKinesisStreamEvent,
1989
+ } from "@kensio/yulin/lambda";
1990
+
1991
+ const simAws = new SimAws();
1992
+
1993
+ await simAws
1994
+ .kinesis()
1995
+ .createStream(new CreateStreamCommand({ StreamName: "orders" }));
1996
+
1997
+ const streamArn = `arn:aws:kinesis:${simAws.defaultRegionName}:${simAws.defaultAccountId}:stream/orders`;
1998
+
1999
+ const { Role } = await simAws.iam().createRole(
2000
+ new CreateRoleCommand({
2001
+ RoleName: "OrderProjectorRole",
2002
+ AssumeRolePolicyDocument: JSON.stringify({
2003
+ Version: "2012-10-17",
2004
+ Statement: {
2005
+ Effect: "Allow",
2006
+ Principal: { Service: "lambda.amazonaws.com" },
2007
+ Action: "sts:AssumeRole",
2008
+ },
2009
+ }),
2010
+ }),
2011
+ );
2012
+
2013
+ await simAws.iam().putRolePolicy(
2014
+ new PutRolePolicyCommand({
2015
+ RoleName: "OrderProjectorRole",
2016
+ PolicyName: "ReadOrders",
2017
+ PolicyDocument: JSON.stringify({
2018
+ Version: "2012-10-17",
2019
+ Statement: [
2020
+ {
2021
+ Effect: "Allow",
2022
+ Action: [
2023
+ "kinesis:DescribeStream",
2024
+ "kinesis:GetRecords",
2025
+ "kinesis:GetShardIterator",
2026
+ ],
2027
+ Resource: streamArn,
2028
+ },
2029
+ { Effect: "Allow", Action: "kinesis:ListStreams", Resource: "*" },
2030
+ ],
2031
+ }),
2032
+ }),
2033
+ );
2034
+
2035
+ const projected: string[] = [];
2036
+
2037
+ await simAws.lambda().createFunction(
2038
+ new CreateFunctionCommand({
2039
+ FunctionName: "order-projector",
2040
+ Role: Role.Arn,
2041
+ Code: {
2042
+ ZipFile: makeLambdaZipFileInput(
2043
+ (event: SimLambdaKinesisStreamEvent): void => {
2044
+ for (const record of event.Records) {
2045
+ // The payload arrives base64 encoded, as it does on AWS.
2046
+ projected.push(
2047
+ Buffer.from(record.kinesis.data, "base64").toString("utf8"),
2048
+ );
2049
+ }
2050
+ },
2051
+ ),
2052
+ },
2053
+ }),
2054
+ );
2055
+
2056
+ await simAws.lambda().createEventSourceMapping(
2057
+ new CreateEventSourceMappingCommand({
2058
+ EventSourceArn: streamArn,
2059
+ FunctionName: "order-projector",
2060
+ StartingPosition: "TRIM_HORIZON",
2061
+ }),
2062
+ );
2063
+
2064
+ await simAws.kinesis().putRecord(
2065
+ new PutRecordCommand({
2066
+ StreamName: "orders",
2067
+ PartitionKey: "customer-1",
2068
+ Data: new TextEncoder().encode('{"id":"order-1"}'),
2069
+ }),
2070
+ );
2071
+
2072
+ // Delivery happens in the background, so wait for the simulation to settle.
2073
+ await simAws.backgroundTasksComplete();
2074
+
2075
+ console.log(projected[0]); // {"id":"order-1"}
2076
+ ```
2077
+
2078
+ Each record carries `eventID`, `eventName`, `eventVersion`, `eventSource`, `awsRegion`,
2079
+ `eventSourceARN`, `invokeIdentityArn` and a `kinesis` body holding `kinesisSchemaVersion`,
2080
+ `partitionKey`, `sequenceNumber`, `data` and `approximateArrivalTimestamp`. `eventID` is the shard
2081
+ identifier and the sequence number joined by a colon, so it is unique across the whole stream rather
2082
+ than within one shard. `invokeIdentityArn` is the execution role the records were read with.
2083
+
2084
+ The two translations worth knowing are the payload and the instant. `data` is base64 of the bytes
2085
+ that were put, because the event is JSON and JSON has no bytes, and `approximateArrivalTimestamp` is
2086
+ seconds since the epoch where
2087
+ [the Kinesis API](https://yulinsim.dev/services/kinesis/#putting-a-record-and-reading-it-back "Simulated Kinesis docs") hands
2088
+ out a `Date`. Both are what a deployed function receives.
2089
+
2090
+ `SimLambdaKinesisStreamEvent` and `SimLambdaKinesisStreamEventRecord` are exported from
2091
+ `@kensio/yulin/lambda` for typing a handler, and are minimal structural equivalents of the
2092
+ `KinesisStreamEvent` and `KinesisStreamRecord` types from the `aws-lambda` typings package.
2093
+
2094
+ Creating the mapping checks what real Lambda checks. The stream has to exist, and the function's
2095
+ execution role has to be allowed `kinesis:DescribeStream`, `kinesis:GetRecords` and
2096
+ `kinesis:GetShardIterator` on it, plus `kinesis:ListStreams` on `*`. Those four are what both the
2097
+ AWS managed policy and CDK's own grant give a stream consumer. A role missing one of them fails with
2098
+ `InvalidParameterValueException` naming the operation.
2099
+
2100
+ `FunctionResponseTypes: ["ReportBatchItemFailures"]` works as it does for a DynamoDB stream. A
2101
+ handler names a record by its `sequenceNumber`, and the mapping goes back to the lowest one the
2102
+ report names, so that record and everything after it on that shard is delivered again. A failing
2103
+ batch blocks its own shard and no other.
2104
+
2105
+ A mapping naming an enhanced fan-out consumer ARN is refused, since consumers are unsimulated.
2106
+ `AWS::Lambda::EventSourceMapping` deploys a Kinesis mapping the same way it deploys a DynamoDB one.
2107
+
2108
+ ## Function URLs
2109
+
2110
+ A Function URL is an HTTP endpoint for one function. Creating one with
2111
+ `CreateFunctionUrlConfigCommand` returns an AWS-shaped endpoint:
2112
+
2113
+ ```text
2114
+ https://<url-id>.lambda-url.<region>.on.aws/
2115
+ ```
2116
+
2117
+ Serve that URL with `serveSimAws` and application code, a frontend dev server, or curl can make real
2118
+ HTTP requests to the function, alongside the other simulated services on the same local server. Pass
2119
+ the Function URL through `srv.localUrl(...)`, which keeps the endpoint's hostname but sends the
2120
+ request to the local server, in the same way it adapts simulated S3 website and CloudFront URLs.
2121
+
2122
+ ```typescript sim-lambda-function-url
2123
+ /**
2124
+ * Serving a simulated Lambda Function URL on localhost.
2125
+ */
2126
+
2127
+ import {
2128
+ CreateFunctionCommand,
2129
+ CreateFunctionUrlConfigCommand,
2130
+ } from "@aws-sdk/client-lambda";
2131
+
2132
+ import { SimAws } from "@kensio/yulin";
2133
+ import {
2134
+ type SimLambdaFunctionUrlEvent,
2135
+ makeLambdaZipFileInput,
2136
+ } from "@kensio/yulin/lambda";
2137
+ import { serveSimAws } from "@kensio/yulin/serve";
2138
+
2139
+ const simAws = new SimAws();
2140
+ const lambda = simAws.lambda();
2141
+
2142
+ await lambda.createFunction(
2143
+ new CreateFunctionCommand({
2144
+ FunctionName: "greeter",
2145
+ Role: "arn:aws:iam::111111111111:role/GreeterRole",
2146
+ Code: {
2147
+ ZipFile: makeLambdaZipFileInput((event: SimLambdaFunctionUrlEvent) => ({
2148
+ statusCode: 200,
2149
+ headers: { "content-type": "text/plain" },
2150
+ body: `Hello ${event.queryStringParameters?.["name"] ?? "world"}`,
2151
+ })),
2152
+ },
2153
+ }),
2154
+ );
2155
+
2156
+ const urlConfig = await lambda.createFunctionUrlConfig(
2157
+ new CreateFunctionUrlConfigCommand({
2158
+ FunctionName: "greeter",
2159
+ AuthType: "NONE",
2160
+ }),
2161
+ );
2162
+
2163
+ // https://<url-id>.lambda-url.us-east-1.on.aws/
2164
+ console.log(urlConfig.FunctionUrl);
2165
+
2166
+ const srv = await serveSimAws({ simAws });
2167
+
2168
+ try {
2169
+ const response = await fetch(
2170
+ srv.localUrl(`${urlConfig.FunctionUrl}greet?name=Yulin`),
2171
+ );
2172
+
2173
+ console.log(response.status);
2174
+ console.log(await response.text());
2175
+ } finally {
2176
+ await srv.close();
2177
+ }
2178
+ ```
2179
+
2180
+ On localhost the endpoint hostname becomes
2181
+ `<url-id>.lambda-url.<region>.sim-aws.localhost:<port>`, dropping the `.on.aws` tail the way
2182
+ simulated S3 endpoints drop `.amazonaws.com`. Requests are routed by that hostname. A Function URL
2183
+ created in a non-default account or region reaches the right function without any extra
2184
+ configuration.
2185
+
2186
+ ### The invocation event and the response
2187
+
2188
+ The handler receives the API Gateway HTTP API payload format 2.0 event that real Function URLs
2189
+ send, the only format they use:
2190
+
2191
+ ```json
2192
+ {
2193
+ "version": "2.0",
2194
+ "routeKey": "$default",
2195
+ "rawPath": "/greet",
2196
+ "rawQueryString": "name=Yulin",
2197
+ "headers": { "host": "...", "user-agent": "..." },
2198
+ "queryStringParameters": { "name": "Yulin" },
2199
+ "cookies": ["session=abc"],
2200
+ "requestContext": {
2201
+ "http": { "method": "GET", "path": "/greet", "sourceIp": "127.0.0.1" }
2202
+ },
2203
+ "isBase64Encoded": false
2204
+ }
2205
+ ```
2206
+
2207
+ Cookies arrive in their own `cookies` field rather than in `headers`, and a request body arrives on
2208
+ `body` as text or, for binary content types, as base64 with `isBase64Encoded` set.
2209
+
2210
+ A handler can answer in either of the two shapes real Lambda accepts:
2211
+
2212
+ - a structured response, recognised by its `statusCode`, whose `headers`, `body`, `cookies` (sent
2213
+ as `set-cookie` headers) and `isBase64Encoded` control the HTTP response
2214
+ - any other value, which becomes a `200` JSON response, as in
2215
+ `return { greeting: "hello" }`
2216
+
2217
+ If the handler throws, the endpoint answers `502` with an AWS-like error document. The handler's
2218
+ error stays visible to the test, as the thrown error would be through `InvokeCommand`.
2219
+
2220
+ ### Making an invocation event without a request
2221
+
2222
+ A test of the handler on its own, with no endpoint serving it, still has to pass it a whole event.
2223
+ `lambdaFunctionUrlEventFactory` makes one. Such a test then says what the request was and leaves the
2224
+ rest to the factory:
2225
+
2226
+ ```typescript sim-lambda-function-url-event-factory
2227
+ /**
2228
+ * Making a Lambda Function URL invocation event to call a handler with.
2229
+ */
2230
+
2231
+ import { VariantFactory } from "@kensio/part-factory";
2232
+
2233
+ import {
2234
+ lambdaFunctionUrlEventFactory,
2235
+ type SimLambdaFunctionUrlEvent,
2236
+ type SimLambdaFunctionUrlResult,
2237
+ } from "@kensio/yulin/lambda";
2238
+
2239
+ function greeter(event: SimLambdaFunctionUrlEvent): SimLambdaFunctionUrlResult {
2240
+ return {
2241
+ statusCode: 200,
2242
+ headers: { "content-type": "text/plain" },
2243
+ body: `Hello ${event.queryStringParameters?.["name"] ?? "world"}`,
2244
+ };
2245
+ }
2246
+
2247
+ const event = lambdaFunctionUrlEventFactory.make({
2248
+ rawPath: "/greet",
2249
+ rawQueryString: "name=Yulin",
2250
+ });
2251
+
2252
+ // Hello Yulin
2253
+ console.log(greeter(event).body);
2254
+
2255
+ // A named variation of a request is a VariantFactory around it, as with any
2256
+ // other @kensio/part-factory factory.
2257
+ const formPostFactory = new VariantFactory(lambdaFunctionUrlEventFactory, {
2258
+ headers: { "content-type": "application/x-www-form-urlencoded" },
2259
+ requestContext: { http: { method: "POST" } },
2260
+ });
2261
+
2262
+ const formPost = formPostFactory.make({
2263
+ rawPath: "/subscribe",
2264
+ body: "email=someone%40yulin.test",
2265
+ });
2266
+
2267
+ // POST /subscribe
2268
+ console.log(
2269
+ `${formPost.requestContext.http.method} ${formPost.requestContext.http.path}`,
2270
+ );
2271
+ ```
2272
+
2273
+ The defaults describe an anonymous `GET /` to a `NONE` auth Function URL, down to the headers AWS
2274
+ stamps on a proxied request. A handler reading `host`, `x-forwarded-for` or `x-amzn-trace-id` finds
2275
+ what it would find on AWS. The fields a Function URL invocation never carries (`pathParameters` and
2276
+ `stageVariables`) are absent, as they are in a served event.
2277
+
2278
+ A real event says several things twice, and the factory computes its defaults from the overrides so
2279
+ that supplying either copy sets both:
2280
+
2281
+ | What the request says | Where the event says it |
2282
+ | --------------------- | ------------------------------------------------------------------------------------------------- |
2283
+ | the path | `rawPath` and `requestContext.http.path` |
2284
+ | the query | `rawQueryString` and the parsed `queryStringParameters` |
2285
+ | the endpoint | `requestContext.apiId`, `requestContext.domainPrefix`, `requestContext.domainName`, `host` header |
2286
+ | the caller | `requestContext.http.sourceIp` and `userAgent`, the `x-forwarded-for` and `user-agent` headers |
2287
+ | the time | `requestContext.timeEpoch` and the Common Log Format `requestContext.time` |
2288
+
2289
+ So `make({ rawPath: "/user/status" })` is a request for `/user/status` in both places, and the
2290
+ request context follows the override. Overriding both copies with different values is still allowed,
2291
+ for a test that wants an event no real invocation produces.
2292
+
2293
+ The same events go to a handler through
2294
+ [the API Gateway HTTP API](https://yulinsim.dev/services/apigatewayv2/ "Simulated API Gateway HTTP API usage docs") too, where
2295
+ the route key, the stage and the path parameters are the endpoint's rather than a Function URL's
2296
+ `$default`. An event for one of those is this factory with those fields overridden.
2297
+
2298
+ ### Managing a Function URL
2299
+
2300
+ `GetFunctionUrlConfigCommand` reads the configuration back, `UpdateFunctionUrlConfigCommand`
2301
+ changes the `AuthType` or `InvokeMode` while keeping the same endpoint, and
2302
+ `DeleteFunctionUrlConfigCommand` removes it, after which the hostname stops resolving and returns
2303
+ `404`. `ListFunctionUrlConfigsCommand` lists what a function has, which is one configuration or
2304
+ none, since a function has at most one Function URL.
2305
+
2306
+ ### IAM-authenticated Function URLs
2307
+
2308
+ A URL created with `AuthType: "AWS_IAM"` invokes the function only for a caller allowed
2309
+ `lambda:InvokeFunctionUrl` on the function ARN, and answers `403` otherwise. That is a different
2310
+ action from `lambda:InvokeFunction`, which the Invoke API uses. Real AWS separates the two so a
2311
+ policy can grant the HTTP endpoint without granting the SDK operation, and a policy naming only one
2312
+ of them grants only that one here as well.
2313
+
2314
+ The caller comes from the request itself, through either a SigV4 signature or an `x-sim-aws-caller`
2315
+ header naming a principal directly. A request that offers no caller at all is anonymous, owns no
2316
+ policies, and is refused. See [callers of HTTP requests](https://yulinsim.dev/services/iam/#callers-of-http-requests) in the IAM docs for how
2317
+ that resolution works and how to sign a served request.
2318
+
2319
+ A grant conditioned on `AWS:SourceArn` or `AWS:SourceAccount` is evaluated against what the request
2320
+ says it is being made for. That is how a permission granting `cloudfront.amazonaws.com` names one
2321
+ Distribution. Sim CloudFront states that itself when it reaches a Function URL Origin through an
2322
+ origin access control, and a Function URL behind a Distribution runs for that Distribution and
2323
+ refuses everything else. See
2324
+ [origin access controls](https://yulinsim.dev/services/cloudfront/#origin-access-controls) in the CloudFront docs.
2325
+
2326
+ A request declaring what its body hashes to in an `x-amz-content-sha256` header is held to it,
2327
+ whichever method it used. The header is checked against the bytes that arrived, and a request
2328
+ declaring `UNSIGNED-PAYLOAD` is refused with `403` and `The request signature we calculated does not
2329
+ match the signature you provided`, because Lambda supports no unsigned payload. A request that
2330
+ declares no hash is invoked as before. That is what makes a POST through a CloudFront origin access
2331
+ control need the viewer's own digest. See
2332
+ [posting to a Function URL Origin](https://yulinsim.dev/services/cloudfront/#posting-to-a-function-url-origin) in the
2333
+ CloudFront docs.
2334
+
2335
+ CloudFront is the exception to the two actions being separate. A request from
2336
+ `cloudfront.amazonaws.com` is authorized against `lambda:InvokeFunctionUrl` and
2337
+ `lambda:InvokeFunction`, and needs a grant for both, exactly what real Lambda asks an origin access
2338
+ control for. A caller signing its own request still needs only `lambda:InvokeFunctionUrl`.
2339
+
2340
+ An `AWS_IAM` invocation carries its caller into the event as `requestContext.authorizer.iam`, the
2341
+ part a handler reads. The `authorizer` block is absent for a `NONE` invocation, as it is on real
2342
+ AWS, and `requestContext.accountId` carries the caller's Account, where a `NONE` invocation reports
2343
+ `anonymous`. The block is
2344
+ shared with simulated API Gateway HTTP APIs, whose JWT authorizers would fill a `jwt` member
2345
+ instead, and `iam` is optional on the type.
2346
+
2347
+ ```typescript sim-lambda-function-url-iam-auth
2348
+ /**
2349
+ * Invoking a simulated Lambda Function URL that requires IAM authentication.
2350
+ */
2351
+
2352
+ import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
2353
+ import {
2354
+ CreateFunctionCommand,
2355
+ CreateFunctionUrlConfigCommand,
2356
+ } from "@aws-sdk/client-lambda";
2357
+
2358
+ import { SimAws } from "@kensio/yulin";
2359
+ import {
2360
+ type SimLambdaFunctionUrlEvent,
2361
+ makeLambdaZipFileInput,
2362
+ } from "@kensio/yulin/lambda";
2363
+ import { serveSimAws } from "@kensio/yulin/serve";
2364
+
2365
+ const simAws = new SimAws();
2366
+ const roleArn = "arn:aws:iam::888888888888:role/Reporter";
2367
+
2368
+ const created = await simAws.lambda().createFunction(
2369
+ new CreateFunctionCommand({
2370
+ FunctionName: "reporter",
2371
+ Role: "arn:aws:iam::888888888888:role/ReporterExecutionRole",
2372
+ Code: {
2373
+ ZipFile: makeLambdaZipFileInput((event: SimLambdaFunctionUrlEvent) => ({
2374
+ statusCode: 200,
2375
+ body: `called by ${event.requestContext.authorizer?.iam?.userArn ?? "nobody"}`,
2376
+ })),
2377
+ },
2378
+ }),
2379
+ );
2380
+
2381
+ const urlConfig = await simAws.lambda().createFunctionUrlConfig(
2382
+ new CreateFunctionUrlConfigCommand({
2383
+ FunctionName: "reporter",
2384
+ AuthType: "AWS_IAM",
2385
+ }),
2386
+ );
2387
+
2388
+ // The Role that is allowed to call the endpoint.
2389
+ await simAws.iam().createRole(
2390
+ new CreateRoleCommand({
2391
+ RoleName: "Reporter",
2392
+ AssumeRolePolicyDocument: JSON.stringify({
2393
+ Version: "2012-10-17",
2394
+ Statement: {
2395
+ Effect: "Allow",
2396
+ Principal: { AWS: "arn:aws:iam::888888888888:root" },
2397
+ Action: "sts:AssumeRole",
2398
+ },
2399
+ }),
2400
+ }),
2401
+ );
2402
+
2403
+ await simAws.iam().putRolePolicy(
2404
+ new PutRolePolicyCommand({
2405
+ RoleName: "Reporter",
2406
+ PolicyName: "InvokeReporterUrl",
2407
+ PolicyDocument: JSON.stringify({
2408
+ Version: "2012-10-17",
2409
+ Statement: {
2410
+ Effect: "Allow",
2411
+ Action: "lambda:InvokeFunctionUrl",
2412
+ Resource: created.FunctionArn,
2413
+ },
2414
+ }),
2415
+ }),
2416
+ );
2417
+
2418
+ const srv = await serveSimAws({ simAws });
2419
+
2420
+ try {
2421
+ const url = srv.localUrl(urlConfig.FunctionUrl);
2422
+
2423
+ // Unauthenticated, so anonymous, so refused.
2424
+ const refused = await fetch(url);
2425
+ console.log(refused.status); // 403
2426
+
2427
+ // Named as the Role that is allowed to invoke.
2428
+ const allowed = await fetch(url, {
2429
+ headers: { "x-sim-aws-caller": roleArn },
2430
+ });
2431
+
2432
+ console.log(allowed.status); // 200
2433
+ console.log(await allowed.text()); // called by arn:aws:iam::888888888888:role/Reporter
2434
+ } finally {
2435
+ await srv.close();
2436
+ }
2437
+ ```
2438
+
2439
+ ## Resource-based policies
2440
+
2441
+ A function's resource-based policy is the other half of Lambda authorization. An identity policy
2442
+ says what a principal may do, and a resource policy says who may act on the function. Either one is
2443
+ enough to allow a call within the same Account. A principal from another Account needs both, the
2444
+ grant on the function and an identity policy in its own Account allowing the action. That is how AWS
2445
+ decides a cross-Account request. See
2446
+ [Cross-Account requests](https://yulinsim.dev/services/iam/#cross-account-requests).
2447
+
2448
+ `AddPermissionCommand` grants a statement, `RemovePermissionCommand` revokes it by `StatementId`,
2449
+ and `GetPolicyCommand` returns the assembled document. `AddPermission` is a shorthand. Lambda expands
2450
+ its parts into one statement, and reading that statement back shows what the grant means:
2451
+
2452
+ ```typescript sim-lambda-add-permission
2453
+ /**
2454
+ * Granting another Account permission to invoke a simulated Lambda function.
2455
+ */
2456
+
2457
+ import {
2458
+ AddPermissionCommand,
2459
+ CreateFunctionCommand,
2460
+ GetPolicyCommand,
2461
+ } from "@aws-sdk/client-lambda";
2462
+
2463
+ import { SimAws } from "@kensio/yulin";
2464
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
2465
+
2466
+ const simAws = new SimAws();
2467
+
2468
+ await simAws.lambda().createFunction(
2469
+ new CreateFunctionCommand({
2470
+ FunctionName: "greeter",
2471
+ Role: "arn:aws:iam::888888888888:role/GreeterRole",
2472
+ Code: { ZipFile: makeLambdaZipFileInput(() => "hello") },
2473
+ }),
2474
+ );
2475
+
2476
+ const added = await simAws.lambda().addPermission(
2477
+ new AddPermissionCommand({
2478
+ FunctionName: "greeter",
2479
+ StatementId: "AllowOtherAccount",
2480
+ Action: "lambda:InvokeFunctionUrl",
2481
+ Principal: "222222222222",
2482
+ FunctionUrlAuthType: "AWS_IAM",
2483
+ }),
2484
+ );
2485
+
2486
+ // The statement the shorthand expanded into.
2487
+ console.log(added.Statement);
2488
+
2489
+ const policy = await simAws
2490
+ .lambda()
2491
+ .getPolicy(new GetPolicyCommand({ FunctionName: "greeter" }));
2492
+
2493
+ console.log(policy.Policy);
2494
+ ```
2495
+
2496
+ `Principal` takes the same shorthand real Lambda does, and is expanded the same way. A 12-digit
2497
+ Account id becomes `{"AWS": "arn:aws:iam::<id>:root"}`, an ARN becomes `{"AWS": "<arn>"}`, anything
2498
+ else is read as a service principal, and `*` stays `*`.
2499
+
2500
+ `FunctionUrlAuthType` becomes a `lambda:FunctionUrlAuthType` condition, evaluated when a Function
2501
+ URL is invoked. That is what a Function URL grant conditions on in practice. A permission granted
2502
+ for `AWS_IAM` leaves a URL later switched to `NONE` closed.
2503
+
2504
+ `SourceArn` becomes an `ArnLike` condition on `AWS:SourceArn`, and `SourceAccount` a `StringEquals`
2505
+ condition on `AWS:SourceAccount`. Both are evaluated when another simulated service invokes the
2506
+ function on a resource's behalf, and every simulated service that does so supplies them. That covers
2507
+ a simulated API Gateway HTTP API invoking it through a Lambda proxy integration or as a `REQUEST`
2508
+ authorizer, a simulated S3 Bucket delivering an event notification, a simulated SNS topic delivering
2509
+ a message, a simulated Cognito user pool running a Lambda trigger, and an EventBridge or ELBv2
2510
+ target. The source ARN is what that service is invoking the function for, and the source Account is
2511
+ that service's resource's own. See
2512
+ [Granting the API permission to invoke the function](https://yulinsim.dev/services/apigatewayv2/#granting-the-api-permission-to-invoke-the-function)
2513
+ and [Lambda triggers](https://yulinsim.dev/services/cognito/#lambda-triggers). A served Function URL request carries a
2514
+ source ARN when it says what it is being made for, which is how a CloudFront origin access control
2515
+ reaches one. A direct `Invoke` and an SQS event source mapping supply no value for either, and a
2516
+ statement carrying one matches no request of theirs.
2517
+
2518
+ `PrincipalOrgID` and `InvokedViaFunctionUrl` are written into the statement so `GetPolicy` reports
2519
+ the grant that was made. No value is supplied for them at request time, and a statement carrying one
2520
+ of those never matches.
2521
+
2522
+ All three commands take a `Qualifier` naming a published version or an alias, and each qualified
2523
+ resource holds its own policy. See
2524
+ [Versions and aliases](#versions-and-aliases) for what a grant on one covers.
2525
+
2526
+ A function with no grant on it has no policy at all. `GetPolicy` reports that as a
2527
+ `ResourceNotFoundException`, and never as an empty document. Granting a `StatementId` that is
2528
+ already in use is a `ResourceConflictException`, and removing one that was never granted is a
2529
+ `ResourceNotFoundException`, as on AWS.
2530
+
2531
+ ### Permissions in templates
2532
+
2533
+ `AWS::Lambda::Permission` creates the same permission from a CloudFormation template, which matters
2534
+ because CDK emits one for every `grantInvoke` and `grantInvokeUrl` to a principal outside the
2535
+ stack's own Account. The Resource has no `StatementId` property. CloudFormation names the statement
2536
+ after the logical ID, and so does this.
2537
+
2538
+ ```json
2539
+ {
2540
+ "AllowOtherAccount": {
2541
+ "Type": "AWS::Lambda::Permission",
2542
+ "Properties": {
2543
+ "FunctionName": { "Ref": "GreeterFunction" },
2544
+ "Action": "lambda:InvokeFunctionUrl",
2545
+ "Principal": "222222222222",
2546
+ "FunctionUrlAuthType": "AWS_IAM"
2547
+ }
2548
+ }
2549
+ }
2550
+ ```
2551
+
2552
+ `FunctionName` accepts either a `Ref` to the function, giving its name, or an `Fn::GetAtt` on it,
2553
+ giving the ARN. A synthesized CDK app deploys either way with no special casing.
2554
+
2555
+ A `FunctionName` carrying a version number or an alias name grants on that qualified resource, and
2556
+ the statement's `Resource` is the qualified ARN. This is how CDK writes `grantInvoke` on a
2557
+ `lambda.Alias`, and a grant made that way admits a call through the alias while `$LATEST` keeps a
2558
+ policy of its own. See [versions and aliases](#versions-and-aliases).
2559
+
2560
+ ## Environment variables
2561
+
2562
+ A function can declare its own environment variables with `Environment.Variables`, as on real
2563
+ Lambda. While the function runs, its code reads those variables from `process.env`, alongside the
2564
+ AWS-provided runtime variables (`AWS_REGION`, `AWS_LAMBDA_FUNCTION_NAME`, and the rest). Those
2565
+ include placeholder execution role credentials in `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and
2566
+ `AWS_SESSION_TOKEN`, where an AWS SDK in the function code finds credentials, as it does on real
2567
+ Lambda. Their values authorize nothing. A call from function code is attributed to the execution
2568
+ Role because the invocation is running as it.
2569
+
2570
+ ```typescript sim-lambda-environment-variables
2571
+ /**
2572
+ * Giving a simulated Lambda function its own environment variables, read by
2573
+ * a real in-process handler function.
2574
+ */
2575
+
2576
+ import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
2577
+
2578
+ import { SimAws } from "@kensio/yulin";
2579
+ import { makeLambdaZipFileInput } from "@kensio/yulin/lambda";
2580
+
2581
+ const simAws = new SimAws();
2582
+ const lambda = simAws.lambda();
2583
+
2584
+ await lambda.createFunction(
2585
+ new CreateFunctionCommand({
2586
+ FunctionName: "greeter",
2587
+ Role: "arn:aws:iam::111111111111:role/GreeterRole",
2588
+ Environment: {
2589
+ Variables: { GREETING: "Hello", TABLE_NAME: "widgets" },
2590
+ },
2591
+ Code: {
2592
+ ZipFile: makeLambdaZipFileInput((event: { name: string }) => ({
2593
+ // Read inside the handler, so this sees the function's own
2594
+ // variables rather than the ones the test process happens to have.
2595
+ message: `${process.env["GREETING"] ?? "Hi"} ${event.name}`,
2596
+ tableName: process.env["TABLE_NAME"],
2597
+ region: process.env["AWS_REGION"],
2598
+ })),
2599
+ },
2600
+ }),
2601
+ );
2602
+
2603
+ const invokeOutput = await lambda.invoke(
2604
+ new InvokeCommand({
2605
+ FunctionName: "greeter",
2606
+ Payload: JSON.stringify({ name: "Yulin" }),
2607
+ }),
2608
+ );
2609
+
2610
+ if (invokeOutput.Payload === undefined) throw new Error("No invoke Payload");
2611
+ // {"message":"Hello Yulin","tableName":"widgets","region":"eu-west-2"}
2612
+ console.log(Buffer.from(invokeOutput.Payload).toString());
2613
+ ```
2614
+
2615
+ A function that declares variables gets only those and the AWS-provided ones. Variables that happen
2616
+ to be set in the process running your tests stay invisible to it, and a function cannot accidentally
2617
+ pass because your shell or CI environment had the right variable set. Two functions declaring the
2618
+ same variable name with different values each see their own, including when their invocations
2619
+ overlap.
2620
+
2621
+ The same applies to zip-packaged code in the vm runtime and to functions deployed from an
2622
+ `AWS::Lambda::Function` template with an `Environment` property, including ones backed by an
2623
+ [executable binding](#executable-bindings).
2624
+
2625
+ A function backed by a real in-process handler and declaring no variables at all is the exception.
2626
+ It keeps reading the test process's environment, with the AWS-provided variables laid over it, since
2627
+ that is where such a handler's configuration comes from when nothing declares it. Declaring the
2628
+ variables on the function keeps the test explicit about where they came from. Zip-packaged code in
2629
+ the vm runtime gets the function's own variables either way, and never the test process's.
2630
+
2631
+ This is also how a function reaches something outside the simulation, such as a Redis or a
2632
+ Postgres. See [non-AWS dependencies](https://yulinsim.dev/non-aws-dependencies/).
2633
+
2634
+ Variable names are validated as on real AWS. A name must match the Lambda name pattern
2635
+ `[a-zA-Z]([a-zA-Z0-9_])+`, meaning it starts with a letter, is at least two characters, and otherwise
2636
+ holds letters, digits and underscores. A name breaking that pattern is rejected with
2637
+ `ValidationException`. The names Lambda reserves for the runtime (`AWS_REGION`,
2638
+ `AWS_LAMBDA_FUNCTION_NAME`, `LAMBDA_TASK_ROOT` and so on) cannot be declared, and are rejected with
2639
+ `InvalidParameterValueException`. As on AWS, the pattern is checked first, and a reserved name that
2640
+ also breaks it, such as `_HANDLER`, is reported as the constraint violation.
2641
+
2642
+ ### Read environment variables inside the handler
2643
+
2644
+ A function backed by a real in-process handler behaves differently here. That handler is an ordinary
2645
+ function in your test process rather than code loaded into a sandbox. It only gets the function's
2646
+ own `process.env` while it is actually running.
2647
+
2648
+ That means a variable read at module scope is read too early:
2649
+
2650
+ ```typescript
2651
+ // Evaluated when your test file imports this module, before any invocation,
2652
+ // so it sees the test process's environment, not the function's.
2653
+ const TABLE_NAME = process.env.TABLE_NAME;
2654
+
2655
+ export const handler = async () => {
2656
+ // Read during the invocation, so this sees the function's own value.
2657
+ return { tableName: process.env.TABLE_NAME };
2658
+ };
2659
+ ```
2660
+
2661
+ Moving the read inside the handler fixes it. Zip code in the vm runtime is unaffected, because it is
2662
+ imported at cold start, during an invocation.
2663
+
2664
+ This rarely comes up, because test suites commonly export the same variables they configure their
2665
+ functions with, and then a module-scope read gets the right value anyway. Sim Lambda warns on the
2666
+ console in the two situations where the difference changes what your code sees:
2667
+
2668
+ - a declared variable whose name the host process also sets, with a different value
2669
+ - two simulated functions declaring the same variable name with different values
2670
+
2671
+ ## The time inside a handler
2672
+
2673
+ A function runs on its simulation's clock, and so does the function code. `Date.now()` and
2674
+ `new Date()` inside a handler report simulated time. Freezing the clock gives an invocation a
2675
+ constant `Date.now()`, and advancing it changes what the next invocation reads.
2676
+ `context.getRemainingTimeInMillis()` counts down against the same clock. A frozen clock leaves a
2677
+ handler with a constant budget, where it would otherwise drain in real time.
2678
+
2679
+ Zip code gets this from its own vm sandbox. A real in-process handler gets it from a substituted
2680
+ global `Date` that reports the invocation's clock while an invocation is running and the host clock
2681
+ otherwise. A time read at module scope is therefore read too early, exactly as it is for environment
2682
+ variables. See [simulated time](https://yulinsim.dev/time/) for the whole picture, including where real
2683
+ AWS puts the time on the event.
2684
+
2685
+ ## CloudFormation functions
2686
+
2687
+ Sim CloudFormation can create Lambda functions from `AWS::Lambda::Function`, typically alongside a
2688
+ same-stack `AWS::IAM::Role` referenced as the execution role. Inline `ZipFile` template source is
2689
+ packaged and run in the vm runtime, exactly as if it had been zipped and passed to
2690
+ `CreateFunctionCommand`.
2691
+
2692
+ ```typescript sim-lambda-cloudformation-function
2693
+ /**
2694
+ * Creating an invokable Lambda function through simulated CloudFormation.
2695
+ */
2696
+
2697
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
2698
+
2699
+ import { SimAws } from "@kensio/yulin";
2700
+
2701
+ const simAws = new SimAws();
2702
+
2703
+ const stack = await simAws.cloudFormation().deployTemplate({
2704
+ stackName: "greeter-stack",
2705
+ template: {
2706
+ Resources: {
2707
+ GreeterRole: {
2708
+ Type: "AWS::IAM::Role",
2709
+ Properties: {
2710
+ RoleName: "GreeterRole",
2711
+ AssumeRolePolicyDocument: {
2712
+ Version: "2012-10-17",
2713
+ Statement: [
2714
+ {
2715
+ Effect: "Allow",
2716
+ Principal: { Service: "lambda.amazonaws.com" },
2717
+ Action: "sts:AssumeRole",
2718
+ },
2719
+ ],
2720
+ },
2721
+ },
2722
+ },
2723
+ GreeterFunction: {
2724
+ Type: "AWS::Lambda::Function",
2725
+ Properties: {
2726
+ FunctionName: "greeter",
2727
+ Role: {
2728
+ "Fn::GetAtt": ["GreeterRole", "Arn"],
2729
+ },
2730
+ Handler: "index.handler",
2731
+ Runtime: "nodejs20.x",
2732
+ Code: {
2733
+ ZipFile:
2734
+ "exports.handler = async (event) => 'Hello ' + event.name;",
2735
+ },
2736
+ },
2737
+ },
2738
+ },
2739
+ Outputs: {
2740
+ FunctionName: {
2741
+ Value: {
2742
+ Ref: "GreeterFunction",
2743
+ },
2744
+ },
2745
+ FunctionArn: {
2746
+ Value: {
2747
+ "Fn::GetAtt": ["GreeterFunction", "Arn"],
2748
+ },
2749
+ },
2750
+ },
2751
+ },
2752
+ });
2753
+ await stack.waitForDeployComplete();
2754
+
2755
+ console.log(stack.output("FunctionName"));
2756
+ console.log(stack.output("FunctionArn"));
2757
+
2758
+ const output = await simAws.lambda().invoke(
2759
+ new InvokeCommand({
2760
+ FunctionName: "greeter",
2761
+ Payload: JSON.stringify({ name: "Yulin" }),
2762
+ }),
2763
+ );
2764
+
2765
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
2766
+ console.log(Buffer.from(output.Payload).toString());
2767
+
2768
+ await simAws.backgroundTasksComplete();
2769
+ ```
2770
+
2771
+ For `AWS::Lambda::Function`, `Ref` returns the function name and `Fn::GetAtt` supports `Arn`.
2772
+
2773
+ Supported function properties:
2774
+
2775
+ - `FunctionName` (defaults to the logical ID)
2776
+ - `Role` (typically a `Ref`/`Fn::GetAtt` to a same-stack `AWS::IAM::Role`, both resolving to the
2777
+ role's ARN)
2778
+ - `Code` (inline `ZipFile` source string, or `S3Bucket`/`S3Key` fetched from same-scope sim S3)
2779
+ - `Handler`
2780
+ - `Runtime`
2781
+ - `Description`
2782
+ - `Timeout`
2783
+ - `MemorySize`
2784
+ - `Environment`
2785
+ - `DeadLetterConfig`, whose `TargetArn` names a queue or a topic. See
2786
+ [retries and destinations in templates](#retries-and-destinations-in-templates)
2787
+
2788
+ Code in a missing bucket fails the deploy AWS-style with a `NoSuchBucket` diagnostic.
2789
+
2790
+ ### CDK asset code
2791
+
2792
+ `lambda.Code.fromAsset(...)` and the constructs built on it stage function code in the CDK cloud
2793
+ assembly, and synthesize a `Code.S3Bucket`/`S3Key` pointing at the CDK bootstrap staging bucket.
2794
+ Deploying a synthesized template file with `deployTemplateFile` publishes the cloud assembly's
2795
+ assets into that bucket in sim S3 before creating any resource, mirroring the way a real
2796
+ `cdk deploy` runs `cdk-assets` before CloudFormation. Asset-bundled functions then resolve their
2797
+ code through the ordinary sim S3 fetch and run their real handler modules.
2798
+
2799
+ Both shapes of staged asset are published. A handler directory is zipped on the way into sim S3,
2800
+ as `cdk-assets` zips it on the way to a real bucket. An asset that is already an archive, such as
2801
+ `Code.fromAsset("handler.zip")` or a bundler's archived output, is published as it stands.
2802
+
2803
+ Asset code runs under the same rules as any other sim Lambda code. Modules are evaluated as
2804
+ CommonJS in a vm, so everything the handler imports has to be in the asset, and only Node.js
2805
+ runtimes are simulated.
2806
+
2807
+ Two cases are skipped with a diagnostic, and the stack deploys around them:
2808
+
2809
+ - A function declaring a non-Node.js `Runtime`, such as the Python provider function CDK
2810
+ synthesizes for `BucketDeployment`. Sim CloudFormation simulates that custom resource directly,
2811
+ so its provider never needs to run. Bind a real in-process handler to simulate a function whose
2812
+ runtime Yulin cannot run.
2813
+ - A CDK-shaped template deployed without its cloud assembly, such as a template object passed
2814
+ inline to `deployTemplate`, where there is no asset to publish and no staging bucket.
2815
+
2816
+ ### Container image functions
2817
+
2818
+ A function with `PackageType: Image` names a container image instead of code, as CDK's
2819
+ `DockerImageFunction` and `lambda.DockerImageCode` synthesize it. Yulin never reads an image, and
2820
+ has nothing to run. The Resource is skipped with a diagnostic naming the image, and the rest of the
2821
+ stack deploys.
2822
+
2823
+ There are two ways to give that function a real in-process handler to run instead, and they suit
2824
+ different shapes of test:
2825
+
2826
+ - Bind one to the function for this deploy, the same mechanism as
2827
+ [executable bindings](#executable-bindings) and shown below.
2828
+ - Register one as the image in a
2829
+ [simulated ECR repository](https://yulinsim.dev/services/ecr/ "Simulated ECR usage docs"). That is a standing statement about
2830
+ what the image is, made once and good for every stack that runs it, and for a function created
2831
+ directly through `CreateFunction`.
2832
+
2833
+ Either way the handler replaces the image, and the function is created and invoked like any other. A
2834
+ binding is looked at first, because it is about one deploy where a repository is about the image
2835
+ everywhere.
2836
+
2837
+ ```typescript sim-lambda-container-image-function
2838
+ /**
2839
+ * Simulating a container image Lambda function with a bound handler.
2840
+ */
2841
+
2842
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
2843
+
2844
+ import { SimAws } from "@kensio/yulin";
2845
+
2846
+ const imageFunctionTemplate = {
2847
+ Resources: {
2848
+ OrdersFunction: {
2849
+ Type: "AWS::Lambda::Function",
2850
+ Properties: {
2851
+ FunctionName: "orders",
2852
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
2853
+ PackageType: "Image",
2854
+ Code: {
2855
+ ImageUri:
2856
+ "111111111111.dkr.ecr.eu-west-2.amazonaws.com/orders:latest",
2857
+ },
2858
+ },
2859
+ },
2860
+ },
2861
+ };
2862
+
2863
+ // Without a binding, the function is skipped and the stack still deploys.
2864
+ const skippedSimAws = new SimAws();
2865
+
2866
+ const skippedStack = await skippedSimAws.cloudFormation().deployTemplate({
2867
+ stackName: "orders-stack",
2868
+ template: imageFunctionTemplate,
2869
+ });
2870
+
2871
+ console.log(skippedStack.getResource("OrdersFunction")?.skippedReason);
2872
+
2873
+ await skippedSimAws.backgroundTasksComplete();
2874
+
2875
+ // With a binding, the handler replaces the image and the function runs.
2876
+ const simAws = new SimAws();
2877
+
2878
+ await simAws.cloudFormation().deployTemplate({
2879
+ stackName: "orders-stack",
2880
+ template: imageFunctionTemplate,
2881
+ bindings: [
2882
+ {
2883
+ logicalId: "OrdersFunction",
2884
+ handler: (event: { orderId: string }): string =>
2885
+ `Processed ${event.orderId}`,
2886
+ },
2887
+ ],
2888
+ });
2889
+
2890
+ const output = await simAws.lambda().invoke(
2891
+ new InvokeCommand({
2892
+ FunctionName: "orders",
2893
+ Payload: JSON.stringify({ orderId: "order-1" }),
2894
+ }),
2895
+ );
2896
+
2897
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
2898
+ console.log(Buffer.from(output.Payload).toString());
2899
+
2900
+ await simAws.backgroundTasksComplete();
2901
+ ```
2902
+
2903
+ A function declaring `Code.ImageUri` without `PackageType` is treated the same way. `ImageConfig`
2904
+ is ignored, because `Command`, `EntryPoint` and `WorkingDirectory` have no meaning for a handler
2905
+ running in this process.
2906
+
2907
+ A binding can also name the image repository instead of the function, which covers every function
2908
+ running that image without repeating the binding per stack. See
2909
+ [binding by container image repository](#binding-by-container-image-repository).
2910
+
2911
+ The skip reason says what was looked for. An image whose repository no simulated ECR holds is
2912
+ reported apart from one whose repository holds no image, since those send you to different places.
2913
+ The first is a repository name disagreeing with the template, and the second a handler that was
2914
+ never registered.
2915
+
2916
+ ## Function URLs in templates
2917
+
2918
+ `AWS::Lambda::Url` creates a Function URL for a deployed function, and CDK's
2919
+ `Function.addFunctionUrl(...)` emits one. `TargetFunctionArn` accepts either an `Fn::GetAtt` ARN or a
2920
+ `Ref` to the function, and `Fn::GetAtt` on the URL exposes `FunctionUrl` and `FunctionArn`.
2921
+
2922
+ ```typescript sim-lambda-cloudformation-function-url
2923
+ /**
2924
+ * Deploying a simulated Lambda Function URL from a CloudFormation template.
2925
+ */
2926
+
2927
+ import { SimAws } from "@kensio/yulin";
2928
+ import { serveSimAws } from "@kensio/yulin/serve";
2929
+
2930
+ const simAws = new SimAws();
2931
+
2932
+ const stack = await simAws.cloudFormation().deployTemplate({
2933
+ stackName: "greeter-stack",
2934
+ template: {
2935
+ Resources: {
2936
+ GreeterRole: {
2937
+ Type: "AWS::IAM::Role",
2938
+ Properties: {
2939
+ RoleName: "GreeterRole",
2940
+ AssumeRolePolicyDocument: {
2941
+ Version: "2012-10-17",
2942
+ Statement: [
2943
+ {
2944
+ Effect: "Allow",
2945
+ Principal: { Service: "lambda.amazonaws.com" },
2946
+ Action: "sts:AssumeRole",
2947
+ },
2948
+ ],
2949
+ },
2950
+ },
2951
+ },
2952
+ GreeterFunction: {
2953
+ Type: "AWS::Lambda::Function",
2954
+ Properties: {
2955
+ FunctionName: "greeter",
2956
+ Role: { "Fn::GetAtt": ["GreeterRole", "Arn"] },
2957
+ Handler: "index.handler",
2958
+ Runtime: "nodejs22.x",
2959
+ Code: {
2960
+ ZipFile:
2961
+ "exports.handler = async (event) => " +
2962
+ "({ statusCode: 200, body: 'Hello ' + event.rawPath });",
2963
+ },
2964
+ },
2965
+ },
2966
+ GreeterUrl: {
2967
+ Type: "AWS::Lambda::Url",
2968
+ Properties: {
2969
+ TargetFunctionArn: { "Fn::GetAtt": ["GreeterFunction", "Arn"] },
2970
+ AuthType: "NONE",
2971
+ },
2972
+ },
2973
+ },
2974
+ Outputs: {
2975
+ GreeterFunctionUrl: {
2976
+ Value: { "Fn::GetAtt": ["GreeterUrl", "FunctionUrl"] },
2977
+ },
2978
+ },
2979
+ },
2980
+ });
2981
+ await stack.waitForDeployComplete();
2982
+
2983
+ const functionUrl = stack.output("GreeterFunctionUrl");
2984
+ const srv = await serveSimAws({ simAws });
2985
+
2986
+ try {
2987
+ const response = await fetch(srv.localUrl(`${functionUrl}hello`));
2988
+
2989
+ console.log(await response.text());
2990
+ } finally {
2991
+ await srv.close();
2992
+ }
2993
+ ```
2994
+
2995
+ CDK templates work the same way. Synth the app, deploy the template file, and read
2996
+ `functionUrl.url` from the stack outputs. CDK pairs a public Function URL with an
2997
+ `AWS::Lambda::Permission`, which deploys alongside it as
2998
+ [permissions in templates](#permissions-in-templates) covers.
2999
+
3000
+ ## Versions and aliases in templates
3001
+
3002
+ `AWS::Lambda::Version` publishes a version of the function its `FunctionName` names, and
3003
+ `AWS::Lambda::Alias` gives one of those versions a name. CDK emits both for `fn.currentVersion` and
3004
+ `new lambda.Alias(...)`, and the integrations in such an app point at the alias.
3005
+
3006
+ `FunctionName` accepts either a `Ref` to the function, giving its name, or an `Fn::GetAtt` on it,
3007
+ giving the ARN. `Ref` on the version resolves to the qualified function ARN
3008
+ (`arn:aws:lambda:us-east-1:888888888888:function:greeter:1`) and `Fn::GetAtt` `Version` to the
3009
+ number on the end of it. An alias's `FunctionVersion` is usually written from that number. `Ref` on
3010
+ the alias resolves to the alias ARN. `Fn::GetAtt` also supports `FunctionArn` on a version and
3011
+ `AliasArn` on an alias.
3012
+
3013
+ ```typescript sim-lambda-cloudformation-alias
3014
+ /**
3015
+ * Deploying a Lambda version and an alias on it from a CloudFormation
3016
+ * template, and invoking the function through the alias.
3017
+ */
3018
+
3019
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
3020
+
3021
+ import { SimAws } from "@kensio/yulin";
3022
+
3023
+ const simAws = new SimAws();
3024
+
3025
+ const stack = await simAws.cloudFormation().deployTemplate({
3026
+ stackName: "greeter-stack",
3027
+ template: {
3028
+ Resources: {
3029
+ GreeterFunction: {
3030
+ Type: "AWS::Lambda::Function",
3031
+ Properties: {
3032
+ FunctionName: "greeter",
3033
+ Role: "arn:aws:iam::111111111111:role/GreeterRole",
3034
+ Handler: "index.handler",
3035
+ Runtime: "nodejs22.x",
3036
+ Code: {
3037
+ ZipFile:
3038
+ "exports.handler = async (event, context) => " +
3039
+ "context.functionVersion;",
3040
+ },
3041
+ },
3042
+ },
3043
+ GreeterVersion: {
3044
+ Type: "AWS::Lambda::Version",
3045
+ Properties: {
3046
+ FunctionName: { Ref: "GreeterFunction" },
3047
+ },
3048
+ },
3049
+ GreeterAlias: {
3050
+ Type: "AWS::Lambda::Alias",
3051
+ Properties: {
3052
+ FunctionName: { Ref: "GreeterFunction" },
3053
+ Name: "live",
3054
+ FunctionVersion: { "Fn::GetAtt": ["GreeterVersion", "Version"] },
3055
+ },
3056
+ },
3057
+ },
3058
+ Outputs: {
3059
+ GreeterAliasArn: { Value: { Ref: "GreeterAlias" } },
3060
+ },
3061
+ },
3062
+ });
3063
+ await stack.waitForDeployComplete();
3064
+
3065
+ console.log(stack.output("GreeterAliasArn"));
3066
+
3067
+ const invoked = await simAws
3068
+ .lambda()
3069
+ .invoke(new InvokeCommand({ FunctionName: "greeter", Qualifier: "live" }));
3070
+
3071
+ console.log(invoked.ExecutedVersion);
3072
+
3073
+ await simAws.backgroundTasksComplete();
3074
+ ```
3075
+
3076
+ Supported `AWS::Lambda::Version` properties:
3077
+
3078
+ - `FunctionName`
3079
+ - `Description`, which describes the published version and leaves the function's own description
3080
+ alone
3081
+
3082
+ Supported `AWS::Lambda::Alias` properties:
3083
+
3084
+ - `FunctionName`
3085
+ - `Name`
3086
+ - `FunctionVersion`
3087
+ - `Description`
3088
+
3089
+ An `AWS::Lambda::Permission` naming a version or an alias grants on it. See
3090
+ [permissions in templates](#permissions-in-templates).
3091
+
3092
+ Deleting the Stack deletes the alias. Lambda has no operation that deletes one published version.
3093
+ The version Resource has nothing of its own to do on teardown, and the version it published goes
3094
+ when the function does.
3095
+
3096
+ ## Retries and destinations in templates
3097
+
3098
+ `AWS::Lambda::EventInvokeConfig` writes the event invoke config of the function, version or alias
3099
+ its `FunctionName` and `Qualifier` name. CDK emits one for `onFailure`, `onSuccess`, `retryAttempts`
3100
+ and `maxEventAge` on a function. `DeadLetterConfig` on `AWS::Lambda::Function` is what CDK's
3101
+ `deadLetterQueue` emits, and it sets the same dead-letter target `CreateFunction` takes.
3102
+
3103
+ ```typescript sim-lambda-cloudformation-event-invoke-config
3104
+ /**
3105
+ * Deploying a Lambda failure destination and a dead-letter queue from a
3106
+ * CloudFormation template.
3107
+ */
3108
+
3109
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
3110
+ import { ReceiveMessageCommand } from "@aws-sdk/client-sqs";
3111
+
3112
+ import { SimAws } from "@kensio/yulin";
3113
+ import type { SimLambdaDestinationRecord } from "@kensio/yulin/lambda";
3114
+
3115
+ const simAws = new SimAws();
3116
+
3117
+ const stack = await simAws.cloudFormation().deployTemplate({
3118
+ stackName: "orders-stack",
3119
+ template: {
3120
+ Resources: {
3121
+ OrderFailures: {
3122
+ Type: "AWS::SQS::Queue",
3123
+ Properties: { QueueName: "order-failures" },
3124
+ },
3125
+ OrderDeadLetters: {
3126
+ Type: "AWS::SQS::Queue",
3127
+ Properties: { QueueName: "orders-dlq" },
3128
+ },
3129
+ OrdersFunction: {
3130
+ Type: "AWS::Lambda::Function",
3131
+ Properties: {
3132
+ FunctionName: "orders",
3133
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
3134
+ Handler: "index.handler",
3135
+ Runtime: "nodejs22.x",
3136
+ Code: {
3137
+ ZipFile:
3138
+ "exports.handler = async () => { throw new Error('failed'); };",
3139
+ },
3140
+ DeadLetterConfig: {
3141
+ TargetArn: { "Fn::GetAtt": ["OrderDeadLetters", "Arn"] },
3142
+ },
3143
+ },
3144
+ },
3145
+ OrdersInvokeConfig: {
3146
+ Type: "AWS::Lambda::EventInvokeConfig",
3147
+ Properties: {
3148
+ FunctionName: { Ref: "OrdersFunction" },
3149
+ Qualifier: "$LATEST",
3150
+ MaximumRetryAttempts: 0,
3151
+ DestinationConfig: {
3152
+ OnFailure: {
3153
+ Destination: { "Fn::GetAtt": ["OrderFailures", "Arn"] },
3154
+ },
3155
+ },
3156
+ },
3157
+ },
3158
+ },
3159
+ Outputs: {
3160
+ FailuresQueueUrl: {
3161
+ Value: { "Fn::GetAtt": ["OrderFailures", "QueueUrl"] },
3162
+ },
3163
+ },
3164
+ },
3165
+ });
3166
+ await stack.waitForDeployComplete();
3167
+
3168
+ await simAws.lambda().invoke(
3169
+ new InvokeCommand({
3170
+ FunctionName: "orders",
3171
+ InvocationType: "Event",
3172
+ Payload: JSON.stringify({ id: 7 }),
3173
+ }),
3174
+ );
3175
+ await simAws.backgroundTasksComplete();
3176
+
3177
+ const received = await simAws
3178
+ .sqs()
3179
+ .receiveMessage(
3180
+ new ReceiveMessageCommand({ QueueUrl: stack.output("FailuresQueueUrl") }),
3181
+ );
3182
+ const record = JSON.parse(
3183
+ String(received.Messages?.[0]?.Body),
3184
+ ) as SimLambdaDestinationRecord;
3185
+
3186
+ console.log(record.requestContext.condition);
3187
+ console.log(record.requestPayload);
3188
+ ```
3189
+
3190
+ Supported `AWS::Lambda::EventInvokeConfig` properties:
3191
+
3192
+ - `FunctionName`, as a `Ref` to the function giving its name or an `Fn::GetAtt` on it giving the ARN
3193
+ - `Qualifier`, naming a published version or an alias. `$LATEST` addresses the function itself
3194
+ - `MaximumRetryAttempts`
3195
+ - `MaximumEventAgeInSeconds`
3196
+ - `DestinationConfig`, holding `OnSuccess` and `OnFailure`
3197
+
3198
+ A destination and a `DeadLetterConfig.TargetArn` name a queue or a topic by `Fn::GetAtt` on its ARN
3199
+ or by `Ref`. `Ref` on an `AWS::SQS::Queue` resolves to the queue URL, and both forms reach the same
3200
+ queue.
3201
+
3202
+ Where a destination names something simulated Lambda has nowhere to send to, such as a service
3203
+ outside the template or a Resource the deployment skipped, the Resource is deployed without that
3204
+ destination and the omission is recorded in `stack.ignoredProperties` under the property that named
3205
+ it. The function still deploys, and a stack keeps the destination it can reach when the other end
3206
+ names one it cannot. Refusing a whole stack over one destination would leave a test with nothing to
3207
+ run.
3208
+
3209
+ Deleting the Stack takes the config off the function, ahead of the function itself.
3210
+
3211
+ ## Executable bindings
3212
+
3213
+ Deploy-time `bindings` let a template function be backed by a real in-process handler instead of its
3214
+ template code. They are the CloudFormation counterpart of `makeLambdaZipFileInput(...)`. The bound
3215
+ handler runs with the same execution-role attribution as template code, can close over test state,
3216
+ and can be stepped through in a debugger.
3217
+
3218
+ ```typescript sim-lambda-cloudformation-bindings
3219
+ /**
3220
+ * Binding a real in-process handler to a CloudFormation Lambda function.
3221
+ */
3222
+
3223
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
3224
+
3225
+ import { SimAws } from "@kensio/yulin";
3226
+
3227
+ const simAws = new SimAws();
3228
+ const observedEvents: unknown[] = [];
3229
+
3230
+ await simAws.cloudFormation().deployTemplate({
3231
+ stackName: "bound-greeter-stack",
3232
+ template: {
3233
+ Resources: {
3234
+ GreeterFunction: {
3235
+ Type: "AWS::Lambda::Function",
3236
+ Properties: {
3237
+ FunctionName: "bound-greeter",
3238
+ Role: "arn:aws:iam::111111111111:role/BoundGreeterRole",
3239
+ },
3240
+ },
3241
+ },
3242
+ },
3243
+ bindings: [
3244
+ {
3245
+ logicalId: "GreeterFunction",
3246
+ handler: (event: { name: string }): string => {
3247
+ observedEvents.push(event);
3248
+ return `Hello ${event.name} from the bound handler`;
3249
+ },
3250
+ },
3251
+ ],
3252
+ });
3253
+
3254
+ const output = await simAws.lambda().invoke(
3255
+ new InvokeCommand({
3256
+ FunctionName: "bound-greeter",
3257
+ Payload: JSON.stringify({ name: "Yulin" }),
3258
+ }),
3259
+ );
3260
+
3261
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
3262
+ console.log(Buffer.from(output.Payload).toString());
3263
+ console.log(observedEvents.length);
3264
+
3265
+ await simAws.backgroundTasksComplete();
3266
+ ```
3267
+
3268
+ A binding can target the function by `logicalId` (which also matches a CDK construct ID from
3269
+ `aws:cdk:path` metadata), by `functionName`, by `arn`, by full `cdkPath`, or by `imageRepository`
3270
+ for a function packaged as a container image. A bound function may omit template `Code` and
3271
+ `Handler` entirely, and unbound functions in the same template keep their template code on the vm
3272
+ path. A binding that resolves to no template resource fails the deploy with the unmatched target
3273
+ named for diagnosis. Where two bindings could both back the same function, the one listed first is
3274
+ the one that backs it.
3275
+
3276
+ ### Invoking a function bound by construct ID
3277
+
3278
+ A CDK function usually leaves `FunctionName` out of the template, and sim Lambda creates it under
3279
+ the synthesized logical ID. `stack.getResource` takes the construct ID the binding named. The
3280
+ Resource it answers with carries that logical ID, and it is the name to invoke. The hash CDK
3281
+ generated stays out of the test.
3282
+
3283
+ ```typescript sim-lambda-construct-id-invoke
3284
+ /**
3285
+ * Invoking a Lambda function bound by its CDK construct ID.
3286
+ */
3287
+
3288
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
3289
+
3290
+ import { SimAws } from "@kensio/yulin";
3291
+
3292
+ const simAws = new SimAws();
3293
+
3294
+ const stack = await simAws.cloudFormation().deployTemplate({
3295
+ stackName: "uploads-stack",
3296
+ template: {
3297
+ Resources: {
3298
+ UploadFunction8A7B6C5D: {
3299
+ Type: "AWS::Lambda::Function",
3300
+ Metadata: {
3301
+ "aws:cdk:path": "UploadsStack/UploadFunction/Resource",
3302
+ },
3303
+ Properties: {
3304
+ Role: "arn:aws:iam::111111111111:role/UploadFunctionRole",
3305
+ },
3306
+ },
3307
+ },
3308
+ },
3309
+ bindings: [
3310
+ {
3311
+ logicalId: "UploadFunction",
3312
+ handler: (event: { key: string }): string => `stored ${event.key}`,
3313
+ },
3314
+ ],
3315
+ });
3316
+
3317
+ const upload = stack.getResource("UploadFunction");
3318
+ if (upload === undefined) throw new Error("No UploadFunction Resource");
3319
+
3320
+ const output = await simAws.lambda().invoke(
3321
+ new InvokeCommand({
3322
+ FunctionName: upload.logicalId,
3323
+ Payload: JSON.stringify({ key: "receipt.pdf" }),
3324
+ }),
3325
+ );
3326
+
3327
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
3328
+ console.log(Buffer.from(output.Payload).toString());
3329
+ // "stored receipt.pdf"
3330
+
3331
+ await simAws.backgroundTasksComplete();
3332
+ ```
3333
+
3334
+ A function with a `FunctionName` in the template is invoked by that name. The caller wrote it and
3335
+ already holds it.
3336
+
3337
+ ### Binding by container image repository
3338
+
3339
+ `imageRepository` matches any function whose resolved `Code.ImageUri` names that repository. One
3340
+ binding covers every function running that image, in every stack deployed from the same `SimAws`.
3341
+ A logical ID belongs to one construct tree.
3342
+
3343
+ The image tag is ignored on both sides of the match. No tag is stable enough to write into a test.
3344
+ A CDK image asset is tagged with the asset content hash, which changes whenever the image source
3345
+ does, and a pipeline-built image is usually tagged with a git sha or a build number passed in as a
3346
+ stack parameter. The registry host is part of the repository, so the account and region have to
3347
+ match too, and an `ImageUri` built by `Fn::Sub` or from a stack parameter is matched on what it
3348
+ resolves to.
3349
+
3350
+ ```typescript sim-lambda-image-repository-binding
3351
+ /**
3352
+ * Binding a handler to a container image function by its image repository.
3353
+ */
3354
+
3355
+ import { InvokeCommand } from "@aws-sdk/client-lambda";
3356
+
3357
+ import { SimAws } from "@kensio/yulin";
3358
+
3359
+ const simAws = new SimAws();
3360
+
3361
+ await simAws.cloudFormation().deployTemplate({
3362
+ stackName: "orders-stack",
3363
+ template: {
3364
+ Parameters: {
3365
+ ImageTag: { Type: "String" },
3366
+ },
3367
+ Resources: {
3368
+ OrdersFunction: {
3369
+ Type: "AWS::Lambda::Function",
3370
+ Properties: {
3371
+ FunctionName: "orders",
3372
+ Role: "arn:aws:iam::111111111111:role/OrdersRole",
3373
+ PackageType: "Image",
3374
+ Code: {
3375
+ ImageUri: {
3376
+ "Fn::Sub":
3377
+ // eslint-disable-next-line no-template-curly-in-string
3378
+ "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/orders:${ImageTag}",
3379
+ },
3380
+ },
3381
+ },
3382
+ },
3383
+ },
3384
+ },
3385
+ parameters: { ImageTag: "build-4172" },
3386
+ bindings: [
3387
+ {
3388
+ imageRepository:
3389
+ `${simAws.defaultAccountId}.dkr.ecr.` +
3390
+ `${simAws.defaultRegionName}.amazonaws.com/orders`,
3391
+ handler: (event: { orderId: string }): string =>
3392
+ `Processed ${event.orderId}`,
3393
+ },
3394
+ ],
3395
+ });
3396
+
3397
+ const output = await simAws.lambda().invoke(
3398
+ new InvokeCommand({
3399
+ FunctionName: "orders",
3400
+ Payload: JSON.stringify({ orderId: "order-1" }),
3401
+ }),
3402
+ );
3403
+
3404
+ if (output.Payload === undefined) throw new Error("No invoke Payload");
3405
+ console.log(Buffer.from(output.Payload).toString());
3406
+
3407
+ await simAws.backgroundTasksComplete();
3408
+ ```
3409
+
3410
+ A function matched this way is created from the bound handler, and never reaches the
3411
+ [container image skip](#container-image-functions). Functions in the same template running an image
3412
+ from another repository are skipped as usual.
3413
+
3414
+ A binding like this and a handler registered in
3415
+ [simulated ECR](https://yulinsim.dev/services/ecr/ "Simulated ECR usage docs") match on the same thing, and the binding is what
3416
+ backs the function where both could. Reach for the binding when the handler belongs to one deploy,
3417
+ and for the repository when it belongs to the image.
3418
+
3419
+ ## Available functionality
3420
+
3421
+ Sim Lambda currently supports:
3422
+
3423
+ - `CreateFunctionCommand` and `GetFunctionCommand`, including a function created from the
3424
+ [simulated ECR](https://yulinsim.dev/services/ecr/ "Simulated ECR usage docs") image its `Code.ImageUri` names
3425
+ - `UpdateFunctionCodeCommand`, replacing the code `$LATEST` runs while the function keeps its
3426
+ policy, Function URL, versions and aliases
3427
+ - `UpdateFunctionConfigurationCommand`, changing the `Role`, `Handler`, `Runtime`, `Description`,
3428
+ `Timeout`, `MemorySize` and `Environment` a function runs with
3429
+ - `ListFunctionsCommand`, reporting every function in the Account and Region, and their published
3430
+ versions with `FunctionVersion: "ALL"`
3431
+ - `InvokeCommand`, with the `RequestResponse`, `Event` and `DryRun` invocation types
3432
+ - Asynchronous invocation retries on the simulated clock, and `OnSuccess`/`OnFailure` destinations
3433
+ written with `PutFunctionEventInvokeConfigCommand`, delivering the AWS destination record to a
3434
+ simulated SQS queue, SNS topic, EventBridge event bus or Lambda function
3435
+ - `GetFunctionEventInvokeConfigCommand`, `UpdateFunctionEventInvokeConfigCommand`,
3436
+ `DeleteFunctionEventInvokeConfigCommand` and `ListFunctionEventInvokeConfigsCommand`, each taking
3437
+ a `Qualifier` for a version's or an alias's own config
3438
+ - `DeadLetterConfig` on `CreateFunction` and `UpdateFunctionConfiguration`, sending an abandoned
3439
+ event to a simulated SQS queue or SNS topic
3440
+ - Function URLs, created with `CreateFunctionUrlConfigCommand` and served over HTTP on localhost
3441
+ with `serveSimAws`
3442
+ - `AuthType: "AWS_IAM"` Function URLs, authorizing `lambda:InvokeFunctionUrl` against the caller
3443
+ resolved from the request, and `lambda:InvokeFunction` as well for a CloudFront origin access
3444
+ control
3445
+ - `lambdaFunctionUrlEventFactory`, making a Function URL invocation event for a test that calls a
3446
+ handler directly
3447
+ - `AddPermissionCommand`, `RemovePermissionCommand` and `GetPolicyCommand`, for resource-based
3448
+ policies evaluated alongside identity policies
3449
+ - SQS, DynamoDB stream and Kinesis stream event source mappings, created with
3450
+ `CreateEventSourceMappingCommand` and read with `GetEventSourceMappingCommand`,
3451
+ `ListEventSourceMappingsCommand` and `DeleteEventSourceMappingCommand`, delivering real-shaped SQS,
3452
+ DynamoDB stream and Kinesis events and honouring `BatchSize`
3453
+ - `StartingPosition: "TRIM_HORIZON"` and `"LATEST"` on a stream mapping, and `"AT_TIMESTAMP"` on a
3454
+ Kinesis one, with a failing batch blocking its shard until it is through or discarded
3455
+ - Every shard of a Kinesis stream read by a processor of its own, as real Lambda reads one
3456
+ - `FunctionResponseTypes: ["ReportBatchItemFailures"]` on a queue mapping, returning only the
3457
+ message ids the handler reported, and on a stream mapping, rewinding to the lowest sequence number
3458
+ the handler reported
3459
+ - Function code from three sources:
3460
+ - an in-process handler function passed via `makeLambdaZipFileInput(...)`
3461
+ - zip archive bytes on `Code.ZipFile` (build them with `makeLambdaCodeZip(...)`)
3462
+ - a zip object stored in sim S3 via `Code.S3Bucket`/`S3Key`
3463
+ - A Node.js `vm` runtime for zip-packaged code, with warm module state across invocations, and
3464
+ writable standard streams for handler output, including a bundled AWS Lambda Powertools logger's
3465
+ own console
3466
+ - Per-function environment variables with `Environment.Variables`
3467
+ - Runtime-provided `@aws-sdk/*` packages inside function code, routed into the owning simulated AWS
3468
+ environment
3469
+ - `fetch`, `node:http` and `node:https` requests from function code, answered by the simulation for
3470
+ every hostname it serves, including a Cognito user pool domain's OAuth endpoints and the JWKS a
3471
+ token verifier fetches from the regional Cognito endpoint
3472
+ - Execution roles, evaluated against simulated IAM
3473
+ - Published versions and aliases, with `PublishVersion`, `ListVersionsByFunction`, `CreateAlias`,
3474
+ `UpdateAlias`, `GetAlias`, `ListAliases` and `DeleteAlias`, and a `Qualifier` on `Invoke`,
3475
+ `GetFunction` and the permission commands, each qualified resource holding its own policy
3476
+ - IAM authorization of the Lambda commands themselves (`lambda:CreateFunction`,
3477
+ `lambda:GetFunction`, `lambda:UpdateFunctionCode`, `lambda:InvokeFunction`, the Function URL
3478
+ config actions, and the version and alias actions), and `lambda:ListFunctions` on `*` for the
3479
+ listing
3480
+ - AWS-like validation and errors, such as `ResourceConflictException` for a duplicate function name
3481
+ - The `AWS::Lambda::Function`, `AWS::Lambda::Url`, `AWS::Lambda::Permission`,
3482
+ `AWS::Lambda::Version`, `AWS::Lambda::Alias`, `AWS::Lambda::EventSourceMapping` and
3483
+ `AWS::Lambda::EventInvokeConfig` CloudFormation resources, with `Ref`/`Fn::GetAtt` support and
3484
+ deploy-time executable bindings
3485
+ - A CDK app built on `fn.currentVersion` or a `lambda.Alias`, which deploys with the alias its
3486
+ integrations point at, and where an `AWS::Lambda::Permission` naming that alias grants on the
3487
+ alias
3488
+ - `AWS::Lambda::EventSourceMapping` on a queue, on a table's stream or on a Kinesis stream,
3489
+ including the `StartingPosition` a stream mapping needs, so a CDK `SqsEventSource`,
3490
+ `DynamoEventSource` or `KinesisEventSource` deploys as it is synthesised
3491
+ - A CDK function given `onFailure`, `onSuccess`, `retryAttempts`, `maxEventAge` or
3492
+ `deadLetterQueue`, which deploys the `AWS::Lambda::EventInvokeConfig` and the `DeadLetterConfig`
3493
+ those synthesise
3494
+
3495
+ ## Limitations
3496
+
3497
+ Current documented limitations:
3498
+
3499
+ - Only `CreateFunctionCommand`, `GetFunctionCommand`, `UpdateFunctionCodeCommand`,
3500
+ `UpdateFunctionConfigurationCommand`, `ListFunctionsCommand`, `DeleteFunctionCommand`,
3501
+ `InvokeCommand`, the permission commands (`AddPermissionCommand`, `RemovePermissionCommand`,
3502
+ `GetPolicyCommand`), the version and alias commands, the Function URL config commands and the
3503
+ event source mapping commands are supported. `GetFunctionConfiguration` and the concurrency and
3504
+ tagging commands are absent so far.
3505
+ - `UpdateFunctionCode` leaves out the `RevisionId` and `DryRun` preconditions real Lambda takes,
3506
+ along with `Architectures` and `SourceKMSKeyArn`. `UpdateFunctionConfiguration` takes only the
3507
+ settings simulated Lambda models, leaving out `Layers`, `VpcConfig`, `TracingConfig`, `KMSKeyArn`,
3508
+ `EphemeralStorage`, `SnapStart`, `LoggingConfig` and `RevisionId`. `ListFunctions` leaves out
3509
+ `Marker`/`MaxItems` paging and `MasterRegion`.
3510
+ - A destination is delivered to without checking that the function's execution role may write to it.
3511
+ Real Lambda delivers under that role and drops the record where the role cannot, which would be
3512
+ silent, so simulated Lambda delivers instead. Nothing else about the destination has to be set up,
3513
+ since a destination needs no resource policy on real AWS either.
3514
+ - SAM's `EventInvokeConfig` and `DeadLetterQueue` on `AWS::Serverless::Function` are left out. A
3515
+ SAM application declaring either deploys a function with the default retries, no destinations and
3516
+ no dead-letter target. The `AWS::Lambda::EventInvokeConfig` Resource and the `DeadLetterConfig`
3517
+ property a CloudFormation or CDK template writes are both deployed. See
3518
+ [retries and destinations in templates](#retries-and-destinations-in-templates).
3519
+ - Throttling and timeouts do not drive a retry. A retry follows a handler that threw, and the
3520
+ `MaximumEventAgeInSeconds` a config carries is measured from when the invocation was accepted.
3521
+ - `DestinationConfig` on an event source mapping is left out. It is a different mechanism from the
3522
+ asynchronous invocation destinations above.
3523
+ - A settings change takes effect at once. Real Lambda reports `LastUpdateStatus: "InProgress"` while
3524
+ it rolls the change out, and neither that member nor the wait it implies is simulated.
3525
+ - A cross-account grant is only half of what admits a call. The caller's own Account has to allow
3526
+ the action too, and its IAM has to be part of the same `SimAws` instance for its policies to be
3527
+ found. A caller from an Account outside the simulation is denied.
3528
+ - `lambda:FunctionUrlAuthType`, `AWS:SourceArn` and `AWS:SourceAccount` are the only condition keys
3529
+ given a value at request time. The first is supplied when a Function URL is invoked, and the other
3530
+ two when another simulated service invokes the function on a resource's behalf. See
3531
+ [Resource-based policies](#resource-based-policies) for which paths those are.
3532
+ `PrincipalOrgID` and `InvokedViaFunctionUrl` are written into the statement so `GetPolicy` reports
3533
+ the grant that was made, and no value is supplied for them, so a statement carrying one never
3534
+ matches.
3535
+ - `RevisionId` and `EventSourceToken` on the permission commands are left out.
3536
+ - `requestContext.authorizer.iam` reports `accessKey` as empty, and `callerId` and `userId` as the
3537
+ caller ARN rather than the opaque unique id real AWS uses. `cognitoIdentity` and `principalOrgId`
3538
+ are always null.
3539
+ - The Function URL `Cors` configuration is left out, including OPTIONS preflight handling.
3540
+ - `InvokeMode: "RESPONSE_STREAM"` is accepted and reported, but responses are always served
3541
+ buffered.
3542
+ - A function has at most one Function URL, and qualified (version or alias) Function URLs are left
3543
+ out.
3544
+ - A published version keeps what it was published with, so `UpdateFunctionCode` moves `$LATEST`
3545
+ alone. The `CodeSha256` and `RevisionId` checks `PublishVersion` makes are left out, along with
3546
+ alias `RoutingConfig` weights, provisioned concurrency, and the `Marker`/`MaxItems` paging on the
3547
+ two listings. `CodeSha256`, `RuntimePolicy`
3548
+ and `ProvisionedConcurrencyConfig` on `AWS::Lambda::Version`, and `RoutingConfig` and
3549
+ `ProvisionedConcurrencyConfig` on `AWS::Lambda::Alias`, are accepted and ignored. SAM's
3550
+ `AutoPublishAlias` is left out.
3551
+ - A qualified function ARN reaches a function through S3 notifications, SNS subscriptions,
3552
+ CloudWatch Logs subscriptions, Cognito triggers, EventBridge targets, event source mappings and
3553
+ API Gateway integration and authorizer URIs, and `AWS::Lambda::Permission`. The
3554
+ `AWS::Lambda::Url` and `AWS::Lambda::EventSourceMapping` template readers still refuse or drop a
3555
+ qualifier.
3556
+ - The vm runtime supports CommonJS function code only. An ES module deployment package is refused
3557
+ at cold start, whether the handler file ends in `.mjs` or a `.js` file opens on `import`.
3558
+ Evaluating one would need `vm.SourceTextModule`, which Node.js gates behind
3559
+ `--experimental-vm-modules` at process launch, and a simulator that made every consumer pass a
3560
+ Node.js flag would cost more than it repaid. Back the function with an in-process handler, or
3561
+ deploy a CommonJS build of the same source. See
3562
+ [zip-packaged code and the vm runtime](#zip-packaged-code-and-the-vm-runtime).
3563
+ - A handler function reference is recorded through the process console and the process standard
3564
+ streams, both of which a test runner is free to replace. `console.trace` and `console.dir`
3565
+ decorate what they print, and either one reaches the log group only where the host console passes
3566
+ it on to `process.stdout`. See [What a handler prints](#what-a-handler-prints).
3567
+ - The platform `START`, `END` and `REPORT` lines a real log stream carries are left out, and
3568
+ execution environments are never recycled, so a function keeps one log stream for as long as it
3569
+ exists.
3570
+ - Container image functions are never run. Yulin never reads a container image, and stays
3571
+ Docker-free.
3572
+ A function with `PackageType: Image` is skipped, or refused on `CreateFunction`, unless a real
3573
+ in-process handler stands in for its image, either one bound to it or one registered in the
3574
+ [simulated ECR](https://yulinsim.dev/services/ecr/ "Simulated ECR usage docs") repository the image URI names. See
3575
+ [Container image functions](#container-image-functions).
3576
+ - Lambda Layers are left out.
3577
+ - Environment variables declared with `Environment.Variables` reach a real in-process handler
3578
+ function only while it runs, so a variable read at module scope sees the host process value
3579
+ instead. See [Environment variables](#environment-variables).
3580
+ - Outbound HTTP is routed for `fetch`, `node:http` and `node:https` alone. A handler using another
3581
+ client, or a request made from a handler module while it is being imported, reaches the network.
3582
+ A routed response comes back as the simulation answered it, with redirects left for the caller to
3583
+ follow. See [The HTTP requests function code makes](#the-http-requests-function-code-makes).
3584
+ - The AWS service API endpoints answered as Commands are the ones a request can be read back from,
3585
+ and the hostnames answered over HTTP are the ones simulated Route53 resolves. The endpoints AWS
3586
+ issues for one resource, a Lambda Function URL and an API Gateway HTTP API, resolve under the
3587
+ hostnames the simulator serves them on. A request to the AWS form of one of those reaches the
3588
+ network.
3589
+ - An unsigned request to a service API endpoint is served over HTTP when the simulation serves that
3590
+ endpoint, which today means Cognito's regional endpoint and the S3 endpoints. Anywhere else it is
3591
+ read as a Command and refused as one.
3592
+ - `Timeout` is recorded and never interrupts handler execution.
3593
+ - Timers inside a handler are host timers. `setTimeout` waits in real time, and advancing the
3594
+ simulation's clock leaves a sleeping handler asleep.
3595
+ - A time read at module scope, like an environment variable read there, is read before any
3596
+ invocation and sees the host clock. See [The time inside a handler](#the-time-inside-a-handler).
3597
+ - `Event` invocation retries and failure destinations are left out, and handler errors are dropped.
3598
+ - The S3 object version a code location names is accepted but ignored, as sim S3 has no object
3599
+ versioning yet. That covers `Code.S3ObjectVersion` on `CreateFunction` and on a template
3600
+ function, and `S3ObjectVersion` on `UpdateFunctionCode`. A versioned location loads the object as
3601
+ it stands.
3602
+ - SQS queues, DynamoDB streams and Kinesis streams are the only event sources. Kafka, DocumentDB and
3603
+ Kinesis enhanced fan-out consumers are refused outright, and so are `FilterCriteria`,
3604
+ `ScalingConfig`, `DestinationConfig`, `MaximumRetryAttempts`, `BisectBatchOnFunctionError`,
3605
+ `ParallelizationFactor`, `TumblingWindowInSeconds` and the other mapping inputs this simulation
3606
+ has no behaviour for.
3607
+ - A stream batch is delivered again five times, after 1, 2, 4, 8 and 16 seconds, and then discarded.
3608
+ AWS documents no delay between attempts and retries until the records age out. Both differences
3609
+ are deliberate. A delay of zero falls due at the instant the clock already reads, and a handler
3610
+ that always throws would leave `advanceBy` with work falling due forever. A batch item failure
3611
+ report counts against the same five attempts, and never starts them again for the records it
3612
+ rewound to.
3613
+ - A handler writing into the table whose stream invoked it is refused with
3614
+ `SimLambdaStreamCascadeError` rather than being delivered its own writes forever. Real Lambda runs
3615
+ that loop.
3616
+ - A shard iterator never expires, where a real one is good for 15 minutes.
3617
+ - `MaximumBatchingWindowInSeconds` is only simulated as 0. A partial batch is delivered as soon as
3618
+ anything is on the event source, leaving a batching window nothing to wait for. A non-zero value
3619
+ is refused, which also caps a queue mapping's `BatchSize` at 10. The documented rule that a
3620
+ `BatchSize` above 10 needs a batching window goes unenforced, because the same AWS documentation
3621
+ gives a stream mapping `BatchSize` 100 and window 0 as simultaneous defaults, and CDK emits
3622
+ exactly that.
3623
+ - An execution role that gets its stream permissions from the AWS managed policy
3624
+ `AWSLambdaDynamoDBExecutionRole` has none here, since simulated IAM has no model for managed
3625
+ policy ARNs, so the mapping is refused when it is created. A hand-written template and a SAM application
3626
+ usually attach that policy where CDK writes an inline one, so the two declaration paths differ.
3627
+ Write the grant inline to deploy either.
3628
+ - `UpdateEventSourceMapping` is absent, and a mapping's batch size or enabled state is fixed once it
3629
+ is created. `Enabled: false` at creation is simulated.
3630
+ - One poll of one shard delivers one batch. Real Lambda runs several pollers at once and scales them
3631
+ with the event source, and what that concurrency does to ordering or to a downstream service is
3632
+ invisible here. A simulated DynamoDB stream has one shard and never splits, so a mapping on one has
3633
+ a single thing to read either way. A Kinesis stream has the shards it was created with, each read
3634
+ by a processor of its own, and none of them ever splits or merges.
3635
+ - CloudFormation resource types other than `AWS::Lambda::Function`, `AWS::Lambda::Url`,
3636
+ `AWS::Lambda::Permission`, `AWS::Lambda::Version`, `AWS::Lambda::Alias`,
3637
+ `AWS::Lambda::EventSourceMapping` and `AWS::Lambda::EventInvokeConfig` (`LayerVersion`,
3638
+ `CodeSigningConfig`, ...) are skipped with an "Unsupported" diagnostic.
3639
+ - The `vm` context is a namespacing convenience rather than a security boundary. Function code runs
3640
+ in-process with the same trust as the test suite itself. Do not run untrusted code through the
3641
+ simulator.
3642
+ - `serveSimAws` serves nineteen of these operations over HTTP, listed in the
3643
+ [serving docs](https://yulinsim.dev/serve/#lambda-over-the-endpoint). The version and alias operations have no
3644
+ route there yet, and reach the simulation through `SimAws` or
3645
+ [SDK interception](https://yulinsim.dev/sdk/) instead.