@jini-ai/db 0.6.19 → 0.7.0
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/CHANGELOG.md +19 -0
- package/dist/core/pg-types.d.ts +2 -0
- package/dist/data-modules/data-module.d.ts +90 -0
- package/dist/data-modules/data-module.js +851 -0
- package/dist/data-modules/disk-headroom.d.ts +11 -0
- package/dist/data-modules/disk-headroom.js +44 -0
- package/dist/data-modules/index.d.ts +18 -0
- package/dist/data-modules/index.js +17 -0
- package/dist/data-modules/migration-journal.d.ts +65 -0
- package/dist/data-modules/migration-journal.js +90 -0
- package/dist/data-modules/migration-recovery.d.ts +37 -0
- package/dist/data-modules/migration-recovery.js +62 -0
- package/dist/data-modules/plugin-identity.d.ts +43 -0
- package/dist/data-modules/plugin-identity.js +101 -0
- package/dist/data-modules/plugin-store.d.ts +43 -0
- package/dist/data-modules/plugin-store.js +6 -0
- package/dist/data-modules/restore.d.ts +5 -0
- package/dist/data-modules/restore.js +42 -0
- package/dist/data-modules/snapshot.d.ts +57 -0
- package/dist/data-modules/snapshot.js +94 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.d.ts +2 -0
- package/dist/kernel/kernel-core.js +2 -0
- package/dist/kernel/postgres/driver.js +13 -0
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/session-lock.d.ts +40 -0
- package/dist/kernel/session-lock.js +48 -0
- package/package.json +14 -5
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type PluginStore } from "./plugin-store.js";
|
|
2
|
+
/**
|
|
3
|
+
* True when `dbPath` is one of SQLite's special non-file identifiers rather than a real path on
|
|
4
|
+
* disk, for any of which `path.dirname`/`path.basename` produce meaningless fragments:
|
|
5
|
+
* - the literal `:memory:` identifier (an anonymous, process-private in-memory database);
|
|
6
|
+
* - the empty string `""` (SQLite's OTHER special identifier — an anonymous, private on-disk temp
|
|
7
|
+
* database deleted when the connection closes; like `:memory:` it never has a stable path to
|
|
8
|
+
* snapshot to or restore from, so it gets the same no-op treatment);
|
|
9
|
+
* - a `file:` URI naming the same thing via SQLite's URI-filename syntax — either the path
|
|
10
|
+
* component is itself the `:memory:` token (e.g. `file::memory:?cache=shared`, the form SQLite's
|
|
11
|
+
* own docs use) or the query string sets `mode=memory` explicitly (e.g. `file:x?mode=memory`).
|
|
12
|
+
* See sqlite.org/inmemorydb.html and sqlite.org/uri.html.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isInMemoryDbPath({ dbPath }: {
|
|
15
|
+
dbPath: string;
|
|
16
|
+
}, _optional?: Record<string, never>): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Snapshot `db` (the SQLite database file at `dbPath`) to a sibling file and return its path — or
|
|
19
|
+
* `null` for an in-memory `dbPath` (see `isInMemoryDbPath` and this file's header), for which no
|
|
20
|
+
* snapshot is taken because no real file backs the database at all. The copy is the kernel's
|
|
21
|
+
* `backupTo`: on SQLite, the online backup API, a consistent whole-file copy of a live WAL db.
|
|
22
|
+
* Call it outside a transaction.
|
|
23
|
+
*/
|
|
24
|
+
export declare function snapshotDb(required: {
|
|
25
|
+
db: PluginStore;
|
|
26
|
+
dbPath: string;
|
|
27
|
+
label: string;
|
|
28
|
+
}, _optional?: Record<string, never>): Promise<string | null>;
|
|
29
|
+
/**
|
|
30
|
+
* Delete a snapshot whose recovery window has closed. Best-effort and never throws: this runs
|
|
31
|
+
* AFTER the migration it guarded is already committed, so a failure to unlink is untidy, not
|
|
32
|
+
* unsafe, and must not turn a successful migration into a reported failure.
|
|
33
|
+
*
|
|
34
|
+
* ADR-023 §4 amendment (2026-08-02). §4 specified taking the snapshot but never said when one
|
|
35
|
+
* stops being needed, so nothing ever deleted them: every plugin that declared tables left a
|
|
36
|
+
* whole-database copy on disk permanently, three at a time for a stock install (`store`,
|
|
37
|
+
* `newsletter`, `comments`), each the full size of `content.db`.
|
|
38
|
+
*
|
|
39
|
+
* The retention rule that replaces "forever" is not a heuristic or a count — it falls out of who
|
|
40
|
+
* reads these files. The only consumer is `migration-recovery.ts`, which acts exclusively on
|
|
41
|
+
* journal entries in a NON-terminal phase (see `findIncompleteJournalEntries`). The instant an
|
|
42
|
+
* entry reaches `COMMITTED`, its snapshot is unreachable by every code path that exists. Deleting
|
|
43
|
+
* it there removes zero recovery capability: the never-brick guarantee covers the window between
|
|
44
|
+
* "snapshot taken" and "DDL committed", and that window has closed.
|
|
45
|
+
*
|
|
46
|
+
* **A failed migration keeps its snapshot**, deliberately — the catch path leaves the entry
|
|
47
|
+
* non-terminal precisely so the next boot can restore from it, and §9 also wants it retained for
|
|
48
|
+
* operator forensics.
|
|
49
|
+
*
|
|
50
|
+
* `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
|
|
51
|
+
* row is history — it says what protected the change at the time, which stays true — so a path
|
|
52
|
+
* pointing at a since-deleted file is expected, not a dangling reference to repair.
|
|
53
|
+
*/
|
|
54
|
+
export declare function discardCommittedSnapshot({ snapshotPath }: {
|
|
55
|
+
snapshotPath: string;
|
|
56
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
57
|
+
//# sourceMappingURL=snapshot.d.ts.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file SPIKE — whole-file snapshot before a schema change (ADR-023 §4, §11).
|
|
3
|
+
*
|
|
4
|
+
* The never-brick reversibility anchor: core takes a whole-file snapshot via SQLite's ONLINE
|
|
5
|
+
* BACKUP API (not a raw `fs` copy — the backup API is WAL-safe on a live db) before ANY plugin
|
|
6
|
+
* DDL. If the change fails, the snapshot is the named recovery point (§9). Copy-on-write
|
|
7
|
+
* shadow-tables are a deferred >~1GB optimization (§11), not this.
|
|
8
|
+
*
|
|
9
|
+
* BUG FIX (2026-07-28): for an in-memory (or SQLite's other non-file) `dbPath`, this function is a
|
|
10
|
+
* no-op that returns `null` instead of attempting a file backup. This is NOT a weakened guarantee —
|
|
11
|
+
* it's recognizing the guarantee doesn't apply. §4's whole doctrine is "next-boot recovery from a
|
|
12
|
+
* crash" (see `data-module.ts`'s file header and `migration-recovery.ts`): for `:memory:`, there is
|
|
13
|
+
* no "next boot" — the database is discarded in full the instant the process ends, whether or not a
|
|
14
|
+
* snapshot exists. Before this fix, `path.dirname(":memory:")` resolved to `"."` (the process's
|
|
15
|
+
* current working directory) and `path.basename(":memory:")` resolved to the literal string
|
|
16
|
+
* `":memory:"`, so every call against an in-memory test db (used pervasively by this repo's test
|
|
17
|
+
* suite, e.g. `src/newsletter/__tests__/repo.contract.test.ts` via `openContentDb(":memory:")`)
|
|
18
|
+
* wrote a REAL, non-empty SQLite backup file literally named `:memory:.snapshot-<label>-<ts>` into
|
|
19
|
+
* the repo root — hundreds of MB accumulated across a single session's test runs.
|
|
20
|
+
*/
|
|
21
|
+
import fs from "node:fs/promises";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { pluginKernel } from "./plugin-store.js";
|
|
24
|
+
/**
|
|
25
|
+
* True when `dbPath` is one of SQLite's special non-file identifiers rather than a real path on
|
|
26
|
+
* disk, for any of which `path.dirname`/`path.basename` produce meaningless fragments:
|
|
27
|
+
* - the literal `:memory:` identifier (an anonymous, process-private in-memory database);
|
|
28
|
+
* - the empty string `""` (SQLite's OTHER special identifier — an anonymous, private on-disk temp
|
|
29
|
+
* database deleted when the connection closes; like `:memory:` it never has a stable path to
|
|
30
|
+
* snapshot to or restore from, so it gets the same no-op treatment);
|
|
31
|
+
* - a `file:` URI naming the same thing via SQLite's URI-filename syntax — either the path
|
|
32
|
+
* component is itself the `:memory:` token (e.g. `file::memory:?cache=shared`, the form SQLite's
|
|
33
|
+
* own docs use) or the query string sets `mode=memory` explicitly (e.g. `file:x?mode=memory`).
|
|
34
|
+
* See sqlite.org/inmemorydb.html and sqlite.org/uri.html.
|
|
35
|
+
*/
|
|
36
|
+
export function isInMemoryDbPath({ dbPath }, _optional = {}) {
|
|
37
|
+
if (dbPath === ":memory:" || dbPath === "")
|
|
38
|
+
return true;
|
|
39
|
+
if (!dbPath.startsWith("file:"))
|
|
40
|
+
return false;
|
|
41
|
+
const withoutScheme = dbPath.slice("file:".length);
|
|
42
|
+
const queryIndex = withoutScheme.indexOf("?");
|
|
43
|
+
const pathPart = queryIndex === -1 ? withoutScheme : withoutScheme.slice(0, queryIndex);
|
|
44
|
+
if (pathPart === ":memory:")
|
|
45
|
+
return true;
|
|
46
|
+
const queryPart = queryIndex === -1 ? "" : withoutScheme.slice(queryIndex + 1);
|
|
47
|
+
return new URLSearchParams(queryPart).get("mode") === "memory";
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Snapshot `db` (the SQLite database file at `dbPath`) to a sibling file and return its path — or
|
|
51
|
+
* `null` for an in-memory `dbPath` (see `isInMemoryDbPath` and this file's header), for which no
|
|
52
|
+
* snapshot is taken because no real file backs the database at all. The copy is the kernel's
|
|
53
|
+
* `backupTo`: on SQLite, the online backup API, a consistent whole-file copy of a live WAL db.
|
|
54
|
+
* Call it outside a transaction.
|
|
55
|
+
*/
|
|
56
|
+
export async function snapshotDb(required, _optional = {}) {
|
|
57
|
+
const { db, dbPath, label } = required;
|
|
58
|
+
if (isInMemoryDbPath({ dbPath }))
|
|
59
|
+
return null;
|
|
60
|
+
const dir = path.dirname(dbPath);
|
|
61
|
+
const base = path.basename(dbPath);
|
|
62
|
+
const snapshotPath = path.join(dir, `${base}.snapshot-${label}-${Date.now()}`);
|
|
63
|
+
await pluginKernel({ store: db }).backupTo(snapshotPath);
|
|
64
|
+
return snapshotPath;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Delete a snapshot whose recovery window has closed. Best-effort and never throws: this runs
|
|
68
|
+
* AFTER the migration it guarded is already committed, so a failure to unlink is untidy, not
|
|
69
|
+
* unsafe, and must not turn a successful migration into a reported failure.
|
|
70
|
+
*
|
|
71
|
+
* ADR-023 §4 amendment (2026-08-02). §4 specified taking the snapshot but never said when one
|
|
72
|
+
* stops being needed, so nothing ever deleted them: every plugin that declared tables left a
|
|
73
|
+
* whole-database copy on disk permanently, three at a time for a stock install (`store`,
|
|
74
|
+
* `newsletter`, `comments`), each the full size of `content.db`.
|
|
75
|
+
*
|
|
76
|
+
* The retention rule that replaces "forever" is not a heuristic or a count — it falls out of who
|
|
77
|
+
* reads these files. The only consumer is `migration-recovery.ts`, which acts exclusively on
|
|
78
|
+
* journal entries in a NON-terminal phase (see `findIncompleteJournalEntries`). The instant an
|
|
79
|
+
* entry reaches `COMMITTED`, its snapshot is unreachable by every code path that exists. Deleting
|
|
80
|
+
* it there removes zero recovery capability: the never-brick guarantee covers the window between
|
|
81
|
+
* "snapshot taken" and "DDL committed", and that window has closed.
|
|
82
|
+
*
|
|
83
|
+
* **A failed migration keeps its snapshot**, deliberately — the catch path leaves the entry
|
|
84
|
+
* non-terminal precisely so the next boot can restore from it, and §9 also wants it retained for
|
|
85
|
+
* operator forensics.
|
|
86
|
+
*
|
|
87
|
+
* `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
|
|
88
|
+
* row is history — it says what protected the change at the time, which stays true — so a path
|
|
89
|
+
* pointing at a since-deleted file is expected, not a dangling reference to repair.
|
|
90
|
+
*/
|
|
91
|
+
export async function discardCommittedSnapshot({ snapshotPath }, _optional = {}) {
|
|
92
|
+
await fs.rm(snapshotPath, { force: true }).catch(() => { });
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=snapshot.js.map
|
package/dist/kernel/index.d.ts
CHANGED
|
@@ -12,4 +12,5 @@ export { databaseFile, readSchemaShape, type SchemaShape, type TableShape } from
|
|
|
12
12
|
export { renderDatabaseTypes } from "./typegen.js";
|
|
13
13
|
export { outsideTransactionOf, StorageOpError, StorageOpNotSupportedError, type StorageOps, verifyLedgerReadBack, } from "./ops.js";
|
|
14
14
|
export { postgresLockKey } from "./postgres-lock.js";
|
|
15
|
+
export { withKernelSessionLock, kernelSessionPoolMax } from "./session-lock.js";
|
|
15
16
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/kernel/index.js
CHANGED
|
@@ -12,4 +12,5 @@ export { databaseFile, readSchemaShape } from "./schema-shape.js";
|
|
|
12
12
|
export { renderDatabaseTypes } from "./typegen.js";
|
|
13
13
|
export { outsideTransactionOf, StorageOpError, StorageOpNotSupportedError, verifyLedgerReadBack, } from "./ops.js";
|
|
14
14
|
export { postgresLockKey } from "./postgres-lock.js";
|
|
15
|
+
export { withKernelSessionLock, kernelSessionPoolMax } from "./session-lock.js";
|
|
15
16
|
//# sourceMappingURL=index.js.map
|
|
@@ -22,6 +22,8 @@ export interface KernelDriver<DB> {
|
|
|
22
22
|
lockKey(tx: Kysely<DB>, key: string): Promise<void>;
|
|
23
23
|
/** Share one connection between all callers: take turns (see `turn-lock.ts`). */
|
|
24
24
|
oneConnection: boolean;
|
|
25
|
+
/** Native pooled drivers advertise capacity so session owners cannot consume the only connection. */
|
|
26
|
+
poolMax?: number;
|
|
25
27
|
/**
|
|
26
28
|
* The turn lock to take turns on, when several connections in this process open the SAME
|
|
27
29
|
* database (two better-sqlite3 handles on one file): they must take turns as one, or one
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { registerKernelSessionDatabase } from "./session-lock.js";
|
|
1
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
3
|
import { UnsupportedCapabilityError, } from "./port.js";
|
|
3
4
|
import { TurnLock } from "./turn-lock.js";
|
|
@@ -111,6 +112,7 @@ export function buildKernel(driver) {
|
|
|
111
112
|
assertAvailable: assertOwnedAvailable,
|
|
112
113
|
transaction: (work, optional = {}) => transaction(work, optional),
|
|
113
114
|
} });
|
|
115
|
+
registerKernelSessionDatabase({ kernel: kernel, database: driver.base, ...(driver.poolMax === undefined ? {} : { poolMax: driver.poolMax }) });
|
|
114
116
|
return kernel;
|
|
115
117
|
}
|
|
116
118
|
//# sourceMappingURL=kernel-core.js.map
|
|
@@ -28,6 +28,18 @@ export function openPostgresKernel(required, optional = {}) {
|
|
|
28
28
|
// idle cut) is evicted by the pool and reopened on next use; without a listener it would crash the
|
|
29
29
|
// process.
|
|
30
30
|
pool.on("error", (err) => console.warn('[postgres] idle pool connection dropped:', redactSecrets({ input: inspect(err) }, { redactPii: false })));
|
|
31
|
+
// Pool error listeners cover idle clients only. Session-owned workers hold a client for
|
|
32
|
+
// longer, so absorb its error event while the next query rejects and stops that owner.
|
|
33
|
+
const connected = new WeakSet();
|
|
34
|
+
const connect = pool.connect.bind(pool);
|
|
35
|
+
pool.connect = async () => {
|
|
36
|
+
const client = await connect();
|
|
37
|
+
if (!connected.has(client)) {
|
|
38
|
+
connected.add(client);
|
|
39
|
+
client.on?.("error", () => console.warn('[postgres] active pool connection dropped; its operation will stop.'));
|
|
40
|
+
}
|
|
41
|
+
return client;
|
|
42
|
+
};
|
|
31
43
|
const base = new Kysely({ dialect: new PostgresDialect({ pool }) });
|
|
32
44
|
return buildKernel({
|
|
33
45
|
dialect: "postgres",
|
|
@@ -36,6 +48,7 @@ export function openPostgresKernel(required, optional = {}) {
|
|
|
36
48
|
ready: Promise.resolve(),
|
|
37
49
|
base,
|
|
38
50
|
oneConnection: false,
|
|
51
|
+
poolMax: optional.max ?? 10,
|
|
39
52
|
begin: (body) => base.transaction().execute((tx) => body(tx)),
|
|
40
53
|
lockKey: postgresLockKey,
|
|
41
54
|
close: () => base.destroy(),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { inheritKernelSessionDatabase } from "./session-lock.js";
|
|
1
2
|
import { inheritOwnedTransaction } from "./owned-transaction.js";
|
|
2
3
|
/**
|
|
3
4
|
* @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
|
|
@@ -18,6 +19,7 @@ export function scopeToSchema(kernel, schema) {
|
|
|
18
19
|
run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
|
|
19
20
|
};
|
|
20
21
|
inheritOwnedTransaction({ from: kernel, to: scoped });
|
|
22
|
+
inheritKernelSessionDatabase({ from: kernel, to: scoped });
|
|
21
23
|
return scoped;
|
|
22
24
|
}
|
|
23
25
|
//# sourceMappingURL=schema-scope.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type Kysely } from 'kysely';
|
|
2
|
+
import type { StorageKernel } from './port.js';
|
|
3
|
+
/** Private driver registration, kept separate from run() so the callback owns no transaction scope. */
|
|
4
|
+
export declare function registerKernelSessionDatabase({ kernel, database, poolMax }: {
|
|
5
|
+
kernel: StorageKernel<unknown>;
|
|
6
|
+
database: Kysely<unknown>;
|
|
7
|
+
poolMax?: number;
|
|
8
|
+
}, _optional?: Record<string, never>): void;
|
|
9
|
+
/** A schema wrapper uses the same pool and therefore the same database ownership scope. */
|
|
10
|
+
export declare function inheritKernelSessionDatabase({ from, to }: {
|
|
11
|
+
from: StorageKernel<unknown>;
|
|
12
|
+
to: StorageKernel<unknown>;
|
|
13
|
+
}, _optional?: Record<string, never>): void;
|
|
14
|
+
/** Read the registered pool capacity without reserving a connection; schema wrappers share it. O(1). */
|
|
15
|
+
export declare function kernelSessionPoolMax({ kernel }: {
|
|
16
|
+
kernel: StorageKernel<unknown>;
|
|
17
|
+
}, _optional?: Record<string, never>): number | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Run one background owner under a dedicated PostgreSQL session advisory lock.
|
|
20
|
+
* A competing owner returns acquired:false. The callback uses normal kernel transactions:
|
|
21
|
+
* a durable dispatch snapshot commits before provider HTTP, unlike a transaction advisory lock.
|
|
22
|
+
* The session is always unlocked/released after callback success or failure.
|
|
23
|
+
* The pool needs a spare connection (max >= 2) for callback transactions.
|
|
24
|
+
* assertOwned probes the held session before the next background cycle.
|
|
25
|
+
* @throws For non-pooled kernels, unknown wrappers, a pool smaller than two, or an existing transaction scope.
|
|
26
|
+
* @complexity Two O(1) lock queries and one reserved pool connection for the callback lifetime.
|
|
27
|
+
*/
|
|
28
|
+
export declare function withKernelSessionLock<T>({ kernel, key, run }: {
|
|
29
|
+
kernel: StorageKernel<unknown>;
|
|
30
|
+
key: string;
|
|
31
|
+
run: (lease: {
|
|
32
|
+
assertOwned(): Promise<void>;
|
|
33
|
+
}) => Promise<T>;
|
|
34
|
+
}, _optional?: Record<string, never>): Promise<{
|
|
35
|
+
acquired: false;
|
|
36
|
+
} | {
|
|
37
|
+
acquired: true;
|
|
38
|
+
value: T;
|
|
39
|
+
}>;
|
|
40
|
+
//# sourceMappingURL=session-lock.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { sql } from 'kysely';
|
|
2
|
+
const databases = new WeakMap();
|
|
3
|
+
/** Private driver registration, kept separate from run() so the callback owns no transaction scope. */
|
|
4
|
+
export function registerKernelSessionDatabase({ kernel, database, poolMax }, _optional = {}) { databases.set(kernel, { database, ...(poolMax === undefined ? {} : { poolMax }) }); }
|
|
5
|
+
/** A schema wrapper uses the same pool and therefore the same database ownership scope. */
|
|
6
|
+
export function inheritKernelSessionDatabase({ from, to }, _optional = {}) {
|
|
7
|
+
const database = databases.get(from);
|
|
8
|
+
if (database)
|
|
9
|
+
databases.set(to, database);
|
|
10
|
+
}
|
|
11
|
+
/** Read the registered pool capacity without reserving a connection; schema wrappers share it. O(1). */
|
|
12
|
+
export function kernelSessionPoolMax({ kernel }, _optional = {}) {
|
|
13
|
+
return databases.get(kernel)?.poolMax;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Run one background owner under a dedicated PostgreSQL session advisory lock.
|
|
17
|
+
* A competing owner returns acquired:false. The callback uses normal kernel transactions:
|
|
18
|
+
* a durable dispatch snapshot commits before provider HTTP, unlike a transaction advisory lock.
|
|
19
|
+
* The session is always unlocked/released after callback success or failure.
|
|
20
|
+
* The pool needs a spare connection (max >= 2) for callback transactions.
|
|
21
|
+
* assertOwned probes the held session before the next background cycle.
|
|
22
|
+
* @throws For non-pooled kernels, unknown wrappers, a pool smaller than two, or an existing transaction scope.
|
|
23
|
+
* @complexity Two O(1) lock queries and one reserved pool connection for the callback lifetime.
|
|
24
|
+
*/
|
|
25
|
+
export async function withKernelSessionLock({ kernel, key, run }, _optional = {}) {
|
|
26
|
+
if (kernel.transport !== 'node-postgres')
|
|
27
|
+
throw new Error('A database session lock requires the pooled PostgreSQL transport.');
|
|
28
|
+
if (kernel.inTransaction())
|
|
29
|
+
throw new Error('A database session owner cannot start inside a transaction.');
|
|
30
|
+
const registered = databases.get(kernel);
|
|
31
|
+
if (!registered)
|
|
32
|
+
throw new Error('A database session lock requires a kernel built by buildKernel.');
|
|
33
|
+
if (registered.poolMax !== undefined && registered.poolMax < 2)
|
|
34
|
+
throw new Error('A database session owner requires a PostgreSQL pool with at least 2 connections.');
|
|
35
|
+
await kernel.ready;
|
|
36
|
+
return registered.database.connection().execute(async (connection) => {
|
|
37
|
+
const result = await sql `SELECT pg_try_advisory_lock(hashtextextended(${key}, 0)) AS locked`.execute(connection);
|
|
38
|
+
if (result.rows[0]?.locked !== true)
|
|
39
|
+
return { acquired: false };
|
|
40
|
+
try {
|
|
41
|
+
return { acquired: true, value: await run({ assertOwned: async () => { await sql `SELECT 1`.execute(connection); } }) };
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await sql `SELECT pg_advisory_unlock(hashtextextended(${key}, 0))`.execute(connection);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=session-lock.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/db",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
"src/kernel/port.ts",
|
|
30
30
|
"src/kernel/postgres-lock.ts",
|
|
31
31
|
"src/kernel/schema-scope.ts",
|
|
32
|
+
"src/kernel/session-lock.ts",
|
|
32
33
|
"src/kernel/schema-shape.ts",
|
|
33
34
|
"src/kernel/store-copy.ts",
|
|
34
35
|
"src/kernel/turn-lock.ts",
|
|
@@ -132,6 +133,11 @@
|
|
|
132
133
|
"types": "./dist/secrets-vault/index.d.ts",
|
|
133
134
|
"import": "./dist/secrets-vault/index.js",
|
|
134
135
|
"default": "./dist/secrets-vault/index.js"
|
|
136
|
+
},
|
|
137
|
+
"./data-modules": {
|
|
138
|
+
"types": "./dist/data-modules/index.d.ts",
|
|
139
|
+
"import": "./dist/data-modules/index.js",
|
|
140
|
+
"default": "./dist/data-modules/index.js"
|
|
135
141
|
}
|
|
136
142
|
},
|
|
137
143
|
"typesVersions": {
|
|
@@ -189,6 +195,9 @@
|
|
|
189
195
|
],
|
|
190
196
|
"secrets-vault": [
|
|
191
197
|
"./dist/secrets-vault/index.d.ts"
|
|
198
|
+
],
|
|
199
|
+
"data-modules": [
|
|
200
|
+
"./dist/data-modules/index.d.ts"
|
|
192
201
|
]
|
|
193
202
|
}
|
|
194
203
|
},
|
|
@@ -211,13 +220,13 @@
|
|
|
211
220
|
},
|
|
212
221
|
"dependencies": {
|
|
213
222
|
"kysely": "^0.29.6",
|
|
214
|
-
"@jini-ai/core": "^0.
|
|
223
|
+
"@jini-ai/core": "^0.7.0"
|
|
215
224
|
},
|
|
216
225
|
"peerDependencies": {
|
|
217
226
|
"better-sqlite3": "^13.0.0",
|
|
218
227
|
"@electric-sql/pglite": "0.5.8",
|
|
219
228
|
"pg": "^8.23.0",
|
|
220
|
-
"@jini-ai/platform": "^0.
|
|
229
|
+
"@jini-ai/platform": "^0.7.0"
|
|
221
230
|
},
|
|
222
231
|
"devDependencies": {
|
|
223
232
|
"@electric-sql/pglite": "0.5.8",
|
|
@@ -227,8 +236,8 @@
|
|
|
227
236
|
"better-sqlite3": "13.0.3",
|
|
228
237
|
"kysely": "0.29.6",
|
|
229
238
|
"pg": "8.23.0",
|
|
230
|
-
"@jini-ai/core": "0.
|
|
231
|
-
"@jini-ai/platform": "0.
|
|
239
|
+
"@jini-ai/core": "0.7.0",
|
|
240
|
+
"@jini-ai/platform": "0.7.0"
|
|
232
241
|
},
|
|
233
242
|
"peerDependenciesMeta": {
|
|
234
243
|
"better-sqlite3": {
|