AWS Lambda 函数在 context.fail 之后继续运行一段时间

AWS Lambda function continues for a bit after context.fail

我有一个简单的 AWS Lambda 函数,它对保存到 S3 存储桶的图像进行一些验证。我正在使用 async.waterfall 下载图像并对其进行处理,但在进入第一个瀑布函数之前,我对从 S3 PutObject 触发器获取的事件数据进行了一些基本验证,特别是大小信息(event.Records[0].s3.object.size)。如果事件引用的图像大于我的 MAX_SIZE,我会使用 context.fail(new Error("Validation error: the file is too big.")) 来结束执行。

一切正常,但我在日志中注意到,在记录错误后,该函数在退出之前继续 运行 一小段时间。例如,我的 async.waterfall 调用中的第一个函数被调用(即来自该函数的消息显示在日志中)。我什至尝试在 context.fail 之后立即添加一个 context.done(errorMessage),它被执行(即我传入的消息被记录)以及更多的代码行。

这是预期的行为吗?我在文档中找不到任何提及。该函数是否需要一点时间才能退出,或者我是否误解了 async.waterfall 之前的处理函数中代码的同步性质?

下面是我的一些代码。 context.fail 之后显示的所有 console.log 消息都打印到日志中,我不希望发生这种情况。

exports.handler = function(event, context) {
  console.log('Received event:', JSON.stringify(event, null, 2));

  if (event.Records[0].s3.object.size > MAX_FILE_SIZE) {
    var error = new Error("Validation error: the file is too big.")
    context.fail(error);
  }
  console.log('Event validation complete.')

  var bucket = event.Records[0].s3.bucket.name;
  var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  var fileName = key.split("/")[1];
  var params = {
    Bucket: bucket,
    Key: key
  };
  console.log('Starting processing of the following file: ' + JSON.stringify(params, null, 2));

  async.waterfall([
    function download(callback) {
        // Download the image from S3 into a buffer.
        console.log("Downloading the image from S3...");
        s3.getObject(params, function(err, data) {
            if (err) {
                callback(err);
            } else {
                callback(null, data);
            }
        });
    },
  ...
  ], ...)
}

这似乎是预期的行为,即使没有很好的记录。 context documentation 确实说 fail() “表示失败”但不承诺停止进一步执行。

context.fail()

Indicates the Lambda function execution and all callbacks completed unsuccessfully, resulting in a handled exception.

对您的代码来说,好消息是在调用 context.fail() 后从函数中 return 应该相当容易,以避免进一步处理。

我相信自从提出这个问题(以及 James 的回答)以来 aws lambda 结构发生了一些变化。

现在处理程序另外有一个third argument、'callback',可以调用它来停止脚本的执行。根据您的调用方式,它会成功或出错退出进程。有关详细信息,请参阅这些文档。

此外,检查上下文 属性、callbackWaitsForEmptyEventLoop。它默认为 true,但您需要将其设置为 false,以便在调用回调后,节点进程不会等待运行时循环清除,即您的异步调用将被丢弃。