@jskit-ai/resource-runtime 0.2.32 → 0.2.34
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
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Depends on json-rest-api 3.1.10 exactly (from 3.1.9): in `lock`, `lockMany`, `lockWhere` and `lockPages` (and so in a `patch` with `lockVersion` or `onlyIf`, and `lockOrCreate`, which lock first), every subquery of the table's row policy and its contributions (an `ownTable` read, another owner's `joinSource`, any `whereExists` or `whereIn` it writes) takes a shared lock, `FOR SHARE` on PostgreSQL and `LOCK IN SHARE MODE` on MySQL and MariaDB, whatever the lock's `lockMode`. Before, those subqueries were plain reads: on MySQL and MariaDB, inside a transaction that had already read plainly, a lock decided from that read's snapshot, so a member removed since still locked and read the rows and a grant added, revoked or moved since was ignored; on PostgreSQL a lock that waited for its row rechecked it against the policy's rows as they were when its statement began. Now the lock decides from the membership and grant rows as last committed, waits for a transaction changing them, and holds them unchanged until commit, while other locks that read them go on at once. No policy changes. A change to a membership or grant now waits for the locks that read it; work that locks through a policy and then writes a row the policy read can deadlock with work doing the same (the database fails one, and `withTransaction` runs it again when it opened the transaction); on MySQL and MariaDB a locking subquery locks every row it examines, so the policy's subqueries need an index that finds the deciding rows directly. With MariaDB's `innodb_snapshot_isolation` on, a deciding row written since the snapshot can fail the lock with errno 1020, as the lock's own rows can, and `withTransaction` runs the work again when it opened the transaction. `claim` and every read that takes no lock are unchanged.
|
|
5
6
|
- Depends on json-rest-api 3.1.9 exactly (from 3.1.8): a handle's `patchWhere` and `deleteWhere` select their rows with a locking read on MySQL and MariaDB, so inside a transaction that has already read they write the rows committed since, as `UPDATE … WHERE` does (with MariaDB's `innodb_snapshot_isolation` on, the write fails with errno 1020 instead and `withTransaction` runs the work again when it opened the transaction); `lockWhere` takes `after`, which `lockPages` pages by (above); and `createMany`'s `onConflict` ignore takes rows that carry an id (above).
|
|
6
7
|
- `lockPages(filters, txOptions)` locks every row the filters select, a page at a time: `for await (const records of handle.lockPages(filters, txOptions))`. Each page is one locking read of up to `pageSize` rows (1 to 1,000, the default) in id order, after the last id of the page before (json-rest-api's `lockWhere` `after`), so the statements follow the pages: 3 pages among 25 rows and among 250 send the same statements. A locking read sees the latest committed rows whatever the transaction's snapshot, so work that joins a transaction that may already have read plainly (on MySQL and MariaDB the snapshot of a transaction's first plain read) reads a set larger than one `lockWhere` as it stands now. In a request it throws `RowLimitError` past the request row limit, as `queryPages` does; background work locks without one. It takes no `sort` or `limit`, and on MySQL and MariaDB needs an index that reads in id order after the ownership columns and the filters' equalities.
|
|
7
8
|
- `createMany(rows, { onConflict: { keys, action: "ignore" } })` takes rows that carry an id, for a table whose ids the code makes (a random `uuid`): a row its keys match writes nothing and keeps its stored id, a new row takes the id it brings, and an id that is already another row's, with other keys, fails the batch, on every database (json-rest-api skips only a clash on the keys' unique index). A merge still takes rows without an id, unless the id is its one key on a table with no owners.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/resource-runtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.34",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
"./locales/en.json": "./locales/en.json"
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@jskit-ai/resource-core": "0.1.
|
|
19
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
20
|
-
"json-rest-api": "3.1.
|
|
18
|
+
"@jskit-ai/resource-core": "0.1.217",
|
|
19
|
+
"@jskit-ai/resource-crud-core": "0.1.219",
|
|
20
|
+
"json-rest-api": "3.1.10"
|
|
21
21
|
},
|
|
22
22
|
"description": "The resource runtime: features own their tables through it and read and write them with scoped handles on json-rest-api.",
|
|
23
23
|
"jskit": {
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
}
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
68
|
-
"@jskit-ai/kernel": "0.2.
|
|
67
|
+
"@jskit-ai/database-runtime": "0.1.275",
|
|
68
|
+
"@jskit-ai/kernel": "0.2.26"
|
|
69
69
|
}
|
|
70
70
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { lockPolicyCases } from "./support/lockPolicyCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of lockPolicyCases(ownMysqlDatabase)) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { createPackageTestKnex } from "../src/test/index.js";
|
|
3
|
+
import { lockPolicyCases } from "./support/lockPolicyCases.js";
|
|
4
|
+
|
|
5
|
+
// SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
|
|
6
|
+
for (const [name, run] of lockPolicyCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
3
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
4
|
+
|
|
5
|
+
// A lock decides which rows its caller may lock from the rows its row policy reads as last committed: every subquery
|
|
6
|
+
// of the policy (here ownTable reads of a membership and a grant) takes a shared lock in lock(), lockMany(),
|
|
7
|
+
// lockWhere() and lockPages(). On MySQL and MariaDB a plain subquery inside a transaction that has already read
|
|
8
|
+
// plainly answers from that read's snapshot, and on PostgreSQL a lock that waited for its row rechecked it against
|
|
9
|
+
// the policy's rows as they were when the statement began. Each database's test file runs these cases on its own
|
|
10
|
+
// connection.
|
|
11
|
+
|
|
12
|
+
const ADA = "7";
|
|
13
|
+
const asAda = Object.freeze({ context: Object.freeze({ actor: Object.freeze({ id: ADA }), workspace: Object.freeze({ id: "1" }) }) });
|
|
14
|
+
|
|
15
|
+
const memberResource = defineTableResource({
|
|
16
|
+
name: "members",
|
|
17
|
+
tableName: "lp_members",
|
|
18
|
+
ownership: "workspace",
|
|
19
|
+
schema: {
|
|
20
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
21
|
+
userId: { type: "string", required: true, storage: { column: "user_id" } }
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
const grantResource = defineTableResource({
|
|
25
|
+
name: "grants",
|
|
26
|
+
tableName: "lp_grants",
|
|
27
|
+
ownership: "workspace",
|
|
28
|
+
schema: {
|
|
29
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
30
|
+
userId: { type: "string", required: true, storage: { column: "user_id" } },
|
|
31
|
+
projectId: { type: "integer", required: true, storage: { column: "project_id" } }
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const projectResource = defineTableResource({
|
|
35
|
+
name: "projects",
|
|
36
|
+
tableName: "lp_projects",
|
|
37
|
+
ownership: "workspace",
|
|
38
|
+
schema: {
|
|
39
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
40
|
+
name: { type: "string", required: true, search: true }
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// A member of the project's workspace with a grant of the project itself.
|
|
45
|
+
function memberWithGrant({ query, caller, column, ownTable }) {
|
|
46
|
+
if (caller.kind !== "user") {
|
|
47
|
+
return caller.kind !== "anonymous";
|
|
48
|
+
}
|
|
49
|
+
query.whereExists(ownTable("members").select(1)
|
|
50
|
+
.whereColumn("lp_members.workspace_id", column("workspaceId"))
|
|
51
|
+
.where("lp_members.user_id", caller.userId));
|
|
52
|
+
query.whereIn(column("id"), ownTable("grants").select("project_id").where("lp_grants.user_id", caller.userId));
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Projects 1 to 3 of workspace 1; Ada (7) is its member and holds a grant of project 1.
|
|
58
|
+
* `reset()` puts those rows back.
|
|
59
|
+
* @param {import("knex").Knex} knex
|
|
60
|
+
*/
|
|
61
|
+
async function projectsOf(knex) {
|
|
62
|
+
await knex.schema.createTable("lp_members", (table) => {
|
|
63
|
+
table.increments("id");
|
|
64
|
+
table.integer("workspace_id").nullable();
|
|
65
|
+
table.string("user_id").notNullable();
|
|
66
|
+
table.unique(["workspace_id", "user_id"]);
|
|
67
|
+
});
|
|
68
|
+
await knex.schema.createTable("lp_grants", (table) => {
|
|
69
|
+
table.increments("id");
|
|
70
|
+
table.integer("workspace_id").nullable();
|
|
71
|
+
table.string("user_id").notNullable();
|
|
72
|
+
table.integer("project_id").notNullable();
|
|
73
|
+
table.index(["user_id", "project_id"]);
|
|
74
|
+
});
|
|
75
|
+
await knex.schema.createTable("lp_projects", (table) => {
|
|
76
|
+
table.increments("id");
|
|
77
|
+
table.integer("workspace_id").nullable();
|
|
78
|
+
table.string("name").notNullable();
|
|
79
|
+
// An index that reads a workspace's rows in id order, which lockWhere and lockPages need on MySQL and MariaDB.
|
|
80
|
+
table.index(["workspace_id"], "lp_projects_workspace");
|
|
81
|
+
});
|
|
82
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
83
|
+
const { projects } = await runtime.own("projects.feature", [memberResource, grantResource, { resource: projectResource, rowPolicy: memberWithGrant }]);
|
|
84
|
+
const reset = async () => {
|
|
85
|
+
for (const table of ["lp_grants", "lp_members", "lp_projects"]) {
|
|
86
|
+
await knex(table).del();
|
|
87
|
+
}
|
|
88
|
+
await knex("lp_projects").insert([1, 2, 3].map((id) => ({ id, workspace_id: 1, name: `P${id}` })));
|
|
89
|
+
await knex("lp_members").insert({ id: 1, workspace_id: 1, user_id: ADA });
|
|
90
|
+
await knex("lp_grants").insert({ id: 1, workspace_id: 1, user_id: ADA, project_id: 1 });
|
|
91
|
+
};
|
|
92
|
+
await reset();
|
|
93
|
+
return { projects, reset };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Each lock method's lock of Ada's rows among projects 1 to 3, as the names it answers. */
|
|
97
|
+
const LOCKS = {
|
|
98
|
+
lockMany: (projects, tx) => projects.lockMany(["1", "2", "3"], { ...tx, missing: "skip", fields: ["name"] }),
|
|
99
|
+
lockWhere: (projects, tx) => projects.lockWhere({}, { ...tx, fields: ["name"] }),
|
|
100
|
+
lockPages: async (projects, tx) => {
|
|
101
|
+
const records = [];
|
|
102
|
+
for await (const page of projects.lockPages({}, { ...tx, pageSize: 2, fields: ["name"] })) {
|
|
103
|
+
records.push(...page);
|
|
104
|
+
}
|
|
105
|
+
return records;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const namesOf = (records) => records.map(({ name }) => name).sort();
|
|
109
|
+
|
|
110
|
+
// What another transaction commits, and what Ada's lock must then answer.
|
|
111
|
+
const CHANGES = {
|
|
112
|
+
"her membership revoked": { write: (db) => db("lp_members").where({ id: 1 }).del(), names: [] },
|
|
113
|
+
"her grant revoked": { write: (db) => db("lp_grants").where({ id: 1 }).del(), names: [] },
|
|
114
|
+
"a grant of project 2 added": { write: (db) => db("lp_grants").insert({ id: 2, workspace_id: 1, user_id: ADA, project_id: 2 }), names: ["P1", "P2"] },
|
|
115
|
+
"her grant moved to project 2": { write: (db) => db("lp_grants").where({ id: 1 }).update({ project_id: 2 }), names: ["P2"] }
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** PostgreSQL's id of the connection a transaction holds; MySQL and MariaDB need none (see lockWaitOf). */
|
|
119
|
+
async function backendOf(trx) {
|
|
120
|
+
return trx.client.config.client === "pg" ? (await trx.raw("SELECT pg_backend_pid() AS id")).rows[0].id : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Resolves once the lock waits for the writer; fails at once if `waiter` ends first. PostgreSQL shows the wait of
|
|
125
|
+
* backend `id` in pg_stat_activity. MySQL and MariaDB show a lock wait only to a user with the PROCESS privilege,
|
|
126
|
+
* which a test database's user may lack, so there the lock must still run after 300 ms: a lock that waits for nothing
|
|
127
|
+
* answers in milliseconds, and what it answers once the writer commits is checked either way.
|
|
128
|
+
* @param {import("knex").Knex} knex another connection's Knex
|
|
129
|
+
* @param {number | null} id
|
|
130
|
+
* @param {Promise<unknown>} waiter
|
|
131
|
+
*/
|
|
132
|
+
async function lockWaitOf(knex, id, waiter) {
|
|
133
|
+
let outcome;
|
|
134
|
+
waiter.then(() => {
|
|
135
|
+
outcome = "answered without waiting for a lock";
|
|
136
|
+
}, (error) => {
|
|
137
|
+
outcome = `failed before it waited: ${error.message}`;
|
|
138
|
+
});
|
|
139
|
+
const running = () => {
|
|
140
|
+
if (outcome) {
|
|
141
|
+
assert.fail(`the lock ${outcome}`);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
if (id === null) {
|
|
145
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
146
|
+
running();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
for (const deadline = Date.now() + 5000; Date.now() < deadline;) {
|
|
150
|
+
running();
|
|
151
|
+
const { rows: [{ waiting }] } = await knex.raw("SELECT COUNT(*)::int AS waiting FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock'", [id]);
|
|
152
|
+
if (waiting > 0) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
156
|
+
}
|
|
157
|
+
assert.fail("the lock never waited for the writer");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
162
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
163
|
+
*/
|
|
164
|
+
function lockPolicyCases(connect) {
|
|
165
|
+
const needsTwoConnections = async (t, suffix) => {
|
|
166
|
+
const knex = await connect(t, suffix);
|
|
167
|
+
if (knex.client.config.client === "better-sqlite3") {
|
|
168
|
+
t.skip("SQLite has one writer, so no other transaction commits while a lock's is open");
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return knex;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const cases = [
|
|
175
|
+
["a lock's row policy subqueries take a shared lock on MySQL, MariaDB and PostgreSQL, and none on SQLite", async (t) => {
|
|
176
|
+
const knex = await connect(t, "da_lp_sql");
|
|
177
|
+
const { projects } = await projectsOf(knex);
|
|
178
|
+
const client = knex.client.config.client;
|
|
179
|
+
const clause = client === "pg" ? / for share\)/giu : / lock in share mode\)/giu;
|
|
180
|
+
for (const [method, lock] of Object.entries(LOCKS)) {
|
|
181
|
+
const statements = [];
|
|
182
|
+
const record = ({ sql }) => statements.push(sql);
|
|
183
|
+
knex.on("query", record);
|
|
184
|
+
try {
|
|
185
|
+
assert.deepEqual(namesOf(await projects.withTransaction(asAda, (tx) => lock(projects, tx))), ["P1"], method);
|
|
186
|
+
} finally {
|
|
187
|
+
knex.removeListener("query", record);
|
|
188
|
+
}
|
|
189
|
+
const locking = statements.filter((sql) => sql.includes("lp_members"));
|
|
190
|
+
assert.ok(locking.length > 0, method);
|
|
191
|
+
for (const sql of locking) {
|
|
192
|
+
// The membership's and the grant's subqueries; SQLite has no row locks, so nothing changes there.
|
|
193
|
+
assert.equal(sql.match(clause)?.length ?? 0, client === "better-sqlite3" ? 0 : 2, `${method}: ${sql}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}]
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
for (const [method, lock] of Object.entries(LOCKS)) {
|
|
200
|
+
cases.push([`${method} decides from the membership and grants other transactions committed after the transaction's first plain read`, async (t) => {
|
|
201
|
+
const knex = await needsTwoConnections(t, `da_lp_read_${method.toLowerCase()}`);
|
|
202
|
+
if (!knex) return;
|
|
203
|
+
const { projects, reset } = await projectsOf(knex);
|
|
204
|
+
for (const [change, { write, names }] of Object.entries(CHANGES)) {
|
|
205
|
+
await reset();
|
|
206
|
+
const locked = await projects.withTransaction(asAda, async (tx) => {
|
|
207
|
+
// On MySQL and MariaDB this read fixes the transaction's REPEATABLE READ snapshot.
|
|
208
|
+
assert.deepEqual(namesOf(await projects.queryAll({}, tx)), ["P1"], change);
|
|
209
|
+
await write(knex);
|
|
210
|
+
return lock(projects, tx);
|
|
211
|
+
});
|
|
212
|
+
assert.deepEqual(namesOf(locked), names, change);
|
|
213
|
+
}
|
|
214
|
+
}]);
|
|
215
|
+
|
|
216
|
+
cases.push([`${method} waits for a writer of the policy's rows, then decides from what it committed`, async (t) => {
|
|
217
|
+
const knex = await needsTwoConnections(t, `da_lp_wait_${method.toLowerCase()}`);
|
|
218
|
+
if (!knex) return;
|
|
219
|
+
const { projects, reset } = await projectsOf(knex);
|
|
220
|
+
const writers = {
|
|
221
|
+
// One that holds project 1 itself: the lock waits for its row, then must not recheck it against the old grant.
|
|
222
|
+
"holds project 1 and revokes her grant": async (db) => {
|
|
223
|
+
await db("lp_projects").where({ id: 1 }).update({ name: "P1 renamed" });
|
|
224
|
+
await db("lp_grants").where({ id: 1 }).del();
|
|
225
|
+
},
|
|
226
|
+
// One that touches no row the lock takes: the lock waits only because its subquery locks the membership.
|
|
227
|
+
"revokes her membership": (db) => db("lp_members").where({ id: 1 }).del()
|
|
228
|
+
};
|
|
229
|
+
for (const [writes, write] of Object.entries(writers)) {
|
|
230
|
+
await reset();
|
|
231
|
+
const writer = await knex.transaction();
|
|
232
|
+
try {
|
|
233
|
+
await write(writer);
|
|
234
|
+
const locked = await projects.withTransaction({ ...asAda, retry: false }, async (tx) => {
|
|
235
|
+
assert.deepEqual(namesOf(await projects.queryAll({}, tx)), ["P1"], writes);
|
|
236
|
+
const id = await backendOf(tx.trx);
|
|
237
|
+
const waiting = lock(projects, tx);
|
|
238
|
+
try {
|
|
239
|
+
await lockWaitOf(knex, id, waiting);
|
|
240
|
+
} finally {
|
|
241
|
+
// Also when the lock never waited, so a lock still running ends rather than waits for the writer.
|
|
242
|
+
await writer.commit();
|
|
243
|
+
}
|
|
244
|
+
return waiting;
|
|
245
|
+
});
|
|
246
|
+
assert.deepEqual(namesOf(locked), [], writes);
|
|
247
|
+
} finally {
|
|
248
|
+
if (!writer.isCompleted()) await writer.rollback();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}]);
|
|
252
|
+
}
|
|
253
|
+
return cases;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export { lockPolicyCases };
|