@jskit-ai/resource-runtime 0.2.30 → 0.2.32
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 +3 -0
- package/package.json +6 -6
- package/src/server/errors.js +1 -1
- package/src/server/handleGuards.js +9 -5
- package/src/server/handleLocks.js +57 -2
- package/src/server/resourceHandle.js +3 -2
- package/test/countOnlyTable.mysql.test.js +8 -0
- package/test/countOnlyTable.test.js +8 -0
- package/test/resourceRuntime.test.js +3 -3
- package/test/support/countOnlyTableCases.js +112 -0
- package/test/support/lockWhereOrderCases.js +104 -9
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- 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
|
+
- `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
|
+
- `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.
|
|
5
8
|
- Depends on json-rest-api 3.1.8 exactly (from 3.1.7): a handle's `lockWhere` takes `sort` and `limit` (below); on MySQL and MariaDB a lock or read no longer reads the connection's schema at each call when the client's settings name a database (a `USE` on such a client's connection is not followed); and a read, in any context, reads no to-one link to a table with no ownership, no row policy and no filtering hook of the application's own whose declared foreign key protects it (SQLite still reads it).
|
|
6
9
|
- A row policy's `options.trx` names the transaction its read runs in. A write whose caller named no transaction runs in one json-rest-api opens for it, and its row policy runs inside it (the lookup before a patch, the read-back after a create), where `options.trx` was null: a handle call the policy made with its `options` (an owner API's role check, say) took a second connection, waiting on a one-connection pool until it gave up. It now joins the write's transaction, and the handle accepts it as one a handle opened. A policy that passes its `options` on, as the guide says, needs no change.
|
|
7
10
|
- `lockWhere(filters, { ...txOptions, sort, limit })` locks in an order the caller names and only as many rows as it needs, with json-rest-api 3.1.8. `sort` (fields, `"-field"` for descending, a list or one field) locks and answers the rows in that order, then by id, so two paths that lock overlapping rows take them in one order and wait for each other instead of deadlocking. `limit` (1 to 1,000) locks only the first rows of that order, by id without a `sort`, and lifts the 1,000-row refusal: a lock of one row by a unique key other than its id (`limit: 1`) is one statement, as `lock(id)` is, where PostgreSQL read twice. Without either, `lockWhere` locks as before. On MySQL and MariaDB the index `lockWhere` reads must read the rows in that order (after the ownership columns and the filters' single-value equalities, the sort's columns), or it refuses naming the columns, since InnoDB locks rows in the order it reads them.
|
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.32",
|
|
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.216",
|
|
19
|
+
"@jskit-ai/resource-crud-core": "0.1.218",
|
|
20
|
+
"json-rest-api": "3.1.9"
|
|
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.274",
|
|
68
|
+
"@jskit-ai/kernel": "0.2.25"
|
|
69
69
|
}
|
|
70
70
|
}
|
package/src/server/errors.js
CHANGED
|
@@ -93,7 +93,7 @@ class RowLimitError extends AppError {
|
|
|
93
93
|
* @param {string} resourceName
|
|
94
94
|
* @param {number} rowLimit
|
|
95
95
|
* @param {unknown} [cause]
|
|
96
|
-
* @param {"queryAll" | "queryPages"} [caller]
|
|
96
|
+
* @param {"queryAll" | "queryPages" | "lockPages"} [caller]
|
|
97
97
|
*/
|
|
98
98
|
constructor(resourceName, rowLimit, cause, caller = "queryAll") {
|
|
99
99
|
super(
|
|
@@ -92,20 +92,24 @@ function whereSelection(name, operation, filters, options) {
|
|
|
92
92
|
}
|
|
93
93
|
|
|
94
94
|
/**
|
|
95
|
-
* An upsert matches rows by its conflict keys alone
|
|
95
|
+
* An upsert matches rows by its conflict keys alone. A merge's rows carry no id, which could name another owner's
|
|
96
96
|
* record, unless the id is the one key: json-rest-api allows that only on a table with no owners and no row policy.
|
|
97
|
+
* An ignore's rows may carry one, for a table whose ids the caller makes (a random uuid): a row its keys match writes
|
|
98
|
+
* nothing and keeps its stored id, a new row takes the given id, and an id that is already another row's fails the
|
|
99
|
+
* batch, as json-rest-api skips only a clash on the keys' unique index.
|
|
97
100
|
* @param {string} name
|
|
98
101
|
* @param {unknown[]} rows
|
|
99
|
-
* @param {{ keys?: unknown }} onConflict
|
|
102
|
+
* @param {{ keys?: unknown, action?: unknown }} onConflict
|
|
100
103
|
* @param {string | undefined} idProperty
|
|
101
104
|
*/
|
|
102
105
|
function requireUpsertRows(name, rows, onConflict, idProperty) {
|
|
103
106
|
const keys = Array.isArray(onConflict.keys) ? onConflict.keys : [];
|
|
104
107
|
const byId = keys.length === 1 && (keys[0] === "id" || keys[0] === idProperty);
|
|
105
|
-
if (!byId && rows.some((row) => isRecord(row) && Object.hasOwn(row, "id"))) {
|
|
108
|
+
if (!byId && onConflict.action !== "ignore" && rows.some((row) => isRecord(row) && Object.hasOwn(row, "id"))) {
|
|
106
109
|
throw new TypeError(
|
|
107
|
-
`${name}.createMany() with onConflict takes rows without an id; the conflict keys find the existing rows. ` +
|
|
108
|
-
"Only onConflict: { keys: [\"id\"] }, on a table with no owners, matches rows by their id
|
|
110
|
+
`${name}.createMany() with onConflict merge takes rows without an id; the conflict keys find the existing rows. ` +
|
|
111
|
+
"Only onConflict: { keys: [\"id\"] }, on a table with no owners, matches rows by their id, and an ignore's rows " +
|
|
112
|
+
"may carry the ids of the rows it inserts."
|
|
109
113
|
);
|
|
110
114
|
}
|
|
111
115
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
|
|
2
|
+
import { isJobContext } from "./contexts.js";
|
|
3
|
+
import { RowLimitError } from "./errors.js";
|
|
2
4
|
import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
|
|
3
5
|
import { missingOf, requireDefinedFilters } from "./handleGuards.js";
|
|
4
6
|
import { defaultFieldList, handleRecords, includedRelationships, sparseFieldset, textList } from "./handleRecords.js";
|
|
@@ -47,6 +49,9 @@ function lockModeOf(name, caller, lockMode) {
|
|
|
47
49
|
// The most rows one read of the locked rows' links names, as the lock itself reads its ids in chunks of 1,000.
|
|
48
50
|
const LINKS_PER_READ = 1000;
|
|
49
51
|
|
|
52
|
+
// The most rows a page of lockPages() locks: json-rest-api's most for one lockWhere.
|
|
53
|
+
const MAX_LOCK_PAGE = 1000;
|
|
54
|
+
|
|
50
55
|
/**
|
|
51
56
|
* The relationships a locking read includes, each a belongs-to field of the resource named by its relationship (`as`,
|
|
52
57
|
* or the field's own name): `{ relationshipName, field, target, below }`, `below` the include paths under it. A lock
|
|
@@ -78,7 +83,7 @@ function lockedIncludes(resource, caller, include) {
|
|
|
78
83
|
}
|
|
79
84
|
|
|
80
85
|
/**
|
|
81
|
-
* A handle's locking reads: lock, lockMany, lockWhere and claim. Each needs the
|
|
86
|
+
* A handle's locking reads: lock, lockMany, lockWhere, lockPages and claim. Each needs the
|
|
82
87
|
* caller's transaction (`options.trx`), locks only rows the caller may see, and
|
|
83
88
|
* reads the fields `options.fields` names, or every field a one-record read
|
|
84
89
|
* answers, so a belongs-to field left out costs no check that its related
|
|
@@ -98,8 +103,9 @@ function lockedIncludes(resource, caller, include) {
|
|
|
98
103
|
* owned tables by resource name, which lock included records.
|
|
99
104
|
* @param {(name: string) => ({ schema: Record<string, any>, relationships?: Record<string, any> } | null)} dependencies.resourceNamed
|
|
100
105
|
* The application's table resources by name, whose collections an included record leaves out.
|
|
106
|
+
* @param {{ requestRowLimit: number }} dependencies.settings The most rows lockPages() locks in a request context.
|
|
101
107
|
*/
|
|
102
|
-
function createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed }) {
|
|
108
|
+
function createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed, settings }) {
|
|
103
109
|
/**
|
|
104
110
|
* The collections of a related table an included record leaves out, as a read's include does (see handleRecord):
|
|
105
111
|
* every one it does not include itself.
|
|
@@ -282,6 +288,54 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
282
288
|
}, options);
|
|
283
289
|
}
|
|
284
290
|
|
|
291
|
+
/**
|
|
292
|
+
* Locks every row the filters select, as lockWhere locks them, a page at a time: `for await (const records of
|
|
293
|
+
* lockPages(filters, txOptions))`. Each page is one locking read of up to `pageSize` rows (1 to 1,000, the
|
|
294
|
+
* default) in id order, after the last id of the page before, locked until the transaction ends. A locking read
|
|
295
|
+
* sees the latest committed rows whatever the transaction's snapshot, so this reads more rows than one lockWhere
|
|
296
|
+
* locks as they stand now, also inside a transaction that has already read plainly (MySQL and MariaDB keep the
|
|
297
|
+
* snapshot of a transaction's first plain read). The pages are locked one after another, and PostgreSQL keeps no
|
|
298
|
+
* new row out of a page already locked: when the whole set must stay as read until commit, every writer of those
|
|
299
|
+
* rows first locks one row that governs them (their parent, say), and so does this work, before it reads. On MySQL
|
|
300
|
+
* and MariaDB it needs an index that reads in id order after the ownership columns and the filters' single-value
|
|
301
|
+
* equalities. In a request it throws RowLimitError past the request row limit, as queryPages() does; background
|
|
302
|
+
* work locks without one. `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
|
|
303
|
+
* @param {object} filters
|
|
304
|
+
* @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number }} options
|
|
305
|
+
* @returns {AsyncGenerator<object[], void, undefined>}
|
|
306
|
+
*/
|
|
307
|
+
async function* lockPages(filters, options) {
|
|
308
|
+
requireDefinedFilters(name, "lockPages", filters);
|
|
309
|
+
const { pageSize = MAX_LOCK_PAGE, sort, limit, ...lockOptions } = options;
|
|
310
|
+
if (sort !== undefined || limit !== undefined) {
|
|
311
|
+
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
|
+
}
|
|
313
|
+
if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > MAX_LOCK_PAGE) {
|
|
314
|
+
throw new TypeError(`${name}.lockPages() pageSize is an integer from 1 to ${MAX_LOCK_PAGE}. Received: ${JSON.stringify(pageSize)}`);
|
|
315
|
+
}
|
|
316
|
+
const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
|
|
317
|
+
let rows = 0;
|
|
318
|
+
for (let after; ;) {
|
|
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
|
+
}
|
|
325
|
+
rows += page.length;
|
|
326
|
+
if (rowLimit !== undefined && rows > rowLimit) {
|
|
327
|
+
throw new RowLimitError(name, rowLimit, undefined, "lockPages");
|
|
328
|
+
}
|
|
329
|
+
if (page.length > 0) {
|
|
330
|
+
yield page;
|
|
331
|
+
}
|
|
332
|
+
if (page.length < pageSize) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
after = page.at(-1).id;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
285
339
|
/**
|
|
286
340
|
* Takes up to `take` (default 1) of the rows the filters select that no
|
|
287
341
|
* other transaction holds, in `sort` order, locked until the transaction ends.
|
|
@@ -309,6 +363,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
309
363
|
lock,
|
|
310
364
|
lockMany,
|
|
311
365
|
lockWhere,
|
|
366
|
+
lockPages,
|
|
312
367
|
claim
|
|
313
368
|
});
|
|
314
369
|
}
|
|
@@ -157,8 +157,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
|
|
|
157
157
|
const hiddenFields = createHiddenFieldReads({ resource, scopedQuery, column });
|
|
158
158
|
// The table as a join source, with its visible columns only (see handleHidden.js).
|
|
159
159
|
const joinSource = createJoinSource({ api, resource, jsonRest, scopedQuery, column });
|
|
160
|
-
// lock, lockMany, lockWhere and claim (see handleLocks.js).
|
|
161
|
-
const { lock, lockMany, lockWhere, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed });
|
|
160
|
+
// lock, lockMany, lockWhere, lockPages and claim (see handleLocks.js).
|
|
161
|
+
const { lock, lockMany, lockWhere, lockPages, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed, settings });
|
|
162
162
|
|
|
163
163
|
/**
|
|
164
164
|
* Runs work in the caller's transaction (`options.trx`), or in one it opens,
|
|
@@ -724,6 +724,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
|
|
|
724
724
|
lock,
|
|
725
725
|
lockMany,
|
|
726
726
|
lockWhere,
|
|
727
|
+
lockPages,
|
|
727
728
|
lockOrCreate: lockOrCreateRecord,
|
|
728
729
|
claim,
|
|
729
730
|
changeHorizon,
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { countOnlyTableCases } from "./support/countOnlyTableCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of countOnlyTableCases(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 { countOnlyTableCases } from "./support/countOnlyTableCases.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 countOnlyTableCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -418,7 +418,7 @@ test("an upsert on a table with no owners may key on the id alone; an owned tabl
|
|
|
418
418
|
]);
|
|
419
419
|
await assert.rejects(
|
|
420
420
|
resources.settings.createMany([{ id: "theme", value: "x" }], { ...system, onConflict: { keys: ["id", "value"], action: "merge" } }),
|
|
421
|
-
/onConflict takes rows without an id/u
|
|
421
|
+
/onConflict merge takes rows without an id/u
|
|
422
422
|
);
|
|
423
423
|
// On a workspace table the conflict keys must hold the owner, so json-rest-api refuses the id alone.
|
|
424
424
|
await assert.rejects(notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict: { keys: ["id"], action: "merge" } }));
|
|
@@ -430,8 +430,8 @@ test("an upsert finds rows by its conflict keys alone, never by an id, and stays
|
|
|
430
430
|
await knex.schema.alterTable("notes", (table) => table.unique(["workspace_id", "title"]));
|
|
431
431
|
const upsert = { keys: ["workspaceId", "title"], action: "merge", merge: ["status"] };
|
|
432
432
|
await assert.rejects(
|
|
433
|
-
notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict:
|
|
434
|
-
/onConflict takes rows without an id/u
|
|
433
|
+
notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict: upsert }),
|
|
434
|
+
/onConflict merge takes rows without an id/u
|
|
435
435
|
);
|
|
436
436
|
await assert.rejects(
|
|
437
437
|
notes.createMany([{ title: "a" }, { title: "a", status: "done" }], { context: WORKSPACE_A, onConflict: upsert }),
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
5
|
+
|
|
6
|
+
// A table its feature counts but never reads back row by row (who took part in an anonymous survey): each row takes a
|
|
7
|
+
// random v4 uuid the caller makes, never a sequence, and a unique key on the workspace, the record and the user. A
|
|
8
|
+
// duplicate create hits that key. createMany's onConflict ignore makes a duplicate by those keys a no-op that keeps the
|
|
9
|
+
// stored id, gives a new row the id it brings, and fails on an id that is already another row's: the ignore covers only
|
|
10
|
+
// a clash on the keys' unique index, on MySQL and MariaDB as elsewhere. Each database's test file runs these cases on
|
|
11
|
+
// its own connection.
|
|
12
|
+
|
|
13
|
+
const WORKSPACE_A = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
|
|
14
|
+
const WORKSPACE_B = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "2" }) }) });
|
|
15
|
+
const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
16
|
+
const KEYS = Object.freeze(["workspaceId", "recordId", "userId"]);
|
|
17
|
+
const IGNORE = Object.freeze({ keys: KEYS, action: "ignore" });
|
|
18
|
+
|
|
19
|
+
// A unique key's violation, as each driver reports it, anywhere in the error's causes.
|
|
20
|
+
const DUPLICATE_CODES = new Set(["23505", "ER_DUP_ENTRY", "SQLITE_CONSTRAINT_UNIQUE", "SQLITE_CONSTRAINT_PRIMARYKEY"]);
|
|
21
|
+
function duplicateKey(error) {
|
|
22
|
+
for (let current = error; current; current = current.cause) {
|
|
23
|
+
if (DUPLICATE_CODES.has(current.code)) {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const participationResource = defineTableResource({
|
|
31
|
+
name: "participations",
|
|
32
|
+
tableName: "participations",
|
|
33
|
+
ownership: "workspace",
|
|
34
|
+
schema: {
|
|
35
|
+
id: { type: "uuid", primary: true },
|
|
36
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
37
|
+
recordId: { type: "integer", required: true, search: true, storage: { column: "record_id" } },
|
|
38
|
+
userId: { type: "integer", required: true, search: true, storage: { column: "user_id" } }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** @param {import("knex").Knex} knex */
|
|
43
|
+
async function participationsOf(knex) {
|
|
44
|
+
await knex.schema.createTable("participations", (table) => {
|
|
45
|
+
table.uuid("id").primary();
|
|
46
|
+
table.integer("workspace_id").notNullable();
|
|
47
|
+
table.integer("record_id").notNullable();
|
|
48
|
+
table.integer("user_id").notNullable();
|
|
49
|
+
table.unique(["workspace_id", "record_id", "user_id"]);
|
|
50
|
+
});
|
|
51
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
52
|
+
const { participations } = await runtime.own("survey.feature", [participationResource]);
|
|
53
|
+
return participations;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The stored rows as `[id, workspace, user]`, by workspace and user. @param {import("knex").Knex} knex */
|
|
57
|
+
async function storedRows(knex) {
|
|
58
|
+
const rows = await knex("participations").orderBy(["workspace_id", "user_id"]).select("id", "workspace_id", "user_id");
|
|
59
|
+
return rows.map((row) => [String(row.id), Number(row.workspace_id), Number(row.user_id)]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
64
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
65
|
+
*/
|
|
66
|
+
function countOnlyTableCases(connect) {
|
|
67
|
+
return [
|
|
68
|
+
["a count-only table takes the caller's random v4 ids in a member's request, refuses a duplicate by its unique key, and answers counts", async (t) => {
|
|
69
|
+
const knex = await connect(t, "da_co_create");
|
|
70
|
+
const participations = await participationsOf(knex);
|
|
71
|
+
const ids = [randomUUID(), randomUUID(), randomUUID()];
|
|
72
|
+
await participations.create({ id: ids[0], recordId: 7, userId: 1 }, { ...WORKSPACE_A, returning: "none" });
|
|
73
|
+
await participations.create({ id: ids[1], recordId: 7, userId: 2 }, { ...WORKSPACE_A, returning: "none" });
|
|
74
|
+
await participations.create({ id: ids[2], recordId: 7, userId: 1 }, { ...WORKSPACE_B, returning: "none" });
|
|
75
|
+
// The same person twice for one record hits the unique key.
|
|
76
|
+
await assert.rejects(participations.create({ id: randomUUID(), recordId: 7, userId: 1 }, { ...WORKSPACE_A, returning: "none" }), duplicateKey);
|
|
77
|
+
assert.deepEqual(await storedRows(knex), [[ids[0], 1, 1], [ids[1], 1, 2], [ids[2], 2, 1]]);
|
|
78
|
+
assert.ok(ids.every((id) => V4.test(id)));
|
|
79
|
+
const [counted] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId: 7 } }, WORKSPACE_A);
|
|
80
|
+
assert.equal(counted.participants, 2);
|
|
81
|
+
}],
|
|
82
|
+
|
|
83
|
+
["onConflict ignore keeps a duplicate's stored id, gives a new row its own id, and fails on an id that is another row's", async (t) => {
|
|
84
|
+
const knex = await connect(t, "da_co_ignore");
|
|
85
|
+
const participations = await participationsOf(knex);
|
|
86
|
+
const first = randomUUID();
|
|
87
|
+
const fresh = randomUUID();
|
|
88
|
+
await participations.createMany([{ id: first, recordId: 7, userId: 1 }], { ...WORKSPACE_A, onConflict: IGNORE });
|
|
89
|
+
// A duplicate by the keys writes nothing and keeps the stored id; a new row takes the id it brings.
|
|
90
|
+
await participations.createMany([{ id: randomUUID(), recordId: 7, userId: 1 }, { id: fresh, recordId: 7, userId: 2 }], { ...WORKSPACE_A, onConflict: IGNORE });
|
|
91
|
+
assert.deepEqual(await storedRows(knex), [[first, 1, 1], [fresh, 1, 2]]);
|
|
92
|
+
// An id that is already another row's, with other keys, fails loudly, in its workspace and in another.
|
|
93
|
+
for (const options of [WORKSPACE_A, WORKSPACE_B]) {
|
|
94
|
+
await assert.rejects(participations.createMany([{ id: first, recordId: 8, userId: 3 }], { ...options, onConflict: IGNORE }), duplicateKey, options.context.workspace.id);
|
|
95
|
+
}
|
|
96
|
+
assert.deepEqual(await storedRows(knex), [[first, 1, 1], [fresh, 1, 2]]);
|
|
97
|
+
// Inside one transaction the second ignore is a no-op too, and the transaction goes on.
|
|
98
|
+
await participations.withTransaction(WORKSPACE_A, async (tx) => {
|
|
99
|
+
await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 1 }], { ...tx, onConflict: IGNORE });
|
|
100
|
+
await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 1 }], { ...tx, onConflict: IGNORE });
|
|
101
|
+
await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 2 }], { ...tx, onConflict: IGNORE });
|
|
102
|
+
});
|
|
103
|
+
const [counted] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId: 9 } }, WORKSPACE_A);
|
|
104
|
+
assert.equal(counted.participants, 2);
|
|
105
|
+
// A merge still takes rows without an id: the keys find the row it changes.
|
|
106
|
+
await assert.rejects(participations.createMany([{ id: randomUUID(), recordId: 7, userId: 1 }], { ...WORKSPACE_A, onConflict: { keys: KEYS, action: "merge" } }),
|
|
107
|
+
/onConflict merge takes rows without an id/u);
|
|
108
|
+
}]
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export { countOnlyTableCases };
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
3
3
|
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
-
import {
|
|
4
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
|
+
import { createResourceHost } from "../../src/server/resourceHost.js";
|
|
6
|
+
import { createResourceRuntime } from "../../src/server/resourceRuntime.js";
|
|
5
7
|
|
|
6
8
|
// lockWhere's sort and limit, on every database the runtime supports: the rows are locked in the sort's order, then by
|
|
7
|
-
// id, and limit locks only the first of them, so a lock of one row by its unique key costs what lock(id) costs.
|
|
8
|
-
//
|
|
9
|
+
// id, and limit locks only the first of them, so a lock of one row by its unique key costs what lock(id) costs. And
|
|
10
|
+
// lockPages, which locks every row a page at a time in id order, each page one locking read that sees the latest rows.
|
|
11
|
+
// Each database's test file runs these cases on its own connection.
|
|
9
12
|
|
|
10
13
|
const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
|
|
11
14
|
const IN_WORKSPACE_A = Object.freeze({ context: WORKSPACE_A });
|
|
@@ -24,22 +27,44 @@ const slotResource = defineTableResource({
|
|
|
24
27
|
|
|
25
28
|
const codeOf = (index) => `C${String(index).padStart(4, "0")}`;
|
|
26
29
|
|
|
27
|
-
/**
|
|
28
|
-
|
|
30
|
+
/**
|
|
31
|
+
* `count` slots in each of workspaces 1 and 2, codes C0000 up, their turns in the codes' reverse order, and a system
|
|
32
|
+
* scope for background work on them.
|
|
33
|
+
* @param {import("knex").Knex} knex
|
|
34
|
+
* @param {number} count
|
|
35
|
+
* @param {{ requestRowLimit?: number }} [settings]
|
|
36
|
+
*/
|
|
37
|
+
async function slotsOf(knex, count, settings = {}) {
|
|
29
38
|
await knex.schema.createTable("slots", (table) => {
|
|
30
39
|
table.increments("id");
|
|
31
40
|
table.integer("workspace_id").nullable();
|
|
32
41
|
table.string("code").notNullable();
|
|
33
42
|
table.integer("turn").notNullable();
|
|
34
43
|
table.unique(["workspace_id", "code"]);
|
|
44
|
+
// An index that reads a workspace's rows in id order, which lockPages needs on MySQL and MariaDB.
|
|
45
|
+
table.index(["workspace_id"], "slots_workspace");
|
|
35
46
|
});
|
|
36
47
|
const rows = [1, 2].flatMap((workspace) => Array.from({ length: count }, (_, index) => ({ workspace_id: workspace, code: codeOf(index), turn: count - index })));
|
|
37
48
|
for (let start = 0; start < rows.length; start += 200) {
|
|
38
49
|
await knex("slots").insert(rows.slice(start, start + 200));
|
|
39
50
|
}
|
|
40
|
-
const
|
|
51
|
+
const api = await createResourceHost({ knex, logger: silentLogger });
|
|
52
|
+
const runtime = createResourceRuntime({ api, ...settings });
|
|
41
53
|
const { slots } = await runtime.own("slots.feature", [slotResource]);
|
|
42
|
-
|
|
54
|
+
const system = runtime.declareSystemScope("slots.feature", "count every workspace's slots")("count the slots");
|
|
55
|
+
return { slots, system, api };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every page lockPages answers. Past 10 pages it throws, so a lockPages that never ends fails its case at once. */
|
|
59
|
+
async function pagesOf(pages) {
|
|
60
|
+
const all = [];
|
|
61
|
+
for await (const page of pages) {
|
|
62
|
+
all.push(page);
|
|
63
|
+
if (all.length > 10) {
|
|
64
|
+
throw new Error("lockPages answered more than 10 pages: its pages never end");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return all;
|
|
43
68
|
}
|
|
44
69
|
|
|
45
70
|
/**
|
|
@@ -50,7 +75,7 @@ function lockWhereOrderCases(connect) {
|
|
|
50
75
|
return [
|
|
51
76
|
["lockWhere locks and answers the rows in sort order, then id, and limit takes the first of them", async (t) => {
|
|
52
77
|
const knex = await connect(t, "da_lw_order");
|
|
53
|
-
const slots = await slotsOf(knex, 4);
|
|
78
|
+
const { slots } = await slotsOf(knex, 4);
|
|
54
79
|
const codes = (rows) => rows.map(({ code }) => code);
|
|
55
80
|
const every = { codes: [0, 1, 2, 3].map(codeOf) };
|
|
56
81
|
await slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
|
|
@@ -72,7 +97,7 @@ function lockWhereOrderCases(connect) {
|
|
|
72
97
|
for (const count of [4, 400]) {
|
|
73
98
|
const knex = await connect(t, `da_lw_cost_${count}`);
|
|
74
99
|
client = knex.client.config.client;
|
|
75
|
-
const slots = await slotsOf(knex, count);
|
|
100
|
+
const { slots } = await slotsOf(knex, count);
|
|
76
101
|
const [{ id }] = await knex("slots").where({ workspace_id: 1, code: "C0001" }).select("id");
|
|
77
102
|
const statements = async (lock) => {
|
|
78
103
|
// MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
|
|
@@ -94,6 +119,76 @@ function lockWhereOrderCases(connect) {
|
|
|
94
119
|
const one = client === "better-sqlite3" ? 2 : 1;
|
|
95
120
|
const expected = { lock: one, "lockWhere limit 1": one, lockWhere: client === "pg" ? 2 : one };
|
|
96
121
|
assert.deepEqual(costs, [expected, expected]);
|
|
122
|
+
}],
|
|
123
|
+
|
|
124
|
+
["lockPages locks every row a page at a time in id order, the same statements for 3 pages among 25 rows and 250", async (t) => {
|
|
125
|
+
const sizes = [];
|
|
126
|
+
for (const [count, pageSize] of [[25, 10], [250, 100]]) {
|
|
127
|
+
const knex = await connect(t, `da_lp_pages_${count}`);
|
|
128
|
+
const { slots } = await slotsOf(knex, count);
|
|
129
|
+
const lockAll = (tx) => pagesOf(slots.lockPages({}, { ...tx, pageSize, fields: ["code"] }));
|
|
130
|
+
// MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
|
|
131
|
+
await slots.withTransaction(IN_WORKSPACE_A, lockAll);
|
|
132
|
+
const { result: pages, count: statements } = await slots.withTransaction(IN_WORKSPACE_A, (tx) => countQueries(knex, () => lockAll(tx)));
|
|
133
|
+
assert.deepEqual(pages.flat().map(({ code }) => code), Array.from({ length: count }, (_, index) => codeOf(index)));
|
|
134
|
+
sizes.push({ pages: pages.map((page) => page.length), statements });
|
|
135
|
+
}
|
|
136
|
+
assert.deepEqual(sizes.map(({ pages }) => pages), [[10, 10, 5], [100, 100, 50]]);
|
|
137
|
+
assert.equal(sizes[1].statements, sizes[0].statements);
|
|
138
|
+
}],
|
|
139
|
+
|
|
140
|
+
["lockPages locks the rows committed since the transaction first read plainly", async (t) => {
|
|
141
|
+
const knex = await connect(t, "da_lp_current");
|
|
142
|
+
if (knex.client.config.client === "better-sqlite3") {
|
|
143
|
+
t.skip("SQLite has one writer, so no row commits while the transaction is open");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const { slots } = await slotsOf(knex, 3);
|
|
147
|
+
const codes = await slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
|
|
148
|
+
// A plain read first: on MySQL and MariaDB it fixes the transaction's snapshot.
|
|
149
|
+
assert.equal((await slots.queryAll({}, tx)).length, 3);
|
|
150
|
+
await knex("slots").insert({ workspace_id: 1, code: "C0100", turn: 0 });
|
|
151
|
+
return (await pagesOf(slots.lockPages({}, { ...tx, pageSize: 2 }))).flat().map(({ code }) => code);
|
|
152
|
+
});
|
|
153
|
+
assert.deepEqual(codes, ["C0000", "C0001", "C0002", "C0100"]);
|
|
154
|
+
}],
|
|
155
|
+
|
|
156
|
+
["lockPages throws at the request row limit, locks without one in background work, and refuses sort, limit and a bad pageSize", async (t) => {
|
|
157
|
+
const knex = await connect(t, "da_lp_limit");
|
|
158
|
+
const { slots, system } = await slotsOf(knex, 7, { requestRowLimit: 5 });
|
|
159
|
+
const read = [];
|
|
160
|
+
await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
|
|
161
|
+
for await (const page of slots.lockPages({}, { ...tx, pageSize: 3 })) {
|
|
162
|
+
read.push(page.length);
|
|
163
|
+
}
|
|
164
|
+
}), (error) => error.code === "RESOURCE_ROW_LIMIT" && /slots\.lockPages\(\) read more than 5 rows inside a request/u.test(error.message));
|
|
165
|
+
assert.deepEqual(read, [3]);
|
|
166
|
+
const job = await slots.withTransaction({ context: system.forWorkspace("1") }, (tx) => pagesOf(slots.lockPages({}, { ...tx, pageSize: 3 })));
|
|
167
|
+
assert.deepEqual(job.map((page) => page.length), [3, 3, 1]);
|
|
168
|
+
for (const options of [{ sort: ["code"] }, { limit: 2 }, { pageSize: 0 }, { pageSize: 1001 }, { pageSize: 1.5 }]) {
|
|
169
|
+
await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, (tx) => pagesOf(slots.lockPages({}, { ...tx, ...options }))),
|
|
170
|
+
(error) => error instanceof TypeError && /slots\.lockPages\(\)/u.test(error.message), JSON.stringify(options));
|
|
171
|
+
}
|
|
172
|
+
}],
|
|
173
|
+
|
|
174
|
+
["lockPages throws, rather than page forever, when its storage answers the page before again", async (t) => {
|
|
175
|
+
const knex = await connect(t, "da_lp_stuck");
|
|
176
|
+
const { slots, system, api } = await slotsOf(knex, 4);
|
|
177
|
+
// A storage whose lockWhere ignores after, as json-rest-api's did before it took after, in background work,
|
|
178
|
+
// which has no row limit to stop it.
|
|
179
|
+
const storage = api.resources.slots;
|
|
180
|
+
const lockWhere = storage.lockWhere;
|
|
181
|
+
storage.lockWhere = (params, context) => lockWhere.call(storage, { ...params, after: undefined }, context);
|
|
182
|
+
const read = [];
|
|
183
|
+
await assert.rejects(slots.withTransaction({ context: system.forWorkspace("1") }, async (tx) => {
|
|
184
|
+
for await (const page of slots.lockPages({}, { ...tx, pageSize: 2 })) {
|
|
185
|
+
read.push(page.map(({ code }) => code));
|
|
186
|
+
if (read.length > 10) {
|
|
187
|
+
throw new Error("lockPages answered more than 10 pages: its pages never end");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}), /slots\.lockPages\(\) read the row "2" again in the page after it/u);
|
|
191
|
+
assert.deepEqual(read, [["C0000", "C0001"]]);
|
|
97
192
|
}]
|
|
98
193
|
];
|
|
99
194
|
}
|