init-stage v0.1.0
init-stage
Run async functions in the init stage of AWS Lambda.
If you don't know the init stage, please read the following awesome post first.
This package provides functions to run async functions in the init stage.
The following screenshot is the timeline when async functions have run in the init stage.
Installation
npm i init-stage
If you will use with AWS X-Ray, run the following step:
npm i aws-xray-sdk-core
Usage
const { initStage } = require('init-stage');
const done = initStage(async () => {
// This function is called in the init stage.
});
exports.handler = async (event, context) => {
const result = await done;
};
API
initStage(fn: () => T): T
This function calls a specified function in the init stage. If the function is async function, the Lambda handler is not called until the async task is completed. In case this function is called multiple times, the Lambda handler is not called until all async tasks are completed.
All async tasks is executed in parallel, and they must be completed in 10 seconds.
arguments
fn
: () => T- A function or an async function that is called in the init stage.
return
Result that fn
returns. If fn
is an async function, it is a promise.
initStageWithTracing(name: string, fn: (subsegment: Subsegment) => Promise): Promise
This function is equivalent to the initStage
except tracing by AWS X-Ray.
If this function is used, you have to install aws-xray-sdk-core.
arguments
name
: string- A name of a subsegment that records informations of an async task with X-Ray.
fn
: (subsegment: Subsegment) => Promise- An async function that is called in the init stage.
return
Result that fn
returns.
How it works
When your Lambda function is invoked, official Node.js runtime of Lambda executes following steps:
- Initialize the execution environment.
- Load your module that defines a handler.
- Get a first event.
- Set environment variables for X-Ray.
- Call your handler.
- Get a second event.
Lambda calls setImmediate()
once between step 2 and 3 and between 5 and 6.
initStage()
and initStageWithTracing()
replace setImmediate()
for following purposes:
- Waiting completions of all async tasks before getting a first event.
- Sending tracing data for async tasks to X-Ray after environment variables for X-Ray is set.
TODO
- Support AWSXRay.captureAWS().
License
MIT
4 years ago