@bridgebrew/storage-postgres 0.0.0-stage → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +37 -2
- package/connection.ts +94 -0
- package/package.json +108 -4
- package/protocol.ts +141 -0
- package/proxy.ts +369 -0
- package/remote.ts +225 -0
- package/server.ts +473 -0
- package/supabase-root-2021.crt +23 -0
- package/tsconfig.json +3 -0
package/proxy.ts
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// The Postgres storage proxy (owner, 20 October 2026: only this process holds the password): Bridge starts it with the
|
|
2
|
+
// connection string's secret marker in `BRIDGE_STORAGE_URL`, and the host replaces the marker with its value as it
|
|
3
|
+
// starts the process. It checks the connection string, opens `postgresBackend`, and serves every `Backend` method over
|
|
4
|
+
// one JSON object per line on stdin/stdout, version 1 (`./protocol.ts`). A `storage_unreachable` answer is followed by
|
|
5
|
+
// exit code 3, so the plugin starts a new process; a login refused at the open is `storage_auth_refused`. `BRIDGE_STORAGE_TEST=1` only tests the connection and reports the
|
|
6
|
+
// server's major version and, when the lease is held elsewhere, who holds it.
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { hostname } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { Client } from 'pg';
|
|
11
|
+
import type {
|
|
12
|
+
AuditMeta,
|
|
13
|
+
AuditQuery,
|
|
14
|
+
Backend,
|
|
15
|
+
Change,
|
|
16
|
+
Filter,
|
|
17
|
+
GroupOptions,
|
|
18
|
+
LogWindow,
|
|
19
|
+
Page,
|
|
20
|
+
} from '@bridge/storage';
|
|
21
|
+
import { postgresBackend } from '@bridge/storage/postgres';
|
|
22
|
+
import { checkConnection, connectionKind } from './connection.ts';
|
|
23
|
+
import {
|
|
24
|
+
decodeValue,
|
|
25
|
+
encodeError,
|
|
26
|
+
encodeValue,
|
|
27
|
+
isRecord,
|
|
28
|
+
lineOf,
|
|
29
|
+
type WireError,
|
|
30
|
+
} from './protocol.ts';
|
|
31
|
+
|
|
32
|
+
const env = process.env;
|
|
33
|
+
const rawUrl = env.BRIDGE_STORAGE_URL ?? '';
|
|
34
|
+
const dataDir = env.BRIDGE_STORAGE_DATA_DIR ?? '';
|
|
35
|
+
const machine = env.BRIDGE_STORAGE_MACHINE || hostname();
|
|
36
|
+
const takeOver = env.BRIDGE_STORAGE_TAKE_OVER === '1';
|
|
37
|
+
/** The settings' query timeout and read connections (`server.ts` checks them); unset: the backend's defaults. */
|
|
38
|
+
const timeoutMs = env.BRIDGE_STORAGE_TIMEOUT_MS ? Number(env.BRIDGE_STORAGE_TIMEOUT_MS) : undefined;
|
|
39
|
+
const readConnections = env.BRIDGE_STORAGE_READ_CONNECTIONS
|
|
40
|
+
? Number(env.BRIDGE_STORAGE_READ_CONNECTIONS)
|
|
41
|
+
: undefined;
|
|
42
|
+
|
|
43
|
+
/** The password in the forms it may appear in, longest first, so nothing this process writes carries it. */
|
|
44
|
+
const passwords = (() => {
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(rawUrl);
|
|
47
|
+
const raw = url.password;
|
|
48
|
+
let decoded = raw;
|
|
49
|
+
try {
|
|
50
|
+
decoded = decodeURIComponent(raw);
|
|
51
|
+
} catch {
|
|
52
|
+
// The URL left it encoded: that form is scrubbed too.
|
|
53
|
+
}
|
|
54
|
+
return [...new Set([raw, decoded])]
|
|
55
|
+
.filter((each) => each !== '')
|
|
56
|
+
.sort((a, b) => b.length - a.length);
|
|
57
|
+
} catch {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
})();
|
|
61
|
+
const scrub = (text: string) => {
|
|
62
|
+
for (const password of passwords) text = text.split(password).join('<password>');
|
|
63
|
+
return text;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const send = (value: unknown, done?: () => void) => {
|
|
67
|
+
process.stdout.write(lineOf(value), done);
|
|
68
|
+
};
|
|
69
|
+
const exitAfter = (value: unknown, code: number) => send(value, () => process.exit(code));
|
|
70
|
+
|
|
71
|
+
const errorLineOf = (cause: unknown): WireError => {
|
|
72
|
+
const error = encodeError(cause);
|
|
73
|
+
return { ...error, message: scrub(error.message) };
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const codeOf = (cause: unknown) => {
|
|
77
|
+
if (!(cause instanceof Error)) return undefined;
|
|
78
|
+
const descriptor = Object.getOwnPropertyDescriptor(cause, 'code');
|
|
79
|
+
const value: unknown = descriptor?.value;
|
|
80
|
+
return typeof value === 'string' ? value : undefined;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Postgres refused the login (wrong user or password, or no access from here): a code of the error or of its cause
|
|
84
|
+
* (the backend wraps a failed connection as `storage_unreachable`). */
|
|
85
|
+
const authRefused = (cause: unknown): boolean => {
|
|
86
|
+
const code = codeOf(cause);
|
|
87
|
+
if (code === '28P01' || code === '28000') return true;
|
|
88
|
+
return cause instanceof Error && cause.cause !== undefined && cause.cause !== cause
|
|
89
|
+
? authRefused(cause.cause)
|
|
90
|
+
: false;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const hintOf = (cause: unknown) => {
|
|
94
|
+
const code = codeOf(cause);
|
|
95
|
+
if (authRefused(cause))
|
|
96
|
+
return 'The login was refused: check the user and the password in the connection string.';
|
|
97
|
+
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT')
|
|
98
|
+
return 'The server did not answer: check the host and the port.';
|
|
99
|
+
return undefined;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** The lease's holder when it is another Bridge: its machine and since. */
|
|
103
|
+
const leaseOf = async (client: Client) => {
|
|
104
|
+
try {
|
|
105
|
+
const { rows } = await client.query<Record<string, unknown>>(
|
|
106
|
+
'select holder, machine, since from bridge.lease order by since desc limit 1',
|
|
107
|
+
);
|
|
108
|
+
const row = rows[0];
|
|
109
|
+
if (!row) return {};
|
|
110
|
+
const holder = typeof row.holder === 'string' ? row.holder : '';
|
|
111
|
+
let local = '';
|
|
112
|
+
try {
|
|
113
|
+
local =
|
|
114
|
+
dataDir === '' ? '' : readFileSync(join(dataDir, 'storage-postgres.holder'), 'utf8').trim();
|
|
115
|
+
} catch {
|
|
116
|
+
// No local holder: a row is another Bridge's.
|
|
117
|
+
}
|
|
118
|
+
if (holder !== '' && holder === local) return {};
|
|
119
|
+
const since = Number(row.since);
|
|
120
|
+
return {
|
|
121
|
+
machine:
|
|
122
|
+
typeof row.machine === 'string' && row.machine !== '' ? row.machine : 'another machine',
|
|
123
|
+
...(Number.isFinite(since) ? { since } : {}),
|
|
124
|
+
};
|
|
125
|
+
} catch {
|
|
126
|
+
// No `bridge` schema yet (or no right to read it): the connection itself is what the test reports.
|
|
127
|
+
return {};
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const testConnection = async (url: string) => {
|
|
132
|
+
const client = new Client({
|
|
133
|
+
connectionString: url,
|
|
134
|
+
connectionTimeoutMillis: 10_000,
|
|
135
|
+
query_timeout: 10_000,
|
|
136
|
+
application_name: 'bridge-storage-test',
|
|
137
|
+
});
|
|
138
|
+
client.on('error', () => {});
|
|
139
|
+
try {
|
|
140
|
+
await client.connect();
|
|
141
|
+
const answer = await client.query<Record<string, unknown>>(
|
|
142
|
+
"select current_setting('server_version_num') as n",
|
|
143
|
+
);
|
|
144
|
+
const number = Number(answer.rows[0]?.n);
|
|
145
|
+
const major = Number.isFinite(number) && number > 0 ? Math.floor(number / 10000) : 0;
|
|
146
|
+
return { ok: true as const, major, kind: connectionKind(url), ...(await leaseOf(client)) };
|
|
147
|
+
} catch (cause) {
|
|
148
|
+
const hint = hintOf(cause);
|
|
149
|
+
return {
|
|
150
|
+
ok: false as const,
|
|
151
|
+
error: scrub(cause instanceof Error ? cause.message : String(cause)),
|
|
152
|
+
...(hint === undefined ? {} : { hint }),
|
|
153
|
+
};
|
|
154
|
+
} finally {
|
|
155
|
+
await client.end().catch(() => {});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
let backend: Backend | undefined;
|
|
160
|
+
let closing = false;
|
|
161
|
+
|
|
162
|
+
/** The `Backend` call a request names; a bad arg is the backend's own refusal. */
|
|
163
|
+
const invoke = async (op: string, args: unknown[]): Promise<unknown> => {
|
|
164
|
+
if (!backend) throw new Error('the storage backend is not open');
|
|
165
|
+
const arg = <T>(index: number): T => args[index] as T;
|
|
166
|
+
switch (op) {
|
|
167
|
+
case 'version':
|
|
168
|
+
return backend.version(arg<string>(0));
|
|
169
|
+
case 'get':
|
|
170
|
+
return backend.get(arg<string>(0), arg<string>(1));
|
|
171
|
+
case 'list':
|
|
172
|
+
return backend.list(arg<string>(0), arg<Filter | undefined>(1), arg<Page | undefined>(2));
|
|
173
|
+
case 'count':
|
|
174
|
+
return backend.count(arg<string>(0), arg<Filter | undefined>(1));
|
|
175
|
+
case 'countBy':
|
|
176
|
+
return backend.countBy(
|
|
177
|
+
arg<string>(0),
|
|
178
|
+
arg<string>(1),
|
|
179
|
+
arg<string[]>(2),
|
|
180
|
+
arg<Filter | undefined>(3),
|
|
181
|
+
);
|
|
182
|
+
case 'groupBy':
|
|
183
|
+
return backend.groupBy(
|
|
184
|
+
arg<string>(0),
|
|
185
|
+
arg<string>(1),
|
|
186
|
+
arg<Filter | undefined>(2),
|
|
187
|
+
arg<GroupOptions | undefined>(3),
|
|
188
|
+
);
|
|
189
|
+
case 'index':
|
|
190
|
+
return backend.index(arg<string>(0), arg<string[]>(1));
|
|
191
|
+
case 'searchable':
|
|
192
|
+
return backend.searchable(
|
|
193
|
+
arg<string>(0),
|
|
194
|
+
arg<string[]>(1),
|
|
195
|
+
arg<{ trigram?: boolean } | undefined>(2),
|
|
196
|
+
);
|
|
197
|
+
case 'write':
|
|
198
|
+
return backend.write(arg<Change[]>(0));
|
|
199
|
+
case 'backup':
|
|
200
|
+
return backend.backup(arg<string>(0));
|
|
201
|
+
case 'append':
|
|
202
|
+
return backend.append(
|
|
203
|
+
arg<string>(0),
|
|
204
|
+
arg<number>(1),
|
|
205
|
+
arg<string>(2),
|
|
206
|
+
arg<{ at: number; data: unknown }[]>(3),
|
|
207
|
+
arg<{ after?: number } | undefined>(4),
|
|
208
|
+
);
|
|
209
|
+
case 'read':
|
|
210
|
+
return backend.read(arg<string>(0), arg<string>(1), arg<LogWindow | undefined>(2));
|
|
211
|
+
case 'last':
|
|
212
|
+
return backend.last(arg<string>(0), arg<string>(1));
|
|
213
|
+
case 'streams':
|
|
214
|
+
return backend.streams(arg<string>(0), arg<{ after?: string; take?: number } | undefined>(1));
|
|
215
|
+
case 'purge':
|
|
216
|
+
return backend.purge(arg<string>(0), arg<string>(1), arg<AuditMeta | undefined>(2));
|
|
217
|
+
case 'attach':
|
|
218
|
+
return backend.attach(arg<string>(0), arg<string>(1), arg<Uint8Array>(2), arg<string>(3));
|
|
219
|
+
case 'attachFile':
|
|
220
|
+
return backend.attachFile(arg<string>(0), arg<string>(1), arg<string>(2), arg<string>(3));
|
|
221
|
+
case 'blob':
|
|
222
|
+
return backend.blob(arg<string>(0), arg<string>(1));
|
|
223
|
+
case 'queryAudit':
|
|
224
|
+
return backend.queryAudit(arg<AuditQuery | undefined>(0));
|
|
225
|
+
case 'auditActors':
|
|
226
|
+
return backend.auditActors(arg<{ domain: string; key: string }>(0));
|
|
227
|
+
case 'auditObjects':
|
|
228
|
+
return backend.auditObjects(arg<{ actor: string }>(0));
|
|
229
|
+
case 'pruneAudit':
|
|
230
|
+
return backend.pruneAudit(arg<number>(0));
|
|
231
|
+
case 'sizes':
|
|
232
|
+
return backend.sizes();
|
|
233
|
+
case 'close':
|
|
234
|
+
await backend.close();
|
|
235
|
+
return null;
|
|
236
|
+
default:
|
|
237
|
+
throw Object.assign(new Error(`unknown storage operation ${JSON.stringify(op)}`), {
|
|
238
|
+
code: 'bad_request',
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const answer = async (line: string) => {
|
|
244
|
+
let id: unknown;
|
|
245
|
+
try {
|
|
246
|
+
const parsed: unknown = JSON.parse(line);
|
|
247
|
+
if (!isRecord(parsed)) throw new Error('a request is a JSON object');
|
|
248
|
+
id = parsed.id;
|
|
249
|
+
if (parsed.v !== undefined && parsed.v !== 1)
|
|
250
|
+
throw Object.assign(new Error('this proxy speaks protocol 1'), { code: 'bad_request' });
|
|
251
|
+
const op = parsed.op;
|
|
252
|
+
if (typeof op !== 'string')
|
|
253
|
+
throw Object.assign(new Error('a request names an op'), { code: 'bad_request' });
|
|
254
|
+
const sent = parsed.args;
|
|
255
|
+
const args = Array.isArray(sent) ? sent.map(decodeValue) : [];
|
|
256
|
+
const result = await invoke(op, args);
|
|
257
|
+
const response = {
|
|
258
|
+
v: 1,
|
|
259
|
+
id: typeof id === 'number' ? id : null,
|
|
260
|
+
result: encodeValue(result),
|
|
261
|
+
};
|
|
262
|
+
if (op === 'close') exitAfter(response, 0);
|
|
263
|
+
else send(response);
|
|
264
|
+
} catch (cause) {
|
|
265
|
+
const error = errorLineOf(cause);
|
|
266
|
+
const response = { v: 1, id: typeof id === 'number' ? id : null, error };
|
|
267
|
+
if (error.code === 'storage_unreachable') exitAfter(response, 3);
|
|
268
|
+
else send(response);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const closeBackend = async () => {
|
|
273
|
+
if (closing) return;
|
|
274
|
+
closing = true;
|
|
275
|
+
await backend?.close().catch(() => {});
|
|
276
|
+
};
|
|
277
|
+
const stop = (code: number) => {
|
|
278
|
+
void closeBackend()
|
|
279
|
+
.catch(() => {})
|
|
280
|
+
.finally(() => process.exit(code));
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
/** Calls `onLine` with each line of `input` ended at `\n` alone (a trailing `\r` dropped), then `onEnd`: `readline`
|
|
284
|
+
* also ends a line at U+2028 and U+2029, which `JSON.stringify` leaves raw inside strings (bridge-plugins#55). */
|
|
285
|
+
const readLines = (
|
|
286
|
+
input: NodeJS.ReadStream,
|
|
287
|
+
onLine: (line: string) => void,
|
|
288
|
+
onEnd: () => void = () => {},
|
|
289
|
+
) => {
|
|
290
|
+
let rest = '';
|
|
291
|
+
input.setEncoding('utf8');
|
|
292
|
+
input.on('data', (chunk: string) => {
|
|
293
|
+
rest += chunk;
|
|
294
|
+
for (let at = rest.indexOf('\n'); at >= 0; at = rest.indexOf('\n')) {
|
|
295
|
+
onLine(rest.slice(0, at).replace(/\r$/, ''));
|
|
296
|
+
rest = rest.slice(at + 1);
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
input.on('end', () => {
|
|
300
|
+
if (rest) onLine(rest.replace(/\r$/, ''));
|
|
301
|
+
onEnd();
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const serve = () => {
|
|
306
|
+
readLines(
|
|
307
|
+
process.stdin,
|
|
308
|
+
(line) => {
|
|
309
|
+
if (line.trim() !== '')
|
|
310
|
+
void answer(line).catch((cause) => {
|
|
311
|
+
send({ v: 1, id: null, error: errorLineOf(cause) });
|
|
312
|
+
});
|
|
313
|
+
},
|
|
314
|
+
() => stop(0),
|
|
315
|
+
);
|
|
316
|
+
process.on('SIGTERM', () => stop(0));
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
const main = async () => {
|
|
320
|
+
const checked = checkConnection(rawUrl);
|
|
321
|
+
if (env.BRIDGE_STORAGE_TEST === '1') {
|
|
322
|
+
if (!checked.ok) {
|
|
323
|
+
const error = {
|
|
324
|
+
ok: false,
|
|
325
|
+
error: checked.error,
|
|
326
|
+
...(checked.hint === undefined ? {} : { hint: checked.hint }),
|
|
327
|
+
};
|
|
328
|
+
exitAfter({ v: 1, event: 'test', ...error }, 0);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
exitAfter({ v: 1, event: 'test', ...(await testConnection(checked.url)) }, 0);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (!checked.ok) {
|
|
335
|
+
const message =
|
|
336
|
+
checked.hint === undefined ? checked.error : `${checked.error}. ${checked.hint}`;
|
|
337
|
+
const error = Object.assign(new Error(message), { code: 'invalid_connection' });
|
|
338
|
+
exitAfter({ v: 1, event: 'open', ok: false, error: errorLineOf(error) }, 1);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
backend = await postgresBackend({
|
|
343
|
+
url: checked.url,
|
|
344
|
+
dataDir,
|
|
345
|
+
machine,
|
|
346
|
+
takeOver,
|
|
347
|
+
...(timeoutMs !== undefined && { timeoutMs }),
|
|
348
|
+
...(readConnections !== undefined && { readConnections }),
|
|
349
|
+
});
|
|
350
|
+
} catch (cause) {
|
|
351
|
+
// A refused login is not retried: only a new connection string gets out of it.
|
|
352
|
+
const error = authRefused(cause)
|
|
353
|
+
? { ...errorLineOf(cause), code: 'storage_auth_refused' }
|
|
354
|
+
: errorLineOf(cause);
|
|
355
|
+
exitAfter(
|
|
356
|
+
{ v: 1, event: 'open', ok: false, error },
|
|
357
|
+
error.code === 'storage_unreachable' ? 3 : 1,
|
|
358
|
+
);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
send({ v: 1, event: 'open', ok: true });
|
|
362
|
+
serve();
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
void main().catch((cause: unknown) => {
|
|
366
|
+
const error = errorLineOf(cause);
|
|
367
|
+
process.stderr.write(`${error.message}\n`);
|
|
368
|
+
process.exit(1);
|
|
369
|
+
});
|
package/remote.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// The plugin's side of the Postgres storage proxy (`./proxy.ts`): one process, its JSON lines (version 1), and a
|
|
2
|
+
// `Backend` that forwards every call to it. The open resolves once the proxy reports the backend open, and rejects with
|
|
3
|
+
// the proxy's own error (its `code`, `machine`, `since` and message). Once the process ends, calls in flight or later
|
|
4
|
+
// reject `storage_unreachable`; `close` asks the proxy to close the backend, then ends the process, and resolves even
|
|
5
|
+
// when it is already gone.
|
|
6
|
+
import type { ProcessHandle } from '@bridge/worker-runtime/workspace';
|
|
7
|
+
import type {
|
|
8
|
+
AuditActor,
|
|
9
|
+
AuditObject,
|
|
10
|
+
AuditQuery,
|
|
11
|
+
AuditRow,
|
|
12
|
+
Backend,
|
|
13
|
+
BlobRef,
|
|
14
|
+
Change,
|
|
15
|
+
Entry,
|
|
16
|
+
Filter,
|
|
17
|
+
Group,
|
|
18
|
+
GroupOptions,
|
|
19
|
+
LogEvent,
|
|
20
|
+
LogStream,
|
|
21
|
+
LogWindow,
|
|
22
|
+
Page,
|
|
23
|
+
} from '@bridge/storage';
|
|
24
|
+
import { decodeError, decodeValue, isRecord, lineOf, requestLine } from './protocol.ts';
|
|
25
|
+
|
|
26
|
+
export interface RemoteBackend extends Backend {
|
|
27
|
+
/** Resolves when the process ended, with the `storage_unreachable` error it answered last, if one. */
|
|
28
|
+
ended: Promise<Error | undefined>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const codeOf = (error: Error) => {
|
|
32
|
+
const descriptor = Object.getOwnPropertyDescriptor(error, 'code');
|
|
33
|
+
const value: unknown = descriptor?.value;
|
|
34
|
+
return typeof value === 'string' ? value : undefined;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const unreachable = (message = 'the Postgres storage process ended') =>
|
|
38
|
+
Object.assign(new Error(message), { code: 'storage_unreachable' });
|
|
39
|
+
|
|
40
|
+
const closedError = () => new Error('storage backend is closed');
|
|
41
|
+
|
|
42
|
+
const within = (work: Promise<unknown>, ms: number) =>
|
|
43
|
+
new Promise<void>((resolve) => {
|
|
44
|
+
const timer = setTimeout(resolve, ms);
|
|
45
|
+
work.then(
|
|
46
|
+
() => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
resolve();
|
|
49
|
+
},
|
|
50
|
+
() => {
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
resolve();
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export function remoteBackend(handle: ProcessHandle): Promise<RemoteBackend> {
|
|
58
|
+
let buffered = '';
|
|
59
|
+
let openSettled = false;
|
|
60
|
+
let exited = false;
|
|
61
|
+
let closed = false;
|
|
62
|
+
let closePromise: Promise<void> | undefined;
|
|
63
|
+
let openError: Error | undefined;
|
|
64
|
+
let lastUnreachable: Error | undefined;
|
|
65
|
+
let nextId = 1;
|
|
66
|
+
let settleOpen!: {
|
|
67
|
+
resolve(backend: RemoteBackend): void;
|
|
68
|
+
reject(error: Error): void;
|
|
69
|
+
};
|
|
70
|
+
let settleEnded!: (error: Error | undefined) => void;
|
|
71
|
+
const opening = new Promise<RemoteBackend>((resolve, reject) => {
|
|
72
|
+
settleOpen = { resolve, reject };
|
|
73
|
+
});
|
|
74
|
+
const ended = new Promise<Error | undefined>((resolve) => {
|
|
75
|
+
settleEnded = resolve;
|
|
76
|
+
});
|
|
77
|
+
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
|
|
78
|
+
|
|
79
|
+
const resolveOpen = (backend: RemoteBackend) => {
|
|
80
|
+
if (openSettled) return;
|
|
81
|
+
openSettled = true;
|
|
82
|
+
settleOpen.resolve(backend);
|
|
83
|
+
};
|
|
84
|
+
const rejectOpen = (error: Error) => {
|
|
85
|
+
if (openSettled) return;
|
|
86
|
+
openSettled = true;
|
|
87
|
+
settleOpen.reject(error);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const finish = () => {
|
|
91
|
+
if (exited) return;
|
|
92
|
+
exited = true;
|
|
93
|
+
const error = lastUnreachable ?? unreachable();
|
|
94
|
+
rejectOpen(openError ?? error);
|
|
95
|
+
for (const waiting of pending.values()) waiting.reject(error);
|
|
96
|
+
pending.clear();
|
|
97
|
+
settleEnded(lastUnreachable);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const onLine = (line: string) => {
|
|
101
|
+
let parsed: unknown;
|
|
102
|
+
try {
|
|
103
|
+
parsed = JSON.parse(line);
|
|
104
|
+
} catch {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (!isRecord(parsed)) return;
|
|
108
|
+
if (parsed.event === 'open') {
|
|
109
|
+
if (parsed.ok !== true) {
|
|
110
|
+
openError = decodeError(parsed.error);
|
|
111
|
+
rejectOpen(openError);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (backend) resolveOpen(backend);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (typeof parsed.id !== 'number') return;
|
|
118
|
+
const waiting = pending.get(parsed.id);
|
|
119
|
+
if (!waiting) return;
|
|
120
|
+
pending.delete(parsed.id);
|
|
121
|
+
if (parsed.error !== undefined) {
|
|
122
|
+
const error = decodeError(parsed.error);
|
|
123
|
+
if (codeOf(error) === 'storage_unreachable') lastUnreachable = error;
|
|
124
|
+
waiting.reject(error);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
waiting.resolve(decodeValue(parsed.result));
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const request = async (op: string, args: unknown[]): Promise<unknown> => {
|
|
131
|
+
if (exited) throw lastUnreachable ?? unreachable();
|
|
132
|
+
const id = nextId++;
|
|
133
|
+
const answered = new Promise<unknown>((resolve, reject) => {
|
|
134
|
+
pending.set(id, { resolve, reject });
|
|
135
|
+
});
|
|
136
|
+
// The process may end while the line is written: `finish` then rejects this before anyone awaits it.
|
|
137
|
+
answered.catch(() => {});
|
|
138
|
+
try {
|
|
139
|
+
await handle.write(lineOf(requestLine(id, op, args)));
|
|
140
|
+
} catch {
|
|
141
|
+
pending.delete(id);
|
|
142
|
+
const error = lastUnreachable ?? unreachable();
|
|
143
|
+
lastUnreachable = error;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
return answered;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const call = async <T>(op: string, args: unknown[]): Promise<T> => {
|
|
150
|
+
if (closed) throw closedError();
|
|
151
|
+
return (await request(op, args)) as T;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const backend: RemoteBackend = {
|
|
155
|
+
ended,
|
|
156
|
+
version: (id) => call<number | undefined>('version', [id]),
|
|
157
|
+
get: (id, key) => call<unknown>('get', [id, key]),
|
|
158
|
+
list: (id, filter?: Filter, page?: Page) => call<Entry[]>('list', [id, filter, page]),
|
|
159
|
+
count: (id, filter?: Filter) => call<number>('count', [id, filter]),
|
|
160
|
+
countBy: (id, path, keys, filter?: Filter) =>
|
|
161
|
+
call<Record<string, number>>('countBy', [id, path, keys, filter]),
|
|
162
|
+
groupBy: (id, path, filter?: Filter, options?: GroupOptions) =>
|
|
163
|
+
call<Group[]>('groupBy', [id, path, filter, options]),
|
|
164
|
+
index: (id, paths) => call<void>('index', [id, paths]),
|
|
165
|
+
searchable: (id, paths, options?: { trigram?: boolean }) =>
|
|
166
|
+
call<void>('searchable', [id, paths, options]),
|
|
167
|
+
write: (changes: Change[]) => call<void>('write', [changes]),
|
|
168
|
+
backup: (id) => call<void>('backup', [id]),
|
|
169
|
+
append: (id, versionNumber, stream, events, options?: { after?: number }) =>
|
|
170
|
+
call<number>('append', [id, versionNumber, stream, events, options]),
|
|
171
|
+
read: (id, stream, window?: LogWindow) => call<LogEvent[]>('read', [id, stream, window]),
|
|
172
|
+
last: (id, stream) => call<number>('last', [id, stream]),
|
|
173
|
+
streams: (id, page?: { after?: string; take?: number }) =>
|
|
174
|
+
call<LogStream[]>('streams', [id, page]),
|
|
175
|
+
purge: (id, stream, audit) => call<void>('purge', [id, stream, audit]),
|
|
176
|
+
attach: (id, stream, bytes: Uint8Array, type) =>
|
|
177
|
+
call<BlobRef>('attach', [id, stream, bytes, type]),
|
|
178
|
+
attachFile: (id, stream, path, type) => call<BlobRef>('attachFile', [id, stream, path, type]),
|
|
179
|
+
blob: (id, blob) => call<(BlobRef & { path: string }) | undefined>('blob', [id, blob]),
|
|
180
|
+
queryAudit: (query?: AuditQuery) =>
|
|
181
|
+
call<{ rows: AuditRow[]; next?: number }>('queryAudit', [query]),
|
|
182
|
+
auditActors: (entry) => call<AuditActor[]>('auditActors', [entry]),
|
|
183
|
+
auditObjects: (of) => call<AuditObject[]>('auditObjects', [of]),
|
|
184
|
+
pruneAudit: (before) => call<number>('pruneAudit', [before]),
|
|
185
|
+
sizes: () => call<{ file: string; bytes: number }[]>('sizes', []),
|
|
186
|
+
close: () => {
|
|
187
|
+
closePromise ??= (async () => {
|
|
188
|
+
closed = true;
|
|
189
|
+
if (!exited) {
|
|
190
|
+
const answered = request('close', []).then(
|
|
191
|
+
() => undefined,
|
|
192
|
+
() => undefined,
|
|
193
|
+
);
|
|
194
|
+
await Promise.race([within(answered, 5000), ended.then(() => undefined)]);
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
await handle.kill();
|
|
198
|
+
} catch {
|
|
199
|
+
// Already gone.
|
|
200
|
+
}
|
|
201
|
+
})();
|
|
202
|
+
return closePromise;
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
handle.onOutput((stream, chunk) => {
|
|
207
|
+
if (stream !== 'stdout') return;
|
|
208
|
+
buffered += chunk;
|
|
209
|
+
let at: number;
|
|
210
|
+
while ((at = buffered.indexOf('\n')) >= 0) {
|
|
211
|
+
const line = buffered.slice(0, at);
|
|
212
|
+
buffered = buffered.slice(at + 1);
|
|
213
|
+
onLine(line);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
void handle.exited
|
|
218
|
+
.then(
|
|
219
|
+
() => finish(),
|
|
220
|
+
() => finish(),
|
|
221
|
+
)
|
|
222
|
+
.catch(() => {});
|
|
223
|
+
|
|
224
|
+
return opening;
|
|
225
|
+
}
|