@jskit-ai/resource-runtime 0.2.25 → 0.2.27
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 +6 -0
- package/package.json +6 -6
- package/src/server/filterJoinSources.js +13 -3
- package/src/server/handleGuards.js +25 -2
- package/src/server/handleLocks.js +25 -7
- package/src/server/resourceHandle.js +11 -12
- package/src/server/resourceRuntime.js +33 -9
- package/test/lockedReads.mysql.test.js +36 -0
- package/test/locks.postgres.test.js +46 -0
- package/test/resourceRuntime.test.js +197 -10
- package/test/support/transactionChecksCases.js +172 -0
- package/test/support/transactionChecksFixture.js +243 -0
- package/test/transactionChecks.mysql.test.js +8 -0
- package/test/transactionChecks.test.js +8 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Depends on json-rest-api 3.1.6 exactly (from 3.1.5): within one transaction (a handle's `withTransaction`, or a write's own), json-rest-api answers a check of a row a write links to, or of a to-one link a response shows, from the transaction's own earlier check of that row in the same scope (the same ownership, row policy and filter values) under a lock at least as strong, until the transaction sends a statement that could change the answer: an insert or update of a table the check reads, an update of a column a remembered check names (such as `workspace_id`), a delete, a savepoint's rollback, or any other statement. A check that found no row is never remembered, and nothing carries from one transaction to the next. Installing one module (a form and a module, each published from a draft version, every row naming its author and publisher) in one transaction sent 55 statements and now sends 30; 32 modules in one transaction sent 1,698 and now send 836: its checks went from 1,024 to 162, the two users every row names checked twice instead of 480 times, and each module's own new rows 5 times instead of 17 (again only after a write to their table), on MariaDB 11.4 and PostgreSQL alike. `transactionChecks.test.js` (SQLite, and PostgreSQL in CI) and `transactionChecks.mysql.test.js` compare 1 and 32 modules, and show a transaction refusing a row it removed, moved out of the caller's scope or hid, another workspace's or user's row in the same transaction, a row an earlier transaction checked, and every link refused before.
|
|
6
|
+
- Depends on json-rest-api 3.1.5 exactly (from 3.1.4), from the registry with its published integrity: a read-only builder (a `scopedQuery()`, a join source, a row policy's `ownTable()`) that json-rest-api's own query compiles as a subquery keeps its joins, where 3.1.4 dropped them and the subquery matched more rows than it should (a row policy or filter narrowing with `whereExists` over a joined subquery widened), and `lockByIds`/`lockWhere` take `lockMode: 'share'`.
|
|
7
|
+
- **Security.** A row policy's calls that are not where calls (`join`, `leftJoin`, `select` and the rest) now throw a TypeError naming the feature, the policy and the table, as the policy makes them. Its calls replay inside one `where` group, where Knex compiles predicates only and dropped a join without a word, so a policy that narrowed through a join narrowed nothing and its readers saw rows it meant to hide. A policy narrows through another table with `whereExists` over `ownTable(name)` (which may join the owner's tables) or over another owner's `joinSource({ alias }, options)`. Upgrading: a policy that called `join` now fails every read of its table; rewrite it as a `whereExists`.
|
|
8
|
+
- A row policy is told the call's options as `options`, `{ context, trx }` as the caller passed them (frozen), so a policy that reads another owner's join source passes them on: `requires.members.joinSource({ alias: "tm" }, options)` reads in the caller's scope and transaction.
|
|
9
|
+
- `lock`, `lockMany` and `lockWhere` take `lockMode: "share"`: `FOR SHARE` on PostgreSQL and `LOCK IN SHARE MODE` on MySQL and MariaDB, which other reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows must not change until the transaction ends (`workspaces.lock` and `memberships.lockByWorkspaceIdAndUserId` pass it on). Never write a row the transaction holds shared: two transactions that each hold it shared and then write it deadlock. `claim`, `patchWhere` and `lockOrCreate` refuse `"share"` with a TypeError saying why, and any other mode is still a TypeError before any statement.
|
|
10
|
+
- `withTransaction({ ...options, joinOnly: true }, work)` joins the caller's transaction and refuses, with a TypeError before the work runs, a call outside one, for work whose writes must commit or roll back with its caller's; with `outermost: true` too it is a TypeError.
|
|
5
11
|
- Depends on json-rest-api 3.1.4 exactly (from 3.1.3), from the registry with its published integrity: a patch, put or patchMany that stores the values a row already holds answers the row as stored on MySQL and MariaDB (it answered the values this transaction first read), and AnyAPI storage checks its tables' columns with one statement at start-up.
|
|
6
12
|
- A paged `aggregate()` (`page: { size, number }`) answers `{ rows, page: { size, number, hasMore, next } }`, as `query()` answers a page, instead of a bare array a caller could take for every group; read the next page while `page.hasMore`. An unpaged grouped aggregate still answers every group or throws `GroupLimitError`, whose message now says to read pages. Upgrading: a caller passing `page` reads the groups from `.rows`.
|
|
7
13
|
- Depends on json-rest-api 3.1.3 exactly (from 3.1.2), from the registry with its published integrity: a write checks each linked target type with one read of the targets' ids (their minimal records only for a target resource with a `checkPermissions` hook), which also takes the shared lock on the belongs-to and polymorphic targets it stores, before `beforeSchemaValidate` rather than after the `beforeDataCall` hooks; in a system context a belongs-to its declared foreign key protects is left to that key, so a missing target there fails with the database's foreign key error instead of `not_found`. json-rest-api now asks for json-rest-schema ^1.0.20.
|
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.27",
|
|
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.212",
|
|
19
|
+
"@jskit-ai/resource-crud-core": "0.1.214",
|
|
20
|
+
"json-rest-api": "3.1.6"
|
|
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.270",
|
|
68
|
+
"@jskit-ai/kernel": "0.2.21"
|
|
69
69
|
}
|
|
70
70
|
}
|
|
@@ -9,8 +9,8 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
|
|
|
9
9
|
// while a join source is built asynchronously in the caller's scope, so a filtering hook builds the join sources the
|
|
10
10
|
// read's filters use first, from the call's own options, and applyFilter takes a fresh copy of one each time it asks.
|
|
11
11
|
|
|
12
|
-
// The call options a handle's json-rest-api context carries for the join sources its filters build:
|
|
13
|
-
// context and transaction, as the caller passed them. Module-private, so nothing but a handle sets it.
|
|
12
|
+
// The call options a handle's json-rest-api context carries for the join sources its filters and its row policy build:
|
|
13
|
+
// the caller's context and transaction, as the caller passed them. Module-private, so nothing but a handle sets it.
|
|
14
14
|
const CALL_OPTIONS = Symbol("jskit.resources.callOptions");
|
|
15
15
|
// The join sources a read's filters use, built by the filtering hook: by resource name, filter and alias.
|
|
16
16
|
const PREPARED_SOURCES = Symbol("jskit.resources.filterJoinSources");
|
|
@@ -30,6 +30,16 @@ function withCallOptions(jsonRestContext, options) {
|
|
|
30
30
|
return jsonRestContext;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* The call options a json-rest-api context carries (see withCallOptions): frozen `{ context, trx }`, or undefined for
|
|
35
|
+
* a context no handle built.
|
|
36
|
+
* @param {unknown} jsonRestContext
|
|
37
|
+
* @returns {Readonly<{ context: object | null, trx: object | null }> | undefined}
|
|
38
|
+
*/
|
|
39
|
+
function callOptionsOf(jsonRestContext) {
|
|
40
|
+
return isRecord(jsonRestContext) ? /** @type {any} */ (jsonRestContext)[CALL_OPTIONS] : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
33
43
|
/**
|
|
34
44
|
* The owns entry's search schema as json-rest-api takes it, and the filters in it that read join sources. Each such
|
|
35
45
|
* filter's `joinSources` is checked here, at startup, and taken out; its applyFilter is wrapped so that it receives
|
|
@@ -174,4 +184,4 @@ function joinSourceHooks({ resourceName, declared, ownerOf }) {
|
|
|
174
184
|
};
|
|
175
185
|
}
|
|
176
186
|
|
|
177
|
-
export { filterJoinSources, joinSourceHooks, withCallOptions };
|
|
187
|
+
export { callOptionsOf, filterJoinSources, joinSourceHooks, withCallOptions };
|
|
@@ -227,7 +227,30 @@ function matchesNoRow(filters, schemaInfo) {
|
|
|
227
227
|
return Object.entries(filters).some(([key, value]) => Array.isArray(value) && value.length === 0 && search[key]?.filterOperator === "in");
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
+
/**
|
|
231
|
+
* Refuses a withTransaction() call that runs where its setting says its work cannot, before the work runs: `outermost`
|
|
232
|
+
* work commits before it answers, so never inside the caller's transaction; `joinOnly` work commits or rolls back with
|
|
233
|
+
* the caller's, so never outside one, and never opens a transaction of its own. Both at once is a TypeError too.
|
|
234
|
+
* @param {string} name The resource's name.
|
|
235
|
+
* @param {{ outermost: boolean, joinOnly: boolean }} settings
|
|
236
|
+
* @param {boolean} joined Whether the call runs in its caller's transaction.
|
|
237
|
+
*/
|
|
238
|
+
function refuseTransactionPlace(name, { outermost, joinOnly }, joined) {
|
|
239
|
+
if (outermost && joinOnly) {
|
|
240
|
+
throw new TypeError(`${name}.withTransaction() takes outermost or joinOnly, not both: outermost work opens its own transaction, joinOnly work never does.`);
|
|
241
|
+
}
|
|
242
|
+
if (outermost && joined) {
|
|
243
|
+
throw new TypeError(`${name}.withTransaction() outermost work commits before it answers, so it cannot run inside the caller's transaction.`);
|
|
244
|
+
}
|
|
245
|
+
if (joinOnly && !joined) {
|
|
246
|
+
throw new TypeError(
|
|
247
|
+
`${name}.withTransaction() joinOnly work commits or rolls back with its caller's transaction, and this call has none: ` +
|
|
248
|
+
"call it from inside the caller's withTransaction(options, work), passing on the txOptions it gives work."
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
230
253
|
export {
|
|
231
|
-
formatOf, matchesNoRow, missingOf, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners,
|
|
232
|
-
requireReadParams, requireUpsertRows, passedOn, whereSelection
|
|
254
|
+
formatOf, matchesNoRow, missingOf, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
|
|
255
|
+
requirePatchConditions, requireReadParams, requireUpsertRows, passedOn, whereSelection
|
|
233
256
|
};
|
|
@@ -9,10 +9,22 @@ import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
|
|
|
9
9
|
// reference it (a foreign key's check takes FOR KEY SHARE); MySQL, MariaDB and SQLite have no weaker exclusive lock and
|
|
10
10
|
// lock as for "update".
|
|
11
11
|
const LOCK_MODES = Object.freeze(["update", "noKeyUpdate"]);
|
|
12
|
+
// lock, lockMany and lockWhere also take "share": FOR SHARE (LOCK IN SHARE MODE on MySQL and MariaDB), which other
|
|
13
|
+
// reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows must not change until
|
|
14
|
+
// the transaction ends. A row held shared is never written in the same transaction: two transactions that each hold it
|
|
15
|
+
// shared and then write it deadlock.
|
|
16
|
+
const SHARED_LOCK_MODES = Object.freeze([...LOCK_MODES, "share"]);
|
|
17
|
+
// Why the methods that take or write their rows refuse "share".
|
|
18
|
+
const NO_SHARE = Object.freeze({
|
|
19
|
+
claim: "a claimed row is taken to be worked on, and a shared lock would let another worker claim it too",
|
|
20
|
+
patchWhere: "it writes the rows it selects, and two transactions that each hold a row shared and then write it deadlock",
|
|
21
|
+
lockOrCreate: "its work writes the record it locks, and two transactions that each hold it shared and then write it deadlock"
|
|
22
|
+
});
|
|
12
23
|
|
|
13
24
|
/**
|
|
14
25
|
* json-rest-api's lock mode for a locking read: none when the call names none, so json-rest-api takes its default.
|
|
15
|
-
* Another value is a TypeError naming the handle method, before anything runs
|
|
26
|
+
* Another value is a TypeError naming the handle method, before anything runs: "share" too for claim, patchWhere and
|
|
27
|
+
* lockOrCreate, which take or write their rows.
|
|
16
28
|
* @param {string} name The resource's name.
|
|
17
29
|
* @param {string} caller The handle method, for the message.
|
|
18
30
|
* @param {unknown} lockMode
|
|
@@ -21,8 +33,13 @@ function lockModeOf(name, caller, lockMode) {
|
|
|
21
33
|
if (lockMode === undefined) {
|
|
22
34
|
return {};
|
|
23
35
|
}
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
const refusal = Object.hasOwn(NO_SHARE, caller) ? NO_SHARE[/** @type {keyof typeof NO_SHARE} */ (caller)] : null;
|
|
37
|
+
if (lockMode === "share" && refusal) {
|
|
38
|
+
throw new TypeError(`${name}.${caller}() takes lockMode "update" (the default) or "noKeyUpdate", not "share": ${refusal}.`);
|
|
39
|
+
}
|
|
40
|
+
if (!(refusal ? LOCK_MODES : SHARED_LOCK_MODES).includes(/** @type {string} */ (lockMode))) {
|
|
41
|
+
const modes = refusal ? '"update" (the default) or "noKeyUpdate"' : '"update" (the default), "noKeyUpdate" or "share"';
|
|
42
|
+
throw new TypeError(`${name}.${caller}() lockMode is ${modes}. Received: ${JSON.stringify(lockMode)}`);
|
|
26
43
|
}
|
|
27
44
|
return { lockMode };
|
|
28
45
|
}
|
|
@@ -210,11 +227,12 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
210
227
|
* left out with `missing: "skip"`. MySQL locks every listed id, a hidden one too: take ids from scoped reads.
|
|
211
228
|
* `fields` names the fields the lock reads, so a belongs-to field left out costs no check that its related
|
|
212
229
|
* record is visible; without it every field is read. `lockMode: "noKeyUpdate"` takes PostgreSQL's FOR NO KEY
|
|
213
|
-
* UPDATE, so other transactions may still insert rows that reference the locked ones (see LOCK_MODES)
|
|
230
|
+
* UPDATE, so other transactions may still insert rows that reference the locked ones (see LOCK_MODES), and
|
|
231
|
+
* `lockMode: "share"` a shared lock, which other reads and shared locks pass, for rows this transaction only reads.
|
|
214
232
|
* `include` names belongs-to relationships whose records are locked after the rows, through their own tables'
|
|
215
233
|
* handles, and nested as a read's include nests them (see withLockedIncludes).
|
|
216
234
|
* @param {unknown[]} ids
|
|
217
|
-
* @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
|
|
235
|
+
* @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
|
|
218
236
|
*/
|
|
219
237
|
async function lockMany(ids, options) {
|
|
220
238
|
return lockRead("lockMany", "lockByIds", { ids, ...(options.missing ? { missing: options.missing } : {}) }, options);
|
|
@@ -231,7 +249,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
231
249
|
* json-rest-api's not-found error, or answers null with `missing: "skip"`.
|
|
232
250
|
* `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
|
|
233
251
|
* @param {unknown} id
|
|
234
|
-
* @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
|
|
252
|
+
* @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
|
|
235
253
|
*/
|
|
236
254
|
async function lock(id, options) {
|
|
237
255
|
missingOf(name, "lock", options.missing);
|
|
@@ -248,7 +266,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
|
|
|
248
266
|
* with the ownership columns (no owners: with a filtered column), or it refuses.
|
|
249
267
|
* `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
|
|
250
268
|
* @param {object} filters
|
|
251
|
-
* @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
|
|
269
|
+
* @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
|
|
252
270
|
*/
|
|
253
271
|
async function lockWhere(filters, options) {
|
|
254
272
|
requireDefinedFilters(name, "lockWhere", filters);
|
|
@@ -13,8 +13,8 @@ import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
|
|
|
13
13
|
import { valueOnlyRaw } from "./rawExpression.js";
|
|
14
14
|
import { GroupLimitError, PageSizeError, StaleRecordError, UnpagedQueryError } from "./errors.js";
|
|
15
15
|
import {
|
|
16
|
-
formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners,
|
|
17
|
-
requireReadParams, requireUpsertRows, whereSelection
|
|
16
|
+
formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
|
|
17
|
+
requirePatchConditions, requireReadParams, requireUpsertRows, whereSelection
|
|
18
18
|
} from "./handleGuards.js";
|
|
19
19
|
import {
|
|
20
20
|
aggregateMeasures,
|
|
@@ -180,12 +180,12 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
|
|
|
180
180
|
* (`returning`, `missing`, `format`...), which was for the call it was named on. When work throws, the caller gets work's
|
|
181
181
|
* own error; a failed write inside it, or a failed commit, arrives as
|
|
182
182
|
* json-rest-api's RestApiWriteError with the transaction's outcome.
|
|
183
|
-
* Settings ride in options: `{ ...options, retry: false }` runs work once, for
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
183
|
+
* Settings ride in options: `{ ...options, retry: false }` runs work once, for work that cannot be repeated (it calls a
|
|
184
|
+
* provider); `{ ...options, outermost: true }` refuses a call inside a transaction, for work that must commit before
|
|
185
|
+
* the caller goes on (mail sent after it, say); `{ ...options, joinOnly: true }` refuses a call outside one, for work
|
|
186
|
+
* that must commit or roll back with its caller's (see refuseTransactionPlace).
|
|
187
187
|
* @template T
|
|
188
|
-
* @param {{ trx?: object | null, context?: object | null, retry?: boolean, outermost?: boolean }} options
|
|
188
|
+
* @param {{ trx?: object | null, context?: object | null, retry?: boolean, outermost?: boolean, joinOnly?: boolean }} options
|
|
189
189
|
* @param {(txOptions: Readonly<{ context?: object | null, trx: object }>) => Promise<T> | T} work
|
|
190
190
|
* @returns {Promise<T>}
|
|
191
191
|
*/
|
|
@@ -193,12 +193,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
|
|
|
193
193
|
if (rest.length > 0) {
|
|
194
194
|
throw new TypeError(`${name}.withTransaction() takes (options, work); settings ride in options: withTransaction({ ...options, retry: false }, work).`);
|
|
195
195
|
}
|
|
196
|
-
const { retry = true, outermost = false, ...callOptions } = options;
|
|
196
|
+
const { retry = true, outermost = false, joinOnly = false, ...callOptions } = options;
|
|
197
197
|
requireHandleTransaction(name, callOptions);
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}
|
|
198
|
+
const joined = inTransaction(callOptions);
|
|
199
|
+
refuseTransactionPlace(name, { outermost, joinOnly }, joined);
|
|
200
|
+
if (joined) {
|
|
202
201
|
return work(passedOn(callOptions));
|
|
203
202
|
}
|
|
204
203
|
const run = () => openTransaction(api, callOptions, work);
|
|
@@ -4,7 +4,7 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
|
|
|
4
4
|
import { isTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
5
5
|
import { callerOf, createSystemContext } from "./contexts.js";
|
|
6
6
|
import { DuplicateOwnerError } from "./errors.js";
|
|
7
|
-
import { filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
|
|
7
|
+
import { callOptionsOf, filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
|
|
8
8
|
import { createResourceHandle } from "./resourceHandle.js";
|
|
9
9
|
import { resourceScopeOptions } from "./resourceHost.js";
|
|
10
10
|
|
|
@@ -64,21 +64,39 @@ function crossTableFilters(scopeOptions) {
|
|
|
64
64
|
}));
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
// The calls a row policy makes on its query: where, andWhere and orWhere and their kin (whereIn, whereExists, whereNot,
|
|
68
|
+
// orWhereNull...). They replay inside one where group, where Knex compiles predicates only: a join there is dropped
|
|
69
|
+
// without a word, and the policy would no longer narrow the rows. Any other call is refused.
|
|
70
|
+
const POLICY_CALL = /^(?:where|andWhere|orWhere)/u;
|
|
71
|
+
|
|
67
72
|
/**
|
|
68
73
|
* Applies one row policy, the owner's or a contribution, inside its own
|
|
69
74
|
* parenthesised group, so whatever it writes (an orWhere among it) only narrows
|
|
70
75
|
* the rows ownership and the other policies left.
|
|
71
|
-
* The policy writes to a recorder; its calls replay inside `query.where(...)`.
|
|
76
|
+
* The policy writes to a recorder; its calls replay inside `query.where(...)`. A call other than a where call (see
|
|
77
|
+
* POLICY_CALL) throws a TypeError naming the policy, when the policy makes it.
|
|
72
78
|
* @param {Function} policy
|
|
73
79
|
* @param {Record<string, any>} args
|
|
80
|
+
* @param {string} label The policy, for the message: its feature and the resource it narrows.
|
|
74
81
|
*/
|
|
75
|
-
async function applyGrouped(policy, args) {
|
|
82
|
+
async function applyGrouped(policy, args, label) {
|
|
76
83
|
const calls = [];
|
|
77
84
|
const recorder = new Proxy({}, {
|
|
78
85
|
get(_target, method) {
|
|
79
|
-
if (method === "then") {
|
|
86
|
+
if (method === "then" || typeof method === "symbol") {
|
|
80
87
|
return undefined;
|
|
81
88
|
}
|
|
89
|
+
if (!POLICY_CALL.test(method)) {
|
|
90
|
+
return () => {
|
|
91
|
+
throw new TypeError(
|
|
92
|
+
`${label} calls query.${method}(), which a row policy cannot use: its calls run inside one where group, where ` +
|
|
93
|
+
"Knex compiles predicates only and drops a join, so the policy would no longer narrow the rows. A row policy " +
|
|
94
|
+
"narrows with where calls (where, andWhere, orWhere, whereIn, whereExists, whereNot and their kin). To narrow " +
|
|
95
|
+
"through another table, tie a subquery to the row: query.whereExists(ownTable(name).select(1).join(...)" +
|
|
96
|
+
".whereColumn(...)), or the same over another owner's joinSource({ alias }, options)."
|
|
97
|
+
);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
82
100
|
return (...callArgs) => {
|
|
83
101
|
calls.push([method, callArgs]);
|
|
84
102
|
return recorder;
|
|
@@ -158,24 +176,30 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
|
|
|
158
176
|
|
|
159
177
|
// The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
|
|
160
178
|
// Each gets who the call runs for as `caller` (see callerOf), its one way to tell: json-rest-api's own `system` flag
|
|
161
|
-
// is left out.
|
|
162
|
-
//
|
|
179
|
+
// is left out. Each gets the call's own options as `options`, `{ context, trx }` as the caller passed them, to pass
|
|
180
|
+
// on to an owner it reads (another owner's joinSource), never one built by hand. The owner's policy also gets the
|
|
181
|
+
// owning feature's dependencies as `requires`; a contribution is a function its feature built in setup, with its own.
|
|
163
182
|
function composedRowPolicy(featureId, entry, contributions, requires) {
|
|
164
183
|
if (!entry.rowPolicy && !entry.acceptsContributions) {
|
|
165
184
|
return undefined;
|
|
166
185
|
}
|
|
186
|
+
const resourceName = entry.resource.name;
|
|
187
|
+
const labelOf = (policyFeatureId, policy, relation) =>
|
|
188
|
+
`Feature "${policyFeatureId}" row policy ${policy.name ? `${policy.name} ` : ""}${relation} "${resourceName}"`;
|
|
167
189
|
return async function ownedRowPolicy(jsonRestArgs) {
|
|
168
|
-
const args = { ...jsonRestArgs };
|
|
190
|
+
const args = { ...jsonRestArgs, options: callOptionsOf(jsonRestArgs.context) };
|
|
169
191
|
delete args.system;
|
|
170
192
|
const caller = callerOf(args.context);
|
|
171
193
|
if (entry.rowPolicy) {
|
|
172
|
-
const
|
|
194
|
+
const policyArgs = { ...args, caller, ownTable: ownTableReader(featureId, args.db), requires };
|
|
195
|
+
const result = await applyGrouped(entry.rowPolicy, policyArgs, labelOf(featureId, entry.rowPolicy, "for"));
|
|
173
196
|
if (result !== true) {
|
|
174
197
|
return result;
|
|
175
198
|
}
|
|
176
199
|
}
|
|
177
200
|
for (const contribution of contributions) {
|
|
178
|
-
const
|
|
201
|
+
const policyArgs = { ...args, caller, ownTable: ownTableReader(contribution.featureId, args.db) };
|
|
202
|
+
const result = await applyGrouped(contribution.policy, policyArgs, labelOf(contribution.featureId, contribution.policy, "contributed to"));
|
|
179
203
|
if (result !== true) {
|
|
180
204
|
return result;
|
|
181
205
|
}
|
|
@@ -154,3 +154,39 @@ test("a lock's include reads the records committed after the transaction's snaps
|
|
|
154
154
|
assert.deepEqual(read.locked.map(({ guest, ticketId, ticket }) => [guest, ticketId !== null && ticketId === ticket?.id, ticket?.number ?? null]), [["first", true, "T1"]]);
|
|
155
155
|
assert.deepEqual(read.after, []);
|
|
156
156
|
});
|
|
157
|
+
|
|
158
|
+
test("lock, lockMany and lockWhere with lockMode share let another transaction share-lock the row, and hold its writes and exclusive locks", async (t) => {
|
|
159
|
+
const { seats, bookings } = await database(t, "da_lr_share");
|
|
160
|
+
const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
|
|
161
|
+
const bookingId = await bookings.create({ seatId, guest: "first" }, { ...WORKSPACE, returning: "id" });
|
|
162
|
+
// What another transaction does while the row is held shared: it gives up after 1 s (ER_LOCK_WAIT_TIMEOUT) when it
|
|
163
|
+
// would wait.
|
|
164
|
+
const meanwhile = (work) => bookings.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
165
|
+
await tx.trx.raw("SET SESSION innodb_lock_wait_timeout = 1");
|
|
166
|
+
await work(tx);
|
|
167
|
+
}).then(() => "proceeds", (error) => error.code);
|
|
168
|
+
const others = {
|
|
169
|
+
"shared lock": (tx) => bookings.lock(bookingId, { ...tx, lockMode: "share" }),
|
|
170
|
+
"exclusive lock": (tx) => bookings.lock(bookingId, tx),
|
|
171
|
+
write: (tx) => bookings.patch(bookingId, { guest: "other" }, { ...tx, returning: "none" })
|
|
172
|
+
};
|
|
173
|
+
const lockers = {
|
|
174
|
+
lock: (tx) => bookings.lock(bookingId, tx),
|
|
175
|
+
lockMany: (tx) => bookings.lockMany([bookingId], tx),
|
|
176
|
+
lockWhere: (tx) => bookings.lockWhere({ seatIds: [seatId] }, tx)
|
|
177
|
+
};
|
|
178
|
+
const outcomes = {};
|
|
179
|
+
for (const [name, locker] of Object.entries(lockers)) {
|
|
180
|
+
outcomes[name] = await bookings.withTransaction(WORKSPACE, async (tx) => {
|
|
181
|
+
assert.deepEqual((await locker({ ...tx, lockMode: "share" })).length ?? 1, 1, name);
|
|
182
|
+
const seen = {};
|
|
183
|
+
for (const [what, work] of Object.entries(others)) {
|
|
184
|
+
seen[what] = await meanwhile(work);
|
|
185
|
+
}
|
|
186
|
+
return seen;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
const shared = { "shared lock": "proceeds", "exclusive lock": "ER_LOCK_WAIT_TIMEOUT", write: "ER_LOCK_WAIT_TIMEOUT" };
|
|
190
|
+
assert.deepEqual(outcomes, { lock: shared, lockMany: shared, lockWhere: shared });
|
|
191
|
+
assert.deepEqual((await bookings.queryAll({}, WORKSPACE)).map(({ guest }) => guest), ["first"]);
|
|
192
|
+
});
|
|
@@ -343,3 +343,49 @@ test("a lock or patchWhere with lockMode noKeyUpdate lets another transaction ad
|
|
|
343
343
|
])));
|
|
344
344
|
assert.equal(Number((await knex("entries").count({ count: "*" }).first()).count), 6);
|
|
345
345
|
});
|
|
346
|
+
|
|
347
|
+
test("lock, lockMany and lockWhere with lockMode share let another transaction read and share-lock the row, and hold its writes and exclusive locks", { skip }, async (t) => {
|
|
348
|
+
const { knex, slots } = await database(t);
|
|
349
|
+
const [slot] = (await slots.createMany([{ status: "open" }], { ...WORKSPACE, returning: "ids" })).map(String);
|
|
350
|
+
// What another transaction does while the row is held shared: it gives up after 500 ms (55P03) when it would wait.
|
|
351
|
+
const meanwhile = async (work) => {
|
|
352
|
+
const { error } = await settle(() => knex.transaction(async (trx) => {
|
|
353
|
+
await trx.raw("SET LOCAL lock_timeout = '500ms'");
|
|
354
|
+
await work(trx);
|
|
355
|
+
}));
|
|
356
|
+
return error ? error.code : "proceeds";
|
|
357
|
+
};
|
|
358
|
+
const others = {
|
|
359
|
+
read: (trx) => trx("slots").where({ id: slot }),
|
|
360
|
+
"shared lock": (trx) => trx("slots").where({ id: slot }).forShare(),
|
|
361
|
+
"exclusive lock": (trx) => trx("slots").where({ id: slot }).forUpdate(),
|
|
362
|
+
write: (trx) => trx("slots").where({ id: slot }).update({ taken_by: "other" })
|
|
363
|
+
};
|
|
364
|
+
const lockers = {
|
|
365
|
+
lock: (txOptions) => slots.lock(slot, txOptions),
|
|
366
|
+
lockMany: (txOptions) => slots.lockMany([slot], txOptions),
|
|
367
|
+
lockWhere: (txOptions) => slots.lockWhere({ status: "open" }, txOptions)
|
|
368
|
+
};
|
|
369
|
+
const outcomes = {};
|
|
370
|
+
for (const [name, locker] of Object.entries(lockers)) {
|
|
371
|
+
const statements = [];
|
|
372
|
+
const recorded = ({ sql }) => statements.push(sql);
|
|
373
|
+
outcomes[name] = await slots.withTransaction(WORKSPACE, async (txOptions) => {
|
|
374
|
+
knex.on("query", recorded);
|
|
375
|
+
try {
|
|
376
|
+
await locker({ ...txOptions, lockMode: "share" });
|
|
377
|
+
} finally {
|
|
378
|
+
knex.off("query", recorded);
|
|
379
|
+
}
|
|
380
|
+
assert.ok(statements.some((sql) => /\bfor share\b/iu.test(sql)) && !statements.some((sql) => /\bfor (?:no key )?update\b/iu.test(sql)), `${name}: ${statements.join(" | ")}`);
|
|
381
|
+
const seen = {};
|
|
382
|
+
for (const [what, work] of Object.entries(others)) {
|
|
383
|
+
seen[what] = await meanwhile(work);
|
|
384
|
+
}
|
|
385
|
+
return seen;
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
const shared = { read: "proceeds", "shared lock": "proceeds", "exclusive lock": "55P03", write: "55P03" };
|
|
389
|
+
assert.deepEqual(outcomes, { lock: shared, lockMany: shared, lockWhere: shared });
|
|
390
|
+
assert.equal((await knex("slots").where({ id: slot }).first()).taken_by, null);
|
|
391
|
+
});
|
|
@@ -514,7 +514,12 @@ test("lockOrCreate() runs work on the locked record, creating it first when miss
|
|
|
514
514
|
knex.on("query", counted);
|
|
515
515
|
await assert.rejects(resources.counters.lockOrCreate({ id: "moded", value: 0 }, { ...options, lockMode: "share" }, bump), {
|
|
516
516
|
name: "TypeError",
|
|
517
|
-
message: 'counters.lockOrCreate() lockMode
|
|
517
|
+
message: 'counters.lockOrCreate() takes lockMode "update" (the default) or "noKeyUpdate", not "share": its work writes the record it ' +
|
|
518
|
+
"locks, and two transactions that each hold it shared and then write it deadlock."
|
|
519
|
+
});
|
|
520
|
+
await assert.rejects(resources.counters.lockOrCreate({ id: "moded", value: 0 }, { ...options, lockMode: "exclusive" }, bump), {
|
|
521
|
+
name: "TypeError",
|
|
522
|
+
message: 'counters.lockOrCreate() lockMode is "update" (the default) or "noKeyUpdate". Received: "exclusive"'
|
|
518
523
|
});
|
|
519
524
|
knex.off("query", counted);
|
|
520
525
|
assert.deepEqual(statements, []);
|
|
@@ -775,6 +780,30 @@ test("withTransaction() rethrows its work's own error, and takes its settings in
|
|
|
775
780
|
await assert.rejects(notes.withTransaction({ ...txOptions, outermost: true }, () => null), /cannot run inside the caller's transaction/u);
|
|
776
781
|
assert.equal(await notes.withTransaction(txOptions, () => "joined"), "joined");
|
|
777
782
|
});
|
|
783
|
+
// joinOnly work commits or rolls back with its caller's transaction, so a call outside one is refused before the work
|
|
784
|
+
// runs, and inside one it joins: its write rolls back with the caller's.
|
|
785
|
+
let ran = false;
|
|
786
|
+
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A, joinOnly: true }, () => {
|
|
787
|
+
ran = true;
|
|
788
|
+
}), {
|
|
789
|
+
name: "TypeError",
|
|
790
|
+
message: "notes.withTransaction() joinOnly work commits or rolls back with its caller's transaction, and this call has none: call " +
|
|
791
|
+
"it from inside the caller's withTransaction(options, work), passing on the txOptions it gives work."
|
|
792
|
+
});
|
|
793
|
+
assert.equal(ran, false);
|
|
794
|
+
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, async (txOptions) => {
|
|
795
|
+
await notes.withTransaction({ ...txOptions, joinOnly: true }, async (joined) => {
|
|
796
|
+
assert.equal(joined.trx, txOptions.trx);
|
|
797
|
+
assert.equal(Object.hasOwn(joined, "joinOnly"), false);
|
|
798
|
+
await notes.create({ title: "joined, then undone" }, joined);
|
|
799
|
+
});
|
|
800
|
+
throw failure;
|
|
801
|
+
}), (error) => error === failure);
|
|
802
|
+
assert.equal((await notes.queryAll({}, { context: WORKSPACE_A })).length, 0);
|
|
803
|
+
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A, outermost: true, joinOnly: true }, () => null), {
|
|
804
|
+
name: "TypeError",
|
|
805
|
+
message: "notes.withTransaction() takes outermost or joinOnly, not both: outermost work opens its own transaction, joinOnly work never does."
|
|
806
|
+
});
|
|
778
807
|
});
|
|
779
808
|
|
|
780
809
|
test("findOrCreate() answers the record with the id, creating it only when it is missing", async (t) => {
|
|
@@ -843,28 +872,41 @@ test("locks need a transaction and take only the caller's rows", async (t) => {
|
|
|
843
872
|
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, (txOptions) => notes.lock(other.id, txOptions)), notFound);
|
|
844
873
|
});
|
|
845
874
|
|
|
846
|
-
test("every lock and patchWhere take lockMode \"update\" or \"noKeyUpdate\" and
|
|
875
|
+
test("every lock and patchWhere take lockMode \"update\" or \"noKeyUpdate\", and lock, lockMany and lockWhere \"share\", reaching the same rows; another is refused before any statement", async (t) => {
|
|
847
876
|
const { knex, notes } = await createFixture(t);
|
|
848
877
|
const [a] = await notes.createMany([{ title: "a", status: "queued" }], { context: WORKSPACE_A, returning: "ids" });
|
|
849
878
|
const statements = [];
|
|
850
879
|
const counted = ({ sql }) => statements.push(sql);
|
|
851
880
|
await notes.withTransaction({ context: WORKSPACE_A }, async (txOptions) => {
|
|
852
|
-
for (const lockMode of ["update", "noKeyUpdate"]) {
|
|
881
|
+
for (const lockMode of ["update", "noKeyUpdate", "share"]) {
|
|
853
882
|
const options = { ...txOptions, lockMode };
|
|
854
883
|
assert.equal((await notes.lock(a, options)).title, "a", lockMode);
|
|
855
884
|
assert.deepEqual((await notes.lockMany([a], options)).map(({ title }) => title), ["a"], lockMode);
|
|
856
885
|
assert.deepEqual((await notes.lockWhere({ status: "queued" }, options)).map(({ title }) => title), ["a"], lockMode);
|
|
886
|
+
if (lockMode === "share") continue;
|
|
857
887
|
assert.deepEqual((await notes.claim({ filters: { status: "queued" } }, options)).map(({ title }) => title), ["a"], lockMode);
|
|
858
888
|
assert.equal(await notes.patchWhere({ status: "queued" }, { title: "a" }, { ...options, returning: "count" }), 1, lockMode);
|
|
859
889
|
}
|
|
860
890
|
knex.on("query", counted);
|
|
861
|
-
const
|
|
862
|
-
const
|
|
863
|
-
await assert.rejects(notes.
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
891
|
+
const shared = { ...txOptions, lockMode: "share" };
|
|
892
|
+
const writes = "two transactions that each hold a row shared and then write it deadlock";
|
|
893
|
+
await assert.rejects(notes.claim({ filters: { status: "queued" } }, shared), {
|
|
894
|
+
name: "TypeError",
|
|
895
|
+
message: 'notes.claim() takes lockMode "update" (the default) or "noKeyUpdate", not "share": a claimed row is taken to be worked ' +
|
|
896
|
+
"on, and a shared lock would let another worker claim it too."
|
|
897
|
+
});
|
|
898
|
+
await assert.rejects(notes.patchWhere({ status: "queued" }, { title: "b" }, shared), {
|
|
899
|
+
name: "TypeError",
|
|
900
|
+
message: `notes.patchWhere() takes lockMode "update" (the default) or "noKeyUpdate", not "share": it writes the rows it selects, and ${writes}.`
|
|
901
|
+
});
|
|
902
|
+
const exclusive = { ...txOptions, lockMode: "exclusive" };
|
|
903
|
+
const refused = (method, modes) => ({ name: "TypeError", message: `notes.${method}() lockMode is ${modes}. Received: "exclusive"` });
|
|
904
|
+
const withShare = '"update" (the default), "noKeyUpdate" or "share"';
|
|
905
|
+
await assert.rejects(notes.lock(a, exclusive), refused("lock", withShare));
|
|
906
|
+
await assert.rejects(notes.lockMany([a], exclusive), refused("lockMany", withShare));
|
|
907
|
+
await assert.rejects(notes.lockWhere({ status: "queued" }, exclusive), refused("lockWhere", withShare));
|
|
908
|
+
await assert.rejects(notes.claim({ filters: { status: "queued" } }, exclusive), refused("claim", '"update" (the default) or "noKeyUpdate"'));
|
|
909
|
+
await assert.rejects(notes.patchWhere({ status: "queued" }, { title: "b" }, exclusive), refused("patchWhere", '"update" (the default) or "noKeyUpdate"'));
|
|
868
910
|
knex.off("query", counted);
|
|
869
911
|
// Nothing reached the database, so the transaction goes on (on PostgreSQL a failed statement would end it).
|
|
870
912
|
assert.equal((await notes.lock(a, txOptions)).title, "a");
|
|
@@ -1158,6 +1200,151 @@ test("row policies read their own tables read-only, and contributions only narro
|
|
|
1158
1200
|
assert.deepEqual(records.map(({ name }) => name), ["general", "banned"]);
|
|
1159
1201
|
});
|
|
1160
1202
|
|
|
1203
|
+
// Teams with members, and documents filed under a team, each table in its workspace. Ada (7) is in the active team,
|
|
1204
|
+
// Grace (8) only in the archived one.
|
|
1205
|
+
async function teamDocuments(t, { owns, documentsPolicy, contribution }) {
|
|
1206
|
+
const knex = await testKnex(t);
|
|
1207
|
+
await knex.schema.createTable("teams", (table) => {
|
|
1208
|
+
table.increments("id");
|
|
1209
|
+
table.integer("workspace_id");
|
|
1210
|
+
table.string("status");
|
|
1211
|
+
});
|
|
1212
|
+
await knex.schema.createTable("team_members", (table) => {
|
|
1213
|
+
table.increments("id");
|
|
1214
|
+
table.integer("workspace_id");
|
|
1215
|
+
table.integer("team_id");
|
|
1216
|
+
table.integer("user_id");
|
|
1217
|
+
});
|
|
1218
|
+
await knex.schema.createTable("documents", (table) => {
|
|
1219
|
+
table.increments("id");
|
|
1220
|
+
table.integer("workspace_id");
|
|
1221
|
+
table.integer("team_id");
|
|
1222
|
+
table.string("title");
|
|
1223
|
+
});
|
|
1224
|
+
await knex("teams").insert([{ workspace_id: 1, status: "active" }, { workspace_id: 1, status: "archived" }, { workspace_id: 2, status: "active" }]);
|
|
1225
|
+
await knex("team_members").insert([
|
|
1226
|
+
{ workspace_id: 1, team_id: 1, user_id: 7 },
|
|
1227
|
+
{ workspace_id: 1, team_id: 2, user_id: 7 },
|
|
1228
|
+
{ workspace_id: 1, team_id: 2, user_id: 8 },
|
|
1229
|
+
{ workspace_id: 2, team_id: 3, user_id: 8 }
|
|
1230
|
+
]);
|
|
1231
|
+
await knex("documents").insert([
|
|
1232
|
+
{ workspace_id: 1, team_id: 1, title: "plan" },
|
|
1233
|
+
{ workspace_id: 1, team_id: 2, title: "old plan" },
|
|
1234
|
+
{ workspace_id: 2, team_id: 3, title: "elsewhere" }
|
|
1235
|
+
]);
|
|
1236
|
+
const owned = (name, tableName, fields) => defineTableResource({
|
|
1237
|
+
name,
|
|
1238
|
+
tableName,
|
|
1239
|
+
ownership: "workspace",
|
|
1240
|
+
defaultSort: ["id"],
|
|
1241
|
+
schema: {
|
|
1242
|
+
id: { type: "id", primary: true },
|
|
1243
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
1244
|
+
...fields
|
|
1245
|
+
}
|
|
1246
|
+
});
|
|
1247
|
+
const teamsTable = owned("teams", "teams", { status: { type: "string" } });
|
|
1248
|
+
const membersTable = owned("teamMembers", "team_members", {
|
|
1249
|
+
teamId: { type: "integer", storage: { column: "team_id" } },
|
|
1250
|
+
userId: { type: "integer", storage: { column: "user_id" } }
|
|
1251
|
+
});
|
|
1252
|
+
const documentsTable = owned("documents", "documents", { teamId: { type: "integer", storage: { column: "team_id" } }, title: { type: "string" } });
|
|
1253
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
1254
|
+
const documentsEntry = { resource: documentsTable, rowPolicy: documentsPolicy, acceptsContributions: Boolean(contribution) };
|
|
1255
|
+
if (owns === "together") {
|
|
1256
|
+
const handles = await runtime.own("documents.feature", [documentsEntry, teamsTable, membersTable]);
|
|
1257
|
+
return { knex, ...handles };
|
|
1258
|
+
}
|
|
1259
|
+
const teams = await runtime.own("teams.feature", [teamsTable, membersTable]);
|
|
1260
|
+
const { documents } = await runtime.own("documents.feature", [documentsEntry], { requires: { members: teams.teamMembers } });
|
|
1261
|
+
if (contribution) {
|
|
1262
|
+
teams.contributeRowPolicy("documents", contribution);
|
|
1263
|
+
}
|
|
1264
|
+
return { knex, documents, ...teams };
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
const ADA = Object.freeze({ ...WORKSPACE_A, actor: Object.freeze({ id: "7" }) });
|
|
1268
|
+
const GRACE = Object.freeze({ ...WORKSPACE_A, actor: Object.freeze({ id: "8" }) });
|
|
1269
|
+
|
|
1270
|
+
test("a row policy narrows with where calls only: a join, which Knex would drop from the policy's where group, throws naming the policy", async (t) => {
|
|
1271
|
+
const joinedTeams = ({ query, column, caller }) => {
|
|
1272
|
+
query.join("team_members as tm", "tm.team_id", column("teamId")).where("tm.user_id", caller.userId);
|
|
1273
|
+
return true;
|
|
1274
|
+
};
|
|
1275
|
+
const owner = await teamDocuments(t, { owns: "together", documentsPolicy: joinedTeams });
|
|
1276
|
+
for (const read of [() => owner.documents.queryAll({}, { context: ADA }), () => owner.documents.scopedQuery({}, { context: ADA })]) {
|
|
1277
|
+
await assert.rejects(read(), {
|
|
1278
|
+
name: "TypeError",
|
|
1279
|
+
message: /^Feature "documents\.feature" row policy joinedTeams for "documents" calls query\.join\(\), which a row policy cannot use: .* query\.whereExists\(ownTable\(name\)/u
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
// A contribution is held to the same, by its own feature's name; select and its kin are no where call either.
|
|
1283
|
+
const firstTeamOnly = ({ query }) => {
|
|
1284
|
+
query.select("team_id").where("team_id", 1);
|
|
1285
|
+
return true;
|
|
1286
|
+
};
|
|
1287
|
+
const contributed = await teamDocuments(t, { documentsPolicy: () => true, contribution: firstTeamOnly });
|
|
1288
|
+
await assert.rejects(contributed.documents.queryAll({}, { context: ADA }), {
|
|
1289
|
+
name: "TypeError",
|
|
1290
|
+
message: /^Feature "teams\.feature" row policy firstTeamOnly contributed to "documents" calls query\.select\(\), which a row policy cannot use/u
|
|
1291
|
+
});
|
|
1292
|
+
});
|
|
1293
|
+
|
|
1294
|
+
test("a row policy narrows through a join with whereExists over its own tables, which keeps the join's narrowing", async (t) => {
|
|
1295
|
+
// The subquery joins the member's team and keeps only active ones in the join's own condition: a subquery compiled
|
|
1296
|
+
// without its join would let Ada see the archived team's document too.
|
|
1297
|
+
const activeTeamMember = ({ query, column, caller, ownTable }) => {
|
|
1298
|
+
if (caller.kind !== "user") {
|
|
1299
|
+
return caller.kind !== "anonymous";
|
|
1300
|
+
}
|
|
1301
|
+
query.whereExists(ownTable("teamMembers")
|
|
1302
|
+
.select(1)
|
|
1303
|
+
.join("teams", (join) => join.on("teams.id", "team_members.team_id").andOnVal("teams.status", "=", "active"))
|
|
1304
|
+
.whereColumn("team_members.team_id", column("teamId"))
|
|
1305
|
+
.where("team_members.user_id", caller.userId));
|
|
1306
|
+
return true;
|
|
1307
|
+
};
|
|
1308
|
+
const { documents } = await teamDocuments(t, { owns: "together", documentsPolicy: activeTeamMember });
|
|
1309
|
+
const titles = async (context) => (await documents.queryAll({}, { context })).map(({ title }) => title);
|
|
1310
|
+
assert.deepEqual(await titles(ADA), ["plan"]);
|
|
1311
|
+
assert.deepEqual(await titles(GRACE), []);
|
|
1312
|
+
assert.deepEqual(await titles(WORKSPACE_A), []);
|
|
1313
|
+
});
|
|
1314
|
+
|
|
1315
|
+
test("a row policy is told the call's options, and reads another owner's join source in the caller's scope and transaction", async (t) => {
|
|
1316
|
+
const seen = [];
|
|
1317
|
+
const teamDocumentsPolicy = async ({ query, column, caller, options, requires }) => {
|
|
1318
|
+
seen.push(options);
|
|
1319
|
+
if (caller.kind !== "user") {
|
|
1320
|
+
return caller.kind !== "anonymous";
|
|
1321
|
+
}
|
|
1322
|
+
const member = await requires.members.joinSource({ alias: "tm" }, options);
|
|
1323
|
+
query.whereExists(member.query.select(1).whereColumn(member.column("teamId"), column("teamId")).where(member.column("userId"), caller.userId));
|
|
1324
|
+
return true;
|
|
1325
|
+
};
|
|
1326
|
+
const { knex, documents, teamMembers } = await teamDocuments(t, { documentsPolicy: teamDocumentsPolicy });
|
|
1327
|
+
// A document of workspace 1 filed under workspace 2's team, where Grace is a member.
|
|
1328
|
+
await knex("documents").insert({ workspace_id: 1, team_id: 3, title: "misfiled" });
|
|
1329
|
+
const titles = async (options) => (await documents.queryAll({}, options)).map(({ title }) => title);
|
|
1330
|
+
assert.deepEqual(await titles({ context: ADA }), ["plan", "old plan"]);
|
|
1331
|
+
assert.deepEqual(seen, [{ context: ADA, trx: null }]);
|
|
1332
|
+
assert.ok(Object.isFrozen(seen[0]));
|
|
1333
|
+
// Grace's membership of workspace 2's team stays there: the join source reads in the caller's workspace.
|
|
1334
|
+
assert.deepEqual(await titles({ context: GRACE }), ["old plan"]);
|
|
1335
|
+
// Inside a transaction the join source reads there: Grace sees the active team's document as soon as her uncommitted
|
|
1336
|
+
// membership exists, and a write's read-back runs the policy with the transaction too.
|
|
1337
|
+
seen.length = 0;
|
|
1338
|
+
await documents.withTransaction({ context: GRACE }, async (txOptions) => {
|
|
1339
|
+
await teamMembers.create({ teamId: 1, userId: 8 }, txOptions);
|
|
1340
|
+
assert.deepEqual(await titles(txOptions), ["plan", "old plan"]);
|
|
1341
|
+
assert.equal((await documents.create({ teamId: 1, title: "draft" }, txOptions)).title, "draft");
|
|
1342
|
+
assert.ok(seen.length >= 2);
|
|
1343
|
+
assert.ok(seen.every((options) => options.trx === txOptions.trx && options.context === GRACE));
|
|
1344
|
+
});
|
|
1345
|
+
assert.deepEqual(await titles({ context: ADA }), ["plan", "old plan", "draft"]);
|
|
1346
|
+
});
|
|
1347
|
+
|
|
1161
1348
|
test("a row policy is told who the call runs for: a system context, a job it derived, a signed-in user or no one", async (t) => {
|
|
1162
1349
|
const seen = [];
|
|
1163
1350
|
const { notes, runtime } = await createFixture(t, {
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
3
|
+
import { USER_EIGHT, USER_SEVEN, WORKSPACE_ONE, WORKSPACE_TWO, installModule, moduleFixture } from "./transactionChecksFixture.js";
|
|
4
|
+
|
|
5
|
+
// One transaction that installs modules links every row it writes to the users who wrote it and to the rows it wrote
|
|
6
|
+
// before. json-rest-api checks each link with a scoped read of the linked row's id, as it checks each link a response
|
|
7
|
+
// shows; within one transaction it answers a check from its own earlier check of the same row in the same scope, until
|
|
8
|
+
// the transaction sends something that could change the answer. Each database's test file runs these cases on its own
|
|
9
|
+
// connection.
|
|
10
|
+
|
|
11
|
+
// A check: a read of one table's ids and nothing else (on SQLite, the id in a CASE that keeps a large one exact).
|
|
12
|
+
const CHECK = /^select (?:distinct )?([^,*]*?) from ([`"])(\w+)\2 where /iu;
|
|
13
|
+
|
|
14
|
+
function checksOf(queries) {
|
|
15
|
+
const checks = {};
|
|
16
|
+
for (const sql of queries) {
|
|
17
|
+
const [, selected, quote, table] = CHECK.exec(sql) || [];
|
|
18
|
+
if (table && selected.includes(`${quote}${table}${quote}.${quote}id${quote}`)) {
|
|
19
|
+
checks[table] = (checks[table] || 0) + 1;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return checks;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The refusal of a link to a row the caller cannot see, however the handle's errors wrap it.
|
|
26
|
+
function refusedLink(type, id) {
|
|
27
|
+
const message = `Cannot create relationship to non-existent ${type} with id ${id}`;
|
|
28
|
+
return (error) => {
|
|
29
|
+
for (let cause = error; cause; cause = cause.cause) {
|
|
30
|
+
if (cause.message === message) {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
assert.fail(`expected "${message}", got: ${error?.message}`);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
40
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
41
|
+
*/
|
|
42
|
+
function transactionChecksCases(connect) {
|
|
43
|
+
return [
|
|
44
|
+
["a transaction installing 32 modules checks the users they name once, and each module's new rows as often as one module's", async (t) => {
|
|
45
|
+
const knex = await connect(t, "tc_counts");
|
|
46
|
+
const { handles } = await moduleFixture(knex);
|
|
47
|
+
let installed = 0;
|
|
48
|
+
const install = async (modules, { transactionEach = false } = {}) => {
|
|
49
|
+
const inOne = (count) => handles.forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
50
|
+
for (let index = 0; index < count; index += 1) {
|
|
51
|
+
installed += 1;
|
|
52
|
+
await installModule(handles, tx, { name: `module ${installed}`, author: "7", publisher: "8" });
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
const { queries } = await countQueries(knex, async () => {
|
|
56
|
+
for (const count of transactionEach ? Array(modules).fill(1) : [modules]) {
|
|
57
|
+
await inOne(count);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
return { statements: queries.length, checks: checksOf(queries) };
|
|
61
|
+
};
|
|
62
|
+
const one = await install(1);
|
|
63
|
+
const many = await install(32);
|
|
64
|
+
const each = await install(32, { transactionEach: true });
|
|
65
|
+
const counts = JSON.stringify({ one, many, each });
|
|
66
|
+
// Every module names the same two users, its author and its publisher: one transaction checks each once.
|
|
67
|
+
assert.equal(one.checks.users, 2, counts);
|
|
68
|
+
assert.equal(many.checks.users, 2, counts);
|
|
69
|
+
// A transaction per module checks them in each, as every write did before.
|
|
70
|
+
assert.equal(each.checks.users, 32 * 2, counts);
|
|
71
|
+
// A module's own new rows are checked as often in a big transaction as in a small one: the checks follow the
|
|
72
|
+
// rows written, and a write to a table makes its next check read again.
|
|
73
|
+
for (const table of ["forms", "form_versions", "modules", "module_versions"]) {
|
|
74
|
+
assert.equal(many.checks[table], 32 * one.checks[table], `${table}: ${counts}`);
|
|
75
|
+
assert.equal(each.checks[table], 32 * one.checks[table], `${table}: ${counts}`);
|
|
76
|
+
}
|
|
77
|
+
assert.deepEqual(Object.keys(many.checks).sort(), ["form_versions", "forms", "module_versions", "modules", "users"], counts);
|
|
78
|
+
// So one transaction's statements are 32 modules' worth beside its BEGIN, its COMMIT and the users' two checks.
|
|
79
|
+
const fixed = 2 + 2;
|
|
80
|
+
assert.equal(many.statements - fixed, 32 * (one.statements - fixed), counts);
|
|
81
|
+
}],
|
|
82
|
+
|
|
83
|
+
["a transaction checks a row again once it removes the row, moves it out of the caller's scope or changes what hides it", async (t) => {
|
|
84
|
+
const knex = await connect(t, "tc_changes");
|
|
85
|
+
const { handles } = await moduleFixture(knex);
|
|
86
|
+
const { drafts, formVersions, forms, memberships } = handles;
|
|
87
|
+
// User 8 leaves workspace 1 after a form named them.
|
|
88
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
89
|
+
await forms.create({ name: "a", createdBy: "8" }, tx);
|
|
90
|
+
const membership = (await memberships.queryAll({}, tx)).find(({ userId }) => String(userId) === "8");
|
|
91
|
+
await memberships.delete(membership.id, tx);
|
|
92
|
+
await forms.create({ name: "b", createdBy: "8" }, tx);
|
|
93
|
+
}), refusedLink("users", "8"));
|
|
94
|
+
// The transaction moves a form to workspace 2 by a statement of its own, after a version linked it.
|
|
95
|
+
let formId;
|
|
96
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
97
|
+
formId = (await forms.create({ name: "c", createdBy: "7" }, tx)).id;
|
|
98
|
+
await formVersions.create({ formId, status: "draft", createdBy: "7" }, tx);
|
|
99
|
+
await tx.trx("forms").where({ id: formId }).update({ workspace_id: 2 });
|
|
100
|
+
await formVersions.create({ formId, status: "draft", createdBy: "7" }, tx);
|
|
101
|
+
}), (error) => refusedLink("forms", formId)(error));
|
|
102
|
+
// The transaction deletes a draft a form linked.
|
|
103
|
+
let draftId;
|
|
104
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
105
|
+
draftId = (await drafts.create({ title: "mine" }, tx)).id;
|
|
106
|
+
const form = await forms.create({ name: "d", createdBy: "7", draftId }, tx);
|
|
107
|
+
await forms.delete(form.id, tx);
|
|
108
|
+
await drafts.delete(draftId, tx);
|
|
109
|
+
await forms.create({ name: "e", createdBy: "7", draftId }, tx);
|
|
110
|
+
}), (error) => refusedLink("drafts", draftId)(error));
|
|
111
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
112
|
+
}],
|
|
113
|
+
|
|
114
|
+
["a check made for one workspace or user never answers another's in the same transaction", async (t) => {
|
|
115
|
+
const knex = await connect(t, "tc_scopes");
|
|
116
|
+
const { handles } = await moduleFixture(knex);
|
|
117
|
+
const { drafts, forms } = handles;
|
|
118
|
+
// User 7 is a member of workspace 1 only.
|
|
119
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
120
|
+
await forms.create({ name: "a", createdBy: "7" }, tx);
|
|
121
|
+
await forms.create({ name: "b", createdBy: "7" }, { context: WORKSPACE_TWO, trx: tx.trx });
|
|
122
|
+
}), refusedLink("users", "7"));
|
|
123
|
+
// A draft is its own user's.
|
|
124
|
+
const draft = await drafts.create({ title: "mine" }, { context: USER_SEVEN });
|
|
125
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
126
|
+
await forms.create({ name: "c", createdBy: "7", draftId: draft.id }, tx);
|
|
127
|
+
await forms.create({ name: "d", createdBy: "8", draftId: draft.id }, { context: USER_EIGHT, trx: tx.trx });
|
|
128
|
+
}), refusedLink("drafts", draft.id));
|
|
129
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
130
|
+
}],
|
|
131
|
+
|
|
132
|
+
["each transaction checks again what an earlier one checked, whether it rolled back or committed", async (t) => {
|
|
133
|
+
const knex = await connect(t, "tc_next");
|
|
134
|
+
const { handles } = await moduleFixture(knex);
|
|
135
|
+
const { forms } = handles;
|
|
136
|
+
const rollBack = new Error("roll back");
|
|
137
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
138
|
+
await forms.create({ name: "a", createdBy: "7" }, tx);
|
|
139
|
+
throw rollBack;
|
|
140
|
+
}), (error) => error === rollBack);
|
|
141
|
+
await forms.withTransaction({ context: WORKSPACE_ONE }, (tx) => forms.create({ name: "b", createdBy: "8" }, tx));
|
|
142
|
+
// Users 7 and 8 leave workspace 1, outside any transaction.
|
|
143
|
+
await knex("memberships").whereIn("user_id", [7, 8]).delete();
|
|
144
|
+
for (const userId of ["7", "8"]) {
|
|
145
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, (tx) => forms.create({ name: "c", createdBy: userId }, tx)),
|
|
146
|
+
refusedLink("users", userId));
|
|
147
|
+
}
|
|
148
|
+
assert.deepEqual((await knex("forms").select("name")).map(({ name }) => name), ["b"]);
|
|
149
|
+
}],
|
|
150
|
+
|
|
151
|
+
["every link refused before is refused in a transaction that checked other rows of the table: another workspace's user, a missing row, another user's draft", async (t) => {
|
|
152
|
+
const knex = await connect(t, "tc_refusals");
|
|
153
|
+
const { handles } = await moduleFixture(knex);
|
|
154
|
+
const { drafts, forms } = handles;
|
|
155
|
+
const mine = await drafts.create({ title: "mine" }, { context: USER_SEVEN });
|
|
156
|
+
const theirs = await drafts.create({ title: "theirs" }, { context: USER_EIGHT });
|
|
157
|
+
for (const [data, refusal] of [
|
|
158
|
+
[{ createdBy: "9" }, refusedLink("users", "9")],
|
|
159
|
+
[{ createdBy: "999" }, refusedLink("users", "999")],
|
|
160
|
+
[{ createdBy: "7", draftId: theirs.id }, refusedLink("drafts", theirs.id)]
|
|
161
|
+
]) {
|
|
162
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
163
|
+
await forms.create({ name: "kept", createdBy: "7", draftId: mine.id }, tx);
|
|
164
|
+
await forms.create({ name: "refused", ...data }, tx);
|
|
165
|
+
}), refusal);
|
|
166
|
+
}
|
|
167
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
168
|
+
}]
|
|
169
|
+
];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export { transactionChecksCases };
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
2
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
3
|
+
|
|
4
|
+
// A workspace's forms and modules, each published from a draft version, every row naming the users who wrote it: the
|
|
5
|
+
// writes one transaction makes when it installs a module. Users are one table every workspace shares, which a row
|
|
6
|
+
// policy narrows to the members of the caller's workspace; a form may start from a user's own private draft; everything
|
|
7
|
+
// else is the workspace's own.
|
|
8
|
+
|
|
9
|
+
const WORKSPACE_ONE = Object.freeze({ workspace: Object.freeze({ id: "1" }), actor: Object.freeze({ id: "7" }) });
|
|
10
|
+
const WORKSPACE_TWO = Object.freeze({ workspace: Object.freeze({ id: "2" }), actor: Object.freeze({ id: "9" }) });
|
|
11
|
+
// Users 7 and 8 in workspace 1, each signed in, so each reads their own drafts only.
|
|
12
|
+
const signedIn = (userId) => Object.freeze({
|
|
13
|
+
workspace: Object.freeze({ id: "1" }),
|
|
14
|
+
actor: Object.freeze({ id: userId }),
|
|
15
|
+
visibilityContext: Object.freeze({ userId })
|
|
16
|
+
});
|
|
17
|
+
const USER_SEVEN = signedIn("7");
|
|
18
|
+
const USER_EIGHT = signedIn("8");
|
|
19
|
+
// Users 7 and 8 are members of workspace 1; user 9 only of workspace 2.
|
|
20
|
+
const USERS = Object.freeze([
|
|
21
|
+
Object.freeze({ id: 7, name: "Ada", workspaces: [1] }),
|
|
22
|
+
Object.freeze({ id: 8, name: "Grace", workspaces: [1] }),
|
|
23
|
+
Object.freeze({ id: 9, name: "Edsger", workspaces: [2] })
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
const workspaceId = { type: "id", nullable: true, storage: { column: "workspace_id" } };
|
|
27
|
+
const userLink = (as, column, extra = {}) => ({ type: "id", belongsTo: "users", as, storage: { column }, ...extra });
|
|
28
|
+
|
|
29
|
+
const userResource = defineTableResource({
|
|
30
|
+
name: "users",
|
|
31
|
+
tableName: "users",
|
|
32
|
+
ownership: "public",
|
|
33
|
+
schema: { name: { type: "string", required: true } }
|
|
34
|
+
});
|
|
35
|
+
const membershipResource = defineTableResource({
|
|
36
|
+
name: "memberships",
|
|
37
|
+
tableName: "memberships",
|
|
38
|
+
ownership: "workspace",
|
|
39
|
+
schema: { workspaceId, userId: { type: "id", required: true, storage: { column: "user_id" } } },
|
|
40
|
+
foreignKeys: [{ columns: ["userId"], referencedTableName: "users" }]
|
|
41
|
+
});
|
|
42
|
+
const draftResource = defineTableResource({
|
|
43
|
+
name: "drafts",
|
|
44
|
+
tableName: "drafts",
|
|
45
|
+
ownership: "user",
|
|
46
|
+
schema: { userId: { type: "id", storage: { column: "user_id" } }, title: { type: "string", required: true } },
|
|
47
|
+
foreignKeys: [{ columns: ["userId"], referencedTableName: "users" }]
|
|
48
|
+
});
|
|
49
|
+
const formResource = defineTableResource({
|
|
50
|
+
name: "forms",
|
|
51
|
+
tableName: "forms",
|
|
52
|
+
ownership: "workspace",
|
|
53
|
+
schema: {
|
|
54
|
+
workspaceId,
|
|
55
|
+
name: { type: "string", required: true },
|
|
56
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
57
|
+
draftId: { type: "id", nullable: true, belongsTo: "drafts", as: "draft", storage: { column: "draft_id" } },
|
|
58
|
+
currentVersionId: { type: "id", nullable: true, belongsTo: "formVersions", as: "currentVersion", storage: { column: "current_version_id" } }
|
|
59
|
+
},
|
|
60
|
+
foreignKeys: [
|
|
61
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
62
|
+
{ columns: ["draftId"], referencedTableName: "drafts" },
|
|
63
|
+
{ columns: ["currentVersionId"], referencedTableName: "form_versions" }
|
|
64
|
+
]
|
|
65
|
+
});
|
|
66
|
+
const formVersionResource = defineTableResource({
|
|
67
|
+
name: "formVersions",
|
|
68
|
+
tableName: "form_versions",
|
|
69
|
+
ownership: "workspace",
|
|
70
|
+
schema: {
|
|
71
|
+
workspaceId,
|
|
72
|
+
formId: { type: "id", required: true, belongsTo: "forms", as: "form", storage: { column: "form_id" } },
|
|
73
|
+
status: { type: "string", required: true },
|
|
74
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
75
|
+
publishedBy: userLink("publisher", "published_by", { nullable: true })
|
|
76
|
+
},
|
|
77
|
+
foreignKeys: [
|
|
78
|
+
{ columns: ["formId"], referencedTableName: "forms" },
|
|
79
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
80
|
+
{ columns: ["publishedBy"], referencedTableName: "users" }
|
|
81
|
+
]
|
|
82
|
+
});
|
|
83
|
+
const moduleResource = defineTableResource({
|
|
84
|
+
name: "modules",
|
|
85
|
+
tableName: "modules",
|
|
86
|
+
ownership: "workspace",
|
|
87
|
+
schema: {
|
|
88
|
+
workspaceId,
|
|
89
|
+
name: { type: "string", required: true },
|
|
90
|
+
formId: { type: "id", required: true, belongsTo: "forms", as: "form", storage: { column: "form_id" } },
|
|
91
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
92
|
+
currentVersionId: { type: "id", nullable: true, belongsTo: "moduleVersions", as: "currentVersion", storage: { column: "current_version_id" } }
|
|
93
|
+
},
|
|
94
|
+
foreignKeys: [
|
|
95
|
+
{ columns: ["formId"], referencedTableName: "forms" },
|
|
96
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
97
|
+
{ columns: ["currentVersionId"], referencedTableName: "module_versions" }
|
|
98
|
+
]
|
|
99
|
+
});
|
|
100
|
+
const moduleVersionResource = defineTableResource({
|
|
101
|
+
name: "moduleVersions",
|
|
102
|
+
tableName: "module_versions",
|
|
103
|
+
ownership: "workspace",
|
|
104
|
+
schema: {
|
|
105
|
+
workspaceId,
|
|
106
|
+
moduleId: { type: "id", required: true, belongsTo: "modules", as: "module", storage: { column: "module_id" } },
|
|
107
|
+
formVersionId: { type: "id", required: true, belongsTo: "formVersions", as: "formVersion", storage: { column: "form_version_id" } },
|
|
108
|
+
status: { type: "string", required: true },
|
|
109
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
110
|
+
publishedBy: userLink("publisher", "published_by", { nullable: true })
|
|
111
|
+
},
|
|
112
|
+
foreignKeys: [
|
|
113
|
+
{ columns: ["moduleId"], referencedTableName: "modules" },
|
|
114
|
+
{ columns: ["formVersionId"], referencedTableName: "form_versions" },
|
|
115
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
116
|
+
{ columns: ["publishedBy"], referencedTableName: "users" }
|
|
117
|
+
]
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// A request sees the users who are members of its workspace; background work sees every user.
|
|
121
|
+
function workspaceMembers({ query, column, caller, context, ownTable }) {
|
|
122
|
+
if (caller.kind === "system") {
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
const workspace = context.workspace?.id ?? context.scopeValues?.workspaceId;
|
|
126
|
+
if (!workspace) {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
query.whereIn(column("id"), ownTable("memberships").select("user_id").where("workspace_id", workspace));
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Integer keys that reference another table's increments() id, which MySQL and MariaDB make unsigned.
|
|
134
|
+
const reference = (table, column, target, { nullable = false } = {}) => {
|
|
135
|
+
const definition = table.integer(column).unsigned();
|
|
136
|
+
(nullable ? definition.nullable() : definition.notNullable()).references("id").inTable(target);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
async function createTables(knex) {
|
|
140
|
+
await knex.schema.createTable("users", (table) => {
|
|
141
|
+
table.increments("id");
|
|
142
|
+
table.string("name").notNullable();
|
|
143
|
+
});
|
|
144
|
+
await knex.schema.createTable("memberships", (table) => {
|
|
145
|
+
table.increments("id");
|
|
146
|
+
table.integer("workspace_id").nullable().index();
|
|
147
|
+
reference(table, "user_id", "users");
|
|
148
|
+
});
|
|
149
|
+
await knex.schema.createTable("drafts", (table) => {
|
|
150
|
+
table.increments("id");
|
|
151
|
+
reference(table, "user_id", "users");
|
|
152
|
+
table.string("title").notNullable();
|
|
153
|
+
});
|
|
154
|
+
await knex.schema.createTable("forms", (table) => {
|
|
155
|
+
table.increments("id");
|
|
156
|
+
table.integer("workspace_id").nullable().index();
|
|
157
|
+
table.string("name").notNullable();
|
|
158
|
+
reference(table, "created_by", "users");
|
|
159
|
+
reference(table, "draft_id", "drafts", { nullable: true });
|
|
160
|
+
table.integer("current_version_id").unsigned().nullable();
|
|
161
|
+
});
|
|
162
|
+
await knex.schema.createTable("form_versions", (table) => {
|
|
163
|
+
table.increments("id");
|
|
164
|
+
table.integer("workspace_id").nullable().index();
|
|
165
|
+
reference(table, "form_id", "forms");
|
|
166
|
+
table.string("status").notNullable();
|
|
167
|
+
reference(table, "created_by", "users");
|
|
168
|
+
reference(table, "published_by", "users", { nullable: true });
|
|
169
|
+
});
|
|
170
|
+
await knex.schema.alterTable("forms", (table) => {
|
|
171
|
+
table.foreign("current_version_id").references("id").inTable("form_versions");
|
|
172
|
+
});
|
|
173
|
+
await knex.schema.createTable("modules", (table) => {
|
|
174
|
+
table.increments("id");
|
|
175
|
+
table.integer("workspace_id").nullable().index();
|
|
176
|
+
table.string("name").notNullable();
|
|
177
|
+
reference(table, "form_id", "forms");
|
|
178
|
+
reference(table, "created_by", "users");
|
|
179
|
+
table.integer("current_version_id").unsigned().nullable();
|
|
180
|
+
});
|
|
181
|
+
await knex.schema.createTable("module_versions", (table) => {
|
|
182
|
+
table.increments("id");
|
|
183
|
+
table.integer("workspace_id").nullable().index();
|
|
184
|
+
reference(table, "module_id", "modules");
|
|
185
|
+
reference(table, "form_version_id", "form_versions");
|
|
186
|
+
table.string("status").notNullable();
|
|
187
|
+
reference(table, "created_by", "users");
|
|
188
|
+
reference(table, "published_by", "users", { nullable: true });
|
|
189
|
+
});
|
|
190
|
+
await knex.schema.alterTable("modules", (table) => {
|
|
191
|
+
table.foreign("current_version_id").references("id").inTable("module_versions");
|
|
192
|
+
});
|
|
193
|
+
await knex("users").insert(USERS.map(({ id, name }) => ({ id, name })));
|
|
194
|
+
await knex("memberships").insert(USERS.flatMap(({ id, workspaces }) => workspaces.map((workspace) => ({ workspace_id: workspace, user_id: id }))));
|
|
195
|
+
// PostgreSQL's sequence does not follow ids inserted by hand.
|
|
196
|
+
if (String(knex.client.config.client).includes("pg")) {
|
|
197
|
+
await knex.raw("SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT MAX(id) FROM users))");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The tables, their users and memberships, and the handles of one feature that owns them all.
|
|
203
|
+
* @param {import("knex").Knex} knex
|
|
204
|
+
*/
|
|
205
|
+
async function moduleFixture(knex) {
|
|
206
|
+
await createTables(knex);
|
|
207
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
208
|
+
const handles = await runtime.own("modules.feature", [
|
|
209
|
+
{ resource: userResource, rowPolicy: workspaceMembers },
|
|
210
|
+
membershipResource,
|
|
211
|
+
draftResource,
|
|
212
|
+
formResource,
|
|
213
|
+
formVersionResource,
|
|
214
|
+
moduleResource,
|
|
215
|
+
moduleVersionResource
|
|
216
|
+
]);
|
|
217
|
+
const systemContext = runtime.declareSystemScope("modules.feature", "The fixture checks every workspace's rows.");
|
|
218
|
+
return { knex, handles, system: systemContext("check the fixture's rows") };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Installs one module in the caller's transaction, as a setup service does: a form with a draft version it publishes,
|
|
223
|
+
* then a module on that form with a draft version it publishes. Every row names the users who wrote it. Answers the
|
|
224
|
+
* ids it wrote.
|
|
225
|
+
* @param {Record<string, any>} handles
|
|
226
|
+
* @param {{ context: object, trx: object }} tx
|
|
227
|
+
* @param {{ name: string, author: string, publisher: string }} module
|
|
228
|
+
*/
|
|
229
|
+
async function installModule(handles, tx, { name, author, publisher }) {
|
|
230
|
+
const { forms, formVersions, modules, moduleVersions } = handles;
|
|
231
|
+
const form = await forms.create({ name: `${name} form`, createdBy: author }, tx);
|
|
232
|
+
const formVersion = await formVersions.create({ formId: form.id, status: "draft", createdBy: author }, tx);
|
|
233
|
+
await formVersions.patch(formVersion.id, { status: "published", publishedBy: publisher }, tx);
|
|
234
|
+
await forms.patch(form.id, { currentVersionId: formVersion.id }, tx);
|
|
235
|
+
await forms.get(form.id, {}, tx);
|
|
236
|
+
const module = await modules.create({ name, formId: form.id, createdBy: author }, tx);
|
|
237
|
+
const moduleVersion = await moduleVersions.create({ moduleId: module.id, formVersionId: formVersion.id, status: "draft", createdBy: author }, tx);
|
|
238
|
+
await moduleVersions.patch(moduleVersion.id, { status: "published", publishedBy: publisher }, tx);
|
|
239
|
+
await modules.patch(module.id, { currentVersionId: moduleVersion.id }, tx);
|
|
240
|
+
return Object.freeze({ formId: form.id, formVersionId: formVersion.id, moduleId: module.id, moduleVersionId: moduleVersion.id });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export { USERS, USER_EIGHT, USER_SEVEN, WORKSPACE_ONE, WORKSPACE_TWO, installModule, moduleFixture };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { transactionChecksCases } from "./support/transactionChecksCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of transactionChecksCases(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 { transactionChecksCases } from "./support/transactionChecksCases.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 transactionChecksCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|