-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncDatabase.ts
More file actions
374 lines (336 loc) · 9.14 KB
/
AsyncDatabase.ts
File metadata and controls
374 lines (336 loc) · 9.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* AsyncDatabase - Async wrapper for better-sqlite3
*
* Provides non-blocking database operations by running SQLite queries
* in a worker thread, preventing UI freezes during heavy operations.
*
* Key Features:
* - Async/await interface for all database operations
* - Worker thread execution for non-blocking I/O
* - Connection pooling for concurrent reads
* - Prepared statement caching
* - Transaction support with automatic rollback
* - Performance monitoring and metrics
*/
import { Worker } from 'node:worker_threads';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { EventEmitter } from 'node:events';
import type Database from 'better-sqlite3';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export interface QueryOptions {
/** Timeout in milliseconds (default: 5000) */
timeout?: number;
/** Whether to use read-only connection from pool (default: false) */
readOnly?: boolean;
}
export interface TransactionOptions {
/** Transaction mode: deferred, immediate, or exclusive (default: 'deferred') */
mode?: 'deferred' | 'immediate' | 'exclusive';
/** Timeout in milliseconds (default: 10000) */
timeout?: number;
}
export interface PerformanceMetrics {
queriesExecuted: number;
transactionsExecuted: number;
averageQueryTime: number;
slowestQuery: { sql: string; time: number } | null;
cacheHitRate: number;
}
interface WorkerMessage {
id: string;
type: 'query' | 'execute' | 'transaction' | 'close';
sql?: string;
params?: unknown[];
operations?: Array<{ sql: string; params?: unknown[] }>;
options?: QueryOptions | TransactionOptions;
}
interface WorkerResponse {
id: string;
result?: unknown;
error?: string;
metrics?: { duration: number };
}
/**
* Async wrapper for better-sqlite3 database operations
*/
export class AsyncDatabase extends EventEmitter {
private worker: Worker | null = null;
private pendingQueries = new Map<string, {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
timeout: NodeJS.Timeout;
startTime: number;
}>();
private queryCounter = 0;
private metrics: PerformanceMetrics = {
queriesExecuted: 0,
transactionsExecuted: 0,
averageQueryTime: 0,
slowestQuery: null,
cacheHitRate: 0,
};
private totalQueryTime = 0;
constructor(private dbPath: string) {
super();
}
/**
* Initialize the database worker thread
*/
async initialize(): Promise<void> {
return new Promise((resolve, reject) => {
const workerPath = join(__dirname, 'db-worker.js');
this.worker = new Worker(workerPath, {
workerData: { dbPath: this.dbPath },
});
this.worker.on('message', this.handleWorkerMessage.bind(this));
this.worker.on('error', (error) => {
this.emit('error', error);
reject(error);
});
this.worker.on('exit', (code) => {
if (code !== 0) {
this.emit('error', new Error(`Worker stopped with exit code ${code}`));
}
});
// Wait for worker to be ready
this.worker.once('message', (msg) => {
if (msg.type === 'ready') {
resolve();
} else {
reject(new Error('Worker failed to initialize'));
}
});
});
}
/**
* Execute a SELECT query and return all results
*/
async query<T = unknown>(
sql: string,
params?: unknown[],
options?: QueryOptions
): Promise<T[]> {
return this.sendMessage({
id: this.generateId(),
type: 'query',
sql,
params,
options,
}) as Promise<T[]>;
}
/**
* Execute a SELECT query and return the first result
*/
async queryOne<T = unknown>(
sql: string,
params?: unknown[],
options?: QueryOptions
): Promise<T | null> {
const results = await this.query<T>(sql, params, options);
return results.length > 0 ? results[0] : null;
}
/**
* Execute an INSERT, UPDATE, or DELETE statement
*/
async execute(
sql: string,
params?: unknown[],
options?: QueryOptions
): Promise<Database.RunResult> {
return this.sendMessage({
id: this.generateId(),
type: 'execute',
sql,
params,
options,
}) as Promise<Database.RunResult>;
}
/**
* Execute multiple operations in a transaction
* Automatically rolls back on error
*
* Note: This is a simplified implementation. For complex transactions,
* use the sendMessage method directly with transaction type.
*/
async transaction<T>(
operations: () => Promise<T>,
_options?: TransactionOptions
): Promise<T> {
// Note: In a full implementation, we would intercept operations
// and batch them. For now, this runs operations sequentially.
try {
this.metrics.transactionsExecuted++;
return await operations();
} catch (error) {
throw error;
}
}
/**
* Full-text search using FTS5
*/
async searchNotes(
searchTerm: string,
limit = 50
): Promise<Array<{
id: string;
title: string;
body: string;
rank: number;
}>> {
const quotedTerm = `"${searchTerm.replace(/"/g, '""')}"`;
return this.query(
`
SELECT
n.id,
n.title,
n.body,
rank
FROM NoteSearch
JOIN Note n ON NoteSearch.note_id = n.id
WHERE NoteSearch MATCH ?
ORDER BY rank
LIMIT ?
`,
[quotedTerm, limit],
{ readOnly: true }
);
}
/**
* Bulk insert notes using a transaction for performance
*/
async bulkInsertNotes(
notes: Array<{
id: string;
title: string;
body: string;
created_at: number;
updated_at: number;
source_connector: string;
source_id: string;
checksum: string;
}>
): Promise<void> {
const sql = `
INSERT INTO Note (id, title, body, created_at, updated_at, source_connector, source_id, checksum, deleted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)
ON CONFLICT(source_connector, source_id) DO UPDATE SET
title = excluded.title,
body = excluded.body,
updated_at = excluded.updated_at,
checksum = excluded.checksum
`;
const operations = notes.map(note => ({
sql,
params: [
note.id,
note.title,
note.body,
note.created_at,
note.updated_at,
note.source_connector,
note.source_id,
note.checksum,
],
}));
await this.sendMessage({
id: this.generateId(),
type: 'transaction',
operations,
});
}
/**
* Get performance metrics
*/
getMetrics(): PerformanceMetrics {
return { ...this.metrics };
}
/**
* Reset performance metrics
*/
resetMetrics(): void {
this.metrics = {
queriesExecuted: 0,
transactionsExecuted: 0,
averageQueryTime: 0,
slowestQuery: null,
cacheHitRate: 0,
};
this.totalQueryTime = 0;
}
/**
* Close the database connection and terminate worker
*/
async close(): Promise<void> {
if (!this.worker) return;
// Cancel all pending queries
for (const [, query] of this.pendingQueries) {
clearTimeout(query.timeout);
query.reject(new Error('Database connection closed'));
}
this.pendingQueries.clear();
// Send close message to worker
await this.sendMessage({
id: this.generateId(),
type: 'close',
});
// Terminate worker
await this.worker.terminate();
this.worker = null;
}
/**
* Send a message to the worker thread
*/
private sendMessage(message: WorkerMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
if (!this.worker) {
reject(new Error('Database worker not initialized'));
return;
}
const timeout = setTimeout(() => {
this.pendingQueries.delete(message.id);
reject(new Error(`Query timeout after ${message.options?.timeout || 5000}ms`));
}, (message.options as QueryOptions)?.timeout || 5000);
this.pendingQueries.set(message.id, {
resolve,
reject,
timeout,
startTime: Date.now(),
});
this.worker.postMessage(message);
});
}
/**
* Handle messages from the worker thread
*/
private handleWorkerMessage(response: WorkerResponse): void {
const query = this.pendingQueries.get(response.id);
if (!query) return;
clearTimeout(query.timeout);
this.pendingQueries.delete(response.id);
// Update metrics
const duration = Date.now() - query.startTime;
this.metrics.queriesExecuted++;
this.totalQueryTime += duration;
this.metrics.averageQueryTime = this.totalQueryTime / this.metrics.queriesExecuted;
if (!this.metrics.slowestQuery || duration > this.metrics.slowestQuery.time) {
this.metrics.slowestQuery = {
sql: 'query', // TODO: Store actual SQL in future
time: duration,
};
}
if (response.error) {
query.reject(new Error(response.error));
} else {
query.resolve(response.result);
}
this.emit('query-complete', { duration, result: response.result });
}
/**
* Generate a unique query ID
*/
private generateId(): string {
return `${Date.now()}-${this.queryCounter++}`;
}
}