@jini-ai/db 0.6.12 → 0.6.15-rc.1

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +76 -0
  3. package/dist/kernel/kernel-core.js +22 -4
  4. package/dist/kernel/owned-transaction.d.ts +15 -0
  5. package/dist/kernel/owned-transaction.js +9 -0
  6. package/dist/kernel/port.d.ts +1 -0
  7. package/dist/kernel/schema-scope.js +6 -1
  8. package/dist/kernel/sqlite/driver.js +20 -3
  9. package/dist/migrate/ddl.d.ts +11 -0
  10. package/dist/migrate/ddl.js +13 -0
  11. package/dist/migrate/index.d.ts +3 -1
  12. package/dist/migrate/index.js +2 -1
  13. package/dist/migrate/legacy-ledger.d.ts +39 -0
  14. package/dist/migrate/legacy-ledger.js +67 -0
  15. package/dist/migrate/runner.d.ts +58 -0
  16. package/dist/migrate/runner.js +79 -9
  17. package/dist/migrate/step.d.ts +1 -1
  18. package/dist/migrate/step.js +1 -1
  19. package/dist/owner-store/index.d.ts +3 -4
  20. package/dist/owner-store/index.js +3 -4
  21. package/dist/owner-store/migrations/0000_owner_store.js +2 -5
  22. package/dist/owner-store/migrations/index.d.ts +3 -1
  23. package/dist/owner-store/migrations/index.js +3 -1
  24. package/dist/secrets-vault/repo.sql.d.ts +3 -4
  25. package/dist/secrets-vault/repo.sql.js +12 -2
  26. package/dist/sqlite/checked-client.d.ts +19 -0
  27. package/dist/sqlite/checked-client.js +117 -0
  28. package/dist/sqlite/checked-state.d.ts +32 -0
  29. package/dist/sqlite/checked-state.js +26 -0
  30. package/dist/sqlite/index.d.ts +3 -0
  31. package/dist/sqlite/index.js +3 -0
  32. package/dist/sqlite/transaction.d.ts +29 -0
  33. package/dist/sqlite/transaction.js +80 -0
  34. package/package.json +8 -6
  35. package/dist/owner-store/backup.d.ts +0 -32
  36. package/dist/owner-store/backup.js +0 -102
  37. package/dist/owner-store/open.d.ts +0 -25
  38. package/dist/owner-store/open.js +0 -73
  39. package/dist/owner-store/service.d.ts +0 -69
  40. package/dist/owner-store/service.js +0 -122
@@ -1,7 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { sql } from "kysely";
4
+ import { nowIso } from "@jini-ai/core/primitives";
4
5
  import { listTables, tableExists } from "../kernel/index.js";
6
+ import { ownedTransactionOf } from "../kernel/owned-transaction.js";
7
+ import { ensureLegacyLedger, insertLegacyRow, readLegacyLedger, validateLegacyMapping } from "./legacy-ledger.js";
5
8
  import { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
6
9
  function ledgerFor(kernel, options) {
7
10
  const table = options.ledgerTable;
@@ -15,6 +18,7 @@ function ledgerFor(kernel, options) {
15
18
  table,
16
19
  schema,
17
20
  lockKey: schema === undefined ? table : `${schema}.${table}`,
21
+ mapping: options.legacyLedger,
18
22
  run: (fn) => store.run((db) => fn(schema === undefined ? db : db.withSchema(schema))),
19
23
  };
20
24
  }
@@ -37,6 +41,8 @@ export function assertValidSteps(steps) {
37
41
  async function ensureLedger(kernel, ledger) {
38
42
  if (ledger.schema !== undefined)
39
43
  await kernel.run((db) => db.schema.createSchema(ledger.schema).ifNotExists().execute());
44
+ if (ledger.mapping !== undefined)
45
+ return ensureLegacyLedger({ ledger, mapping: ledger.mapping, dialect: kernel.dialect });
40
46
  await ledger.run((db) => db.schema
41
47
  .createTable(ledger.table)
42
48
  .ifNotExists()
@@ -46,18 +52,80 @@ async function ensureLedger(kernel, ledger) {
46
52
  .execute());
47
53
  }
48
54
  async function readLedger(ledger) {
55
+ if (ledger.mapping !== undefined)
56
+ return readLegacyLedger({ ledger, mapping: ledger.mapping });
49
57
  return ledger.run((db) => db.selectFrom(ledger.table).selectAll().orderBy("id").execute());
50
58
  }
51
- function verifyRecorded(rows, steps, appName) {
59
+ function verifyRecorded(rows, steps, options) {
52
60
  const known = new Map(steps.map((step) => [step.id, step]));
53
61
  const unknown = rows.filter((row) => !known.has(row.id)).map((row) => row.id);
54
- if (unknown.length > 0)
55
- throw new UnknownAppliedMigrationError(unknown, appName);
62
+ if (unknown.length > 0 && !options.allowUnknownApplied)
63
+ throw new UnknownAppliedMigrationError(unknown, options.appName);
56
64
  for (const row of rows) {
57
65
  const step = known.get(row.id);
66
+ if (!step)
67
+ continue;
58
68
  if (row.checksum !== step.checksum)
59
69
  throw new MigrationChecksumError(row.id, row.checksum, step.checksum);
60
70
  }
71
+ if (options.historyCheck === "ordered-prefix" && rows.some((row, index) => row.id !== steps[index]?.id)) {
72
+ throw new Error("recorded migration history is not an ordered prefix");
73
+ }
74
+ }
75
+ async function insertRow({ ledger, step, options }, _optional = {}) {
76
+ const timestamp = () => options.clock === undefined ? new Date().toISOString() : nowIso({ clock: options.clock });
77
+ if (ledger.mapping !== undefined)
78
+ return insertLegacyRow({ ledger, mapping: ledger.mapping, step, timestamp });
79
+ await ledger.run((db) => db.insertInto(ledger.table).values({ id: step.id, checksum: step.checksum, applied_at: timestamp() }).execute());
80
+ }
81
+ async function recordedStep({ ledger, step, steps, options }, _optional = {}) {
82
+ const rows = await readLedger(ledger);
83
+ verifyRecorded(rows, steps, options);
84
+ return rows.some((row) => row.id === step.id);
85
+ }
86
+ function validateExtensions({ options, steps }, _optional = {}) {
87
+ if (options.legacyLedger === undefined)
88
+ return;
89
+ validateLegacyMapping({ mapping: options.legacyLedger, steps });
90
+ if (options.clock !== undefined && options.legacyLedger.timestamps !== "iso") {
91
+ throw new Error("a migration clock requires ISO legacy ledger timestamps");
92
+ }
93
+ }
94
+ function assertBatchSteps({ steps, done }, _optional = {}) {
95
+ if (steps.some((step) => !done.has(step.id) && step.prepare !== undefined))
96
+ throw new Error("batch migrations cannot run pending prepare hooks");
97
+ }
98
+ async function applyBatch({ kernel, ledger, steps, options, context, report }, _optional = {}) {
99
+ const control = ownedTransactionOf({ kernel });
100
+ kernel.require("transactionalDdl");
101
+ control.assertAvailable();
102
+ const initiallyDone = new Set(report.alreadyApplied);
103
+ const pending = steps.filter((step) => !initiallyDone.has(step.id));
104
+ assertBatchSteps({ steps, done: initiallyDone });
105
+ if (pending.length === 0)
106
+ return report;
107
+ await backUpBeforeChange(kernel, context);
108
+ return control.transaction(async () => {
109
+ await kernel.lockKey(ledger.lockKey);
110
+ await ensureLedger(kernel, ledger);
111
+ const rows = await readLedger(ledger);
112
+ verifyRecorded(rows, steps, options);
113
+ const done = new Set(rows.map((row) => row.id));
114
+ assertBatchSteps({ steps, done });
115
+ report.alreadyApplied = [...done];
116
+ for (const step of steps) {
117
+ if (done.has(step.id))
118
+ continue;
119
+ await step.up(kernel, context);
120
+ await insertRow({ ledger, step, options });
121
+ report.applied.push(step.id);
122
+ }
123
+ return report;
124
+ });
125
+ }
126
+ /** Object-input facade over the existing runner; all extensions remain opt-in. */
127
+ export function migrate(required, optional = {}) {
128
+ return runMigrations(required.kernel, required.steps, { ...optional, ledgerTable: required.ledgerTable });
61
129
  }
62
130
  /**
63
131
  * Applies every pending step of `steps`, in order, to `kernel`'s database.
@@ -70,14 +138,19 @@ function verifyRecorded(rows, steps, appName) {
70
138
  export async function runMigrations(kernel, steps, options) {
71
139
  assertValidSteps(steps);
72
140
  kernel.require("interactiveTransactions");
141
+ validateExtensions({ options, steps });
142
+ if (options.atomicity === "batch")
143
+ ownedTransactionOf({ kernel }).assertAvailable();
73
144
  const ledger = ledgerFor(kernel, options);
74
145
  const recorded = (await ledgerExists(kernel, ledger)) ? await readLedger(ledger) : [];
75
- verifyRecorded(recorded, steps, options.appName);
146
+ verifyRecorded(recorded, steps, options);
76
147
  const report = { applied: [], alreadyApplied: recorded.map((row) => row.id), notes: [] };
77
148
  const note = (message) => {
78
149
  report.notes.push(message);
79
150
  };
80
151
  const context = options.backupPath === undefined ? { note } : { backupPath: options.backupPath, note };
152
+ if (options.atomicity === "batch")
153
+ return applyBatch({ kernel, ledger, steps, options, context, report });
81
154
  const done = new Set(report.alreadyApplied);
82
155
  let backedUp = false;
83
156
  for (const step of steps) {
@@ -90,13 +163,10 @@ export async function runMigrations(kernel, steps, options) {
90
163
  const applied = await kernel.transaction(async () => {
91
164
  await kernel.lockKey(ledger.lockKey);
92
165
  await ensureLedger(kernel, ledger);
93
- const row = await ledger.run((db) => db.selectFrom(ledger.table).selectAll().where("id", "=", step.id).executeTakeFirst());
94
- if (row !== undefined) {
95
- verifyRecorded([row], steps, options.appName);
166
+ if (await recordedStep({ ledger, step, steps, options }))
96
167
  return false;
97
- }
98
168
  await step.up(kernel, context);
99
- await ledger.run((db) => db.insertInto(ledger.table).values({ id: step.id, checksum: step.checksum, applied_at: new Date().toISOString() }).execute());
169
+ await insertRow({ ledger, step, options });
100
170
  return true;
101
171
  });
102
172
  (applied ? report.applied : report.alreadyApplied).push(step.id);
@@ -1,7 +1,7 @@
1
1
  import type { StorageKernel } from "../kernel/index.js";
2
2
  /**
3
3
  * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
4
- * (`runner.ts`) applies each pending one in its own transaction and records it in the consumer's
4
+ * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
5
5
  * ledger table.
6
6
  */
7
7
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
3
- * (`runner.ts`) applies each pending one in its own transaction and records it in the consumer's
3
+ * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
4
4
  * ledger table.
5
5
  */
6
6
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
@@ -1,5 +1,4 @@
1
- /** Owner-only SQLite store. Native driver dependencies are supplied by the host. */
2
- export { openOwnerStore, OwnerStoreRecoveryError, type OpenOwnerStoreInput, type OpenOwnerStoreOptions, type OpenedOwnerStore } from "./open.js";
3
- export { OwnerStoreService, OWNER_WORKSPACE_ID, ownerContext, type OwnerStoreDatabase, type OwnerGrant, type OwnerPutInput, type OwnerSyncTarget } from "./service.js";
4
- export { exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError } from "./backup.js";
1
+ /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
2
+ export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
+ export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
5
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,4 @@
1
- /** Owner-only SQLite store. Native driver dependencies are supplied by the host. */
2
- export { openOwnerStore, OwnerStoreRecoveryError } from "./open.js";
3
- export { OwnerStoreService, OWNER_WORKSPACE_ID, ownerContext } from "./service.js";
4
- export { exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError } from "./backup.js";
1
+ /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
2
+ export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
+ export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
5
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { sql } from "kysely";
1
+ import { executeDdl } from "../../migrate/ddl.js";
2
2
  /** Owner-only history: no site tables or foreign workspace records are required. */
3
3
  export const ownerStoreDdl = `
4
4
  CREATE TABLE secrets_vault (
@@ -30,10 +30,7 @@ export const ownerStoreMigration = {
30
30
  id: "0000_owner_store",
31
31
  checksum: "ea2c33cf1835f6b1db0f52a4de3419aaf8c1a2e2edeece1e2b3240c517592446",
32
32
  async up(kernel) {
33
- // Kysely executes one SQLite statement at a time; the runner owns the encompassing transaction.
34
- for (const statement of ownerStoreDdl.split(";").filter(part => part.trim())) {
35
- await kernel.execute(sql.raw(statement));
36
- }
33
+ await executeDdl({ kernel, ddl: ownerStoreDdl });
37
34
  },
38
35
  };
39
36
  //# sourceMappingURL=0000_owner_store.js.map
@@ -1,4 +1,6 @@
1
- /** Independent history: a site migration ledger must never govern this database. */
1
+ /** Independent history: a site migration ledger must never govern this database. Read-only now:
2
+ * no host opens an owner store for writing, so this history only describes legacy files.
3
+ */
2
4
  export declare const OWNER_STORE_LEDGER = "owner_migrations";
3
5
  export declare const ownerStoreMigrations: readonly [import("../../migrate/step.js").MigrationStep];
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,7 @@
1
1
  import { ownerStoreMigration } from "./0000_owner_store.js";
2
- /** Independent history: a site migration ledger must never govern this database. */
2
+ /** Independent history: a site migration ledger must never govern this database. Read-only now:
3
+ * no host opens an owner store for writing, so this history only describes legacy files.
4
+ */
3
5
  export const OWNER_STORE_LEDGER = "owner_migrations";
4
6
  export const ownerStoreMigrations = [ownerStoreMigration];
5
7
  //# sourceMappingURL=index.js.map
@@ -64,10 +64,9 @@ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
64
64
  findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
65
65
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
66
66
  private assertLabelAvailable;
67
- put(input: {
68
- record: VaultRecord;
69
- expectedRevision: number | null;
70
- }, _options?: VaultOptions): Promise<VaultRecord>;
67
+ /** One bounded existence query only when the caller leaves default placement unspecified. */
68
+ private defaultForPut;
69
+ put(input: Parameters<VaultRepoPort["put"]>[0], _options?: VaultOptions): Promise<VaultRecord>;
71
70
  /** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
72
71
  patchMeta(input: {
73
72
  workspaceId: string;
@@ -111,6 +111,15 @@ export class SqlSecretsVaultRepo {
111
111
  throw new VaultError({ code: "conflict" });
112
112
  }
113
113
  }
114
+ /** One bounded existence query only when the caller leaves default placement unspecified. */
115
+ async defaultForPut({ record, existing, moved }, _options = {}) {
116
+ if (record.isDefault !== undefined)
117
+ return record.isDefault;
118
+ if (existing !== null && !moved)
119
+ return false;
120
+ return !await this.kernel.run(db => this.scoped({ db, input: this.group(record) })
121
+ .select("id").limit(1).executeTakeFirst());
122
+ }
114
123
  async put(input, _options = {}) {
115
124
  return this.write(input.record.workspaceId, async () => {
116
125
  const existing = await this.find(input.record);
@@ -118,8 +127,9 @@ export class SqlSecretsVaultRepo {
118
127
  const scope = this.group(input.record);
119
128
  const moved = existing !== null && existing.provider !== input.record.provider;
120
129
  await this.assertLabelAvailable({ record: input.record, existing, moved, scope });
121
- const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
122
- const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
130
+ // Auto-select the first row so an ordinary save is usable without a separate default action.
131
+ // Explicit false opts out, keeping unattached project keys from becoming vendor defaults.
132
+ const saved = { ...input.record, isDefault: await this.defaultForPut({ record: input.record, existing, moved }) };
123
133
  // Clear before insert/update so a partial UNIQUE default index never sees two defaults.
124
134
  if (saved.isDefault)
125
135
  await this.kernel.run(db => db.updateTable("secrets_vault")
@@ -0,0 +1,19 @@
1
+ import type { SqliteClient, SqliteStatement } from "./types.js";
2
+ export interface IntegerStatement extends SqliteStatement {
3
+ safeIntegers(enabled: boolean): unknown;
4
+ }
5
+ export type IntegerSource = Omit<SqliteClient, "prepare"> & {
6
+ prepare(source: string): IntegerStatement;
7
+ };
8
+ export interface CheckedSqliteClient extends SqliteClient {
9
+ readonly checked: true;
10
+ }
11
+ /**
12
+ * Borrow a native handle with exact integer decoding and shared quarantine/lease state.
13
+ * Memoized by handle; refuses handles already owned by a raw kernel. Does not close the host handle.
14
+ * @complexity O(cells) per result, O(1) additional rows for lazy iteration.
15
+ */
16
+ export declare function createCheckedSqliteClient(required: {
17
+ database: IntegerSource;
18
+ }, _optional?: {}): CheckedSqliteClient;
19
+ //# sourceMappingURL=checked-client.d.ts.map
@@ -0,0 +1,117 @@
1
+ import { assertCheckedAvailable, checkedClients, checkedStates, rawKernelClients, SqliteClientError } from "./checked-state.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ const clients = new WeakMap();
4
+ function numberCell({ value }, _optional = {}) {
5
+ if (typeof value !== "bigint")
6
+ return value;
7
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
8
+ throw new SqliteClientError({ code: "unsafe_integer" });
9
+ }
10
+ return Number(value);
11
+ }
12
+ /** Decode cells only, preserving blobs and other non-integer values by identity. */
13
+ function decodeRow({ row }, _optional = {}) {
14
+ if (Array.isArray(row))
15
+ return row.map((value) => numberCell({ value }));
16
+ if (row === null || typeof row !== "object" || ArrayBuffer.isView(row))
17
+ return numberCell({ value: row });
18
+ return Object.fromEntries(Object.entries(row).map(([key, value]) => [key, numberCell({ value })]));
19
+ }
20
+ function checkedStatement({ statement, state }, _optional = {}) {
21
+ statement.safeIntegers(true);
22
+ return {
23
+ get reader() { return statement.reader; },
24
+ all(...parameters) {
25
+ assertCheckedAvailable({ state });
26
+ return statement.all(...parameters).map((row) => decodeRow({ row }));
27
+ },
28
+ run(...parameters) {
29
+ assertCheckedAvailable({ state });
30
+ const result = statement.run(...parameters);
31
+ return { changes: numberCell({ value: result.changes }), lastInsertRowid: numberCell({ value: result.lastInsertRowid }) };
32
+ },
33
+ *iterate(...parameters) {
34
+ assertCheckedAvailable({ state });
35
+ const iterator = statement.iterate(...parameters);
36
+ try {
37
+ while (true) {
38
+ assertCheckedAvailable({ state });
39
+ const next = iterator.next();
40
+ if (next.done)
41
+ return;
42
+ yield decodeRow({ row: next.value });
43
+ }
44
+ }
45
+ finally {
46
+ iterator.return?.();
47
+ }
48
+ },
49
+ };
50
+ }
51
+ /** Quarantine only an uncertain outcome: a transaction still open, or a COMMIT that may have applied. */
52
+ function controlFailure({ database, state, command, cause }, _optional = {}) {
53
+ const open = database.inTransaction;
54
+ if (command === "COMMIT") {
55
+ state.quarantined = true;
56
+ // Still open: nothing applied yet, so a following ROLLBACK can settle it and lift the quarantine.
57
+ state.cleanupAllowed = open;
58
+ return new SqliteClientError({ code: "commit_failed" }, { cause });
59
+ }
60
+ state.quarantined = open;
61
+ return new SqliteClientError({ code: "rollback_failed" }, { cause });
62
+ }
63
+ function execChecked({ database, state, source }, _optional = {}) {
64
+ const command = source.trim().replace(/;$/, "").toUpperCase();
65
+ const cleanup = command === "ROLLBACK" && state.cleanupAllowed;
66
+ // Cleanup must remain possible after a failed COMMIT quarantines the handle.
67
+ if (!cleanup)
68
+ assertCheckedAvailable({ state });
69
+ if (command === "ROLLBACK")
70
+ state.cleanupAllowed = false;
71
+ try {
72
+ const result = database.exec(source);
73
+ if (cleanup)
74
+ state.quarantined = false;
75
+ return result;
76
+ }
77
+ catch (cause) {
78
+ if (command !== "COMMIT" && command !== "ROLLBACK")
79
+ throw cause;
80
+ throw controlFailure({ database, state, command, cause });
81
+ }
82
+ }
83
+ /**
84
+ * Borrow a native handle with exact integer decoding and shared quarantine/lease state.
85
+ * Memoized by handle; refuses handles already owned by a raw kernel. Does not close the host handle.
86
+ * @complexity O(cells) per result, O(1) additional rows for lazy iteration.
87
+ */
88
+ export function createCheckedSqliteClient(required, _optional = {}) {
89
+ const { database } = required;
90
+ const known = clients.get(database);
91
+ if (known !== undefined)
92
+ return known;
93
+ if (rawKernelClients.has(database))
94
+ throw new Error("cannot mix raw and checked SQLite kernel ownership");
95
+ const state = { context: new AsyncLocalStorage(), quarantined: false, cleanupAllowed: false };
96
+ const client = {
97
+ checked: true,
98
+ get memory() { return database.memory; },
99
+ get name() { return database.name; },
100
+ get inTransaction() { return database.inTransaction; },
101
+ exec: (source) => execChecked({ database, state, source }),
102
+ prepare(source) {
103
+ assertCheckedAvailable({ state });
104
+ return checkedStatement({ statement: database.prepare(source), state });
105
+ },
106
+ pragma(source) { assertCheckedAvailable({ state }); return database.pragma(source); },
107
+ backup(destination) { assertCheckedAvailable({ state }); return database.backup(destination); },
108
+ close() { },
109
+ };
110
+ clients.set(database, client);
111
+ clients.set(client, client);
112
+ checkedStates.set(database, state);
113
+ checkedStates.set(client, state);
114
+ checkedClients.add(client);
115
+ return client;
116
+ }
117
+ //# sourceMappingURL=checked-client.js.map
@@ -0,0 +1,32 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { SqliteClient } from "./types.js";
3
+ import type { StorageKernel } from "../kernel/port.js";
4
+ export interface SqliteLease {
5
+ active: boolean;
6
+ acquired: boolean;
7
+ }
8
+ export interface CheckedState {
9
+ context: AsyncLocalStorage<SqliteLease>;
10
+ lease?: SqliteLease;
11
+ quarantined: boolean;
12
+ cleanupAllowed: boolean;
13
+ }
14
+ export declare const checkedStates: WeakMap<SqliteClient, CheckedState>;
15
+ export declare const checkedClients: WeakSet<SqliteClient>;
16
+ export declare const rawKernelClients: WeakSet<SqliteClient>;
17
+ /** The reverse of the driver's kernel cache, plus the owning kernels openSqliteFileKernel returns. */
18
+ export declare const connectionsByKernel: WeakMap<StorageKernel<unknown>, SqliteClient>;
19
+ /** A typed failure from the opt-in checked client; the native failure remains its cause. */
20
+ export declare class SqliteClientError extends Error {
21
+ readonly code: "unsafe_integer" | "commit_failed" | "rollback_failed" | "quarantined" | "session_expired" | "transaction_busy";
22
+ constructor(required: {
23
+ code: SqliteClientError["code"];
24
+ }, optional?: {
25
+ cause?: unknown;
26
+ });
27
+ }
28
+ /** Checks both queued work's lifetime and the shared native handle's health. */
29
+ export declare function assertCheckedAvailable({ state }: {
30
+ state: CheckedState;
31
+ }, _optional?: {}): void;
32
+ //# sourceMappingURL=checked-state.d.ts.map
@@ -0,0 +1,26 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export const checkedStates = new WeakMap();
3
+ export const checkedClients = new WeakSet();
4
+ export const rawKernelClients = new WeakSet();
5
+ /** The reverse of the driver's kernel cache, plus the owning kernels openSqliteFileKernel returns. */
6
+ export const connectionsByKernel = new WeakMap();
7
+ /** A typed failure from the opt-in checked client; the native failure remains its cause. */
8
+ export class SqliteClientError extends Error {
9
+ code;
10
+ constructor(required, optional = {}) {
11
+ super(required.code, { cause: optional.cause });
12
+ this.code = required.code;
13
+ this.name = "SqliteClientError";
14
+ }
15
+ }
16
+ /** Checks both queued work's lifetime and the shared native handle's health. */
17
+ export function assertCheckedAvailable({ state }, _optional = {}) {
18
+ if (state.quarantined)
19
+ throw new SqliteClientError({ code: "quarantined" });
20
+ const current = state.context.getStore();
21
+ if (current?.active === false)
22
+ throw new SqliteClientError({ code: "session_expired" });
23
+ if (state.lease?.acquired === true && current !== state.lease)
24
+ throw new SqliteClientError({ code: "transaction_busy" });
25
+ }
26
+ //# sourceMappingURL=checked-state.js.map
@@ -1,5 +1,8 @@
1
1
  /** SQLite connection policy and restore operations; inject the consumer's opener. */
2
2
  export type { SqliteClient, SqliteOpener, SqliteOpenOptions, SqliteStatement } from "./types.js";
3
+ export { createCheckedSqliteClient, type CheckedSqliteClient, type IntegerSource, type IntegerStatement } from "./checked-client.js";
4
+ export { SqliteClientError } from "./checked-state.js";
5
+ export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
3
6
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
4
7
  export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
5
8
  export type { SqliteBackupSource, SqliteRecoveryHook, OpenSqliteConnectionOptions } from "./restore-types.js";
@@ -1,3 +1,6 @@
1
+ export { createCheckedSqliteClient } from "./checked-client.js";
2
+ export { SqliteClientError } from "./checked-state.js";
3
+ export { withSqliteTransaction } from "./transaction.js";
1
4
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
2
5
  export { SqliteDbOpsAdapter } from "./db-ops.js";
3
6
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
@@ -0,0 +1,29 @@
1
+ import type { RawBuilder, StorageKernel } from "../kernel/port.js";
2
+ import type { CheckedSqliteClient } from "./checked-client.js";
3
+ export type Work<T> = (input: {
4
+ session: TransactionSession;
5
+ }) => Promise<T>;
6
+ export interface TransactionSession {
7
+ query<R>(required: {
8
+ statement: RawBuilder<R>;
9
+ }, optional?: {}): Promise<R[]>;
10
+ execute(required: {
11
+ statement: RawBuilder<unknown>;
12
+ }, optional?: {}): Promise<void>;
13
+ transaction<T>(required: {
14
+ work: Work<T>;
15
+ }, optional?: {}): Promise<T>;
16
+ }
17
+ /**
18
+ * Exclusively lease a matching checked kernel. Nested session work joins; only the root result
19
+ * decides optional failed-Outcome rollback. A session is revoked even when cleanup fails.
20
+ * @throws SqliteClientError or the original body error; AggregateError preserves cleanup failures.
21
+ */
22
+ export declare function withSqliteTransaction<T>(required: {
23
+ client: CheckedSqliteClient;
24
+ kernel: StorageKernel<unknown>;
25
+ work: Work<T>;
26
+ }, optional?: {
27
+ rollbackOnFailedOutcome?: boolean;
28
+ }): Promise<T>;
29
+ //# sourceMappingURL=transaction.d.ts.map
@@ -0,0 +1,80 @@
1
+ import { ownedTransactionOf } from "../kernel/owned-transaction.js";
2
+ import { assertCheckedAvailable, checkedClients, checkedStates, connectionsByKernel, SqliteClientError } from "./checked-state.js";
3
+ class FailedOutcome extends Error {
4
+ outcome;
5
+ constructor({ outcome }, _optional = {}) {
6
+ super("returned failed outcome", { cause: outcome });
7
+ this.outcome = outcome;
8
+ }
9
+ }
10
+ function sessionFor({ kernel, state, lease }, _optional = {}) {
11
+ const check = () => {
12
+ if (!lease.active)
13
+ throw new SqliteClientError({ code: "session_expired" });
14
+ assertCheckedAvailable({ state });
15
+ };
16
+ const session = {
17
+ async query({ statement }, _optional = {}) {
18
+ check();
19
+ return kernel.run(async (db) => { check(); return (await statement.execute(db)).rows; });
20
+ },
21
+ async execute({ statement }, _optional = {}) {
22
+ check();
23
+ await kernel.run(async (db) => { check(); await statement.execute(db); });
24
+ },
25
+ async transaction({ work }, _optional = {}) { check(); return work({ session }); },
26
+ };
27
+ return session;
28
+ }
29
+ /**
30
+ * Exclusively lease a matching checked kernel. Nested session work joins; only the root result
31
+ * decides optional failed-Outcome rollback. A session is revoked even when cleanup fails.
32
+ * @throws SqliteClientError or the original body error; AggregateError preserves cleanup failures.
33
+ */
34
+ export async function withSqliteTransaction(required, optional = {}) {
35
+ const { client, kernel, work } = required;
36
+ const state = checkedStates.get(client);
37
+ if (!checkedClients.has(client) || state === undefined || connectionsByKernel.get(kernel) !== client)
38
+ throw new Error("a matching checked SQLite client and kernel are required");
39
+ assertCheckedAvailable({ state });
40
+ if (state.lease !== undefined)
41
+ throw new SqliteClientError({ code: "transaction_busy" });
42
+ if (client.inTransaction)
43
+ throw new Error("an owned transaction cannot join an existing or foreign transaction");
44
+ const control = ownedTransactionOf({ kernel });
45
+ control.assertAvailable();
46
+ const lease = { active: true, acquired: false };
47
+ state.lease = lease;
48
+ const session = sessionFor({ kernel, state, lease });
49
+ const revoke = () => {
50
+ lease.active = false;
51
+ if (state.lease === lease)
52
+ delete state.lease;
53
+ };
54
+ try {
55
+ return await state.context.run(lease, () => control.transaction(async () => {
56
+ // Reserve first to reject overlaps, but let earlier shared runs finish before taking control.
57
+ lease.acquired = true;
58
+ const result = await work({ session });
59
+ if (optional.rollbackOnFailedOutcome === true && isFailedOutcome({ value: result }))
60
+ throw new FailedOutcome({ outcome: result });
61
+ return result;
62
+ }, { onSettled: revoke }));
63
+ }
64
+ catch (error) {
65
+ if (error instanceof FailedOutcome)
66
+ return error.outcome;
67
+ if (error instanceof AggregateError) {
68
+ throw new AggregateError(error.errors.map((part) => part instanceof FailedOutcome ? part.outcome : part), error.message);
69
+ }
70
+ throw error;
71
+ }
72
+ finally {
73
+ // Backstop for failures before the turn was taken; normally revoked inside the turn.
74
+ revoke();
75
+ }
76
+ }
77
+ function isFailedOutcome({ value }, _optional = {}) {
78
+ return value !== null && typeof value === "object" && "ok" in value && value.ok === false;
79
+ }
80
+ //# sourceMappingURL=transaction.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.6.12",
3
+ "version": "0.6.15-rc.1",
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": {
@@ -24,13 +24,15 @@
24
24
  "src/kernel/index.ts",
25
25
  "src/kernel/kernel-core.ts",
26
26
  "src/kernel/ops.ts",
27
+ "src/kernel/owned-transaction.ts",
27
28
  "src/kernel/port.ts",
28
29
  "src/kernel/postgres-lock.ts",
29
30
  "src/kernel/schema-scope.ts",
30
31
  "src/kernel/schema-shape.ts",
31
32
  "src/kernel/store-copy.ts",
32
33
  "src/kernel/turn-lock.ts",
33
- "src/kernel/typegen.ts"
34
+ "src/kernel/typegen.ts",
35
+ "src/sqlite/checked-state.ts"
34
36
  ]
35
37
  }
36
38
  },
@@ -200,14 +202,14 @@
200
202
  "registry": "https://registry.npmjs.org"
201
203
  },
202
204
  "dependencies": {
203
- "@jini-ai/core": "^0.6.12"
205
+ "@jini-ai/core": "^0.6.15-rc.1"
204
206
  },
205
207
  "peerDependencies": {
206
208
  "kysely": "^0.29.6",
207
209
  "better-sqlite3": "^13.0.0",
208
210
  "@electric-sql/pglite": "0.5.8",
209
211
  "pg": "^8.23.0",
210
- "@jini-ai/platform": "^0.6.10"
212
+ "@jini-ai/platform": "^0.6.15-rc.1"
211
213
  },
212
214
  "peerDependenciesMeta": {
213
215
  "better-sqlite3": {
@@ -234,8 +236,8 @@
234
236
  "better-sqlite3": "13.0.3",
235
237
  "kysely": "0.29.6",
236
238
  "pg": "8.23.0",
237
- "@jini-ai/core": "0.6.12",
238
- "@jini-ai/platform": "0.6.12"
239
+ "@jini-ai/core": "0.6.15-rc.1",
240
+ "@jini-ai/platform": "0.6.15-rc.1"
239
241
  },
240
242
  "scripts": {
241
243
  "build": "tsc -p tsconfig.build.json",