Repository navigation
Expand file tree
/
Copy pathplugin-databases.ts
More file actions
495 lines (483 loc) · 17.5 KB
/
Copy pathplugin-databases.ts
File metadata and controls
495 lines (483 loc) · 17.5 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import Sqlite from "better-sqlite3";
import {
Kysely,
PostgresDialect,
SqliteDialect,
sql,
OperationNodeTransformer,
TableNode,
type KyselyPlugin,
type Transaction,
} from "kysely";
import { Pool } from "pg";
import { createHash } from "node:crypto";
import { mkdirSync, existsSync, statSync, chmodSync } from "node:fs";
import { dirname, resolve } from "node:path";
import {
databaseConfig,
onDatabaseClose,
type DatabaseConfig,
} from "@db/connection.js";
import { currentSchemaTables } from "@db/introspection.js";
import { databaseRuntimeScope } from "@db/runtime-scope.js";
import { registerDriver, databaseDriver } from "@db/transactions.js";
import type { DB } from "@db/index.js";
import { createPluginStorageNamespace } from "./plugin-storage-namespaces.js";
export type PluginDatabaseConfig =
| { driver: "sqlite"; path: string }
| { driver: "postgres"; url: string | null; poolMax: number };
/** Fixed host diagnostics that can safely cross the plugin storage boundary. */
export class PluginDatabaseConfigurationError extends Error {
constructor(message: string) {
super(message);
this.name = "PluginDatabaseConfigurationError";
}
}
/** One host-managed business store, never a fallback to the core connection. */
export function pluginDatabaseConfig(
main: DatabaseConfig,
env: NodeJS.ProcessEnv = process.env,
): PluginDatabaseConfig {
if (
env.DOCA_PLUGIN_DATABASES_JSON !== undefined ||
env.DOCA_PLUGIN_DATABASE_DIR !== undefined
)
throw new Error(
"Per-plugin database configuration is obsolete; uninstall plugins using the previous host, then configure the shared plugin database and reinstall",
);
if (main.driver === "sqlite") {
if (
env.DOCA_PLUGIN_DATABASE_URL !== undefined ||
env.DOCA_PLUGIN_DATABASE_POOL_MAX !== undefined
)
throw new Error(
"PostgreSQL plugin database configuration requires PostgreSQL",
);
const path = env.DOCA_PLUGIN_DATABASE_PATH;
if (path !== undefined && !path.trim())
throw new Error("DOCA_PLUGIN_DATABASE_PATH must not be empty");
return {
driver: "sqlite",
path: path
? resolve(path)
: main.path === ":memory:"
? ":memory:"
: resolve(main.path) + ".plugins.db",
};
}
if (env.DOCA_PLUGIN_DATABASE_PATH !== undefined)
throw new Error("DOCA_PLUGIN_DATABASE_PATH requires SQLite");
const poolMax = Number(env.DOCA_PLUGIN_DATABASE_POOL_MAX ?? 4);
if (!Number.isInteger(poolMax) || poolMax < 1 || poolMax > 20)
throw new Error(
"DOCA_PLUGIN_DATABASE_POOL_MAX must be an integer from 1 to 20",
);
if (env.DOCA_PLUGIN_DATABASE_URL === undefined)
return { driver: "postgres", url: null, poolMax };
try {
const url = new URL(env.DOCA_PLUGIN_DATABASE_URL);
if (
!["postgres:", "postgresql:"].includes(url.protocol) ||
!url.username ||
!url.pathname.slice(1) ||
url.searchParams.has("options") ||
url.hash
)
throw new Error("Invalid target");
return { driver: "postgres", url: url.href, poolMax };
} catch {
throw new Error(
"DOCA_PLUGIN_DATABASE_URL must be a PostgreSQL URL for the shared plugin database",
);
}
}
export function configurePluginDatabases(db: DB, config: PluginDatabaseConfig) {
const scope = databaseRuntimeScope(db);
if (scope.has("plugin.databases"))
throw new Error("Plugin databases are already configured");
scope.set("plugin.database.config", config);
}
export function pluginDatabaseNamespace(id: string) {
createPluginStorageNamespace(id);
return "plugin_" + createHash("sha256").update(id).digest("hex").slice(0, 56);
}
const rootMarker = "_doca_shared_plugin_database";
type Scope = {
base: Kysely<any>;
driver: "sqlite" | "postgres";
name: string;
prefix: string;
};
const scopes = new WeakMap<object, Scope>();
class PrefixTransformer extends OperationNodeTransformer {
constructor(private readonly prefix: string) {
super();
}
protected override transformTable(node: TableNode): TableNode {
if (node.table.schema)
throw new Error("Plugin tables cannot select a database schema");
return TableNode.create(this.prefix + node.table.identifier.name);
}
}
function scoped(db: Kysely<any>, id: string) {
const name = pluginDatabaseNamespace(id),
prefix = name + "__",
driver = databaseDriver(db);
const transform = new PrefixTransformer(prefix);
const plugin: KyselyPlugin = {
transformQuery: ({ node, queryId }) =>
transform.transformNode(node, queryId),
transformResult: async ({ result }) => result,
};
const result =
driver === "postgres" ? db.withSchema(name) : db.withPlugin(plugin);
registerDriver(result, driver);
scopes.set(result, { base: db, driver, name, prefix });
return result;
}
export function pluginPhysicalTable(db: Kysely<any>, name: string) {
const scope = scopes.get(db);
if (!scope) throw new Error("Plugin database scope is unavailable");
return scope.driver === "sqlite" ? scope.prefix + name : name;
}
/** Scope metadata before validating/cleaning; other plugins' tables are never candidates. */
export async function pluginDatabaseTables(db: Kysely<any>) {
const scope = scopes.get(db);
if (!scope) throw new Error("Plugin database scope is unavailable");
if (scope.driver === "sqlite")
return (await currentSchemaTables(scope.base))
.filter((t) => t.name.startsWith(scope.prefix))
.map((t) => ({ ...t, name: t.name.slice(scope.prefix.length) }));
if (scope.base.isTransaction) return currentSchemaTables(scope.base);
return scope.base.transaction().execute(async (tx) => {
registerDriver(tx, "postgres");
await sql`select set_config('search_path', ${scope.name}, true)`.execute(
tx,
);
return currentSchemaTables(tx);
});
}
export class PluginDatabases {
private root: Promise<Kysely<any>> | undefined;
private handles = new Map<string, Kysely<any>>();
private required = new Map<string, boolean>();
private closed = false;
constructor(
private readonly core: DB,
readonly config: PluginDatabaseConfig,
) {}
async open(
id: string,
mustExist: boolean,
coreConnection: Kysely<any> = this.core,
): Promise<Kysely<any>> {
createPluginStorageNamespace(id);
const root = await this.shared(mustExist, coreConnection);
if (this.config.driver === "postgres" && mustExist) {
const exists = await sql<{
present: boolean;
}>`select exists(select 1 from pg_namespace where nspname = ${pluginDatabaseNamespace(id)}) as present`.execute(
root,
);
if (!exists.rows[0]!.present)
throw new Error(
"Plugin database namespace is missing; it will not be recreated",
);
}
this.required.set(id, mustExist);
const previous = this.handles.get(id);
if (previous) return previous;
const handle = scoped(root, id);
// All plugins share the root pool. Transaction-local search_path is reset by
// PostgreSQL at commit/rollback; concurrent plugins never inherit another scope.
handle.transaction = () => {
const builder = root.transaction(),
execute = builder.execute.bind(builder);
builder.execute = (run) =>
execute(async (tx) => {
registerDriver(tx, this.config.driver);
if (this.config.driver === "postgres") {
const name = pluginDatabaseNamespace(id);
const exists = await sql<{
present: boolean;
}>`select exists(select 1 from pg_namespace where nspname = ${name}) as present`.execute(
tx,
);
if (!exists.rows[0]!.present) {
if (this.required.get(id))
throw new Error(
"Plugin database namespace is missing; it will not be recreated",
);
try {
await tx.schema.createSchema(name).execute();
} catch (error) {
if ((error as { code?: string }).code === "42501")
throw new PluginDatabaseConfigurationError(
"Shared plugin database role requires CREATE on the plugin database to create plugin schemas; ask the database owner to grant it and retry",
);
throw error;
}
}
await sql`select set_config('search_path', ${name}, true)`.execute(
tx,
);
}
return run(scoped(tx, id) as Transaction<any>);
});
return builder;
};
this.handles.set(id, handle);
return handle;
}
async existing(id: string, coreConnection: Kysely<any>) {
if (
this.config.driver === "sqlite" &&
this.config.path !== ":memory:" &&
!existsSync(this.config.path)
)
return undefined;
if (
this.config.driver === "sqlite" &&
this.config.path === ":memory:" &&
!this.root
)
return undefined;
if (this.config.driver === "postgres" && !this.config.url) return undefined;
const root = await this.shared(false, coreConnection);
if (this.config.driver === "postgres") {
const exists = await sql<{
present: boolean;
}>`select exists(select 1 from pg_namespace where nspname = ${pluginDatabaseNamespace(id)}) as present`.execute(
root,
);
if (!exists.rows[0]!.present) return undefined;
}
return this.open(id, false, coreConnection);
}
private async shared(mustExist: boolean, coreConnection: Kysely<any>) {
if (this.closed) throw new Error("Plugin databases are closed");
if (
this.config.driver === "sqlite" &&
this.config.path !== ":memory:" &&
!existsSync(this.config.path) &&
(mustExist || this.root)
)
throw new Error(
"Shared plugin database file is missing; it will not be recreated",
);
if (!this.root) {
// Assign the promise before the first await, so different plugins share one pool.
this.root = (async () => {
const rows = await coreConnection
.selectFrom("plugin_storage_namespaces")
.select("definition")
.execute();
const recorded = rows.some((row) => {
try {
const d = JSON.parse(row.definition ?? "null");
return d?.storageVersion === 3 && d.schema !== null;
} catch {
return false;
}
});
return this.connect(mustExist || recorded, coreConnection);
})().catch((error) => {
this.root = undefined;
throw error;
});
}
return this.root;
}
private async connect(mustExist: boolean, coreConnection: Kysely<any>) {
let db: Kysely<any>, sqlite: Sqlite.Database | undefined;
if (this.config.driver === "sqlite") {
const path = this.config.path,
main = databaseConfig(this.core);
if (
main.driver !== "sqlite" ||
(path !== ":memory:" && resolve(path) === resolve(main.path))
)
throw new Error(
"Shared plugin database must be separate from the core database",
);
if (
path !== ":memory:" &&
main.path !== ":memory:" &&
existsSync(path) &&
existsSync(main.path)
) {
const target = statSync(path),
core = statSync(main.path);
if (target.dev === core.dev && target.ino === core.ino)
throw new Error(
"Shared plugin database must be separate from the core database",
);
}
if (path !== ":memory:")
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
sqlite = new Sqlite(path, {
fileMustExist: mustExist && path !== ":memory:",
});
sqlite.pragma("foreign_keys = ON");
sqlite.pragma("busy_timeout = 5000");
sqlite.pragma("synchronous = FULL");
db = new Kysely<any>({
dialect: new SqliteDialect({ database: sqlite }),
});
registerDriver(db, "sqlite");
} else {
if (!this.config.url)
throw new PluginDatabaseConfigurationError(
"Configure DOCA_PLUGIN_DATABASE_URL once for all SQL plugins",
);
const pool = new Pool({
connectionString: this.config.url,
max: this.config.poolMax,
options: "-csearch_path=public",
connectionTimeoutMillis: 5000,
});
pool.on("error", () => {
if (!this.closed)
process.emitWarning("Shared plugin database connection lost");
});
db = new Kysely<any>({ dialect: new PostgresDialect({ pool }) });
registerDriver(db, "postgres");
try {
const identity = (
await sql<{
database: string;
address: string | null;
port: number | null;
}>`select current_database() as database, inet_server_addr()::text as address, inet_server_port() as port`.execute(
db,
)
).rows[0]!;
const core = (
await sql<{
database: string;
address: string | null;
port: number | null;
}>`select current_database() as database, inet_server_addr()::text as address, inet_server_port() as port`.execute(
coreConnection,
)
).rows[0]!;
// Account privileges belong to the operator. Only the business database
// target must remain separate from core, including for shared/admin logins.
if (
core.address === identity.address &&
core.port === identity.port &&
core.database === identity.database
)
throw new PluginDatabaseConfigurationError(
"Shared plugin database must be separate from the core database",
);
} catch (error) {
await db.destroy();
throw error;
}
}
try {
await db.transaction().execute(async (tx) => {
registerDriver(tx, this.config.driver);
if (this.config.driver === "postgres")
await sql`select pg_advisory_xact_lock(741093216)`.execute(tx);
const tables = await currentSchemaTables(tx);
// SQLite also contains prefixed business tables. The global marker must
// already exist before any of those can have been created by this host.
const marker = tables.find((t) => t.name === rootMarker);
if (!marker) {
if (mustExist || tables.length)
throw new Error(
"Shared plugin database is missing or contains unknown tables; no data was changed",
);
if (this.config.driver === "postgres") {
const schemas = await sql<{
name: string;
}>`select nspname as name from pg_namespace where nspname !~ '^pg_' and nspname not in ('public','information_schema')`.execute(
tx,
);
if (schemas.rows.length)
throw new Error(
"Shared plugin database contains unknown schemas; no data was changed",
);
}
try {
await tx.schema
.createTable(rootMarker)
.addColumn("id", "text", (c) => c.notNull().primaryKey())
.addColumn("storage_version", "integer", (c) => c.notNull())
.execute();
} catch (error) {
if (
this.config.driver === "postgres" &&
["42501", "3F000"].includes(
(error as { code?: string }).code ?? "",
)
)
throw new PluginDatabaseConfigurationError(
"Shared plugin database role requires USAGE and CREATE on schema public in the plugin database to initialize the shared marker; ask the database owner to grant them and retry",
);
throw error;
}
await tx
.insertInto(rootMarker)
.values({ id: "shared", storage_version: 3 })
.execute();
} else {
if (
marker.columns.length !== 2 ||
!marker.columns.some((c) => c.name === "id") ||
!marker.columns.some((c) => c.name === "storage_version")
)
throw new Error("Shared plugin database marker is invalid");
const rows = await tx.selectFrom(rootMarker).selectAll().execute();
if (
rows.length !== 1 ||
rows[0]?.id !== "shared" ||
rows[0]?.storage_version !== 3
)
throw new Error("Shared plugin database format is unsupported");
if (
tables.some(
(t) =>
t.name !== rootMarker &&
(this.config.driver === "postgres" ||
!/^plugin_[a-f0-9]{56}__/.test(t.name)),
)
)
throw new Error("Shared plugin database contains unknown tables");
}
});
if (sqlite && this.config.driver === "sqlite") {
sqlite.pragma("journal_mode = WAL");
if (this.config.path !== ":memory:") chmodSync(this.config.path, 0o600);
}
return db;
} catch (error) {
await db.destroy();
throw error;
}
}
async close() {
this.closed = true;
this.handles.clear();
const root = await this.root?.catch(() => undefined);
this.root = undefined;
await root?.destroy();
}
}
export function pluginDatabases(db: DB) {
const scope = databaseRuntimeScope(db);
let host = scope.get("plugin.databases") as PluginDatabases | undefined;
if (!host) {
const config = scope.get("plugin.database.config") as
PluginDatabaseConfig | undefined;
host = new PluginDatabases(
db,
config ?? pluginDatabaseConfig(databaseConfig(db)),
);
scope.set("plugin.databases", host);
onDatabaseClose(db, () => host!.close());
}
return host;
}