@bridgebrew/storage-postgres 0.0.0-stage → 0.0.3

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/server.ts ADDED
@@ -0,0 +1,473 @@
1
+ // Postgres storage (research-042 S1): keeps the workspace's data in one Postgres database, through a proxy process of
2
+ // its own (`./proxy.ts`), which alone holds the connection string. The plugin opens it from the `connection` setting,
3
+ // provides the backend as `storageBackend`, and withdraws it when the database cannot be reached (storage stops
4
+ // cleanly), then retries: 1 s, 5 s, 30 s, 30 s… Each cause is reported in the status (`attention`, research-046/047)
5
+ // until the backend is provided: an empty setting (`no_connection`) and a refused login (`auth_refused`) open the
6
+ // setting, a lease held by another Bridge (`lease_held`) waits for Take over (the toast runs the settings action
7
+ // `take-over`), an unreachable database (`unreachable`) heals on its own and toasts nothing. A connection string that
8
+ // does not check (`invalid_connection`, opens the setting), or whose login is refused, is not retried. `POST /test` checks the string it is sent, or the saved one when sent none (Test and save with nothing edited), `POST /take-over` opens it here.
9
+ import { hostname } from 'node:os';
10
+ import { dirname } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import type { Context } from 'cordis';
13
+ import type { Backend } from '@bridge/storage';
14
+ import type {} from '@bridge/worker-runtime/workspace';
15
+ import { isRecord } from './protocol.ts';
16
+ import { remoteBackend, type RemoteBackend } from './remote.ts';
17
+
18
+ declare module 'cordis' {
19
+ interface Context {
20
+ storageBackend: Backend;
21
+ }
22
+ }
23
+
24
+ export const name = 'storage-postgres';
25
+ export const inject = ['workspace', 'nodes', 'router', 'processes'];
26
+
27
+ /** A settings value that is a secret, as the host writes it (`secrets.ts`). */
28
+ const marker = /^\[secret:[a-z0-9_][a-z0-9_-]*\/[A-Za-z0-9_-]{8,64}\]$/;
29
+ const retryDelays = [1000, 5000, 30_000];
30
+
31
+ type Setting =
32
+ | { kind: 'empty' }
33
+ | { kind: 'plain'; value: string }
34
+ | { kind: 'secret'; value: string };
35
+
36
+ const fieldOf = (cause: unknown, key: string): string | number | undefined => {
37
+ if (!(cause instanceof Error)) return undefined;
38
+ const value: unknown = Object.getOwnPropertyDescriptor(cause, key)?.value;
39
+ return typeof value === 'string' || typeof value === 'number' ? value : undefined;
40
+ };
41
+
42
+ const codeOf = (cause: unknown) => {
43
+ const code = fieldOf(cause, 'code');
44
+ return typeof code === 'string' ? code : undefined;
45
+ };
46
+
47
+ const messageOf = (cause: unknown) =>
48
+ cause instanceof Error ? cause.message : typeof cause === 'string' ? cause : 'unknown error';
49
+
50
+ const sinceText = (since: string | number | undefined) => {
51
+ if (typeof since === 'number') return new Date(since).toISOString();
52
+ return since ?? 'an unknown time';
53
+ };
54
+
55
+ const emptyError = () =>
56
+ Object.assign(
57
+ new Error(
58
+ 'the connection setting is empty: enter a Postgres connection string in the Postgres storage settings',
59
+ ),
60
+ { code: 'invalid_connection' },
61
+ );
62
+
63
+ const plainError = () =>
64
+ Object.assign(
65
+ new Error('the connection setting is saved as plain text: enter it again and save'),
66
+ { code: 'invalid_connection' },
67
+ );
68
+
69
+ /** The attention an empty connection setting reports, until the backend is provided. */
70
+ const noConnection = {
71
+ code: 'no_connection',
72
+ severity: 'error',
73
+ recovery: 'user',
74
+ message: 'Postgres storage: no connection',
75
+ resolved: 'Postgres storage: connected',
76
+ fix: { setting: 'connection' },
77
+ } as const;
78
+
79
+ /** A machine's name as the attention shows it: cut at 64 characters, so its message and confirm stay within Bridge's
80
+ * limits (500 and 300) whatever the host is called. */
81
+ const shown = (machine: string) => (machine.length > 64 ? `${machine.slice(0, 63)}…` : machine);
82
+
83
+ /** Another Bridge holds the lease: only Take over (or that Bridge closing) gets it here. */
84
+ export const leaseHeld = (name: string, since: string, machine = shown(name)) => ({
85
+ code: 'lease_held',
86
+ severity: 'error' as const,
87
+ recovery: 'user' as const,
88
+ message: `Postgres storage: open on ${machine} since ${since}`,
89
+ resolved: 'Postgres storage: opened here',
90
+ fix: {
91
+ action: 'take-over',
92
+ label: 'Take over',
93
+ confirm: `Take over from ${machine}? Bridge there stops writing to this database.`,
94
+ },
95
+ });
96
+
97
+ /** Postgres refused the login: the connection string's user or password is wrong. */
98
+ const authRefused = {
99
+ code: 'auth_refused',
100
+ severity: 'error',
101
+ recovery: 'user',
102
+ message: 'Postgres storage: login refused',
103
+ resolved: 'Postgres storage: connected',
104
+ fix: { setting: 'connection' },
105
+ } as const;
106
+
107
+ /** The connection string does not check (or is plain text): not retried, the user fixes it. Its details stay in the
108
+ * logs, never in the status, so nothing of the string can show there. */
109
+ const invalidConnection = {
110
+ code: 'invalid_connection',
111
+ severity: 'error',
112
+ recovery: 'user',
113
+ message: 'Postgres storage: invalid connection string',
114
+ resolved: 'Postgres storage: connected',
115
+ fix: { setting: 'connection' },
116
+ } as const;
117
+
118
+ /** The database does not answer: retried on its own, recorded in Health, no toast. */
119
+ const unreachable = (error: Error) => ({
120
+ code: 'unreachable',
121
+ severity: 'warning' as const,
122
+ recovery: 'automatic' as const,
123
+ message: `Postgres storage: database unreachable, retrying (${error.message.slice(0, 400)})`,
124
+ resolved: 'Postgres storage: connected',
125
+ });
126
+
127
+ interface Live {
128
+ backend: RemoteBackend;
129
+ release: () => void;
130
+ closedByUs: boolean;
131
+ }
132
+
133
+ interface TestAnswer {
134
+ ok: boolean;
135
+ major?: number;
136
+ kind?: string;
137
+ machine?: string;
138
+ since?: number;
139
+ error?: string;
140
+ hint?: string;
141
+ }
142
+
143
+ export function apply(ctx: Context) {
144
+ const logger = ctx.logger(name);
145
+ const script = fileURLToPath(new URL('./proxy.ts', import.meta.url));
146
+ let current: Live | undefined;
147
+ let timer: ReturnType<typeof setTimeout> | undefined;
148
+ let disposed = false;
149
+ let generation = 0;
150
+ let attempts = 0;
151
+ let takeover = false;
152
+
153
+ const readSetting = (): Setting => {
154
+ const value: unknown = ctx.nodes.settings(name, 'root')?.values.connection?.value;
155
+ const raw =
156
+ typeof value === 'string'
157
+ ? value
158
+ : isRecord(value) && typeof value.value === 'string'
159
+ ? value.value
160
+ : '';
161
+ if (raw.trim() === '') return { kind: 'empty' };
162
+ if (!marker.test(raw)) return { kind: 'plain', value: raw };
163
+ return { kind: 'secret', value: raw };
164
+ };
165
+
166
+ /** The timeout and read connections the settings give, as the proxy's environment; a missing or bad one: its default. */
167
+ const tuning = (): Record<string, string> => {
168
+ const values: unknown = ctx.nodes.settings(name, 'root')?.values;
169
+ const integer = (key: string, min: number, max: number) => {
170
+ // A resolved setting is `{ value, origin }`, as `connection` is read above.
171
+ const field: unknown = isRecord(values) ? values[key] : undefined;
172
+ const value = isRecord(field) ? field.value : undefined;
173
+ return typeof value === 'number' &&
174
+ Number.isSafeInteger(value) &&
175
+ value >= min &&
176
+ value <= max
177
+ ? String(value)
178
+ : undefined;
179
+ };
180
+ const timeoutMs = integer('timeoutMs', 100, 86_400_000);
181
+ const readConnections = integer('readConnections', 1, 50);
182
+ return {
183
+ ...(timeoutMs !== undefined && { BRIDGE_STORAGE_TIMEOUT_MS: timeoutMs }),
184
+ ...(readConnections !== undefined && { BRIDGE_STORAGE_READ_CONNECTIONS: readConnections }),
185
+ };
186
+ };
187
+
188
+ const spawn = (env: Record<string, string>) =>
189
+ ctx.processes.spawn(ctx, {
190
+ command: process.execPath,
191
+ args: [script],
192
+ cwd: dirname(script),
193
+ env,
194
+ });
195
+
196
+ const stopCurrent = async () => {
197
+ const live = current;
198
+ current = undefined;
199
+ if (!live) return;
200
+ live.closedByUs = true;
201
+ live.release();
202
+ await live.backend.close().catch(() => {});
203
+ };
204
+
205
+ const retry = (token: number) => {
206
+ if (disposed || token !== generation || timer !== undefined) return;
207
+ const delay = retryDelays[Math.min(attempts, retryDelays.length - 1)] ?? 30_000;
208
+ attempts += 1;
209
+ timer = setTimeout(() => {
210
+ timer = undefined;
211
+ void attempt(token).catch((cause: unknown) => {
212
+ logger.warn(messageOf(cause));
213
+ retry(token);
214
+ });
215
+ }, delay);
216
+ };
217
+
218
+ const failed = (error: Error, token: number) => {
219
+ const code = codeOf(error);
220
+ if (code === 'storage_leased') {
221
+ const machine = String(fieldOf(error, 'machine') ?? 'another machine');
222
+ const since = sinceText(fieldOf(error, 'since'));
223
+ logger.warn(
224
+ `this workspace is open on ${machine} since ${since}: press Take over in the Postgres storage settings to open it here`,
225
+ );
226
+ ctx.workspace.attention(ctx, leaseHeld(machine, since));
227
+ return;
228
+ }
229
+ if (code === 'storage_auth_refused') {
230
+ logger.warn(error.message);
231
+ ctx.workspace.attention(ctx, authRefused);
232
+ return;
233
+ }
234
+ if (code === 'invalid_connection') {
235
+ logger.warn(error.message);
236
+ ctx.workspace.attention(ctx, invalidConnection);
237
+ return;
238
+ }
239
+ logger.warn(error.message);
240
+ ctx.workspace.attention(ctx, unreachable(error));
241
+ retry(token);
242
+ };
243
+
244
+ const attempt = async (token: number): Promise<Error | undefined> => {
245
+ if (disposed || token !== generation) return new Error('the storage settings changed');
246
+ const setting = readSetting();
247
+ if (setting.kind === 'empty') {
248
+ const error = emptyError();
249
+ logger.warn(error.message);
250
+ // Only the user gets out of it (research-046): one toast, its waiting plugins folded under it.
251
+ ctx.workspace.attention(ctx, noConnection);
252
+ return error;
253
+ }
254
+ if (setting.kind === 'plain') {
255
+ const error = plainError();
256
+ logger.warn(error.message);
257
+ // An earlier cause (a lease, a login, an unreachable database) no longer stands: the setting itself is wrong now.
258
+ ctx.workspace.attention(ctx, invalidConnection);
259
+ return error;
260
+ }
261
+ const tuned = tuning();
262
+ logger.info(
263
+ `opening: ${tuned.BRIDGE_STORAGE_READ_CONNECTIONS ?? 'default'} read connections, query timeout ${tuned.BRIDGE_STORAGE_TIMEOUT_MS ?? 'default'} ms`,
264
+ );
265
+ let handle;
266
+ try {
267
+ handle = await spawn({
268
+ BRIDGE_STORAGE_URL: setting.value,
269
+ BRIDGE_STORAGE_DATA_DIR: ctx.workspace.dataDir,
270
+ BRIDGE_STORAGE_MACHINE: hostname(),
271
+ ...tuned,
272
+ ...(takeover ? { BRIDGE_STORAGE_TAKE_OVER: '1' } : {}),
273
+ });
274
+ } catch (cause) {
275
+ const error = cause instanceof Error ? cause : new Error(messageOf(cause));
276
+ if (token === generation && !disposed) failed(error, token);
277
+ return error;
278
+ }
279
+ let backend: RemoteBackend;
280
+ try {
281
+ backend = await remoteBackend(handle);
282
+ } catch (cause) {
283
+ const error = cause instanceof Error ? cause : new Error(messageOf(cause));
284
+ await handle.kill().catch(() => {});
285
+ if (token === generation && !disposed) failed(error, token);
286
+ return error;
287
+ }
288
+ if (disposed || token !== generation) {
289
+ await backend.close().catch(() => {});
290
+ return new Error('the storage settings changed');
291
+ }
292
+ attempts = 0;
293
+ takeover = false;
294
+ const release = ctx.provide('storageBackend', backend);
295
+ ctx.workspace.attention(ctx, undefined);
296
+ const live: Live = { backend, release, closedByUs: false };
297
+ current = live;
298
+ void backend.ended
299
+ .then((reason) => {
300
+ if (live.closedByUs || disposed || token !== generation) return;
301
+ if (current === live) current = undefined;
302
+ live.release();
303
+ const error =
304
+ reason ??
305
+ Object.assign(new Error('the Postgres storage process ended'), {
306
+ code: 'storage_unreachable',
307
+ });
308
+ logger.warn(error.message);
309
+ ctx.workspace.attention(ctx, unreachable(error));
310
+ retry(token);
311
+ })
312
+ .catch(() => {});
313
+ return undefined;
314
+ };
315
+
316
+ const restart = async (take: boolean): Promise<Error | undefined> => {
317
+ generation += 1;
318
+ const token = generation;
319
+ if (timer !== undefined) {
320
+ clearTimeout(timer);
321
+ timer = undefined;
322
+ }
323
+ attempts = 0;
324
+ takeover = take;
325
+ await stopCurrent();
326
+ return attempt(token);
327
+ };
328
+
329
+ const testOnce = async (value: string): Promise<TestAnswer> => {
330
+ let handle;
331
+ try {
332
+ handle = await spawn({
333
+ BRIDGE_STORAGE_TEST: '1',
334
+ BRIDGE_STORAGE_URL: value,
335
+ BRIDGE_STORAGE_DATA_DIR: ctx.workspace.dataDir,
336
+ BRIDGE_STORAGE_MACHINE: hostname(),
337
+ });
338
+ } catch (cause) {
339
+ return { ok: false, error: messageOf(cause) };
340
+ }
341
+ return new Promise<TestAnswer>((resolve) => {
342
+ let done = false;
343
+ let buffered = '';
344
+ let unsubscribe: (() => void) | undefined;
345
+ // A database that accepts the connection and then never answers: the test ends anyway.
346
+ const deadline = setTimeout(
347
+ () => finish({ ok: false, error: 'the database did not answer within 30 s' }),
348
+ 30_000,
349
+ );
350
+ const finish = (answer: TestAnswer) => {
351
+ if (done) return;
352
+ done = true;
353
+ clearTimeout(deadline);
354
+ unsubscribe?.();
355
+ resolve(answer);
356
+ void handle.kill().catch(() => {});
357
+ };
358
+ unsubscribe = handle.onOutput((stream, chunk) => {
359
+ if (stream !== 'stdout') return;
360
+ buffered += chunk;
361
+ let at: number;
362
+ while ((at = buffered.indexOf('\n')) >= 0) {
363
+ const line = buffered.slice(0, at);
364
+ buffered = buffered.slice(at + 1);
365
+ let parsed: unknown;
366
+ try {
367
+ parsed = JSON.parse(line);
368
+ } catch {
369
+ continue;
370
+ }
371
+ if (!isRecord(parsed) || parsed.event !== 'test') continue;
372
+ if (
373
+ parsed.ok === true &&
374
+ typeof parsed.major === 'number' &&
375
+ typeof parsed.kind === 'string'
376
+ )
377
+ finish({
378
+ ok: true,
379
+ major: parsed.major,
380
+ kind: parsed.kind,
381
+ ...(typeof parsed.machine === 'string' && { machine: parsed.machine }),
382
+ ...(typeof parsed.since === 'number' && { since: parsed.since }),
383
+ });
384
+ else if (parsed.ok === false && typeof parsed.error === 'string')
385
+ finish({
386
+ ok: false,
387
+ error: parsed.error,
388
+ ...(typeof parsed.hint === 'string' && { hint: parsed.hint }),
389
+ });
390
+ }
391
+ });
392
+ handle.exited
393
+ .then(() => {
394
+ if (!done) finish({ ok: false, error: 'the connection test ended without an answer' });
395
+ })
396
+ .catch(() => {});
397
+ });
398
+ };
399
+
400
+ const bodyOf = (body: Uint8Array | undefined): unknown => {
401
+ if (!body?.byteLength) return undefined;
402
+ try {
403
+ return JSON.parse(new TextDecoder().decode(body));
404
+ } catch {
405
+ return undefined;
406
+ }
407
+ };
408
+ const valueOf = (sent: unknown): string | undefined => {
409
+ if (typeof sent === 'string') return sent;
410
+ return isRecord(sent) && typeof sent.value === 'string' ? sent.value : undefined;
411
+ };
412
+ const refuse = (error: Error) => ({
413
+ ok: false as const,
414
+ error: error.message,
415
+ });
416
+
417
+ ctx.router.route(ctx, {
418
+ method: 'POST',
419
+ path: '/test',
420
+ agent: false,
421
+ handle: async (request) => {
422
+ // No entry (Save and test connection): the saved setting.
423
+ const sent = bodyOf(request.body);
424
+ const setting = readSetting();
425
+ const value =
426
+ sent === undefined ? (setting.kind === 'empty' ? undefined : setting.value) : valueOf(sent);
427
+ if (value === undefined || value.trim() === '') return refuse(emptyError());
428
+ if (!marker.test(value)) return refuse(plainError());
429
+ const answer = await testOnce(value);
430
+ if (answer.ok !== true)
431
+ return {
432
+ ok: false as const,
433
+ error: answer.error ?? 'the connection could not be tested',
434
+ ...(answer.hint === undefined ? {} : { hint: answer.hint }),
435
+ };
436
+ let message = `Connected to PostgreSQL ${answer.major ?? 0} (${answer.kind ?? 'Postgres'})`;
437
+ if (answer.machine !== undefined && answer.since !== undefined)
438
+ message += `, open on ${answer.machine} since ${sinceText(answer.since)}`;
439
+ return { ok: true as const, message };
440
+ },
441
+ });
442
+
443
+ ctx.router.route(ctx, {
444
+ method: 'POST',
445
+ path: '/take-over',
446
+ agent: false,
447
+ handle: async () => {
448
+ const setting = readSetting();
449
+ if (setting.kind === 'empty') return refuse(emptyError());
450
+ if (setting.kind === 'plain') return refuse(plainError());
451
+ const error = await restart(true);
452
+ if (error) return refuse(error);
453
+ return { ok: true as const, message: 'Opened here: the other Bridge can no longer write.' };
454
+ },
455
+ });
456
+
457
+ ctx.effect(() => async () => {
458
+ disposed = true;
459
+ generation += 1;
460
+ if (timer !== undefined) {
461
+ clearTimeout(timer);
462
+ timer = undefined;
463
+ }
464
+ await stopCurrent();
465
+ });
466
+
467
+ ctx.nodes.on(ctx, 'settings/changed', ({ plugin }: { plugin: string }) => {
468
+ if (plugin !== name || disposed) return;
469
+ void restart(false).catch((cause: unknown) => logger.warn(messageOf(cause)));
470
+ });
471
+
472
+ void restart(false).catch((cause: unknown) => logger.warn(messageOf(cause)));
473
+ }
@@ -0,0 +1,23 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDxDCCAqygAwIBAgIUbLxMod62P2ktCiAkxnKJwtE9VPYwDQYJKoZIhvcNAQEL
3
+ BQAwazELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5l
4
+ dyBDYXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJh
5
+ c2UgUm9vdCAyMDIxIENBMB4XDTIxMDQyODEwNTY1M1oXDTMxMDQyNjEwNTY1M1ow
6
+ azELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5ldyBD
7
+ YXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJhc2Ug
8
+ Um9vdCAyMDIxIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqQXW
9
+ QyHOB+qR2GJobCq/CBmQ40G0oDmCC3mzVnn8sv4XNeWtE5XcEL0uVih7Jo4Dkx1Q
10
+ DmGHBH1zDfgs2qXiLb6xpw/CKQPypZW1JssOTMIfQppNQ87K75Ya0p25Y3ePS2t2
11
+ GtvHxNjUV6kjOZjEn2yWEcBdpOVCUYBVFBNMB4YBHkNRDa/+S4uywAoaTWnCJLUi
12
+ cvTlHmMw6xSQQn1UfRQHk50DMCEJ7Cy1RxrZJrkXXRP3LqQL2ijJ6F4yMfh+Gyb4
13
+ O4XajoVj/+R4GwywKYrrS8PrSNtwxr5StlQO8zIQUSMiq26wM8mgELFlS/32Uclt
14
+ NaQ1xBRizkzpZct9DwIDAQABo2AwXjALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFKjX
15
+ uXY32CztkhImng4yJNUtaUYsMB8GA1UdIwQYMBaAFKjXuXY32CztkhImng4yJNUt
16
+ aUYsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAB8spzNn+4VU
17
+ tVxbdMaX+39Z50sc7uATmus16jmmHjhIHz+l/9GlJ5KqAMOx26mPZgfzG7oneL2b
18
+ VW+WgYUkTT3XEPFWnTp2RJwQao8/tYPXWEJDc0WVQHrpmnWOFKU/d3MqBgBm5y+6
19
+ jB81TU/RG2rVerPDWP+1MMcNNy0491CTL5XQZ7JfDJJ9CCmXSdtTl4uUQnSuv/Qx
20
+ Cea13BX2ZgJc7Au30vihLhub52De4P/4gonKsNHYdbWjg7OWKwNv/zitGDVDB9Y2
21
+ CMTyZKG3XEu5Ghl1LEnI3QmEKsqaCLv12BnVjbkSeZsMnevJPs1Ye6TjjJwdik5P
22
+ o/bKiIz+Fq8=
23
+ -----END CERTIFICATE-----
package/tsconfig.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "./.bridge/tsconfig.json"
3
+ }