Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/mitm/lib/NetworkDb.ts
1030 views
1
import * as Database from 'better-sqlite3';
2
import { Database as SqliteDatabase, Transaction } from 'better-sqlite3';
3
import SqliteTable from '@secret-agent/commons/SqliteTable';
4
import Log from '@secret-agent/commons/Logger';
5
import CertificatesTable from '../models/CertificatesTable';
6
7
const { log } = Log(module);
8
9
export default class NetworkDb {
10
public readonly certificates: CertificatesTable;
11
private db: SqliteDatabase;
12
private readonly batchInsert: Transaction;
13
private readonly saveInterval: NodeJS.Timeout;
14
private readonly tables: SqliteTable<any>[] = [];
15
16
constructor(baseDir: string) {
17
this.db = new Database(`${baseDir}/network.db`);
18
this.certificates = new CertificatesTable(this.db);
19
this.saveInterval = setInterval(this.flush.bind(this), 5e3).unref();
20
21
this.tables = [this.certificates];
22
23
this.batchInsert = this.db.transaction(() => {
24
for (const table of this.tables) {
25
try {
26
table.runPendingInserts();
27
} catch (error) {
28
if (
29
String(error).match(/attempt to write a readonly database/) ||
30
String(error).match(/database is locked/)
31
) {
32
clearInterval(this.saveInterval);
33
this.db = null;
34
}
35
log.error('NetworkDb.flushError', {
36
sessionId: null,
37
error,
38
table: table.tableName,
39
});
40
}
41
}
42
});
43
}
44
45
public close(): void {
46
if (this.db) {
47
clearInterval(this.saveInterval);
48
this.flush();
49
this.db.close();
50
}
51
this.db = null;
52
}
53
54
public flush(): void {
55
if (!this.db || this.db.readonly) return;
56
this.batchInsert.immediate();
57
}
58
}
59
60