一尘不染

为什么AWS Lambda功能总是超时?

node.js

我正在使用4.3版本的nodejs测试aws
lambda。我能够在控制台测试中成功完成我的处理程序函数中的所有语句,其中包括连接到vpc中的mongodb主机。但是,该功能总是超时。我发现了一些帖子和资源,讨论了使用回调,在上下文中设置属性以及IAM角色权限,但是无论我做什么,它总是会超时。当前代码:

'use strict';

var Mongoose = require('mongoose');
var Device = require('./device_model');
var Alarm = require('./alarm_model');
var Event = require('./event_model');

var mongoConnection = process.env.MONGO_URL;

var connection = Mongoose.connect(mongoConnection);

Mongoose.connection.once('open', function() {
    console.log("Connecting to mongo at: " + mongoConnection);
    console.log("Mongoose connection in lambda opened");
});

Mongoose.connection.on('error', function(){
    console.error("Error creating mongoose connection in lambda, exiting!");
    process.exit(1);
});

exports.check_alarms = function(event, context, callback) {

    context.callbackWaitsForEmtpyEventLoop = false;
    console.log("The incoming event: " + JSON.stringify(event));

    var device = null;
    Device.findByUUID(event.uuid, function(error, result){
        if(!error){
            device = result;
            console.log("the device: " + JSON.stringify(device));
            if(event.Ale && event.Ale.length > 0) {
                console.log("We have an alarm, checking if already set");
                callback(null, {"status":"alarms"});
            } else {
                console.log("Event contains no alarm; checking for historic active");
                callback(null, {"status":"no alarms"});
            }
        } else {
            console.log("there's a problem on mongo");
            callback("problem", "status not so good");
        }
    });

    callback(null, {"status":"outside of device find block"});
}

阅读 257

收藏
2020-07-07

共1个答案

一尘不染

您有错别字:

context.callbackWaitsForEmtpyEventLoop = false;

应该:

context.callbackWaitsForEmptyEventLoop = false;

这是文档中有关
callbackWaitsForEmptyEventLoop 行为的内容:

callbackWaitsForEmptyEventLoop

默认值为true。此属性仅在修改回调的默认行为时有用。默认情况下,回调将等待,直到Node.js运行时事件循环为空,然后冻结进程并将结果返回给调用方。您可以将此属性设置为false,以要求AWS
Lambda在调用回调后立即冻结进程,即使事件循环中有事件也是如此。AWS
Lambda将冻结进程,Node.js事件循环中的任何状态数据和事件(事件循环中的所有剩余事件将在下次调用Lambda函数且AWS
Lambda选择使用冻结的过程时进行处理)。有关回调的更多信息,请参见使用回调参数

最小示例:

// Times out due to typo
exports.function1 = (event, context, callback) => {
    setInterval(() => console.log('Long wait'), 100000);
    context.callbackWaitsForEmtpyEventLoop = false;
    callback(null, 'Hello from Lambda');
};

// Returns successfully
exports.function2 = (event, context, callback) => {
    setInterval(() => console.log('Long wait'), 100000);
    context.callbackWaitsForEmptyEventLoop = false;
    callback(null, 'Hello from Lambda');
};
2020-07-07