@jini-ai/db 0.3.5 → 0.6.10

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 CHANGED
@@ -1,3 +1,16 @@
1
+ ## 0.6.10
2
+
3
+ ### Patch Changes
4
+
5
+ - Updated dependencies [22f0619]
6
+ - Updated dependencies [82ed2d3]
7
+ - Updated dependencies [5a3de86]
8
+ - @jini-ai/core@0.6.10
9
+
10
+ ## 0.3.6 — 2026-10-22
11
+
12
+ - 2026-10-22: Security queue fixes, testing helper reads os.userInfo() only when PGUSER is unset, complexity refactors, coverage.
13
+
1
14
  ## 0.3.5 — 2026-10-16
2
15
 
3
16
  - Store copy lets the host exclude retained restore tables from the catalog, emptiness check and copy (b0b13de4); copy only builds indexes for tables it created (d748cf67).
package/NOTICE.md CHANGED
@@ -25,3 +25,6 @@
25
25
  text); a CancelRequest closes its connection; GSSENC requests are answered `N` like SSL.
26
26
  9. Removed: hex `inspect` dumps, `EventTarget` events, debug `console.log` (replaced by an optional `log`
27
27
  callback), TCP host/port options, stats beyond connections/queued.
28
+ 10. **Injectable listener** (2026-10-21): an optional `createServer` option (default `node:net`'s) and
29
+ structural `SocketServerClient`/`SocketServerListener` types, so tests script a client socket's events
30
+ without module mocks. Behaviour with the default is unchanged.
@@ -35,15 +35,15 @@ export function outsideTransactionOf(kernel) {
35
35
  * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
36
36
  */
37
37
  export async function verifyLedgerReadBack(kernel, ledgerTable) {
38
- let steps;
38
+ let anyStep;
39
39
  try {
40
- const [row] = await kernel.query(sql `SELECT count(*)::int AS n FROM ${sql.table(ledgerTable)}`);
41
- steps = row?.n ?? 0;
40
+ // One row when the ledger holds any step, none when it is empty: no count to null-check.
41
+ anyStep = await kernel.query(sql `SELECT 1 AS present FROM ${sql.table(ledgerTable)} LIMIT 1`);
42
42
  }
43
43
  catch (err) {
44
44
  throw new StorageOpError(`the migration ledger ${ledgerTable} cannot be read back: ${err.message}`);
45
45
  }
46
- if (steps === 0)
46
+ if (anyStep.length === 0)
47
47
  throw new StorageOpError(`the migration ledger ${ledgerTable} is empty after compacting`);
48
48
  }
49
49
  //# sourceMappingURL=ops.js.map
@@ -25,7 +25,7 @@ class PgliteConnection {
25
25
  ...(result.affectedRows !== undefined ? { numAffectedRows: BigInt(result.affectedRows) } : {}),
26
26
  };
27
27
  }
28
- // eslint-disable-next-line require-yield -- the interface requires a generator; PGlite has no cursor API here
28
+ // eslint-disable-next-line require-yield, sonarjs/generator-without-yield -- the interface requires a generator; PGlite has no cursor API here
29
29
  async *streamQuery() {
30
30
  throw new Error("streaming queries are not supported on PGlite");
31
31
  }
@@ -1,5 +1,5 @@
1
1
  import { sql } from "kysely";
2
- const squash = (text) => (text ?? "").replace(/\s+/g, " ").trim();
2
+ const squash = (text) => text.replace(/\s+/g, " ").trim();
3
3
  /** Every user table's shape (internal and `sqlite_`/`pg_` tables excluded), keyed by table name. */
4
4
  export async function readSchemaShape(kernel, optional = {}) {
5
5
  const exclude = new Set(optional.exclude ?? []);
@@ -9,7 +9,8 @@ export async function readSchemaShape(kernel, optional = {}) {
9
9
  return shape;
10
10
  }
11
11
  async function sqliteShape(kernel) {
12
- const objects = await kernel.query(sql `SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name`);
12
+ // An auto-index (UNIQUE/PRIMARY KEY in the table text) has no SQL of its own: read it as ''.
13
+ const objects = await kernel.query(sql `SELECT type, name, tbl_name, coalesce(sql, '') AS sql FROM sqlite_schema WHERE substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name`);
13
14
  const tables = {};
14
15
  const others = [];
15
16
  for (const object of objects) {
@@ -18,16 +19,7 @@ async function sqliteShape(kernel) {
18
19
  if (object.type !== "table")
19
20
  continue;
20
21
  const columns = await kernel.query(sql `SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info(${object.name}) ORDER BY cid`);
21
- const indexes = await kernel.query(sql `SELECT name, "unique", origin, partial FROM pragma_index_list(${object.name}) ORDER BY name`);
22
- const indexTexts = [];
23
- for (const index of indexes) {
24
- const cols = await kernel.query(sql `SELECT name FROM pragma_index_info(${index.name}) ORDER BY seqno`);
25
- const definition = objects.find((o) => o.type === "index" && o.name === index.name)?.sql;
26
- const where = index.partial ? ` WHERE ${squash(definition).replace(/^.*? WHERE /i, "")}` : "";
27
- // Auto-named indexes (UNIQUE/PRIMARY KEY in the table text) are identified by what they cover.
28
- const label = index.origin === "c" ? index.name : `(${index.origin})`;
29
- indexTexts.push(`${label} ${index.unique ? "UNIQUE " : ""}(${cols.map((c) => c.name).join(", ")})${where}`);
30
- }
22
+ const indexTexts = await sqliteIndexTexts({ kernel, tableName: object.name, objects });
31
23
  const fks = await kernel.query(sql `SELECT id, "table", "from", "to", on_update, on_delete FROM pragma_foreign_key_list(${object.name}) ORDER BY id, seq`);
32
24
  const byId = new Map();
33
25
  for (const fk of fks)
@@ -46,6 +38,21 @@ async function sqliteShape(kernel) {
46
38
  }
47
39
  return { tables, others: others.sort() };
48
40
  }
41
+ async function sqliteIndexTexts({ kernel, tableName, objects }, _optional = {}) {
42
+ const indexes = await kernel.query(sql `SELECT name, "unique", origin, partial FROM pragma_index_list(${tableName}) ORDER BY name`);
43
+ const indexTexts = [];
44
+ for (const index of indexes) {
45
+ const cols = await kernel.query(sql `SELECT name FROM pragma_index_info(${index.name}) ORDER BY seqno`);
46
+ // Only a CREATE INDEX can be partial, so a partial index always has its own sqlite_schema row.
47
+ const where = index.partial
48
+ ? ` WHERE ${squash(objects.find((o) => o.type === "index" && o.name === index.name).sql).replace(/^.*? WHERE /i, "")}`
49
+ : "";
50
+ // Auto-named indexes (UNIQUE/PRIMARY KEY in the table text) are identified by what they cover.
51
+ const label = index.origin === "c" ? index.name : `(${index.origin})`;
52
+ indexTexts.push(`${label} ${index.unique ? "UNIQUE " : ""}(${cols.map((c) => c.name).join(", ")})${where}`);
53
+ }
54
+ return indexTexts;
55
+ }
49
56
  async function postgresShape(kernel) {
50
57
  const columns = await kernel.query(sql `SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default
51
58
  FROM information_schema.columns c
@@ -108,8 +108,9 @@ async function assertLedgersAgreeInternal(source, target, scope) {
108
108
  }
109
109
  function columnDdl(column) {
110
110
  let ddl = sql `${sql.ref(column.name)} ${sql.raw(column.type)}`;
111
+ // Postgres stores every generated column's expression in pg_attrdef, so `expression` is set here.
111
112
  if (column.generated)
112
- return sql `${ddl} GENERATED ALWAYS AS (${sql.raw(column.expression ?? "NULL")}) STORED`;
113
+ return sql `${ddl} GENERATED ALWAYS AS (${sql.raw(column.expression)}) STORED`;
113
114
  if (column.identity !== "")
114
115
  ddl = sql `${ddl} GENERATED ${sql.raw(column.identity === "a" ? "ALWAYS" : "BY DEFAULT")} AS IDENTITY`;
115
116
  if (column.notNull)
@@ -158,6 +159,20 @@ async function fingerprint(kernel, table) {
158
159
  FROM (SELECT ${key} AS k FROM ${tableRef(table)}) keyed`);
159
160
  return `${row.n}:${row.sum}`;
160
161
  }
162
+ async function addConstraints({ target, constraints }, _optional = {}) {
163
+ for (const constraint of constraints) {
164
+ await target.execute(sql `ALTER TABLE ${tableRef({ schema: constraint.schema, name: constraint.table })} ADD CONSTRAINT ${sql.ref(constraint.name)} ${sql.raw(constraint.definition)}`);
165
+ }
166
+ }
167
+ async function advanceIdentityCounters({ target, tables }, _optional = {}) {
168
+ // Identity counters past the copied ids, or the first insert after the move collides.
169
+ for (const table of tables) {
170
+ for (const column of table.columns.filter((c) => c.identity !== "")) {
171
+ await target.execute(sql `SELECT setval(pg_get_serial_sequence(${quotedName(table)}, ${column.name}),
172
+ COALESCE((SELECT max(${sql.ref(column.name)}) FROM ${tableRef(table)}), 0) + 1, false)`);
173
+ }
174
+ }
175
+ }
161
176
  /**
162
177
  * Copies every table of `source` into `target` (see this file's header). Call it with both at head
163
178
  * and the target empty ({@link nonEmptyTables}); the ledgers are checked here first.
@@ -203,9 +218,7 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
203
218
  await target.execute(sql `CREATE TABLE ${tableRef(table)} (${sql.join(table.columns.map(columnDdl))})`);
204
219
  }
205
220
  const createdConstraints = sourceConstraints.filter((c) => createdIds.has(`${c.schema}.${c.table}`));
206
- for (const constraint of createdConstraints.filter((c) => c.type !== "f")) {
207
- await target.execute(sql `ALTER TABLE ${tableRef({ schema: constraint.schema, name: constraint.table })} ADD CONSTRAINT ${sql.ref(constraint.name)} ${sql.raw(constraint.definition)}`);
208
- }
221
+ await addConstraints({ target, constraints: createdConstraints.filter((c) => c.type !== "f") });
209
222
  for (const index of sourceIndexes.filter((i) => createdIds.has(`${i.schema}.${i.table}`))) {
210
223
  await target.execute(sql.raw(index.definition));
211
224
  }
@@ -214,16 +227,8 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
214
227
  const rows = await copyRows(source, target, table);
215
228
  report.push({ table: qualified(table), rows, created: createdIds.has(qualified(table)) });
216
229
  }
217
- for (const fk of [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")]) {
218
- await target.execute(sql `ALTER TABLE ${tableRef({ schema: fk.schema, name: fk.table })} ADD CONSTRAINT ${sql.ref(fk.name)} ${sql.raw(fk.definition)}`);
219
- }
220
- // Identity counters past the copied ids, or the first insert after the move collides.
221
- for (const table of sourceTables) {
222
- for (const column of table.columns.filter((c) => c.identity !== "")) {
223
- await target.execute(sql `SELECT setval(pg_get_serial_sequence(${quotedName(table)}, ${column.name}),
224
- COALESCE((SELECT max(${sql.ref(column.name)}) FROM ${tableRef(table)}), 0) + 1, false)`);
225
- }
226
- }
230
+ await addConstraints({ target, constraints: [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")] });
231
+ await advanceIdentityCounters({ target, tables: sourceTables });
227
232
  for (const table of sourceTables) {
228
233
  const [a, b] = [await fingerprint(source, table), await fingerprint(target, table)];
229
234
  if (a !== b)
@@ -39,6 +39,62 @@ export declare class PgliteOwnerLockedError extends Error {
39
39
  /** Undefined while the other starter's lock has no pid in it yet. */
40
40
  pid: number | undefined);
41
41
  }
42
+ /**
43
+ * The filesystem calls the owner makes on its lock file, socket dir and socket. Defaults to
44
+ * `node:fs`; a test passes a fake to reach the races and errno paths a real filesystem cannot be
45
+ * made to produce on demand (another starter renaming the lock mid-reap, EIO on a hard link).
46
+ */
47
+ export interface OwnerFsPort {
48
+ openSync(path: string, flags: "r"): number;
49
+ fstatSync(fd: number): {
50
+ ino: number;
51
+ mtimeMs: number;
52
+ };
53
+ readFileSync(fd: number, encoding: "utf8"): string;
54
+ closeSync(fd: number): void;
55
+ writeFileSync(path: string, data: string, options: {
56
+ flag: "wx";
57
+ mode: number;
58
+ }): void;
59
+ linkSync(existingPath: string, newPath: string): void;
60
+ rmSync(path: string, options: {
61
+ force: true;
62
+ }): void;
63
+ renameSync(oldPath: string, newPath: string): void;
64
+ mkdirSync(path: string, options: {
65
+ recursive?: boolean;
66
+ mode: number;
67
+ }): unknown;
68
+ rmdirSync(path: string): void;
69
+ statSync(path: string): {
70
+ ino: number;
71
+ mode: number;
72
+ };
73
+ lstatSync(path: string): {
74
+ isDirectory(): boolean;
75
+ isSymbolicLink(): boolean;
76
+ uid: number;
77
+ mode: number;
78
+ };
79
+ chmodSync(path: string, mode: number): void;
80
+ existsSync(path: string): boolean;
81
+ unlinkSync(path: string): void;
82
+ }
83
+ /** The process facts the owner reads: its own pid and uid, the home dir, the clock, and other pids' liveness. */
84
+ export interface OwnerProcessPort {
85
+ readonly pid: number;
86
+ /** Undefined where the platform has no uids (Windows). */
87
+ uid(): number | undefined;
88
+ homedir(): string;
89
+ nowMs(): number;
90
+ /** `process.kill(pid, 0)`: throws ESRCH for a dead pid, EPERM for another user's live one. */
91
+ kill(pid: number, signal: 0): void;
92
+ }
93
+ /** Optional ports for the owner's filesystem and process access; both default to Node's own. */
94
+ export interface OwnerPorts {
95
+ fs?: OwnerFsPort;
96
+ proc?: OwnerProcessPort;
97
+ }
42
98
  /**
43
99
  * The owner THIS process runs for `dataDir`, if any: how an in-process caller (duplicating the site
44
100
  * it serves) reaches {@link PgliteOwner.runExclusive} without a second open.
@@ -56,6 +112,7 @@ export declare function defaultPgliteSocketDir(required: {
56
112
  runDirName: string;
57
113
  }, optional?: {
58
114
  home?: string;
115
+ proc?: OwnerProcessPort;
59
116
  }): string;
60
117
  /** Throws unless `socketPath` fits in `sun_path`. */
61
118
  export declare function assertSocketPathFits(socketPath: string): void;
@@ -69,7 +126,7 @@ export declare function assertSocketPathFits(socketPath: string): void;
69
126
  */
70
127
  export declare function ensurePrivateDir(dir: string, optional?: {
71
128
  privateParent?: boolean;
72
- }): void;
129
+ } & OwnerPorts): void;
73
130
  /**
74
131
  * Takes the data dir's owner lock: created atomically with our pid in it. A lock whose pid is dead
75
132
  * (or that has had no pid for {@link EMPTY_LOCK_STALE_MS}) is taken over; a live one — including
@@ -80,7 +137,7 @@ export declare function ensurePrivateDir(dir: string, optional?: {
80
137
  export declare function acquireOwnerLock(required: {
81
138
  dataDir: string;
82
139
  lockFileName: string;
83
- }): () => void;
140
+ }, optional?: OwnerPorts): () => void;
84
141
  /**
85
142
  * Opens `dataDir` (creating it on first use — initdb takes several seconds) and serves it on a
86
143
  * private Unix socket.
@@ -91,6 +148,7 @@ export declare function acquireOwnerLock(required: {
91
148
  * @param required.runDirName names the default socket dir; see {@link defaultPgliteSocketDir}.
92
149
  * @param optional.socketDir default {@link defaultPgliteSocketDir}.
93
150
  * @param optional.idleInTransactionTimeoutMs default 30 s; see `PgliteSocketServer`.
151
+ * @param optional.fs / optional.proc see {@link OwnerPorts}; default Node's own.
94
152
  * @throws PgliteOwnerLockedError when another live owner holds `dataDir`.
95
153
  */
96
154
  export declare function startPgliteOwner(required: {
@@ -103,5 +161,5 @@ export declare function startPgliteOwner(required: {
103
161
  idleInTransactionTimeoutMs?: number;
104
162
  maxConnections?: number;
105
163
  log?: (message: string) => void;
106
- }): Promise<PgliteOwner>;
164
+ } & OwnerPorts): Promise<PgliteOwner>;
107
165
  //# sourceMappingURL=owner.d.ts.map
@@ -53,6 +53,35 @@ export class PgliteOwnerLockedError extends Error {
53
53
  this.name = "PgliteOwnerLockedError";
54
54
  }
55
55
  }
56
+ const nodeOwnerFs = {
57
+ openSync,
58
+ fstatSync,
59
+ readFileSync,
60
+ closeSync,
61
+ writeFileSync,
62
+ linkSync,
63
+ rmSync,
64
+ renameSync,
65
+ mkdirSync,
66
+ rmdirSync,
67
+ statSync,
68
+ lstatSync,
69
+ chmodSync,
70
+ existsSync,
71
+ unlinkSync,
72
+ };
73
+ const nodeOwnerProcess = {
74
+ pid: process.pid,
75
+ uid: () => process.getuid?.(),
76
+ homedir,
77
+ nowMs: () => Date.now(),
78
+ kill: (pid, signal) => {
79
+ process.kill(pid, signal);
80
+ },
81
+ };
82
+ function ownerIo(ports) {
83
+ return { fs: ports.fs ?? nodeOwnerFs, proc: ports.proc ?? nodeOwnerProcess };
84
+ }
56
85
  /** The owners this process runs, by resolved data dir (a second owner in-process is refused by the lock). */
57
86
  const runningOwners = new Map();
58
87
  /**
@@ -75,11 +104,12 @@ function dirKey(dataDir) {
75
104
  */
76
105
  export function defaultPgliteSocketDir(required, optional = {}) {
77
106
  assertPlainName(required.runDirName, "runDirName");
107
+ const { proc } = ownerIo(optional);
78
108
  const key = dirKey(required.dataDir);
79
- const inHome = join(optional.home ?? homedir(), `.${required.runDirName}`, "run", key);
109
+ const inHome = join(optional.home ?? proc.homedir(), `.${required.runDirName}`, "run", key);
80
110
  if (Buffer.byteLength(join(inHome, PGLITE_SOCKET_FILE)) <= MAX_SOCKET_PATH_BYTES)
81
111
  return inHome;
82
- return join(tmpSocketParent(required.runDirName), key);
112
+ return join(tmpSocketParent(required.runDirName, proc), key);
83
113
  }
84
114
  /** A consumer-chosen file or directory name: no separator, no leading dot, so it cannot escape its parent. */
85
115
  function assertPlainName(name, what) {
@@ -87,8 +117,8 @@ function assertPlainName(name, what) {
87
117
  throw new Error(`${what} must be a plain name: '${name}'`);
88
118
  }
89
119
  /** The per-user parent of fallback socket dirs. Other users can write `/tmp`, so it is checked, never trusted. */
90
- function tmpSocketParent(runDirName) {
91
- return join("/tmp", `${runDirName}-${process.getuid?.() ?? "user"}`);
120
+ function tmpSocketParent(runDirName, proc) {
121
+ return join("/tmp", `${runDirName}-${proc.uid() ?? "user"}`);
92
122
  }
93
123
  /** Throws unless `socketPath` fits in `sun_path`. */
94
124
  export function assertSocketPathFits(socketPath) {
@@ -97,8 +127,8 @@ export function assertSocketPathFits(socketPath) {
97
127
  throw new Error(`socket path is ${bytes} bytes; Unix sockets allow at most ${MAX_SOCKET_PATH_BYTES}: ${socketPath}`);
98
128
  }
99
129
  }
100
- function ownedByOtherUser(uid) {
101
- const own = process.getuid?.();
130
+ function ownedByOtherUser(uid, proc) {
131
+ const own = proc.uid();
102
132
  return own !== undefined && uid !== own;
103
133
  }
104
134
  /**
@@ -110,30 +140,34 @@ function ownedByOtherUser(uid) {
110
140
  * on when the parent sits directly in `/tmp` (the `/tmp/<app>-<uid>` fallback).
111
141
  */
112
142
  export function ensurePrivateDir(dir, optional = {}) {
143
+ const io = ownerIo(optional);
113
144
  const parent = dirname(resolve(dir));
114
145
  if (optional.privateParent ?? dirname(parent) === "/tmp") {
115
- try {
116
- mkdirSync(parent, { mode: 0o700 });
117
- }
118
- catch (error) {
119
- if (error.code !== "EEXIST")
120
- throw error;
121
- }
122
- const stat = lstatSync(parent);
123
- if (!stat.isDirectory() || ownedByOtherUser(stat.uid) || (stat.mode & 0o077) !== 0) {
124
- throw new Error(`refusing socket parent ${parent}: not a 0700 directory owned by this user`);
125
- }
146
+ ensurePrivateParent({ parent, io });
126
147
  }
127
- mkdirSync(dir, { recursive: true, mode: 0o700 });
128
- const stat = lstatSync(dir);
129
- if (!stat.isDirectory() || stat.isSymbolicLink() || ownedByOtherUser(stat.uid)) {
148
+ io.fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
149
+ const stat = io.fs.lstatSync(dir);
150
+ if (!stat.isDirectory() || stat.isSymbolicLink() || ownedByOtherUser(stat.uid, io.proc)) {
130
151
  throw new Error(`refusing socket dir ${dir}: not a directory owned by this user`);
131
152
  }
132
- chmodSync(dir, 0o700);
153
+ io.fs.chmodSync(dir, 0o700);
154
+ }
155
+ function ensurePrivateParent({ parent, io }, _optional = {}) {
156
+ try {
157
+ io.fs.mkdirSync(parent, { mode: 0o700 });
158
+ }
159
+ catch (error) {
160
+ if (error.code !== "EEXIST")
161
+ throw error;
162
+ }
163
+ const stat = io.fs.lstatSync(parent);
164
+ if (!stat.isDirectory() || ownedByOtherUser(stat.uid, io.proc) || (stat.mode & 0o077) !== 0) {
165
+ throw new Error(`refusing socket parent ${parent}: not a 0700 directory owned by this user`);
166
+ }
133
167
  }
134
- function pidAlive(pid) {
168
+ function pidAlive(pid, proc) {
135
169
  try {
136
- process.kill(pid, 0);
170
+ proc.kill(pid, 0);
137
171
  return true;
138
172
  }
139
173
  catch (error) {
@@ -148,10 +182,10 @@ function parsePid(text) {
148
182
  /** A lock with no pid in it (left by an older build between create and write) is stale only after this long. */
149
183
  const EMPTY_LOCK_STALE_MS = 10_000;
150
184
  /** The lock file's inode, pid and age, read through one descriptor; undefined when there is none. */
151
- function inspectLock(lockPath) {
185
+ function inspectLock(lockPath, fs) {
152
186
  let fd;
153
187
  try {
154
- fd = openSync(lockPath, "r");
188
+ fd = fs.openSync(lockPath, "r");
155
189
  }
156
190
  catch (error) {
157
191
  if (error.code === "ENOENT")
@@ -159,28 +193,34 @@ function inspectLock(lockPath) {
159
193
  throw error;
160
194
  }
161
195
  try {
162
- const { ino, mtimeMs } = fstatSync(fd);
163
- return { ino, mtimeMs, pid: parsePid(readFileSync(fd, "utf8")) };
196
+ const { ino, mtimeMs } = fs.fstatSync(fd);
197
+ return { ino, mtimeMs, pid: parsePid(fs.readFileSync(fd, "utf8")) };
164
198
  }
165
199
  finally {
166
- closeSync(fd);
200
+ fs.closeSync(fd);
167
201
  }
168
202
  }
169
- /** Creates the lock with our pid already in it (write a temp file, hard-link it in): never visible empty. */
170
- function tryCreateLock(lockPath) {
171
- const temp = `${lockPath}.${process.pid}.${randomBytes(4).toString("hex")}`;
172
- writeFileSync(temp, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
203
+ /** Hard-links `existingPath` at `newPath`: false when `newPath` already exists; any other failure throws. */
204
+ function linkUnlessExists(existingPath, newPath, fs) {
173
205
  try {
174
- linkSync(temp, lockPath);
175
- return true;
206
+ fs.linkSync(existingPath, newPath);
176
207
  }
177
208
  catch (error) {
178
209
  if (error.code === "EEXIST")
179
210
  return false;
180
211
  throw error;
181
212
  }
213
+ return true;
214
+ }
215
+ /** Creates the lock with our pid already in it (write a temp file, hard-link it in): never visible empty. */
216
+ function tryCreateLock(lockPath, { fs, proc }) {
217
+ const temp = `${lockPath}.${proc.pid}.${randomBytes(4).toString("hex")}`;
218
+ fs.writeFileSync(temp, `${proc.pid}\n`, { flag: "wx", mode: 0o600 });
219
+ try {
220
+ return linkUnlessExists(temp, lockPath, fs);
221
+ }
182
222
  finally {
183
- rmSync(temp, { force: true });
223
+ fs.rmSync(temp, { force: true });
184
224
  }
185
225
  }
186
226
  /**
@@ -188,38 +228,34 @@ function tryCreateLock(lockPath) {
188
228
  * inode, so a lock another starter took over in the meantime is put back, not deleted.
189
229
  * @throws PgliteOwnerLockedError when the lock moved aside was a newer one.
190
230
  */
191
- function moveStaleLock(dataDir, lockPath, seen) {
192
- const aside = `${lockPath}.stale.${process.pid}.${randomBytes(4).toString("hex")}`;
231
+ function moveStaleLock(dataDir, lockPath, seen, { fs, proc }) {
232
+ const aside = `${lockPath}.stale.${proc.pid}.${randomBytes(4).toString("hex")}`;
193
233
  try {
194
- renameSync(lockPath, aside);
234
+ fs.renameSync(lockPath, aside);
195
235
  }
196
236
  catch (error) {
197
237
  if (error.code === "ENOENT")
198
238
  return; // another starter removed it
199
239
  throw error;
200
240
  }
201
- const moved = inspectLock(aside);
241
+ const moved = inspectLock(aside, fs);
202
242
  if (moved?.ino === seen.ino) {
203
- rmSync(aside, { force: true });
243
+ fs.rmSync(aside, { force: true });
204
244
  return;
205
245
  }
206
246
  try {
207
- linkSync(aside, lockPath);
208
- }
209
- catch (error) {
210
- if (error.code !== "EEXIST")
211
- throw error;
247
+ linkUnlessExists(aside, lockPath, fs); // a lock another starter created since stays theirs
212
248
  }
213
249
  finally {
214
- rmSync(aside, { force: true });
250
+ fs.rmSync(aside, { force: true });
215
251
  }
216
252
  throw new PgliteOwnerLockedError(dataDir, moved?.pid);
217
253
  }
218
254
  /** Whether an observed lock is eligible for takeover; a fresh empty file remains contended. */
219
- function isStaleLock(seen) {
255
+ function isStaleLock(seen, proc) {
220
256
  if (seen.pid === undefined)
221
- return Date.now() - seen.mtimeMs > EMPTY_LOCK_STALE_MS;
222
- return !pidAlive(seen.pid);
257
+ return proc.nowMs() - seen.mtimeMs > EMPTY_LOCK_STALE_MS;
258
+ return !pidAlive(seen.pid, proc);
223
259
  }
224
260
  /**
225
261
  * Serializes removal of one observed inode, then rechecks it before renaming. Without this guard,
@@ -230,10 +266,10 @@ function isStaleLock(seen) {
230
266
  * must confirm no starter is running before removing it; automatic guard takeover would recreate
231
267
  * the same compare/rename race on the guard itself.
232
268
  */
233
- function removeStaleLock(dataDir, lockPath, seen) {
269
+ function removeStaleLock(dataDir, lockPath, seen, io) {
234
270
  const guard = `${lockPath}.reaping-${seen.ino}`;
235
271
  try {
236
- mkdirSync(guard, { mode: 0o700 });
272
+ io.fs.mkdirSync(guard, { mode: 0o700 });
237
273
  }
238
274
  catch (error) {
239
275
  if (error.code === "EEXIST")
@@ -241,15 +277,15 @@ function removeStaleLock(dataDir, lockPath, seen) {
241
277
  throw error;
242
278
  }
243
279
  try {
244
- const current = inspectLock(lockPath);
280
+ const current = inspectLock(lockPath, io.fs);
245
281
  if (current?.ino !== seen.ino)
246
282
  return; // a previous reaper already removed this inode
247
- if (!isStaleLock(current))
283
+ if (!isStaleLock(current, io.proc))
248
284
  throw new PgliteOwnerLockedError(dataDir, current.pid);
249
- moveStaleLock(dataDir, lockPath, current);
285
+ moveStaleLock(dataDir, lockPath, current, io);
250
286
  }
251
287
  finally {
252
- rmdirSync(guard);
288
+ io.fs.rmdirSync(guard);
253
289
  }
254
290
  }
255
291
  /**
@@ -259,29 +295,31 @@ function removeStaleLock(dataDir, lockPath, seen) {
259
295
  * function that only removes the inode acquired by this call.
260
296
  * @complexity O(L) time/space for L bytes in a pid file; at most five acquisition attempts.
261
297
  */
262
- export function acquireOwnerLock(required) {
298
+ export function acquireOwnerLock(required, optional = {}) {
263
299
  const { dataDir } = required;
264
300
  assertPlainName(required.lockFileName, "lockFileName");
301
+ const io = ownerIo(optional);
302
+ const { fs, proc } = io;
265
303
  const lockPath = join(dataDir, required.lockFileName);
266
304
  for (let attempt = 0; attempt < 5; attempt += 1) {
267
- if (tryCreateLock(lockPath)) {
268
- const acquiredInode = statSync(lockPath).ino;
305
+ if (tryCreateLock(lockPath, io)) {
306
+ const acquiredInode = fs.statSync(lockPath).ino;
269
307
  let released = false;
270
308
  return () => {
271
309
  if (released)
272
310
  return;
273
311
  released = true;
274
- const current = inspectLock(lockPath);
275
- if (current?.ino === acquiredInode && current.pid === process.pid)
276
- rmSync(lockPath, { force: true });
312
+ const current = inspectLock(lockPath, fs);
313
+ if (current?.ino === acquiredInode && current.pid === proc.pid)
314
+ fs.rmSync(lockPath, { force: true });
277
315
  };
278
316
  }
279
- const seen = inspectLock(lockPath);
317
+ const seen = inspectLock(lockPath, fs);
280
318
  if (seen === undefined)
281
319
  continue; // released in between
282
- if (!isStaleLock(seen))
320
+ if (!isStaleLock(seen, proc))
283
321
  throw new PgliteOwnerLockedError(dataDir, seen.pid);
284
- removeStaleLock(dataDir, lockPath, seen);
322
+ removeStaleLock(dataDir, lockPath, seen, io);
285
323
  }
286
324
  throw new Error(`could not take the PGlite owner lock ${lockPath}`);
287
325
  }
@@ -295,15 +333,18 @@ export function acquireOwnerLock(required) {
295
333
  * @param required.runDirName names the default socket dir; see {@link defaultPgliteSocketDir}.
296
334
  * @param optional.socketDir default {@link defaultPgliteSocketDir}.
297
335
  * @param optional.idleInTransactionTimeoutMs default 30 s; see `PgliteSocketServer`.
336
+ * @param optional.fs / optional.proc see {@link OwnerPorts}; default Node's own.
298
337
  * @throws PgliteOwnerLockedError when another live owner holds `dataDir`.
299
338
  */
300
339
  export async function startPgliteOwner(required, optional = {}) {
340
+ const io = ownerIo(optional);
341
+ const { fs } = io;
301
342
  const dataDir = resolve(required.dataDir);
302
- const socketDir = optional.socketDir ?? defaultPgliteSocketDir({ dataDir, runDirName: required.runDirName });
343
+ const socketDir = optional.socketDir ?? defaultPgliteSocketDir({ dataDir, runDirName: required.runDirName }, io);
303
344
  const socketPath = join(socketDir, PGLITE_SOCKET_FILE);
304
345
  assertSocketPathFits(socketPath);
305
- mkdirSync(dataDir, { recursive: true, mode: 0o700 });
306
- const releaseLock = acquireOwnerLock({ dataDir, lockFileName: required.lockFileName });
346
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
347
+ const releaseLock = acquireOwnerLock({ dataDir, lockFileName: required.lockFileName }, io);
307
348
  let db;
308
349
  let server;
309
350
  // WASM initialization can await native work with no referenced Node handle. Until the socket
@@ -311,10 +352,10 @@ export async function startPgliteOwner(required, optional = {}) {
311
352
  // Release on both success and failure, so an idle or refused boot retains no extra timer.
312
353
  const startupRef = setInterval(() => { }, 1_000);
313
354
  try {
314
- ensurePrivateDir(socketDir);
355
+ ensurePrivateDir(socketDir, io);
315
356
  // We hold the lock, so a socket file here was left by a dead owner.
316
- if (existsSync(socketPath))
317
- unlinkSync(socketPath);
357
+ if (fs.existsSync(socketPath))
358
+ fs.unlinkSync(socketPath);
318
359
  db = await required.PGlite.create({ dataDir, startParams: pgliteLowMemoryStartParams(required.PGlite) });
319
360
  server = new PgliteSocketServer({
320
361
  db,
@@ -324,14 +365,14 @@ export async function startPgliteOwner(required, optional = {}) {
324
365
  log: optional.log,
325
366
  });
326
367
  await server.start();
327
- chmodSync(socketPath, 0o600);
328
- if ((statSync(socketPath).mode & 0o077) !== 0)
368
+ fs.chmodSync(socketPath, 0o600);
369
+ if ((fs.statSync(socketPath).mode & 0o077) !== 0)
329
370
  throw new Error(`socket ${socketPath} is not owner-only`);
330
371
  }
331
372
  catch (error) {
332
373
  await server?.stop().catch(() => { });
333
374
  await db?.close().catch(() => { });
334
- rmSync(socketPath, { force: true });
375
+ fs.rmSync(socketPath, { force: true });
335
376
  releaseLock();
336
377
  throw error;
337
378
  }
@@ -353,7 +394,7 @@ export async function startPgliteOwner(required, optional = {}) {
353
394
  await open.close();
354
395
  }
355
396
  finally {
356
- rmSync(socketPath, { force: true });
397
+ fs.rmSync(socketPath, { force: true });
357
398
  releaseLock();
358
399
  }
359
400
  })();