-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.ts
More file actions
205 lines (175 loc) · 4.85 KB
/
Copy pathwatcher.ts
File metadata and controls
205 lines (175 loc) · 4.85 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
import { Database } from "bun:sqlite";
import type {
WatcherConfig,
DBChange,
WatcherCallback,
WatchOptions,
ErrorCallback
} from './types';
import { setupDatabase, createTriggers, removeTriggers, cleanup } from './utils/sqlite';
import { EventEmitter } from './utils/events';
export class TableWatcher<T = any> {
private emitter: EventEmitter;
private options: WatchOptions;
private table: string;
constructor(table: string, options: WatchOptions = {}) {
this.table = table;
this.options = options;
this.emitter = new EventEmitter();
}
onInsert(callback: WatcherCallback<T>) {
this.emitter.on('INSERT', callback);
return this;
}
onUpdate(callback: WatcherCallback<T>) {
this.emitter.on('UPDATE', callback);
return this;
}
onDelete(callback: WatcherCallback<T>) {
this.emitter.on('DELETE', callback);
return this;
}
onAny(callback: WatcherCallback<T>) {
this.emitter.on('*', callback);
return this;
}
filter(predicate: (change: DBChange<T>) => boolean) {
this.options.filter = predicate;
return this;
}
async handleChange(change: DBChange<T>) {
if (this.options.filter && !this.options.filter(change)) {
return;
}
await this.emitter.emit(change.operation, change);
}
cleanup() {
this.emitter.removeAllListeners();
}
}
export class SQLiteWatcher {
private db: Database;
private config: Required<WatcherConfig>;
private watchers: Map<string, TableWatcher>;
private intervalId: number | null = null;
private errorHandlers: Set<ErrorCallback>;
private initialized: boolean = false;
constructor(config: WatcherConfig) {
this.config = {
watchIntervalMs: 1000,
maxChangesPerBatch: 1000,
retentionSeconds: 3600,
bufferSize: 10000,
tables: [],
...config
};
this.db = new Database(this.config.dbPath);
this.watchers = new Map();
this.errorHandlers = new Set();
}
private initialize() {
if (!this.initialized) {
setupDatabase(this.db, this.config);
this.initialized = true;
}
}
watch<T = any>(table: string, options: WatchOptions = {}) {
this.initialize();
if (!this.watchers.has(table)) {
createTriggers(this.db, table);
this.watchers.set(table, new TableWatcher<T>(table, options));
}
return this.watchers.get(table) as TableWatcher<T>;
}
unwatch(table: string) {
if (this.watchers.has(table)) {
const watcher = this.watchers.get(table)!;
watcher.cleanup();
removeTriggers(this.db, table);
this.watchers.delete(table);
}
}
private async checkChanges() {
try {
const changes = this.db.query(`
SELECT * FROM _sqlite_watcher_changes
ORDER BY timestamp ASC
LIMIT ?
`).all(this.config.maxChangesPerBatch);
if (changes.length > 0) {
const lastId = changes[changes.length - 1].id;
this.db.run('DELETE FROM _sqlite_watcher_changes WHERE id <= ?', lastId);
for (const change of changes) {
const watcher = this.watchers.get(change.table_name);
if (watcher) {
await watcher.handleChange({
table: change.table_name,
operation: change.operation,
rowId: change.row_id,
timestamp: change.timestamp,
changes: JSON.parse(change.changed_data)
});
}
}
}
} catch (error) {
this.errorHandlers.forEach(handler => handler(error));
}
}
start() {
if (this.intervalId === null) {
this.intervalId = setInterval(
() => this.checkChanges(),
this.config.watchIntervalMs
);
}
return this;
}
stop() {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
return this;
}
onError(handler: ErrorCallback) {
this.errorHandlers.add(handler);
return this;
}
cleanup(removeTable: boolean = false) {
this.stop();
// Remove all triggers and cleanup watchers
for (const [table, watcher] of this.watchers.entries()) {
watcher.cleanup();
removeTriggers(this.db, table);
}
this.watchers.clear();
if (removeTable) {
cleanup(this.db);
}
this.db.close();
this.initialized = false;
}
// Utility methods
isWatching(table: string): boolean {
return this.watchers.has(table);
}
get watchedTables(): string[] {
return Array.from(this.watchers.keys());
}
async hasWatcherTable(): Promise<boolean> {
const result = this.db.query(`
SELECT name FROM sqlite_master
WHERE type='table'
AND name='_sqlite_watcher_changes'
`).get();
return !!result;
}
async getWatcherTableSize(): Promise<number> {
const result = this.db.query(`
SELECT COUNT(*) as count
FROM _sqlite_watcher_changes
`).get();
return (result as any).count;
}
}