@jskit-ai/resource-runtime 0.2.33 → 0.2.35
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 +5 -0
- package/package.json +2 -2
- package/src/server/contexts.js +8 -3
- package/src/server/handleLocks.js +84 -9
- package/src/server/lockOrCreate.js +3 -0
- package/test/hiddenFields.test.js +19 -0
- package/test/lockPolicy.mysql.test.js +8 -0
- package/test/lockPolicy.test.js +8 -0
- package/test/resourceRuntime.test.js +38 -0
- package/test/support/lockPolicyCases.js +256 -0
- package/test/support/lockWhereOrderCases.js +127 -4
- package/test/upsertGaps.mysql.test.js +138 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A row policy's `caller` for a user's context that says why it was made carries the reason: `{ kind: "user", userId, reason }`, as for the context `workspaces.roleContext` builds for installer and seed work. The reason grants nothing: the same read answers the same rows, refuses the same hidden fields and keeps the request row limits. A reason that is no text is none, and a context with a reason but no user is still anonymous.
|
|
6
|
+
- `lockPages(filters, { ...txOptions, pageBy })` pages by a list filter's column, then the id: `pageBy` names a filter of the call whose search entry says `filterOperator: "in"`, on the table's own column, given a list. Each page locks up to `pageSize` rows of the values no page has passed, in that column's order, and the rest of the last value's rows follow in id order, that value alone, so on MySQL and MariaDB every statement reads one value's range after another of an index that holds the column after the ownership columns and the filters' other fixed columns, and examines and holds only the listed values' rows, where id order walks, and holds, every row of the owner it passes. Ten listed actions among 30 and among 300 send the same statements. A `pageBy` that names no such filter, or a filter given no list, is a TypeError before any statement; a value given otherwise than the column stores it throws rather than paging forever. Needs json-rest-api 3.1.11, whose `lockWhere` counts a list filter given one value as an equality when it picks its index.
|
|
7
|
+
- Depends on json-rest-api 3.1.11 exactly (from 3.1.10): on MySQL and MariaDB `createMany`'s `onConflict` ignore and merge read their keys plainly, lock only the rows found and insert the rest with a plain INSERT, so two first saves of new keys in one gap no longer deadlock (20 rounds in each start order, ignore and merge, `upsertGaps.mysql.test.js`); that read is a plain read, which takes the transaction's snapshot when it has none yet, so lock before upserting. A lock's belongs-to fields are checked against their targets as last committed (a shared lock on MySQL and MariaDB), so a link to a target saved after the transaction's first plain read no longer reads null, and `lock` and `lockMany` read the primary key on MySQL and MariaDB, holding the listed rows alone. `lockOrCreate` still locks before it inserts, so its work reads what the record's previous holder committed; first uses of neighbouring ids can still deadlock on MySQL and MariaDB, and run again as before.
|
|
8
|
+
|
|
9
|
+
- 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
10
|
- 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
11
|
- `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
12
|
- `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.35",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@jskit-ai/resource-core": "0.1.217",
|
|
19
19
|
"@jskit-ai/resource-crud-core": "0.1.219",
|
|
20
|
-
"json-rest-api": "3.1.
|
|
20
|
+
"json-rest-api": "3.1.11"
|
|
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": {
|
package/src/server/contexts.js
CHANGED
|
@@ -53,9 +53,10 @@ function isJobContext(context) {
|
|
|
53
53
|
* background work a system context derived for one workspace or user ("job"), each with its reason; a request by a
|
|
54
54
|
* signed-in user ("user", with the user's id); or a request by no one ("anonymous"). A derived job context names a
|
|
55
55
|
* user only as the person it acts for (`actorId`, when it was given one), never as a signed-in user, so a policy
|
|
56
|
-
* that keys on the actor tells it from an anonymous request by its kind.
|
|
56
|
+
* that keys on the actor tells it from an anonymous request by its kind. A user's context that says why it was made
|
|
57
|
+
* (`reason`, as `workspaces.roleContext` records it) hands the reason on; it grants nothing.
|
|
57
58
|
* @param {unknown} context
|
|
58
|
-
* @returns {Readonly<{ kind: "system", reason: string } | { kind: "job", reason: string, actorId?: string } | { kind: "user", userId: string } | { kind: "anonymous" }>}
|
|
59
|
+
* @returns {Readonly<{ kind: "system", reason: string } | { kind: "job", reason: string, actorId?: string } | { kind: "user", userId: string, reason?: string } | { kind: "anonymous" }>}
|
|
59
60
|
*/
|
|
60
61
|
function callerOf(context) {
|
|
61
62
|
if (isSystemContext(context)) {
|
|
@@ -72,7 +73,11 @@ function callerOf(context) {
|
|
|
72
73
|
});
|
|
73
74
|
}
|
|
74
75
|
const userId = resolveActorId(context);
|
|
75
|
-
|
|
76
|
+
if (!userId) {
|
|
77
|
+
return Object.freeze({ kind: "anonymous" });
|
|
78
|
+
}
|
|
79
|
+
const reason = typeof context.reason === "string" ? context.reason.trim() : "";
|
|
80
|
+
return Object.freeze(reason ? { kind: "user", userId, reason } : { kind: "user", userId });
|
|
76
81
|
}
|
|
77
82
|
|
|
78
83
|
/**
|
|
@@ -300,28 +300,27 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
300
300
|
* and MariaDB it needs an index that reads in id order after the ownership columns and the filters' single-value
|
|
301
301
|
* equalities. In a request it throws RowLimitError past the request row limit, as queryPages() does; background
|
|
302
302
|
* work locks without one. `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
|
|
303
|
+
* `pageBy` names a list filter of the filters (one whose search entry says `filterOperator: "in"`, on the table's
|
|
304
|
+
* own column): the pages then follow that column, then the id, so on MySQL and MariaDB an index that starts with the
|
|
305
|
+
* ownership columns, the filters' other single-value equalities and that column reads only the listed values' rows
|
|
306
|
+
* (see listPages). Its values are given as the column stores them.
|
|
303
307
|
* @param {object} filters
|
|
304
|
-
* @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number }} options
|
|
308
|
+
* @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number, pageBy?: string }} options
|
|
305
309
|
* @returns {AsyncGenerator<object[], void, undefined>}
|
|
306
310
|
*/
|
|
307
311
|
async function* lockPages(filters, options) {
|
|
308
312
|
requireDefinedFilters(name, "lockPages", filters);
|
|
309
|
-
const { pageSize = MAX_LOCK_PAGE, sort, limit, ...lockOptions } = options;
|
|
313
|
+
const { pageSize = MAX_LOCK_PAGE, sort, limit, pageBy, ...lockOptions } = options;
|
|
310
314
|
if (sort !== undefined || limit !== undefined) {
|
|
311
315
|
throw new TypeError(`${name}.lockPages() locks in id order, a page of pageSize rows at a time, so it takes no sort or limit.`);
|
|
312
316
|
}
|
|
313
317
|
if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > MAX_LOCK_PAGE) {
|
|
314
318
|
throw new TypeError(`${name}.lockPages() pageSize is an integer from 1 to ${MAX_LOCK_PAGE}. Received: ${JSON.stringify(pageSize)}`);
|
|
315
319
|
}
|
|
320
|
+
const pages = pageBy === undefined ? idPages(filters, pageSize, lockOptions) : listPages(filters, listFilterOf(pageBy, filters), pageSize, lockOptions);
|
|
316
321
|
const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
|
|
317
322
|
let rows = 0;
|
|
318
|
-
for (
|
|
319
|
-
const page = await lockRead("lockPages", "lockWhere", { filters, limit: pageSize, ...(after === undefined ? {} : { after }) }, lockOptions);
|
|
320
|
-
// A page after an id never holds it. A storage that ignored `after` would answer the first page again and
|
|
321
|
-
// again, and background work, which has no row limit, would page forever.
|
|
322
|
-
if (after !== undefined && page.some((record) => record.id === after)) {
|
|
323
|
-
throw new Error(`${name}.lockPages() read the row ${JSON.stringify(after)} again in the page after it: its storage does not page lockWhere by after, so its pages would never end.`);
|
|
324
|
-
}
|
|
323
|
+
for await (const page of pages) {
|
|
325
324
|
rows += page.length;
|
|
326
325
|
if (rowLimit !== undefined && rows > rowLimit) {
|
|
327
326
|
throw new RowLimitError(name, rowLimit, undefined, "lockPages");
|
|
@@ -329,6 +328,26 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
329
328
|
if (page.length > 0) {
|
|
330
329
|
yield page;
|
|
331
330
|
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* lockPages' pages in id order, each after the last id of the page before.
|
|
336
|
+
* @param {object} filters
|
|
337
|
+
* @param {number} pageSize
|
|
338
|
+
* @param {object} lockOptions
|
|
339
|
+
* @param {unknown} [after] The id the pages start after.
|
|
340
|
+
* @returns {AsyncGenerator<object[], void, undefined>}
|
|
341
|
+
*/
|
|
342
|
+
async function* idPages(filters, pageSize, lockOptions, after) {
|
|
343
|
+
for (;;) {
|
|
344
|
+
const page = await lockRead("lockPages", "lockWhere", { filters, limit: pageSize, ...(after === undefined ? {} : { after }) }, lockOptions);
|
|
345
|
+
// A page after an id never holds it. A storage that ignored `after` would answer the first page again and
|
|
346
|
+
// again, and background work, which has no row limit, would page forever.
|
|
347
|
+
if (after !== undefined && page.some((record) => record.id === after)) {
|
|
348
|
+
throw new Error(`${name}.lockPages() read the row ${JSON.stringify(after)} again in the page after it: its storage does not page lockWhere by after, so its pages would never end.`);
|
|
349
|
+
}
|
|
350
|
+
yield page;
|
|
332
351
|
if (page.length < pageSize) {
|
|
333
352
|
return;
|
|
334
353
|
}
|
|
@@ -336,6 +355,62 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
336
355
|
}
|
|
337
356
|
}
|
|
338
357
|
|
|
358
|
+
/**
|
|
359
|
+
* The list filter lockPages' `pageBy` names: its key, the stored field it compares and its distinct values.
|
|
360
|
+
* @param {unknown} pageBy
|
|
361
|
+
* @param {Record<string, unknown>} filters
|
|
362
|
+
*/
|
|
363
|
+
function listFilterOf(pageBy, filters) {
|
|
364
|
+
const definition = typeof pageBy === "string" ? jsonRest().vars.schemaInfo.searchSchemaStructure?.[pageBy] : undefined;
|
|
365
|
+
const field = definition?.actualField || pageBy;
|
|
366
|
+
if (definition?.filterOperator !== "in" || String(field).includes(".") || !Array.isArray(filters[pageBy])) {
|
|
367
|
+
throw new TypeError(
|
|
368
|
+
`${name}.lockPages() pageBy names a filter that matches one of a list of values of ${name}'s own column ` +
|
|
369
|
+
`(filterOperator: "in"), given a list in the filters. Received: ${JSON.stringify(pageBy)}`
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
return { key: pageBy, field, values: [...new Set(filters[pageBy].map(String))] };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* lockPages' pages by a list filter's column, then the id. Each page locks, in that order, up to pageSize rows of
|
|
377
|
+
* the values no page has passed; the rows of the page's last value that follow it are then locked in id order,
|
|
378
|
+
* that value alone, a page at a time. So every statement reads one value range after another, as an index that
|
|
379
|
+
* holds the column after the fixed ones reads them, and examines only the listed values' rows. A value with no row
|
|
380
|
+
* stays in the list, so the pages after it look for it again. One more statement per full page reads the
|
|
381
|
+
* column's stored values of its rows, which this transaction holds.
|
|
382
|
+
* @param {Record<string, unknown>} filters
|
|
383
|
+
* @param {{ key: string, field: string, values: string[] }} list
|
|
384
|
+
* @param {number} pageSize
|
|
385
|
+
* @param {object} lockOptions
|
|
386
|
+
* @returns {AsyncGenerator<object[], void, undefined>}
|
|
387
|
+
*/
|
|
388
|
+
async function* listPages(filters, { key, field, values }, pageSize, lockOptions) {
|
|
389
|
+
const yielded = new Set();
|
|
390
|
+
for (let remaining = values; remaining.length > 0;) {
|
|
391
|
+
const page = await lockRead("lockPages", "lockWhere", { filters: { ...filters, [key]: remaining }, sort: [field], limit: pageSize }, lockOptions);
|
|
392
|
+
// A value given otherwise than the column stores it ("07" for 7) matches rows a page has passed, and would
|
|
393
|
+
// match them again and again.
|
|
394
|
+
const again = page.find((record) => yielded.has(String(record.id)));
|
|
395
|
+
if (again) {
|
|
396
|
+
throw new Error(`${name}.lockPages() read the row ${JSON.stringify(again.id)} again: give pageBy's values as ${field} stores them.`);
|
|
397
|
+
}
|
|
398
|
+
page.forEach((record) => yielded.add(String(record.id)));
|
|
399
|
+
yield page;
|
|
400
|
+
if (page.length < pageSize) {
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const stored = await currentLinks(page.map((record) => String(record.id)), [field], lockOptions);
|
|
404
|
+
const last = stored.get(String(page.at(-1).id))?.[field];
|
|
405
|
+
for await (const rest of idPages({ ...filters, [key]: [last] }, pageSize, lockOptions, page.at(-1).id)) {
|
|
406
|
+
rest.forEach((record) => yielded.add(String(record.id)));
|
|
407
|
+
yield rest;
|
|
408
|
+
}
|
|
409
|
+
const passed = new Set(page.map((record) => stored.get(String(record.id))?.[field]));
|
|
410
|
+
remaining = remaining.filter((value) => !passed.has(value));
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
339
414
|
/**
|
|
340
415
|
* Takes up to `take` (default 1) of the rows the filters select that no
|
|
341
416
|
* other transaction holds, in `sort` order, locked until the transaction ends.
|
|
@@ -32,6 +32,9 @@ async function lockOrCreate(handle, row, options, work) {
|
|
|
32
32
|
// The lock mode the caller names, for both locks of the record, refused before any transaction opens.
|
|
33
33
|
const mode = lockModeOf(handle.name, "lockOrCreate", options.lockMode);
|
|
34
34
|
const locked = async (txOptions) => {
|
|
35
|
+
// The lock comes first, before any plain read: on MySQL and MariaDB a plain read fixes the transaction's snapshot,
|
|
36
|
+
// and an upsert reads its keys plainly, so an upsert first would leave the work reading, after the lock waited,
|
|
37
|
+
// what stood before the record's previous holder committed.
|
|
35
38
|
const existing = await handle.lock(row.id, { ...txOptions, ...mode, missing: "skip" });
|
|
36
39
|
if (existing) {
|
|
37
40
|
return existing;
|
|
@@ -115,6 +115,25 @@ test("withoutHiddenFields refuses another feature's read naming a hidden field,
|
|
|
115
115
|
assert.equal(withoutHiddenFields(cards, plain), cards);
|
|
116
116
|
});
|
|
117
117
|
|
|
118
|
+
test("a reason on a user's context, as a role context records it, grants nothing: the same reads answer the same rows and refuse the same hidden fields", async (t) => {
|
|
119
|
+
const { cards, resource } = await createCardFixture(t);
|
|
120
|
+
const exposed = withoutHiddenFields(cards, resource);
|
|
121
|
+
const user = { ...WORKSPACE_A, actor: { id: "7" } };
|
|
122
|
+
const installing = { ...user, reason: "install the required cards" };
|
|
123
|
+
for (const read of [
|
|
124
|
+
(context) => cards.queryAll({}, { context }),
|
|
125
|
+
(context) => exposed.queryAll({ fields: ["title"] }, { context })
|
|
126
|
+
]) {
|
|
127
|
+
assert.deepEqual(await read(installing), await read(user));
|
|
128
|
+
}
|
|
129
|
+
assert.deepEqual(await exposed.queryAll({}, { context: installing }), [{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]);
|
|
130
|
+
for (const context of [user, installing]) {
|
|
131
|
+
await assert.rejects(exposed.get("1", { fields: ["title", "publicToken"] }, { context }),
|
|
132
|
+
/cards\.get\(\) fields names the hidden field "publicToken", which only the table's owner, or a system context, reads/u);
|
|
133
|
+
await assert.rejects(exposed.withTransaction({ context }, (tx) => exposed.scopedQuery({ alias: "c" }, tx)), /cards\.scopedQuery\(\)/u);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
118
137
|
test("withoutHiddenFields refuses another feature's scopedQuery, and any builder a method answers but a joinSource()'s, which carries no hidden column but the ownership fields", async (t) => {
|
|
119
138
|
const { knex, cards, resource, system, options } = await createCardFixture(t);
|
|
120
139
|
// Methods an owner's decorateRepository adds with the handle it receives, answering its scoped rows as scopedQuery()
|
|
@@ -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
|
+
}
|
|
@@ -1392,6 +1392,44 @@ test("a row policy is told who the call runs for: a system context, a job it der
|
|
|
1392
1392
|
assert.throws(() => systemContext.forWorkspace("1", { actorId: " " }), /forWorkspace needs the id of the user it acts for/u);
|
|
1393
1393
|
});
|
|
1394
1394
|
|
|
1395
|
+
test("a row policy is told the reason a user's context records, as a role context records it, and the reason grants nothing", async (t) => {
|
|
1396
|
+
const seen = [];
|
|
1397
|
+
const { notes } = await createFixture(t, {
|
|
1398
|
+
requestRowLimit: 3,
|
|
1399
|
+
owns: [{
|
|
1400
|
+
resource: noteResource(),
|
|
1401
|
+
rowPolicy: ({ query, column, caller }) => {
|
|
1402
|
+
seen.push(caller);
|
|
1403
|
+
if (caller.kind === "anonymous") return false;
|
|
1404
|
+
if (caller.kind === "user") query.where(column("title"), "shared");
|
|
1405
|
+
return true;
|
|
1406
|
+
}
|
|
1407
|
+
}]
|
|
1408
|
+
});
|
|
1409
|
+
await notes.createMany([{ title: "shared" }, { title: "private" }], { context: WORKSPACE_A });
|
|
1410
|
+
const ada = { ...WORKSPACE_A, actor: { id: "7" } };
|
|
1411
|
+
const installing = { ...ada, reason: " install the required records " };
|
|
1412
|
+
const read = (context) => notes.queryAll({}, { context });
|
|
1413
|
+
seen.length = 0;
|
|
1414
|
+
// The same rows, as the same user.
|
|
1415
|
+
assert.deepEqual(await read(installing), await read(ada));
|
|
1416
|
+
assert.deepEqual((await read(installing)).map(({ title }) => title), ["shared"]);
|
|
1417
|
+
// A reason that is no text is none.
|
|
1418
|
+
await read({ ...ada, reason: 7 });
|
|
1419
|
+
assert.deepEqual(seen, [
|
|
1420
|
+
{ kind: "user", userId: "7", reason: "install the required records" },
|
|
1421
|
+
{ kind: "user", userId: "7" },
|
|
1422
|
+
{ kind: "user", userId: "7", reason: "install the required records" },
|
|
1423
|
+
{ kind: "user", userId: "7" }
|
|
1424
|
+
]);
|
|
1425
|
+
// Without a user it is an anonymous request, reason or not, and request row limits apply with it as without.
|
|
1426
|
+
assert.deepEqual(await read({ ...WORKSPACE_A, reason: "install the required records" }), []);
|
|
1427
|
+
await notes.createMany(Array.from({ length: 3 }, () => ({ title: "shared" })), { context: WORKSPACE_A });
|
|
1428
|
+
for (const context of [ada, installing]) {
|
|
1429
|
+
await assert.rejects(read(context), (error) => error instanceof RowLimitError && error.messageParams.rowLimit === 3);
|
|
1430
|
+
}
|
|
1431
|
+
});
|
|
1432
|
+
|
|
1395
1433
|
test("a job's actorId never moves its scope; a row policy that keys on the person holds a job done for them to their rows", async (t) => {
|
|
1396
1434
|
const drafts = defineTableResource({
|
|
1397
1435
|
name: "drafts",
|
|
@@ -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 };
|
|
@@ -55,18 +55,71 @@ async function slotsOf(knex, count, settings = {}) {
|
|
|
55
55
|
return { slots, system, api };
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/**
|
|
59
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Every page lockPages answers. Past `most` pages it throws, so a lockPages that never ends fails its case at once.
|
|
60
|
+
* @param {AsyncIterable<object[]>} pages
|
|
61
|
+
* @param {number} [most]
|
|
62
|
+
*/
|
|
63
|
+
async function pagesOf(pages, most = 10) {
|
|
60
64
|
const all = [];
|
|
61
65
|
for await (const page of pages) {
|
|
62
66
|
all.push(page);
|
|
63
|
-
if (all.length >
|
|
64
|
-
throw new Error(
|
|
67
|
+
if (all.length > most) {
|
|
68
|
+
throw new Error(`lockPages answered more than ${most} pages: its pages never end`);
|
|
65
69
|
}
|
|
66
70
|
}
|
|
67
71
|
return all;
|
|
68
72
|
}
|
|
69
73
|
|
|
74
|
+
// The links of actions, many to an action, as an export reads every link of a list of actions.
|
|
75
|
+
const linkResource = defineTableResource({
|
|
76
|
+
name: "links",
|
|
77
|
+
tableName: "links",
|
|
78
|
+
ownership: "workspace",
|
|
79
|
+
searchSchema: { actionIds: { type: "array", actualField: "actionId", filterOperator: "in" } },
|
|
80
|
+
schema: {
|
|
81
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
82
|
+
actionId: { type: "integer", required: true, storage: { column: "action_id" } },
|
|
83
|
+
target: { type: "string", required: true }
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* `perAction` links of each of `actions` actions in workspaces 1 and 2, inserted a link of every action at a time, so
|
|
89
|
+
* an action's links are spread over the ids. Each link's target is `T<action>-<link>`.
|
|
90
|
+
* @param {import("knex").Knex} knex
|
|
91
|
+
* @param {number} actions
|
|
92
|
+
* @param {number} perAction
|
|
93
|
+
*/
|
|
94
|
+
async function linksOf(knex, actions, perAction) {
|
|
95
|
+
await knex.schema.createTable("links", (table) => {
|
|
96
|
+
table.increments("id");
|
|
97
|
+
table.integer("workspace_id").nullable();
|
|
98
|
+
table.integer("action_id").notNullable();
|
|
99
|
+
table.string("target").notNullable();
|
|
100
|
+
// lockPages in id order reads a workspace's rows in id order; by the action, each listed action's rows.
|
|
101
|
+
table.index(["workspace_id"], "links_workspace");
|
|
102
|
+
table.index(["workspace_id", "action_id"], "links_workspace_action");
|
|
103
|
+
});
|
|
104
|
+
const rows = [];
|
|
105
|
+
for (let link = 0; link < perAction; link += 1) {
|
|
106
|
+
for (let action = 1; action <= actions; action += 1) {
|
|
107
|
+
rows.push(...[1, 2].map((workspace) => ({ workspace_id: workspace, action_id: action, target: `T${action}-${link}` })));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
for (let start = 0; start < rows.length; start += 200) {
|
|
111
|
+
await knex("links").insert(rows.slice(start, start + 200));
|
|
112
|
+
}
|
|
113
|
+
const api = await createResourceHost({ knex, logger: silentLogger });
|
|
114
|
+
const runtime = createResourceRuntime({ api });
|
|
115
|
+
const { links } = await runtime.own("links.feature", [linkResource]);
|
|
116
|
+
return { links };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// A row another transaction holds, as FOR UPDATE NOWAIT reports it: PostgreSQL 55P03, MySQL ER_LOCK_NOWAIT and MariaDB
|
|
120
|
+
// ER_LOCK_WAIT_TIMEOUT.
|
|
121
|
+
const isHeld = (error) => error?.code === "55P03" || /^ER_LOCK_(NOWAIT|WAIT_TIMEOUT)$/u.test(String(error?.code));
|
|
122
|
+
|
|
70
123
|
/**
|
|
71
124
|
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
72
125
|
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
@@ -189,6 +242,76 @@ function lockWhereOrderCases(connect) {
|
|
|
189
242
|
}
|
|
190
243
|
}), /slots\.lockPages\(\) read the row "2" again in the page after it/u);
|
|
191
244
|
assert.deepEqual(read, [["C0000", "C0001"]]);
|
|
245
|
+
}],
|
|
246
|
+
|
|
247
|
+
["lockPages with pageBy locks a list's rows by its column, then id, each once, the same statements among 30 actions and 300", async (t) => {
|
|
248
|
+
// Ten listed actions of five links each; pages of 7 end inside an action's links, whose rest the next page takes.
|
|
249
|
+
const listed = Array.from({ length: 10 }, (_, index) => (index + 1) * 3);
|
|
250
|
+
const expected = listed.flatMap((action) => [0, 1, 2, 3, 4].map((link) => `T${action}-${link}`));
|
|
251
|
+
const sizes = [];
|
|
252
|
+
for (const actions of [30, 300]) {
|
|
253
|
+
const knex = await connect(t, `da_lp_by_${actions}`);
|
|
254
|
+
const { links } = await linksOf(knex, actions, 5);
|
|
255
|
+
const lockListed = (tx) => pagesOf(links.lockPages({ actionIds: listed }, { ...tx, pageBy: "actionIds", pageSize: 7, fields: ["target"] }), 40);
|
|
256
|
+
// MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
|
|
257
|
+
await links.withTransaction(IN_WORKSPACE_A, lockListed);
|
|
258
|
+
const { result: pages, count: statements } = await links.withTransaction(IN_WORKSPACE_A, (tx) => countQueries(knex, () => lockListed(tx)));
|
|
259
|
+
assert.deepEqual(pages.flat().map(({ target }) => target), expected);
|
|
260
|
+
sizes.push({ pages: pages.map((page) => page.length), statements });
|
|
261
|
+
}
|
|
262
|
+
assert.deepEqual(sizes.map(({ pages }) => pages), [[7, 3, 7, 3, 7, 3, 7, 3, 7, 3], [7, 3, 7, 3, 7, 3, 7, 3, 7, 3]]);
|
|
263
|
+
assert.equal(sizes[1].statements, sizes[0].statements);
|
|
264
|
+
|
|
265
|
+
const knex = await connect(t, "da_lp_by_refusals");
|
|
266
|
+
const { links } = await linksOf(knex, 3, 2);
|
|
267
|
+
await links.withTransaction(IN_WORKSPACE_A, async (tx) => {
|
|
268
|
+
assert.deepEqual(await pagesOf(links.lockPages({ actionIds: [] }, { ...tx, pageBy: "actionIds" })), []);
|
|
269
|
+
for (const [filters, pageBy] of [[{ actionIds: [1] }, "target"], [{ actionIds: [1] }, "missing"], [{ actionIds: 1 }, "actionIds"], [{}, "actionIds"]]) {
|
|
270
|
+
await assert.rejects(pagesOf(links.lockPages(filters, { ...tx, pageBy })),
|
|
271
|
+
(error) => error instanceof TypeError && /links\.lockPages\(\) pageBy names a filter/u.test(error.message), JSON.stringify([filters, pageBy]));
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
}],
|
|
275
|
+
|
|
276
|
+
["lockPages with pageBy holds the listed values' rows and no other; in id order MySQL and MariaDB hold the rows between them too", async (t) => {
|
|
277
|
+
const knex = await connect(t, "da_lp_by_held");
|
|
278
|
+
const client = knex.client.config.client;
|
|
279
|
+
if (client === "better-sqlite3") {
|
|
280
|
+
t.skip("SQLite takes no row locks");
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const { links } = await linksOf(knex, 12, 5);
|
|
284
|
+
const idsOf = async (actions) => (await knex("links").where({ workspace_id: 1 }).whereIn("action_id", actions).orderBy("id").select("id")).map(({ id }) => id);
|
|
285
|
+
const listed = [3, 6, 9];
|
|
286
|
+
const listedIds = await idsOf(listed);
|
|
287
|
+
const unlistedIds = await idsOf([4, 7, 10]);
|
|
288
|
+
const free = (id) => knex.transaction((probe) => probe("links").where({ id }).forUpdate().noWait().select("id"))
|
|
289
|
+
.then(() => true, (error) => {
|
|
290
|
+
if (isHeld(error)) return false;
|
|
291
|
+
throw error;
|
|
292
|
+
});
|
|
293
|
+
const held = (lockMode, pageBy) => links.withTransaction(IN_WORKSPACE_A, async (tx) => {
|
|
294
|
+
const rows = (await pagesOf(links.lockPages({ actionIds: listed }, { ...tx, ...(pageBy ? { pageBy } : {}), pageSize: 4, lockMode, fields: ["target"] }), 40)).flat();
|
|
295
|
+
assert.equal(rows.length, listedIds.length);
|
|
296
|
+
const count = async (ids) => {
|
|
297
|
+
let busy = 0;
|
|
298
|
+
for (const id of ids) busy += (await free(id)) ? 0 : 1;
|
|
299
|
+
return busy;
|
|
300
|
+
};
|
|
301
|
+
return { listed: await count(listedIds), unlisted: await count(unlistedIds) };
|
|
302
|
+
});
|
|
303
|
+
for (const lockMode of ["share", "update"]) {
|
|
304
|
+
assert.deepEqual(await held(lockMode, "actionIds"), { listed: listedIds.length, unlisted: 0 }, lockMode);
|
|
305
|
+
}
|
|
306
|
+
// In id order the read follows the workspace's rows by id, so InnoDB locks every row of it it passes.
|
|
307
|
+
const byId = await held("share", undefined);
|
|
308
|
+
t.diagnostic(`in id order: ${byId.listed} listed rows held, ${byId.unlisted} of ${unlistedIds.length} unlisted rows held`);
|
|
309
|
+
assert.equal(byId.listed, listedIds.length);
|
|
310
|
+
if (client === "mysql2") {
|
|
311
|
+
assert.ok(byId.unlisted > 0, "MySQL and MariaDB lock the unlisted rows an id-order read passes");
|
|
312
|
+
} else {
|
|
313
|
+
assert.equal(byId.unlisted, 0);
|
|
314
|
+
}
|
|
192
315
|
}]
|
|
193
316
|
];
|
|
194
317
|
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { createTestResourceRuntime } from "../src/test/index.js";
|
|
5
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
6
|
+
|
|
7
|
+
// First saves of new keys from two transactions at once on MySQL and MariaDB. InnoDB's locking read of a key no row
|
|
8
|
+
// holds locks the gap where the key would go, and gap locks never wait for each other: two transactions that each lock
|
|
9
|
+
// one gap so, then insert into it, each wait for the other's gap lock, and one is killed as a deadlock. createMany's
|
|
10
|
+
// upserts take no such lock, so new keys that fall in one gap go in side by side. Every transaction here runs once
|
|
11
|
+
// (retry: false), so a deadlock fails the test rather than being run again. lockOrCreate still locks first: an upsert
|
|
12
|
+
// reads its keys plainly, and a plain read before the lock would fix the snapshot its work reads.
|
|
13
|
+
|
|
14
|
+
const inWorkspace = (id) => Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: String(id) }) }) });
|
|
15
|
+
// The counters have no owners; a workspace's request uses them, as the PostgreSQL lock tests' balances.
|
|
16
|
+
const PUBLIC = inWorkspace(1);
|
|
17
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
18
|
+
const outcomeOf = (promise) => promise.then(() => "saved", (error) => String(error?.code ?? error?.cause?.code ?? error?.message));
|
|
19
|
+
|
|
20
|
+
// A table with no owners keyed by an id the server computes, as lockOrCreate takes.
|
|
21
|
+
const counterResource = defineTableResource({
|
|
22
|
+
name: "counters",
|
|
23
|
+
tableName: "counters",
|
|
24
|
+
ownership: "public",
|
|
25
|
+
schema: {
|
|
26
|
+
id: { type: "string", primary: true },
|
|
27
|
+
amount: { type: "integer", defaultTo: 0 }
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
// One binding per workspace and scope key, as a workspace's settings for one scope are.
|
|
31
|
+
const bindingResource = defineTableResource({
|
|
32
|
+
name: "bindings",
|
|
33
|
+
tableName: "bindings",
|
|
34
|
+
ownership: "workspace",
|
|
35
|
+
schema: {
|
|
36
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
37
|
+
scopeKey: { type: "string", required: true, storage: { column: "scope_key" } },
|
|
38
|
+
value: { type: "string", nullable: true }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
async function database(t, suffix) {
|
|
43
|
+
const knex = await ownMysqlDatabase(t, suffix);
|
|
44
|
+
await knex.schema.createTable("counters", (table) => {
|
|
45
|
+
table.string("id").primary();
|
|
46
|
+
table.integer("amount").notNullable().defaultTo(0);
|
|
47
|
+
});
|
|
48
|
+
await knex.schema.createTable("bindings", (table) => {
|
|
49
|
+
table.increments("id");
|
|
50
|
+
table.integer("workspace_id").nullable();
|
|
51
|
+
table.string("scope_key").notNullable();
|
|
52
|
+
table.string("value").nullable();
|
|
53
|
+
table.unique(["workspace_id", "scope_key"]);
|
|
54
|
+
});
|
|
55
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
56
|
+
const { counters, bindings } = await runtime.own("counters.feature", [counterResource, bindingResource]);
|
|
57
|
+
return { knex, counters, bindings };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A transaction of `handle`'s held open until commit() or rollback(); it runs once. */
|
|
61
|
+
async function holdTransaction(handle, options) {
|
|
62
|
+
let opened;
|
|
63
|
+
const ready = new Promise((resolve) => {
|
|
64
|
+
opened = resolve;
|
|
65
|
+
});
|
|
66
|
+
let finish;
|
|
67
|
+
const finished = new Promise((resolve, reject) => {
|
|
68
|
+
finish = { resolve, reject };
|
|
69
|
+
});
|
|
70
|
+
const outcome = handle.withTransaction({ ...options, retry: false }, (txOptions) => {
|
|
71
|
+
opened(txOptions);
|
|
72
|
+
return finished;
|
|
73
|
+
});
|
|
74
|
+
outcome.catch(() => {});
|
|
75
|
+
return {
|
|
76
|
+
txOptions: await Promise.race([ready, outcome.then(() => assert.fail("the transaction ended before it opened"))]),
|
|
77
|
+
commit: () => {
|
|
78
|
+
finish.resolve();
|
|
79
|
+
return outcome;
|
|
80
|
+
},
|
|
81
|
+
rollback: () => {
|
|
82
|
+
finish.reject(new Error("rolled back by the test"));
|
|
83
|
+
return outcome.catch(() => {});
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
test("lockOrCreate's work reads what the record's previous holder committed: its lock comes before any plain read", async (t) => {
|
|
89
|
+
const { counters } = await database(t, "da_gap_lock_first");
|
|
90
|
+
await counters.lockOrCreate({ id: "hot", amount: 0 }, PUBLIC, () => undefined);
|
|
91
|
+
const first = await holdTransaction(counters, PUBLIC);
|
|
92
|
+
const second = await holdTransaction(counters, PUBLIC);
|
|
93
|
+
let seen;
|
|
94
|
+
try {
|
|
95
|
+
// The first transaction holds the record and adds a row beside it.
|
|
96
|
+
await counters.lockOrCreate({ id: "hot", amount: 0 }, first.txOptions, (_record, txOptions) =>
|
|
97
|
+
txOptions.trx("counters").insert({ id: "beside", amount: 5 }));
|
|
98
|
+
// The second waits for the record, then reads the table plainly.
|
|
99
|
+
const pending = counters.lockOrCreate({ id: "hot", amount: 0 }, second.txOptions, async (_record, txOptions) =>
|
|
100
|
+
(await txOptions.trx("counters").orderBy("id").select("id")).map(({ id }) => id));
|
|
101
|
+
pending.catch(() => {});
|
|
102
|
+
await pause(300);
|
|
103
|
+
await first.commit();
|
|
104
|
+
seen = await pending;
|
|
105
|
+
await second.commit();
|
|
106
|
+
} finally {
|
|
107
|
+
await first.rollback();
|
|
108
|
+
await second.rollback();
|
|
109
|
+
}
|
|
110
|
+
assert.deepEqual(seen, ["beside", "hot"]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("first saves of new keys in one gap from two transactions at once never deadlock: 20 rounds in each start order, no retry", async (t) => {
|
|
114
|
+
const { knex, bindings } = await database(t, "da_gap_rounds");
|
|
115
|
+
// Every pair's keys sort after every stored one, so both go into the last gap of the index.
|
|
116
|
+
const neighbour = (base, round, order, side) => base + round * 4 + (order === "ab" ? 0 : 2) + (side === "a" ? 0 : 1);
|
|
117
|
+
const firstBinding = (workspaceId, onConflict) => bindings.withTransaction({ ...inWorkspace(workspaceId), retry: false }, (txOptions) =>
|
|
118
|
+
bindings.createMany([{ scopeKey: "company", value: String(workspaceId) }], { ...txOptions, onConflict }));
|
|
119
|
+
const writers = {
|
|
120
|
+
// Each workspace's first binding for one scope key, in two neighbouring workspaces.
|
|
121
|
+
ignore: (round, order, side) => firstBinding(neighbour(1000, round, order, side), { keys: ["workspaceId", "scopeKey"], action: "ignore" }),
|
|
122
|
+
merge: (round, order, side) => firstBinding(neighbour(3000, round, order, side), { keys: ["workspaceId", "scopeKey"], action: "merge", merge: ["value"] })
|
|
123
|
+
};
|
|
124
|
+
const outcomes = {};
|
|
125
|
+
for (const [name, write] of Object.entries(writers)) {
|
|
126
|
+
for (let round = 10; round < 30; round += 1) {
|
|
127
|
+
for (const order of ["ab", "ba"]) {
|
|
128
|
+
const results = await Promise.all([...order].map((side) => outcomeOf(write(round, order, side))));
|
|
129
|
+
for (const result of results) {
|
|
130
|
+
const key = `${name} ${result}`;
|
|
131
|
+
outcomes[key] = (outcomes[key] ?? 0) + 1;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
assert.deepEqual(outcomes, { "ignore saved": 80, "merge saved": 80 });
|
|
137
|
+
assert.equal(Number((await knex("bindings").count({ count: "*" }).first()).count), 160);
|
|
138
|
+
});
|