我正在为AWS Lambda制作一个本地模拟器,可以在其中设置context.callbackWaitsForEmptyEventLoop = false;
-这允许一个人运行没有disconnecting from database的lambda。这用于使Lambda连接在MongoDB,RethinkDB等上保持打开状态。
我想强调,我知道这里要做的正常的,非Lambda的事情是断开数据库连接。但是,使用
callbackWaitsForEmptyEventLoop
的较低延迟使Lambda更可取,因为它允许microvm保持与数据库的连接,并让后续的Lambda重用相同的连接。
我想在本地模拟AWS的行为。
如何创建等效于callbackWaitsForEmptyEventLoop
= false(即在所有处理完成后立即退出,而不是等待事件循环为空?)?
这是一些演示代码。将FUNCTION_NAME
更改为'connectOnly'
或'connectAndDisconnect'
来演示行为。
目前'connectAndDisconnect'
有效,但'connectOnly'
无效-它已完成处理,但由于连接仍处于打开状态,因此永远不会退出节点。
let spawn = require('child_process').spawn
var log = console.log.bind(console)
let minify = script=> '"' + script.replace(/\n/g, '').trim() + '"'
var functions = {
connectAndDisconnect: `const rethinkdb = require('rethinkdb');
;(async function(request, context) {
var connection = await rethinkdb.connect({ host: 'localhost', port: 28015 });
await connection.close();
console.log('I connected successfully!');
})();`,
connectOnly: `const rethinkdb = require('rethinkdb');
;(async function(request, context) {
var connection = await rethinkdb.connect({ host: 'localhost', port: 28015 });
console.log('I connected successfully!');
})();`
}
const FUNCTION_NAME = 'connectOnly'
log(`Testing ${FUNCTION_NAME}`)
var functionToTest = functions[FUNCTION_NAME]
var child = spawn('node', ['-e', minify(functionToTest)], {
shell: true,
stdio: [0, 'pipe', 'pipe'],
cwd: 'C:\\Users\\mikem\\OneDrive\\Documents\\appless\\documentdb-arc-test\\src\\http\\get-index',
env: {}
})
var completed = false;
let timeout = 5000;
// bake a timeout
setTimeout(function () {
log(`Timed out after ${timeout} ms!`)
child.kill()
}, timeout)
// 'close' will occur if the process finishes naturally
// 'exit' will occur if the process is killed
console.log(`What we want is to be see a 'close' event using the 'connectOnly' code above`)
;['close', 'exit'].forEach(function(event){
child.on(event, function () {
log(`'${event}' event happened!`)
if ( ! completed ) {
completed = true
log(`Done!`)
}
})
})