forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsearch-worker-client.js
More file actions
168 lines (151 loc) · 5.51 KB
/
Copy pathsearch-worker-client.js
File metadata and controls
168 lines (151 loc) · 5.51 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
'use strict';
// search-worker-client.js
//
// Encapsulates the worker-client protocol for the search query worker:
// correlation-ID round-trip, pending-promise map, drain-on-exit, and the
// restart backoff / circuit-breaker.
//
// Extracted from main.js so the protocol can be unit-tested without
// requiring Electron or better-sqlite3. main.js passes real dependencies;
// tests inject mocks.
//
// Factory: createSearchWorkerClient(deps) → { startWorker, searchViaWorker }
//
// deps:
// workerFactory(dbPath) → Worker-like object with .on() and .postMessage()
// searchByType(type, q, limit, titleOnly) → Array (synchronous fallback)
// log → { warn, error } (electron-log or console)
// dbPath → string passed through to workerFactory
// maxRestarts → optional; default 5
// restartWindowMs → optional; default 10 000
function createSearchWorkerClient(deps) {
const {
workerFactory,
searchByType,
log,
dbPath,
maxRestarts = 5,
restartWindowMs = 10000,
} = deps;
let worker = null;
let workerReady = false;
const pending = new Map(); // correlationId → { resolve }
let counter = 0;
// Circuit-breaker state
let failureCount = 0;
let failureWindowTimer = null;
let restartTimer = null;
let shuttingDown = false;
/**
* Resolve all in-flight search promises with [] and clear the map.
* Called from both `error` and `exit` handlers so neither path orphans
* a pending IPC call. A native crash (SIGSEGV) fires only `exit`, so
* without this the renderer's window.api.search() would hang forever.
*/
function drainPending() {
for (const [id, p] of pending) {
p.resolve([]);
pending.delete(id);
}
}
function startWorker() {
if (shuttingDown) return;
worker = workerFactory(dbPath);
worker.on('online', () => {
workerReady = true;
// A clean startup resets the failure-count window.
clearTimeout(failureWindowTimer);
// unref() so this housekeeping timer does not prevent process exit in
// tests (or in a future scenario where the app quits with no open window).
failureWindowTimer = setTimeout(() => {
failureCount = 0;
}, restartWindowMs);
if (failureWindowTimer.unref) failureWindowTimer.unref();
});
worker.on('message', (msg) => {
const p = pending.get(msg.id);
if (!p) return;
pending.delete(msg.id);
if (msg.error) {
// Resolve with empty results — same behaviour as the synchronous
// searchByType catch branch.
p.resolve([]);
} else {
p.resolve(msg.results);
}
});
worker.on('error', (err) => {
log.error('[search-worker] error:', err.message);
// Drain so the renderer is never left hanging.
drainPending();
workerReady = false;
// `exit` will fire next for a JS exception — restart logic lives there.
});
worker.on('exit', (code) => {
workerReady = false;
worker = null;
// Drain in case `error` did NOT fire first (native crash / terminate()
// path: only `exit` fires, so without this drain the renderer awaits
// indefinitely on unresolved Promises).
drainPending();
if (code !== 0) {
failureCount++;
clearTimeout(failureWindowTimer);
if (failureCount >= maxRestarts) {
// Circuit-breaker open: stop restarting and fall back permanently
// to synchronous searchByType on the main thread.
log.error(
`[search-worker] ${failureCount} consecutive failures — ` +
'circuit-breaker open; falling back to synchronous search'
);
return;
}
// Exponential backoff: 250 ms × 2^(failureCount-1), capped at 8 s.
const delay = Math.min(250 * Math.pow(2, failureCount - 1), 8000);
log.warn(
`[search-worker] exited with code ${code} ` +
`(failure ${failureCount}/${maxRestarts}); ` +
`restarting in ${delay} ms`
);
restartTimer = setTimeout(() => startWorker(), delay);
if (restartTimer.unref) restartTimer.unref();
}
});
}
/**
* Send a search query to the worker and return a Promise<results[]>.
* Falls back to the synchronous searchByType on the main thread if the
* worker is not yet ready (first-launch race or circuit-breaker open).
*/
function searchViaWorker(type, query, titleOnly) {
if (!workerReady || !worker) {
return Promise.resolve(searchByType(type, query, 50, !!titleOnly));
}
return new Promise((resolve) => {
const id = String(++counter);
pending.set(id, { resolve });
worker.postMessage({ id, type, query, limit: 50, titleOnly: !!titleOnly });
});
}
/**
* Terminate the worker cleanly (called from will-quit before closeDb()).
* Suppresses the restart logic so the exit handler does not try to respawn
* after the DB connection has already been closed.
*/
function shutdown() {
shuttingDown = true;
clearTimeout(restartTimer);
restartTimer = null;
if (worker) {
worker.removeAllListeners('exit'); // suppress backoff / restart
worker.terminate();
worker = null;
}
workerReady = false;
// The suppressed exit handler would normally drain — do it here so an
// in-flight search never leaves the renderer awaiting a dead promise.
drainPending();
}
return { startWorker, searchViaWorker, drainPending, shutdown };
}
module.exports = { createSearchWorkerClient };