Files
Checkmate/server/src/service/bufferService.ts
T

243 lines
7.8 KiB
TypeScript
Raw Normal View History

2026-06-09 12:34:15 -07:00
import type { Check } from "@/domain/checks/check.type.js";
import type { GeoCheck } from "@/domain/geo-checks/geo-check.type.js";
import type { IGeoChecksService } from "../domain/geo-checks/geo-check.service.js";
2026-02-24 19:19:32 +00:00
import type { ILogger } from "@/utils/logger.js";
2026-06-09 12:34:15 -07:00
import type { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
2026-06-18 09:56:38 -07:00
import type { IJobsRepository } from "@/domain/jobs/job.repository.interface.js";
2026-06-09 12:34:15 -07:00
import { ICheckService } from "../domain/checks/check.service.js";
2026-09-03 11:32:48 -07:00
import { DockerLog } from "@/domain/docker/docker-log.type.js";
import { IDockerLogsService } from "@/domain/docker/docker-log.service.js";
import { PendingCheck } from "@/domain/jobs/job.type.js";
2025-04-20 11:29:53 -07:00
const SERVICE_NAME = "BufferService";
2026-02-12 22:37:40 +00:00
export interface IBufferService {
addToBuffer(check: Check): void;
2026-02-24 18:10:20 +00:00
addGeoCheckToBuffer(geoCheck: GeoCheck): void;
2026-09-03 11:32:48 -07:00
addDockerLogToBuffer(dockerLog: DockerLog): void;
ingestChecks(checks: Check[]): Promise<void>;
2026-02-12 22:37:40 +00:00
scheduleNextFlush(): void;
flushBuffer(): Promise<void>;
2026-02-24 18:44:47 +00:00
flushGeoBuffer(): Promise<void>;
2026-09-03 11:32:48 -07:00
flushDockerLogsBuffer(): Promise<void>;
2026-06-24 11:58:32 -07:00
shutdown(): Promise<void>;
2026-02-12 22:37:40 +00:00
}
2026-03-05 14:46:28 -08:00
export class BufferService implements IBufferService {
2025-07-25 15:15:14 -07:00
static SERVICE_NAME = SERVICE_NAME;
2026-01-16 18:11:04 +00:00
private BUFFER_TIMEOUT: number;
2026-02-24 19:19:32 +00:00
private logger: ILogger;
2026-01-16 18:11:04 +00:00
private SERVICE_NAME: string;
2026-03-03 23:09:10 +00:00
private buffer: Check[];
private geoBuffer: GeoCheck[];
2026-09-03 11:32:48 -07:00
private dockerLogBuffer: DockerLog[];
2026-01-16 18:25:28 +00:00
private bufferTimer: NodeJS.Timeout | null = null;
2026-03-03 23:19:54 +00:00
private checksService: ICheckService;
2026-02-24 19:19:32 +00:00
private geoChecksService: IGeoChecksService;
2026-09-03 11:32:48 -07:00
private dockerLogsService: IDockerLogsService;
2026-06-18 09:56:38 -07:00
private jobsRepository: IJobsRepository;
2026-01-16 18:11:04 +00:00
2026-09-17 12:30:56 -07:00
// Checks that are stored but whose evaluate row could not be armed. Retried on the next flush so they are never unevaluated.
private unarmed: Map<string, PendingCheck[]> = new Map();
2026-06-18 09:56:38 -07:00
constructor(
logger: ILogger,
checkService: ICheckService,
geoChecksService: IGeoChecksService,
2026-09-03 11:32:48 -07:00
dockerLogsService: IDockerLogsService,
2026-06-18 09:56:38 -07:00
settingsService: ISettingsService,
jobsRepository: IJobsRepository
) {
this.BUFFER_TIMEOUT = settingsService.getSettings().nodeEnv === "development" ? 1000 : 1000 * 60 * 1; // 1 minute
2025-04-20 11:29:53 -07:00
this.logger = logger;
2026-01-16 18:11:04 +00:00
this.checksService = checkService;
2026-02-24 18:10:20 +00:00
this.geoChecksService = geoChecksService;
2026-09-03 11:32:48 -07:00
this.dockerLogsService = dockerLogsService;
2026-06-18 09:56:38 -07:00
this.jobsRepository = jobsRepository;
2025-04-20 11:29:53 -07:00
this.SERVICE_NAME = SERVICE_NAME;
2025-08-18 10:55:12 -07:00
this.buffer = [];
2026-02-24 18:10:20 +00:00
this.geoBuffer = [];
2026-09-03 11:32:48 -07:00
this.dockerLogBuffer = [];
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
2026-02-12 22:37:40 +00:00
addToBuffer(check: Check) {
2025-04-20 11:29:53 -07:00
try {
2025-08-18 10:55:12 -07:00
this.buffer.push(check);
2026-03-03 23:19:54 +00:00
} catch (error: unknown) {
2025-04-20 11:29:53 -07:00
this.logger.error({
2026-03-03 23:19:54 +00:00
message: error instanceof Error ? error.message : "Unknown error",
2025-04-20 11:29:53 -07:00
service: this.SERVICE_NAME,
method: "addToBuffer",
2026-03-03 23:19:54 +00:00
stack: error instanceof Error ? error.stack : undefined,
2025-04-20 11:29:53 -07:00
});
}
}
2026-02-24 18:10:20 +00:00
addGeoCheckToBuffer(geoCheck: GeoCheck) {
try {
this.geoBuffer.push(geoCheck);
2026-03-03 23:19:54 +00:00
} catch (error: unknown) {
2026-02-24 18:10:20 +00:00
this.logger.error({
2026-03-03 23:19:54 +00:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 18:10:20 +00:00
service: this.SERVICE_NAME,
method: "addGeoCheckToBuffer",
2026-03-03 23:19:54 +00:00
stack: error instanceof Error ? error.stack : undefined,
2026-02-24 18:10:20 +00:00
});
}
}
2026-09-03 11:32:48 -07:00
addDockerLogToBuffer(dockerLog: DockerLog): void {
try {
this.dockerLogBuffer.push(dockerLog);
} catch (error: unknown) {
this.logger.error({
message: error instanceof Error ? error.message : "Unknown error",
service: this.SERVICE_NAME,
method: "addDockerLogToBuffer",
stack: error instanceof Error ? error.stack : undefined,
});
}
}
ingestChecks = async (checks: Check[]) => {
2026-09-17 12:30:56 -07:00
if (checks.length > 0) await this.checksService.createChecks(checks);
2026-09-17 12:30:56 -07:00
// Group by monitor, starting from any entries a previous flush failed to arm
const byMonitor = this.unarmed;
this.unarmed = new Map();
for (const check of checks) {
const pending = byMonitor.get(check.metadata.monitorId) ?? [];
pending.push({ checkId: check.id, createdAt: new Date(check.createdAt).getTime() });
byMonitor.set(check.metadata.monitorId, pending);
}
2026-09-17 12:30:56 -07:00
if (byMonitor.size === 0) return;
const now = Date.now();
const ops: Promise<boolean>[] = [];
for (const [monitorId, pendingChecks] of byMonitor) {
2026-09-17 12:30:56 -07:00
ops.push(
this.jobsRepository.upsertEvaluate(monitorId, pendingChecks, now).catch((error: unknown) => {
// The checks are already stored, so a failed arm is retried on the next flush rather than dropped
this.unarmed.set(monitorId, pendingChecks);
this.logger.error({
message: `Could not arm evaluation for monitor ${monitorId}, retrying on next flush: ${error instanceof Error ? error.message : String(error)}`,
service: this.SERVICE_NAME,
method: "ingestChecks",
});
return false;
})
);
}
await Promise.all(ops);
};
2025-04-20 11:29:53 -07:00
scheduleNextFlush() {
2026-01-16 18:25:28 +00:00
if (this.bufferTimer) {
clearTimeout(this.bufferTimer);
}
2025-04-20 11:29:53 -07:00
this.bufferTimer = setTimeout(async () => {
try {
2025-08-18 10:55:12 -07:00
await this.flushBuffer();
2026-02-24 18:44:47 +00:00
await this.flushGeoBuffer();
2026-09-03 11:32:48 -07:00
await this.flushDockerLogsBuffer();
2026-03-03 23:19:54 +00:00
} catch (error: unknown) {
2025-04-20 11:29:53 -07:00
this.logger.error({
2026-03-03 23:19:54 +00:00
message: error instanceof Error ? error.message : "Unknown error",
2025-04-20 11:29:53 -07:00
service: this.SERVICE_NAME,
method: "scheduleNextFlush",
2026-03-03 23:19:54 +00:00
stack: error instanceof Error ? error.stack : undefined,
2025-04-20 11:29:53 -07:00
});
} 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() {
2026-09-17 12:30:56 -07:00
if (this.buffer.length === 0 && this.unarmed.size === 0) {
2026-06-18 09:56:38 -07:00
return;
}
// Take the batch first so a write that drains it can't be appended to mid-flush
const batch = this.buffer;
this.buffer = [];
2025-11-18 16:01:47 -05:00
try {
2026-06-18 09:56:38 -07:00
this.logger.debug({
message: `Flushing ${batch.length} checks to database`,
service: this.SERVICE_NAME,
method: "flushBuffer",
});
await this.ingestChecks(batch);
2026-03-03 23:19:54 +00:00
} catch (error: unknown) {
2026-02-24 18:44:47 +00:00
this.logger.error({
2026-03-03 23:19:54 +00:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 18:44:47 +00:00
service: this.SERVICE_NAME,
method: "flushBuffer",
2026-03-03 23:19:54 +00:00
stack: error instanceof Error ? error.stack : undefined,
2026-02-24 18:44:47 +00:00
});
2026-06-18 09:56:38 -07:00
// Batch is already cleared from the buffer; dropping it prevents infinite retry loops
2026-02-24 18:44:47 +00:00
}
}
2026-02-24 18:10:20 +00:00
2026-02-24 18:44:47 +00:00
async flushGeoBuffer() {
try {
if (this.geoBuffer.length > 0) {
this.logger.debug({
message: `Flushing ${this.geoBuffer.length} geo checks to database`,
service: this.SERVICE_NAME,
method: "flushGeoBuffer",
});
2026-02-24 18:10:20 +00:00
await this.geoChecksService.createGeoChecks(this.geoBuffer);
2026-02-24 18:44:47 +00:00
this.geoBuffer = [];
2026-02-24 18:10:20 +00:00
}
2026-03-03 23:19:54 +00:00
} catch (error: unknown) {
2025-11-18 16:01:47 -05:00
this.logger.error({
2026-03-03 23:19:54 +00:00
message: error instanceof Error ? error.message : "Unknown error",
2025-11-18 16:01:47 -05:00
service: this.SERVICE_NAME,
2026-02-24 18:44:47 +00:00
method: "flushGeoBuffer",
2026-03-03 23:19:54 +00:00
stack: error instanceof Error ? error.stack : undefined,
2025-11-18 16:01:47 -05:00
});
2026-02-24 18:44:47 +00:00
// Clear buffer even on error to prevent infinite retry loops
this.geoBuffer = [];
2025-11-18 16:01:47 -05:00
}
2025-04-20 11:29:53 -07:00
}
2026-06-24 11:58:32 -07:00
2026-09-03 11:32:48 -07:00
async flushDockerLogsBuffer() {
if (this.dockerLogBuffer.length === 0) {
return;
}
// Take the batch first so a write that drains it can't be appended to mid-flush
const batch = this.dockerLogBuffer;
this.dockerLogBuffer = [];
try {
this.logger.debug({
message: `Flushing ${batch.length} docker logs to database`,
service: this.SERVICE_NAME,
method: "flushDockerLogsBuffer",
});
await this.dockerLogsService.createDockerLogs(batch);
} catch (error: unknown) {
this.logger.error({
message: error instanceof Error ? error.message : "Unknown error",
service: this.SERVICE_NAME,
method: "flushDockerLogsBuffer",
stack: error instanceof Error ? error.stack : undefined,
});
}
}
2026-06-24 11:58:32 -07:00
async shutdown() {
if (this.bufferTimer) {
clearTimeout(this.bufferTimer);
this.bufferTimer = null;
}
await this.flushBuffer();
await this.flushGeoBuffer();
2026-09-03 11:32:48 -07:00
await this.flushDockerLogsBuffer();
2026-06-24 11:58:32 -07:00
}
2025-04-20 11:29:53 -07:00
}