serverless-s3-local icon indicating copy to clipboard operation
serverless-s3-local copied to clipboard

process.env breaks if any asynchronous code is run

Open benvan opened this issue 5 years ago • 2 comments

You cannot use async / await, or promises inside an s3 event handler using this library.

The issue lies here, specifically line 309: https://github.com/ar90n/serverless-s3-local/blob/master/index.js#L285-L311

To reproduce:

provider:
  environment:
    SOMETHING_IMPORTANT: 123
// handler
module.exports = (event,context,callback) => {
  console.log(process.env.SOMETHING_IMPORTANT) // this works
  new Promise(r => {
    console.log(process.env.SOMETHING_IMPORTANT) // this breaks,
    callback()
  })

Or, perhaps more idiomatically (this is how this bug originally manifest itself):

module.exports = async (event,context) => {
  console.log(process.env.SOMETHING_IMPORTANT) // this works
  await new Promise(r => r())
  console.log(process.env.SOMETHING_IMPORTANT) // this breaks
}

The cause

process.env is set up and the handler is called, but if the handler performs any asynchronous action, control returns to serverless-s3-local, which then reverts process.env to its own context. By the time the asynchronous code runs, process.env has been reverted.

Suggestion:

Either:

  • Run serverless-s3-local in an async context (promises / async)
  • Don't reset the environment ... !

Regarding the latter suggestion, it appears that serverless-offline doesn't bother fully reverting process.env (all modifications to process.env are additive): https://github.com/dherault/serverless-offline/blob/e4724c8aa9bb4ca6c78a495953667f454f30901d/src/index.js#L580

benvan avatar Feb 28 '19 12:02 benvan

Hi @benvan !! Thanks for your great report. It's exactly correct. So I agree with your second suggestion which is to remove the resetting environment. I've already published a new version for solving this issue. Please check the v0.3.22 via npm.

ar90n avatar Mar 03 '19 13:03 ar90n

Ah, nice one. Thanks! :)

benvan avatar Mar 03 '19 22:03 benvan