I am building a simple apm.
I batch events and store them in db batched.
I also want to store anything left in the batch once the process ends/killed/error
This is my code
export function startApm(): void {
process.on('SIGINT', async () => {
try {
console.log('APM - Graceful shutdown');
console.log(`Will insert ${batched.length} entries`);
await insertExecutionTimes(batched);
console.log('Execution times inserted successfully');
} catch (error) {
console.error('Error inserting apm entries:', error);
} finally {
process.exit(0);
}
});
setInterval(async () => {
if (batched.length >= batchSize) {
console.log(`Storing batch of ${batchSize}, total length ${batched.length}`);
await insertExecutionTimes(batched.splice(0, batchSize));
console.log('Length after', batched.length);
}
}, 250);
}
'SIGINT' handler is executed fine
I see console logs
console.log('APM - Graceful shutdown');
but nothing in store in the database, seems like process dies before await insertExecutionTimes(batched); is finished.
async function insertExecutionTimes(data: ApmEntry[]): Promise<void> {
const trx = await db.transaction();
try {
await trx.batchInsert(Tables.Apm, data);
await trx.commit();
console.log(`Inserted ${data.length} records successfully`);
} catch (error) {
await trx.rollback();
console.error('Error inserting execution times', error);
}
}
Any ideas would be appreciated