103 lines
3.0 KiB
TypeScript
103 lines
3.0 KiB
TypeScript
import type { Database } from "bun:sqlite";
|
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { dirname } from "node:path";
|
|
import { getDatabase } from "../../core/db/index.js";
|
|
import type { EventRecord } from "./types.js";
|
|
|
|
interface PersistedEvents {
|
|
version: 1;
|
|
events: Record<string, number>;
|
|
}
|
|
|
|
const MAX_EVENTS = 2000;
|
|
|
|
export class EventStore {
|
|
private readonly scopeKey: string;
|
|
private readonly jsonPath?: string;
|
|
private readonly customDb?: Database;
|
|
|
|
constructor(scopeOrFilePath = "default", db?: Database) {
|
|
this.scopeKey = scopeOrFilePath;
|
|
this.customDb = db;
|
|
if (scopeOrFilePath.endsWith(".json")) {
|
|
this.jsonPath = scopeOrFilePath;
|
|
}
|
|
}
|
|
|
|
private get db(): Database {
|
|
return this.customDb ?? getDatabase();
|
|
}
|
|
|
|
private readJson(): PersistedEvents {
|
|
if (!this.jsonPath || !existsSync(this.jsonPath)) {
|
|
return { version: 1, events: {} };
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedEvents>;
|
|
return {
|
|
version: 1,
|
|
events: parsed.events && typeof parsed.events === "object" ? parsed.events : {},
|
|
};
|
|
} catch {
|
|
return { version: 1, events: {} };
|
|
}
|
|
}
|
|
|
|
has(id: string): boolean {
|
|
if (this.jsonPath && existsSync(this.jsonPath)) {
|
|
if (Object.prototype.hasOwnProperty.call(this.readJson().events, id)) {
|
|
return true;
|
|
}
|
|
}
|
|
const row = this.db
|
|
.query("SELECT 1 FROM observed_events WHERE scope_key = ? AND id = ? LIMIT 1")
|
|
.get(this.scopeKey, id);
|
|
return Boolean(row);
|
|
}
|
|
|
|
commit(records: EventRecord[]): void {
|
|
if (!records.length) return;
|
|
|
|
const db = this.db;
|
|
const upsert = db.prepare(`
|
|
INSERT INTO observed_events (scope_key, id, corp_id, kind, observed_at)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT(scope_key, id) DO UPDATE SET observed_at = excluded.observed_at
|
|
`);
|
|
|
|
const tx = db.transaction((items: EventRecord[]) => {
|
|
for (const record of items) {
|
|
upsert.run(this.scopeKey, record.id, record.corpId, record.kind, record.observedAt);
|
|
}
|
|
db.run(
|
|
`
|
|
DELETE FROM observed_events
|
|
WHERE scope_key = ? AND id NOT IN (
|
|
SELECT id FROM observed_events
|
|
WHERE scope_key = ?
|
|
ORDER BY observed_at DESC
|
|
LIMIT ?
|
|
)
|
|
`,
|
|
[this.scopeKey, this.scopeKey, Math.max(MAX_EVENTS, records.length)]
|
|
);
|
|
});
|
|
tx(records);
|
|
|
|
if (this.jsonPath) {
|
|
const data = this.readJson();
|
|
const merged = { ...data.events };
|
|
for (const record of records) merged[record.id] = record.observedAt;
|
|
const entries = Object.entries(merged)
|
|
.sort((a, b) => a[1] - b[1])
|
|
.slice(-Math.max(MAX_EVENTS, records.length));
|
|
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
|
writeFileSync(
|
|
this.jsonPath,
|
|
`${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`,
|
|
{ mode: 0o600 }
|
|
);
|
|
}
|
|
}
|
|
}
|