elasticsearch/ts/els.classes.elasticscheduler.ts

64 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-08-01 10:24:22 +00:00
import { ElsSmartlogDestination, type IStandardLogParams } from './els.classes.smartlogdestination.js';
2018-11-09 22:15:11 +00:00
export class ElasticScheduler {
2023-08-01 10:24:22 +00:00
elasticSearchRef: ElsSmartlogDestination<any>;
2018-11-09 22:15:11 +00:00
docsScheduled = false;
docsStorage: any[] = [];
2023-08-01 10:24:22 +00:00
// maximum size of the buffer
maxBufferSize = 500;
constructor(elasticLogRefArg: ElsSmartlogDestination<any>) {
2018-11-09 22:15:11 +00:00
this.elasticSearchRef = elasticLogRefArg;
}
public addFailedDoc(objectArg: any | IStandardLogParams) {
2023-08-01 10:24:22 +00:00
this.addToStorage(objectArg);
2018-11-09 22:15:11 +00:00
this.setRetry();
}
2023-08-01 10:24:22 +00:00
2018-11-09 22:15:11 +00:00
public scheduleDoc(logObject: any) {
2023-08-01 10:24:22 +00:00
this.addToStorage(logObject);
}
private addToStorage(logObject: any) {
2018-11-09 22:15:11 +00:00
this.docsStorage.push(logObject);
2023-08-01 10:24:22 +00:00
// if buffer is full, send logs immediately
if (this.docsStorage.length >= this.maxBufferSize) {
this.flushLogsToElasticSearch();
}
}
private flushLogsToElasticSearch() {
const oldStorage = this.docsStorage;
this.docsStorage = [];
for (let logObject of oldStorage) {
this.elasticSearchRef.log(logObject, true);
}
2018-11-09 22:15:11 +00:00
}
public setRetry() {
setTimeout(() => {
2023-08-01 10:24:22 +00:00
this.flushLogsToElasticSearch();
2018-11-09 22:15:11 +00:00
if (this.docsStorage.length === 0) {
console.log('ElasticLog retry success!!!');
this.docsScheduled = false;
} else {
console.log('ElasticLog retry failed');
this.setRetry();
}
}, 5000);
}
public deferSend() {
if (!this.docsScheduled) {
console.log('Retry ElasticLog in 5 seconds!');
this.docsScheduled = true;
this.setRetry();
}
}
}