2025-04-20 11:29:53 -07:00
|
|
|
const SERVICE_NAME = "BufferService";
|
|
|
|
|
|
|
|
|
|
class BufferService {
|
2025-07-25 15:15:14 -07:00
|
|
|
static SERVICE_NAME = SERVICE_NAME;
|
2025-07-28 14:37:18 -07:00
|
|
|
constructor({ db, logger, envSettings }) {
|
2025-08-18 13:40:56 -07:00
|
|
|
this.BUFFER_TIMEOUT = envSettings.nodeEnv === "development" ? 1000 : 1000 * 60 * 1; // 1 minute
|
2025-04-20 11:29:53 -07:00
|
|
|
this.db = db;
|
|
|
|
|
this.logger = logger;
|
|
|
|
|
this.SERVICE_NAME = SERVICE_NAME;
|
2025-08-18 10:55:12 -07:00
|
|
|
this.buffer = [];
|
2025-04-20 11:29:53 -07:00
|
|
|
this.scheduleNextFlush();
|
|
|
|
|
this.logger.info({
|
2025-07-28 14:37:18 -07:00
|
|
|
message: `Buffer service initialized, flushing every ${this.BUFFER_TIMEOUT / 1000}s`,
|
2025-04-20 11:29:53 -07:00
|
|
|
service: this.SERVICE_NAME,
|
|
|
|
|
method: "constructor",
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-07-25 15:15:14 -07:00
|
|
|
|
|
|
|
|
get serviceName() {
|
|
|
|
|
return BufferService.SERVICE_NAME;
|
|
|
|
|
}
|
2025-04-20 11:29:53 -07:00
|
|
|
|
2025-08-18 10:55:12 -07:00
|
|
|
addToBuffer({ check }) {
|
2025-04-20 11:29:53 -07:00
|
|
|
try {
|
2025-08-18 10:55:12 -07:00
|
|
|
this.buffer.push(check);
|
2025-04-20 11:29:53 -07:00
|
|
|
} catch (error) {
|
|
|
|
|
this.logger.error({
|
|
|
|
|
message: error.message,
|
|
|
|
|
service: this.SERVICE_NAME,
|
|
|
|
|
method: "addToBuffer",
|
|
|
|
|
stack: error.stack,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
scheduleNextFlush() {
|
|
|
|
|
this.bufferTimer = setTimeout(async () => {
|
|
|
|
|
try {
|
2025-08-18 10:55:12 -07:00
|
|
|
await this.flushBuffer();
|
2025-04-20 11:29:53 -07:00
|
|
|
} catch (error) {
|
|
|
|
|
this.logger.error({
|
|
|
|
|
message: `Error in flush cycle: ${error.message}`,
|
|
|
|
|
service: this.SERVICE_NAME,
|
|
|
|
|
method: "scheduleNextFlush",
|
|
|
|
|
stack: error.stack,
|
|
|
|
|
});
|
|
|
|
|
} finally {
|
|
|
|
|
// Schedule the next flush only after the current one completes
|
|
|
|
|
this.scheduleNextFlush();
|
|
|
|
|
}
|
2025-07-28 14:37:18 -07:00
|
|
|
}, this.BUFFER_TIMEOUT);
|
2025-04-20 11:29:53 -07:00
|
|
|
}
|
2025-08-18 10:55:12 -07:00
|
|
|
async flushBuffer() {
|
|
|
|
|
let items = this.buffer.length;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await this.db.checkModule.createChecks(this.buffer);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
this.logger.error({
|
|
|
|
|
message: error.message,
|
|
|
|
|
service: this.SERVICE_NAME,
|
|
|
|
|
method: "flushBuffer",
|
|
|
|
|
stack: error.stack,
|
|
|
|
|
});
|
2025-04-20 11:29:53 -07:00
|
|
|
}
|
2025-08-18 10:55:12 -07:00
|
|
|
this.buffer = [];
|
2025-06-09 14:59:26 +08:00
|
|
|
this.logger.debug({
|
2025-04-20 11:29:53 -07:00
|
|
|
message: `Flushed ${items} items`,
|
|
|
|
|
service: this.SERVICE_NAME,
|
2025-08-18 10:55:12 -07:00
|
|
|
method: "flushBuffer",
|
2025-04-20 11:29:53 -07:00
|
|
|
});
|
|
|
|
|
items = 0;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default BufferService;
|