@aria-framework/db-worker 0.8.1 → 0.10.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/driver/sqlite.js +100 -29
- package/package.json +42 -38
- package/settingsStore.js +66 -26
package/driver/sqlite.js
CHANGED
|
@@ -67,17 +67,89 @@ function createSqliteDriver(opts = {}) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** The contract over an open better-sqlite3 handle. */
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
|
|
70
|
+
// NESTING IS A PROPERTY OF THE CALL STACK, NOT OF THE CONNECTION.
|
|
71
|
+
//
|
|
72
|
+
// This was a depth counter hung off the handle, and a counter cannot tell two different things
|
|
73
|
+
// apart, because both look like "a transaction began while a transaction was open":
|
|
74
|
+
//
|
|
75
|
+
// NESTED transaction() called INSIDE another's callback -> a savepoint
|
|
76
|
+
// OVERLAP transaction() called WHILE another is open -> must wait its turn
|
|
77
|
+
//
|
|
78
|
+
// Treating overlap as nesting corrupted both sides: the second got a savepoint, the first's
|
|
79
|
+
// COMMIT destroyed every savepoint on the connection, and the second was then REJECTED while
|
|
80
|
+
// its writes stayed committed — a rollback that did not roll back. AsyncLocalStorage answers
|
|
81
|
+
// the question a counter cannot, because it follows the async call chain, which is what
|
|
82
|
+
// "inside" actually means.
|
|
83
|
+
//
|
|
84
|
+
// The context names the connection it belongs to. That is what the old per-connection counter
|
|
85
|
+
// was really protecting: a legacy { getDb } shim mints its OWN driver over a shared handle
|
|
86
|
+
// (auth/resolveDriver.js), and both must agree about nesting — while two different databases
|
|
87
|
+
// stay independent of each other.
|
|
88
|
+
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
89
|
+
const txContext = new AsyncLocalStorage();
|
|
90
|
+
|
|
91
|
+
/** Per-connection serialisation of TOP-LEVEL transactions. Hung off the handle for the same
|
|
92
|
+
* reason the depth was: every wrapper over one connection has to share one queue. */
|
|
93
|
+
const QUEUE_OWNER = Symbol.for('aria.db-worker.txqueue');
|
|
77
94
|
|
|
78
95
|
function wrap(db) {
|
|
79
96
|
const stmt = (sql) => db.prepare(sql);
|
|
80
|
-
|
|
97
|
+
// The connection is the owner of the top-level queue, and it has to BE an owner object rather
|
|
98
|
+
// than a bare promise so enqueue() can treat it exactly like any other level.
|
|
99
|
+
if (!db[QUEUE_OWNER]) db[QUEUE_OWNER] = { queue: Promise.resolve() };
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* One transaction context per LEVEL, each owning the queue for its own children.
|
|
103
|
+
*
|
|
104
|
+
* A single queue on the connection is not enough: two nested transactions started together
|
|
105
|
+
* inside one parent (a Promise.all over two stores, say) open two savepoints at once, and
|
|
106
|
+
* releasing the outer of the two releases the inner with it — the original bug, one level
|
|
107
|
+
* down. Siblings therefore take turns, exactly as top-level transactions do.
|
|
108
|
+
*
|
|
109
|
+
* Depth is fixed when the context is made rather than incremented and decremented in place,
|
|
110
|
+
* so a sibling cannot observe a depth that belongs to another one.
|
|
111
|
+
*/
|
|
112
|
+
const context = (depth) => ({ db, depth, queue: Promise.resolve() });
|
|
113
|
+
|
|
114
|
+
/** Serialise a child behind its siblings. Chained on BOTH settle paths, so one failure does
|
|
115
|
+
* not wedge every transaction queued after it. */
|
|
116
|
+
function enqueue(owner, run) {
|
|
117
|
+
const mine = owner.queue.then(run, run);
|
|
118
|
+
owner.queue = mine.then(() => {}, () => {});
|
|
119
|
+
return mine;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A real transaction. Entered only with the connection to itself. */
|
|
123
|
+
async function top(fn) {
|
|
124
|
+
const ctx = context(0);
|
|
125
|
+
db.exec('BEGIN');
|
|
126
|
+
try {
|
|
127
|
+
const out = await txContext.run(ctx, () => fn(api));
|
|
128
|
+
db.exec('COMMIT');
|
|
129
|
+
return out;
|
|
130
|
+
} catch (e) {
|
|
131
|
+
// The original error is what matters; a failed rollback must not mask it.
|
|
132
|
+
try { db.exec('ROLLBACK'); } catch (_) { /* noop */ }
|
|
133
|
+
throw e;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A savepoint inside the transaction we are demonstrably running within. */
|
|
138
|
+
async function nested(parent, fn) {
|
|
139
|
+
const ctx = context(parent.depth + 1);
|
|
140
|
+
const sp = `aria_sp_${ctx.depth}`;
|
|
141
|
+
db.exec(`SAVEPOINT ${sp}`);
|
|
142
|
+
try {
|
|
143
|
+
const out = await txContext.run(ctx, () => fn(api));
|
|
144
|
+
db.exec(`RELEASE ${sp}`);
|
|
145
|
+
return out;
|
|
146
|
+
} catch (e) {
|
|
147
|
+
// ROLLBACK TO rewinds to the savepoint but LEAVES it on the stack. Releasing it as well
|
|
148
|
+
// is what keeps the stack balanced for whatever the outer transaction does next.
|
|
149
|
+
try { db.exec(`ROLLBACK TO ${sp}`); db.exec(`RELEASE ${sp}`); } catch (_) { /* noop */ }
|
|
150
|
+
throw e;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
81
153
|
|
|
82
154
|
const api = {
|
|
83
155
|
kind: 'sqlite',
|
|
@@ -107,29 +179,28 @@ function wrap(db) {
|
|
|
107
179
|
/**
|
|
108
180
|
* Transactions are run with explicit BEGIN/COMMIT rather than better-sqlite3's
|
|
109
181
|
* `db.transaction(fn)`, because that helper REFUSES an async callback — and every callback
|
|
110
|
-
* here is async by contract.
|
|
111
|
-
*
|
|
182
|
+
* here is async by contract.
|
|
183
|
+
*
|
|
184
|
+
* Two paths, and telling them apart is the entire point:
|
|
185
|
+
*
|
|
186
|
+
* inside another transaction on THIS connection -> SAVEPOINT, so the inner half can fail
|
|
187
|
+
* without discarding the outer work
|
|
188
|
+
* anywhere else -> a real BEGIN, QUEUED behind whatever
|
|
189
|
+
* is already open on this connection
|
|
190
|
+
*
|
|
191
|
+
* The queue is what makes overlap safe rather than merely detected. SQLite allows one write
|
|
192
|
+
* transaction per connection, so waiting costs nothing that was ever available anyway.
|
|
193
|
+
*
|
|
194
|
+
* A nested call whose async context was somehow lost would be mistaken for a top-level one
|
|
195
|
+
* and queue behind the transaction it is running inside — a hang. AsyncLocalStorage
|
|
196
|
+
* propagates through promises, timers and microtasks, which is all any callback here uses,
|
|
197
|
+
* and test/transactions.js holds that down across await, setImmediate and Promise.all.
|
|
112
198
|
*/
|
|
113
199
|
async transaction(fn) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
// savepoints that can roll back independently without discarding the outer work.
|
|
119
|
-
const depth = db[DEPTH]++;
|
|
120
|
-
const sp = `aria_sp_${depth}`;
|
|
121
|
-
db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
|
|
122
|
-
try {
|
|
123
|
-
const out = await fn(api);
|
|
124
|
-
db.exec(depth === 0 ? 'COMMIT' : `RELEASE ${sp}`);
|
|
125
|
-
return out;
|
|
126
|
-
} catch (e) {
|
|
127
|
-
// The original error is what matters; a failed rollback must not mask it.
|
|
128
|
-
try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
|
|
129
|
-
throw e;
|
|
130
|
-
} finally {
|
|
131
|
-
db[DEPTH] = depth;
|
|
132
|
-
}
|
|
200
|
+
const parent = txContext.getStore();
|
|
201
|
+
if (parent && parent.db === db) return enqueue(parent, () => nested(parent, fn));
|
|
202
|
+
// No parent on this connection: a top-level transaction, queued on the connection itself.
|
|
203
|
+
return enqueue(db[QUEUE_OWNER], () => top(fn));
|
|
133
204
|
},
|
|
134
205
|
|
|
135
206
|
async close() {
|
package/package.json
CHANGED
|
@@ -1,38 +1,42 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
|
|
5
|
-
"license": "UNLICENSED",
|
|
6
|
-
"private": false,
|
|
7
|
-
"publishConfig": {
|
|
8
|
-
"access": "public"
|
|
9
|
-
},
|
|
10
|
-
"main": "index.js",
|
|
11
|
-
"files": [
|
|
12
|
-
"index.js",
|
|
13
|
-
"database.js",
|
|
14
|
-
"worker.js",
|
|
15
|
-
"client.js",
|
|
16
|
-
"tableOrder.js",
|
|
17
|
-
"schemaSnapshot.js",
|
|
18
|
-
"workerRegistry.js",
|
|
19
|
-
"settingsStore.js",
|
|
20
|
-
"dialect.js",
|
|
21
|
-
"driver/"
|
|
22
|
-
],
|
|
23
|
-
"peerDependencies": {
|
|
24
|
-
"better-sqlite3": ">=9",
|
|
25
|
-
"pg": ">=8"
|
|
26
|
-
},
|
|
27
|
-
"peerDependenciesMeta": {
|
|
28
|
-
"better-sqlite3": {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
},
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/db-worker",
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"database.js",
|
|
14
|
+
"worker.js",
|
|
15
|
+
"client.js",
|
|
16
|
+
"tableOrder.js",
|
|
17
|
+
"schemaSnapshot.js",
|
|
18
|
+
"workerRegistry.js",
|
|
19
|
+
"settingsStore.js",
|
|
20
|
+
"dialect.js",
|
|
21
|
+
"driver/"
|
|
22
|
+
],
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"better-sqlite3": ">=9",
|
|
25
|
+
"pg": ">=8"
|
|
26
|
+
},
|
|
27
|
+
"peerDependenciesMeta": {
|
|
28
|
+
"better-sqlite3": {
|
|
29
|
+
"optional": true
|
|
30
|
+
},
|
|
31
|
+
"pg": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"better-sqlite3": "^12.10.0",
|
|
37
|
+
"pg": "^8.23.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/regressions.js && node test/transactions.js && node test/smoke.js && node test/tier2.js"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/settingsStore.js
CHANGED
|
@@ -9,52 +9,78 @@
|
|
|
9
9
|
*
|
|
10
10
|
* The typed accessors (session-timeout parsing, brand-name defaults, currency tables) are app
|
|
11
11
|
* CONTENT and stay in the consuming model, which keeps this store as its base.
|
|
12
|
+
*
|
|
13
|
+
* EVERY METHOD IS ASYNC as of 0.9.0, and takes the DRIVER. There is no synchronous Postgres
|
|
14
|
+
* driver, so a store that runs on both engines has no choice. `{ getDb }` is still accepted and
|
|
15
|
+
* adopted — a consumer can upgrade this package before it rewires — but the handle it returns is
|
|
16
|
+
* wrapped rather than used, because the app owns the connection and opening a second one to the
|
|
17
|
+
* same SQLite file is how a writer ends up fighting its own lock.
|
|
18
|
+
*
|
|
19
|
+
* This store needs no lazy require for that adoption, unlike its siblings in auth/notify/backup/
|
|
20
|
+
* api-auth: it lives INSIDE db-worker, so createSqliteDriver is a local module.
|
|
12
21
|
*/
|
|
13
22
|
|
|
14
23
|
'use strict';
|
|
15
24
|
|
|
25
|
+
const { createSqliteDriver } = require('./driver/sqlite');
|
|
26
|
+
|
|
16
27
|
/**
|
|
17
|
-
* @param {
|
|
28
|
+
* @param {object} opts
|
|
29
|
+
* driver the db-worker driver (preferred since 0.9.0) — engine-agnostic
|
|
30
|
+
* getDb LEGACY: a function returning a better-sqlite3 handle, adopted into a driver here
|
|
31
|
+
* table defaults to 'settings'
|
|
18
32
|
* touchUpdatedAt: set true when the table carries an updated_at column to stamp on write.
|
|
19
33
|
*/
|
|
20
34
|
function createSettingsStore(opts = {}) {
|
|
21
|
-
|
|
22
|
-
if (
|
|
35
|
+
let driver = opts.driver || null;
|
|
36
|
+
if (!driver) {
|
|
37
|
+
if (typeof opts.getDb !== 'function') {
|
|
38
|
+
throw new Error('createSettingsStore: pass { driver } (preferred) or { getDb } (legacy)');
|
|
39
|
+
}
|
|
40
|
+
// LAZY, and it has to be. getDb() throws until the worker has opened the database, while
|
|
41
|
+
// stores are constructed at module load — so the handle is fetched on first use, not here.
|
|
42
|
+
let adopted = null;
|
|
43
|
+
driver = new Proxy({}, {
|
|
44
|
+
get(_t, prop) {
|
|
45
|
+
if (!adopted) adopted = createSqliteDriver({ adopt: opts.getDb() });
|
|
46
|
+
return adopted[prop];
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
23
51
|
const table = opts.table || 'settings';
|
|
24
52
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSettingsStore: suspicious table name "${table}"`);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
30
|
-
const upsert = `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
31
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value${touch}`;
|
|
53
|
+
|
|
54
|
+
// The timestamp comes from the DIALECT rather than being spelled out. SQLite has no date type
|
|
55
|
+
// and stores 'YYYY-MM-DD HH:MM:SS' UTC text; Postgres has a real timestamptz. A hand-written
|
|
56
|
+
// datetime() would be a silent wrong value on the second engine rather than a syntax error on it.
|
|
57
|
+
const now = () => driver.dialect.now();
|
|
32
58
|
|
|
33
59
|
return {
|
|
34
60
|
/** Raw value (string) or null if unset. */
|
|
35
|
-
get(key) {
|
|
36
|
-
const row =
|
|
61
|
+
async get(key) {
|
|
62
|
+
const row = await driver.get(`SELECT value FROM ${table} WHERE key = ?`, [key]);
|
|
37
63
|
return row ? row.value : null;
|
|
38
64
|
},
|
|
39
65
|
|
|
40
66
|
/** Upsert one setting (non-destructive; see the header). */
|
|
41
|
-
set(key, value) {
|
|
42
|
-
return
|
|
67
|
+
async set(key, value) {
|
|
68
|
+
return driver.run(upsertSql(), [key, value == null ? null : String(value)]);
|
|
43
69
|
},
|
|
44
70
|
|
|
45
71
|
/**
|
|
46
72
|
* Upsert several settings in ONE transaction. `undefined` values are skipped (an absent form
|
|
47
73
|
* field is not a request to clear); null is stored as null.
|
|
48
74
|
*/
|
|
49
|
-
setMultiple(keyValues) {
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
75
|
+
async setMultiple(keyValues) {
|
|
76
|
+
const sql = upsertSql();
|
|
77
|
+
await driver.transaction(async (tx) => {
|
|
78
|
+
// for...of, not forEach: forEach discards the promise, so the transaction would commit
|
|
79
|
+
// before a single row was written.
|
|
53
80
|
for (const [key, value] of Object.entries(keyValues || {})) {
|
|
54
|
-
if (value !== undefined)
|
|
81
|
+
if (value !== undefined) await tx.run(sql, [key, value == null ? null : String(value)]);
|
|
55
82
|
}
|
|
56
83
|
});
|
|
57
|
-
run();
|
|
58
84
|
},
|
|
59
85
|
|
|
60
86
|
/**
|
|
@@ -62,21 +88,35 @@ function createSettingsStore(opts = {}) {
|
|
|
62
88
|
* `_` is a LIKE wildcard, so an unescaped 'company_' would also match 'companyXname' — a
|
|
63
89
|
* latent bug in the hand-rolled version this replaces.
|
|
64
90
|
*/
|
|
65
|
-
getByPrefix(prefix) {
|
|
91
|
+
async getByPrefix(prefix) {
|
|
66
92
|
const esc = String(prefix).replace(/[\\%_]/g, (c) => '\\' + c);
|
|
67
|
-
const rows =
|
|
68
|
-
|
|
69
|
-
|
|
93
|
+
const rows = await driver.all(
|
|
94
|
+
`SELECT key, value FROM ${table} WHERE key LIKE ? ESCAPE '\\'`, [esc + '%']
|
|
95
|
+
);
|
|
70
96
|
const out = {};
|
|
71
97
|
for (const r of rows) out[r.key] = r.value;
|
|
72
98
|
return out;
|
|
73
99
|
},
|
|
74
100
|
|
|
75
101
|
/** All settings as an array of { key, value }, ordered by key. */
|
|
76
|
-
all() {
|
|
77
|
-
return
|
|
102
|
+
async all() {
|
|
103
|
+
return driver.all(`SELECT key, value FROM ${table} ORDER BY key`);
|
|
78
104
|
}
|
|
79
105
|
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Built per call rather than once at construction, because it reads the dialect — and with a
|
|
109
|
+
* LEGACY { getDb } the driver is a lazy proxy whose dialect is not resolvable until the first
|
|
110
|
+
* real use. Building it at construction would call getDb() before the worker opened the
|
|
111
|
+
* database, which is the failure the proxy exists to avoid.
|
|
112
|
+
*/
|
|
113
|
+
function upsertSql() {
|
|
114
|
+
const touch = opts.touchUpdatedAt ? `, updated_at = ${now()}` : '';
|
|
115
|
+
const insertCols = opts.touchUpdatedAt ? '(key, value, updated_at)' : '(key, value)';
|
|
116
|
+
const insertVals = opts.touchUpdatedAt ? `(?, ?, ${now()})` : '(?, ?)';
|
|
117
|
+
return `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
|
|
118
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value${touch}`;
|
|
119
|
+
}
|
|
80
120
|
}
|
|
81
121
|
|
|
82
122
|
module.exports = { createSettingsStore };
|