async-local-storage icon indicating copy to clipboard operation
async-local-storage copied to clipboard

Is there a reason this won't work on AWS Lambda?

Open markingram opened this issue 5 years ago • 2 comments

I'm attempting to run this in a Lambda. All works fine locally and on build server from the perspective of unit tests and some functional tests. However when running in Lambda the simplest set/get won't work:

// index.ts

const als = require('async-local-storage');
als.enable();
// ... some code
exports.handler = async (event: APIGatewayEvent, context: APIGatewayEventRequestContext) => {
  // some code
  als.set('blah', '123');
  const blah = als.get('blah');
  console.log(`blah ${blah}`);
}

The console above shows blah null instead of blah 123.

markingram avatar Mar 07 '19 16:03 markingram

I am sorry that I haven't used Lambda before, and I will have a try.

vicanso avatar Mar 08 '19 13:03 vicanso

I do a test like this: DEBUG=als node app.js

const als = require('async-local-storage');
als.enable();
// ... some code
exports.handler = async () => {
  // some code
  als.set('blah', '123');
  const blah = als.get('blah');
  console.log(`blah ${blah}`);
}

exports.handler();

The logs is as follows:

id:5, type:PROMISE, triggerId:1
5(PROMISE) init by 1
set blah:123 to 1
get blah:null from 1
blah null
id:6, type:TickObject, triggerId:1
6(TickObject) init by 1
destroy 6

The exports.handler function is triggered by 1(id). When the 1(id) is initialized, async-local-storage isn't enabled at that moment; therefor it can't initialize the data scope.

I think AWS Lambda calls the exports.handler function in the same way, you can use like this:

const als = require('async-local-storage');
als.enable();

const handler = async () => {
  // some code
  als.set('blah', '123');
  const blah = als.get('blah');
  console.log(`blah ${blah}`);
}
// ... some code
exports.handler = async () => {
  setImmediate(handler);
}

exports.handler();

vicanso avatar Mar 10 '19 11:03 vicanso