@jskit-ai/crud-core 0.2.10 → 0.2.12
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 +12 -0
- package/package.json +8 -8
- package/patterns/json-api-resource-package/example/packages/books/package.json +2 -2
- package/src/server/jsonApiModule/actions.js +8 -1
- package/src/server/jsonApiModule/repository.js +164 -6
- package/src/server/jsonApiModule/service.js +11 -2
- package/test/assistantPagination.integration.test.js +1 -0
- package/test/jsonApiRepositoryDataCosts.test.js +183 -0
- package/test/jsonApiRepositoryPageLimits.test.js +158 -0
- package/test/jsonApiRepositoryRowLocks.test.js +137 -0
- package/test/support/crudJsonApiActionOptions.js +3 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,11 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Depends on json-rest-api 2.4.0 (from 2.1.0); see `@jskit-ai/json-rest-api-core`'s CHANGELOG for what it changes.
|
|
6
|
+
- A CRUD JSON:API repository's `createDocument` and `patchDocumentById` take `returning: "full"` (the default, unchanged), `"minimal"` (`{ data: { type, id } }`) or `"none"`, so server code that ignores the result skips the read-back: a get through the row policy and lookups, about four queries per written record. `createDocuments(payloads, { trx, context, returning })` creates several records in order in one transaction, all or none, returning `"minimal"` results unless asked for `"full"`.
|
|
5
7
|
- The actions of an `internal: true` or `routes: false` CRUD feature are left off the `automation` channel, so the assistant cannot call them, unless their permission names a permission (`require: "all"` or `"any"`), as workspace-scoped CRUD's defaults do. An additional action's own `channels` still decide for it.
|
|
8
|
+
- A CRUD JSON:API repository's `queryDocuments(query, options)` throws a `TypeError` naming `queryEveryDocument` when `query.limit` is above the resource's json-rest-api `queryMaxLimit` (100 unless the resource sets it), instead of silently answering only `queryMaxLimit` records. New `queryEveryDocument(query, options)` answers every record the query matches as one JSON:API document `{ data, included }` (each included record once), reading 1,000-record pages in id order in the caller's transaction; its query takes filters, `include` and `fields`, but no `limit`, `cursor` or `sort`. New `queryMaxLimit()` reports the cap. The HTTP and automation list action still caps a larger `limit` and answers one page, whose `meta.pagination` reports the page size, `hasMore` and the next cursor, as before. `@jskit-ai/json-rest-api-core`'s new `queryAllJsonRestCollectionDocument(resource, params, context)` is the every-row read behind it.
|
|
9
|
+
- A CRUD JSON:API repository's `getDocumentById(recordId, query, { trx, forUpdate: true })` locks the record's row in `trx` before reading it (`SELECT ... FOR UPDATE`; nothing on SQLite, which runs one transaction at a time), so a concurrent `forUpdate` read or write of it waits until the transaction ends. It used to ignore `forUpdate`. Without a transaction it throws a `TypeError`, as does a `forUpdate` that is not a boolean. The CRUD service's `getDocumentById` passes `forUpdate` through, and the service gains `queryEveryDocument`.
|
|
6
10
|
|
|
7
11
|
### Upgrading
|
|
8
12
|
|
|
13
|
+
- json-rest-api 2.4.0 (from 2.1.0): `addResource` now rejects a field type json-rest-schema cannot cast, naming the field (JSKIT's own resources use only castable types); and a write's relationship targets are locked FOR SHARE (LOCK IN SHARE MODE on MySQL), so a lifecycle hook that then updates a referenced parent row in the same transaction should lock that row first, with `getDocumentById(parentId, {}, { trx, forUpdate: true })`, or two such writers can deadlock on the lock upgrade.
|
|
14
|
+
- `getDocumentById(..., { forUpdate: true })` now locks: beepollen's `packages/driers/src/server/drierOperationLifecycle.js` (service, inside its transaction) gets the lock it asked for. A call that passes `forUpdate: true` without `trx` now throws; read inside `withTransaction`.
|
|
9
15
|
- Give an internal resource explicit `permissions` when the assistant should keep reading it for the users who hold them.
|
|
16
|
+
- Server code that calls a CRUD repository's or service's `queryDocuments` with a `limit` above 100 now throws. It already received only 100 records, so a read meant to return more was losing rows. Replace `queryDocuments({ ...filters, limit: N })` and any cursor loop around it with `queryEveryDocument({ ...filters }, options)`, sorting the records it returns in memory; a "too many rows" guard (`rows.length >= N`) then sees the true count. Calls found in the applications' main branches (canonical clones of 1-5 Nov 2026):
|
|
17
|
+
- beepollen: `packages/allowed-login-email-policy/src/server/accessRuntime.js` `listAllowedLoginEmailEntries` (limit 500, cursor loop); `packages/processing-lot-events/src/server/processingLotEventRepositoryExtensions.js` `listByProcessingLotId` (limit 500, no cursor: a lot's events past the 100th are dropped today).
|
|
18
|
+
- compas-next, `packages/owners-work/src/server`: `tariffWorkflowService.js` `listAllRows` (`WORKFLOW_PAGE_LIMIT` 500, cursor loop); `ownersChecklistAiWorkflowService.js` `loadContext` (`CHECKLIST_LIMIT` 500: a checklist past 100 rows is edited from its first 100 and the too-large guard never fires); `unappointedRequestWorkflowService.js` (`INVOICE_GROUP_LIMIT` 500, the same guard); `ownersWorkAiContext.js` (`CONTEXT_COLLECTION_QUERY_LIMIT` 501, the invoice and transaction reads and their too-large guards).
|
|
19
|
+
- dogandgroom: `packages/daycare-engine/src/server/serviceContext.js` `queryRecords` (limit 250, cursor loop).
|
|
20
|
+
- whs2: any server `queryDocuments` with a `limit` above 100 that has not yet moved to its every-row helpers.
|
|
21
|
+
- None in racing, vibe64, vibe64-online, daniela, mercbot or virtual-gp. Client pages that ask the list routes for 200 or 250 rows keep working: HTTP still caps them.
|
|
10
22
|
|
|
11
23
|
## 0.2.0 - 2026-10-29
|
|
12
24
|
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/crud-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
7
7
|
},
|
|
8
8
|
"scripts": {
|
|
9
|
-
"test": "
|
|
9
|
+
"test": "jskit test"
|
|
10
10
|
},
|
|
11
11
|
"exports": {
|
|
12
12
|
"./server/repositorySupport": "./src/server/repositorySupport.js",
|
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
"./locales/en.json": "./locales/en.json"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
31
|
-
"@jskit-ai/json-rest-api-core": "0.2.
|
|
32
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
30
|
+
"@jskit-ai/database-runtime": "0.1.260",
|
|
31
|
+
"@jskit-ai/json-rest-api-core": "0.2.12",
|
|
32
|
+
"@jskit-ai/resource-crud-core": "0.1.202",
|
|
33
33
|
"json-rest-schema": "^1.0.17",
|
|
34
|
-
"json-rest-api": "2.
|
|
34
|
+
"json-rest-api": "2.4.0"
|
|
35
35
|
},
|
|
36
36
|
"description": "Shared server-side CRUD service, repository, route, and query helpers.",
|
|
37
37
|
"jskit": {
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
}
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
54
|
-
"@jskit-ai/kernel": "0.2.
|
|
53
|
+
"@jskit-ai/http-runtime": "0.2.11",
|
|
54
|
+
"@jskit-ai/kernel": "0.2.11"
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
"./shared": "./src/shared/index.js"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@jskit-ai/crud-core": "0.2.
|
|
13
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
12
|
+
"@jskit-ai/crud-core": "0.2.12",
|
|
13
|
+
"@jskit-ai/resource-crud-core": "0.1.202"
|
|
14
14
|
},
|
|
15
15
|
"jskit": {
|
|
16
16
|
"kind": "runtime",
|
|
@@ -208,8 +208,15 @@ function createCrudJsonApiActions({
|
|
|
208
208
|
servedOverHttp
|
|
209
209
|
});
|
|
210
210
|
|
|
211
|
+
// HTTP and automation callers keep json-rest-api's page cap: a larger limit answers
|
|
212
|
+
// queryMaxLimit records, and the response's pagination reports the page size, hasMore
|
|
213
|
+
// and the next cursor, as it always has. Server code asking for more gets an error instead.
|
|
211
214
|
function listDocuments(input, context) {
|
|
212
|
-
|
|
215
|
+
const query = omitInputKeys(input, scopeInputKeys);
|
|
216
|
+
if (query.limit != null && Number(query.limit) > repository.queryMaxLimit()) {
|
|
217
|
+
query.limit = repository.queryMaxLimit();
|
|
218
|
+
}
|
|
219
|
+
return service.queryDocuments(query, { context });
|
|
213
220
|
}
|
|
214
221
|
|
|
215
222
|
function viewDocument(input, context) {
|
|
@@ -1,12 +1,30 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildJsonRestQueryParams,
|
|
3
3
|
createJsonRestContext,
|
|
4
|
+
queryAllJsonRestCollectionDocument,
|
|
4
5
|
returnBadRequestWhenJsonRestFieldsetInvalid,
|
|
5
6
|
returnNullWhenJsonRestResourceMissing
|
|
6
7
|
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
7
8
|
import { resolveTransaction, retryDeadlocks } from "@jskit-ai/database-runtime/shared";
|
|
8
9
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
9
10
|
|
|
11
|
+
/** @typedef {"full" | "minimal" | "none"} WriteReturning */
|
|
12
|
+
|
|
13
|
+
const WRITE_RETURNING = new Set(["full", "minimal", "none"]);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {{ returning?: unknown }} options
|
|
17
|
+
* @param {WriteReturning} [fallback]
|
|
18
|
+
* @returns {WriteReturning}
|
|
19
|
+
*/
|
|
20
|
+
function writeReturning(options, fallback = "full") {
|
|
21
|
+
const returning = options.returning ?? fallback;
|
|
22
|
+
if (!WRITE_RETURNING.has(returning)) {
|
|
23
|
+
throw new TypeError(`returning must be "full", "minimal" or "none". Received: ${JSON.stringify(returning)}`);
|
|
24
|
+
}
|
|
25
|
+
return /** @type {WriteReturning} */ (returning);
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
/**
|
|
11
29
|
* @param {object} dependencies
|
|
12
30
|
* @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} dependencies.api
|
|
@@ -60,7 +78,27 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
|
60
78
|
return apiResource;
|
|
61
79
|
}
|
|
62
80
|
|
|
81
|
+
/** The largest `limit` queryDocuments accepts: the resource's json-rest-api `queryMaxLimit`. */
|
|
82
|
+
function queryMaxLimit() {
|
|
83
|
+
return requireApiResource().vars.queryMaxLimit;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* One page of the records the query matches: `limit` records (the
|
|
88
|
+
* resource's default page without one) after `cursor`, with
|
|
89
|
+
* `meta.pagination` reporting `hasMore` and the next cursor. A `limit`
|
|
90
|
+
* above queryMaxLimit() throws a TypeError naming queryEveryDocument,
|
|
91
|
+
* because json-rest-api would answer only queryMaxLimit() records.
|
|
92
|
+
* @param {Record<string, unknown>} [query]
|
|
93
|
+
* @param {{ trx?: any, context?: object | null }} [options]
|
|
94
|
+
*/
|
|
63
95
|
async function queryDocuments(query = {}, options = {}) {
|
|
96
|
+
if (query.limit != null && Number(query.limit) > queryMaxLimit()) {
|
|
97
|
+
throw new TypeError(
|
|
98
|
+
`${scopeName} queryDocuments limit ${query.limit} is above its queryMaxLimit (${queryMaxLimit()}), so it would ` +
|
|
99
|
+
`return only ${queryMaxLimit()} records. Read every record with queryEveryDocument(query, options), or page with limit and cursor.`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
64
102
|
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
65
103
|
requireApiResource().query(
|
|
66
104
|
{
|
|
@@ -73,7 +111,75 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
|
73
111
|
);
|
|
74
112
|
}
|
|
75
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Every record the query matches, as one JSON:API document `{ data,
|
|
116
|
+
* included }`, for server code that needs them all. It takes
|
|
117
|
+
* queryDocuments' filters, include and fields, but no limit, cursor or
|
|
118
|
+
* sort: it reads 1,000-record pages in id order in the caller's transaction,
|
|
119
|
+
* so no record is skipped or repeated. Sort the records it returns.
|
|
120
|
+
* @param {Record<string, unknown>} [query]
|
|
121
|
+
* @param {{ trx?: any, context?: object | null }} [options]
|
|
122
|
+
*/
|
|
123
|
+
async function queryEveryDocument(query = {}, options = {}) {
|
|
124
|
+
for (const key of ["limit", "cursor", "sort"]) {
|
|
125
|
+
if (query[key] != null) {
|
|
126
|
+
throw new TypeError(
|
|
127
|
+
`${scopeName} queryEveryDocument reads every record in id order, so its query cannot name ${key}; sort the records it returns.`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
132
|
+
queryAllJsonRestCollectionDocument(
|
|
133
|
+
requireApiResource(),
|
|
134
|
+
{
|
|
135
|
+
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
136
|
+
transaction: resolveTransaction(options)
|
|
137
|
+
},
|
|
138
|
+
options.context
|
|
139
|
+
)
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Locks the record's row until trx ends, so another forUpdate read or a write
|
|
144
|
+
// of it waits. SQLite runs one transaction at a time on knex's single
|
|
145
|
+
// connection, so it has no row lock to take.
|
|
146
|
+
async function lockRecord(recordId, trx) {
|
|
147
|
+
if (/sqlite/.test(String(trx.client.config.client))) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const storage = api.knex.helpers.getStorageAdapter(scopeName);
|
|
151
|
+
await storage.buildBaseQuery({ transaction: trx })
|
|
152
|
+
.where(storage.getIdColumn(), storage.translateFilterValue("id", recordId))
|
|
153
|
+
.forUpdate()
|
|
154
|
+
.first(storage.getIdColumn());
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* One record as a JSON:API document, or null when it is missing or hidden.
|
|
159
|
+
* `options.forUpdate: true` first locks its row in `options.trx` (required)
|
|
160
|
+
* until that transaction ends, so a concurrent forUpdate read or write of it
|
|
161
|
+
* waits: read, check and write inside one transaction without a lost update.
|
|
162
|
+
* The lock comes before the read, so on PostgreSQL (READ COMMITTED) the read
|
|
163
|
+
* sees the latest version; on MySQL's REPEATABLE READ it does when the lock
|
|
164
|
+
* is the transaction's first read.
|
|
165
|
+
* @param {unknown} recordId
|
|
166
|
+
* @param {Record<string, unknown>} [query]
|
|
167
|
+
* @param {{ trx?: any, context?: object | null, forUpdate?: boolean }} [options]
|
|
168
|
+
*/
|
|
76
169
|
async function getDocumentById(recordId, query = {}, options = {}) {
|
|
170
|
+
if (options.forUpdate != null && typeof options.forUpdate !== "boolean") {
|
|
171
|
+
throw new TypeError(`${scopeName} getDocumentById forUpdate must be true or false. Received: ${options.forUpdate}`);
|
|
172
|
+
}
|
|
173
|
+
if (options.forUpdate) {
|
|
174
|
+
const trx = resolveTransaction(options);
|
|
175
|
+
if (!trx) {
|
|
176
|
+
throw new TypeError(
|
|
177
|
+
`${scopeName} getDocumentById forUpdate locks the record until its transaction ends, so it needs options.trx ` +
|
|
178
|
+
"(run it inside withTransaction)."
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
await lockRecord(recordId, trx);
|
|
182
|
+
}
|
|
77
183
|
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
78
184
|
returnNullWhenJsonRestResourceMissing(() =>
|
|
79
185
|
requireApiResource().get(
|
|
@@ -89,21 +195,70 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
|
89
195
|
);
|
|
90
196
|
}
|
|
91
197
|
|
|
92
|
-
|
|
93
|
-
return
|
|
198
|
+
function post(payload, returning, options) {
|
|
199
|
+
return requireApiResource().post(
|
|
94
200
|
{
|
|
95
201
|
data: inputData(payload),
|
|
96
|
-
returning
|
|
202
|
+
returning,
|
|
97
203
|
transaction: resolveTransaction(options),
|
|
98
204
|
format: "jsonapi"
|
|
99
205
|
},
|
|
100
206
|
createJsonRestContext(options.context)
|
|
101
|
-
)
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Creates one record. `options.returning` picks the result: "full" (the
|
|
212
|
+
* default) reads the new record back through its row policy and lookups;
|
|
213
|
+
* "minimal" answers `{ data: { type, id } }` and "none" undefined, without
|
|
214
|
+
* that read.
|
|
215
|
+
* @param {Record<string, unknown>} [payload]
|
|
216
|
+
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
217
|
+
*/
|
|
218
|
+
async function createDocument(payload = {}, options = {}) {
|
|
219
|
+
const returning = writeReturning(options);
|
|
220
|
+
return write(options, () => post(payload, returning, options));
|
|
102
221
|
}
|
|
103
222
|
|
|
223
|
+
/**
|
|
224
|
+
* Creates every payload, in order, in one transaction: the caller's `trx`,
|
|
225
|
+
* or one it owns and retries whole on a deadlock, so either all are created
|
|
226
|
+
* or none. Results follow the payloads' order; `options.returning` is
|
|
227
|
+
* "minimal" by default, so no record is read back.
|
|
228
|
+
* @param {Record<string, unknown>[]} payloads
|
|
229
|
+
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
230
|
+
*/
|
|
231
|
+
async function createDocuments(payloads, options = {}) {
|
|
232
|
+
if (!Array.isArray(payloads)) {
|
|
233
|
+
throw new TypeError("createDocuments requires an array of payloads.");
|
|
234
|
+
}
|
|
235
|
+
const returning = writeReturning(options, "minimal");
|
|
236
|
+
async function createAll(trx) {
|
|
237
|
+
const results = [];
|
|
238
|
+
for (const payload of payloads) {
|
|
239
|
+
results.push(await post(payload, returning, { ...options, trx }));
|
|
240
|
+
}
|
|
241
|
+
return results;
|
|
242
|
+
}
|
|
243
|
+
const trx = resolveTransaction(options);
|
|
244
|
+
return trx ? createAll(trx) : withTransaction(createAll);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Patches one record; null when it does not exist or is out of the
|
|
249
|
+
* caller's scope. `options.returning` picks the result as createDocument's.
|
|
250
|
+
* @param {string | number} recordId
|
|
251
|
+
* @param {Record<string, unknown>} patch
|
|
252
|
+
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
253
|
+
*/
|
|
104
254
|
async function patchDocumentById(recordId, patch, options = {}) {
|
|
255
|
+
const returning = writeReturning(options);
|
|
105
256
|
if (Object.keys(patch).length < 1) {
|
|
106
|
-
|
|
257
|
+
const document = await getDocumentById(recordId, {}, options);
|
|
258
|
+
if (!document || returning === "full") {
|
|
259
|
+
return document;
|
|
260
|
+
}
|
|
261
|
+
return returning === "minimal" ? { data: { type: scopeName, id: document.data.id } } : undefined;
|
|
107
262
|
}
|
|
108
263
|
|
|
109
264
|
return returnNullWhenJsonRestResourceMissing(() => write(options, () =>
|
|
@@ -111,7 +266,7 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
|
111
266
|
{
|
|
112
267
|
id: recordId,
|
|
113
268
|
data: inputData(patch),
|
|
114
|
-
returning
|
|
269
|
+
returning,
|
|
115
270
|
transaction: resolveTransaction(options),
|
|
116
271
|
format: "jsonapi"
|
|
117
272
|
},
|
|
@@ -185,9 +340,12 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
|
185
340
|
|
|
186
341
|
return Object.freeze({
|
|
187
342
|
withTransaction,
|
|
343
|
+
queryMaxLimit,
|
|
188
344
|
queryDocuments,
|
|
345
|
+
queryEveryDocument,
|
|
189
346
|
getDocumentById,
|
|
190
347
|
createDocument,
|
|
348
|
+
createDocuments,
|
|
191
349
|
patchDocumentById,
|
|
192
350
|
patchDocumentIfLockVersion,
|
|
193
351
|
deleteDocumentById
|
|
@@ -24,8 +24,16 @@ function createCrudJsonApiService({ repository }) {
|
|
|
24
24
|
return returnJsonApiDocument(await repository.queryDocuments(query, repositoryCallOptions(options)));
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
async function
|
|
28
|
-
return returnJsonApiDocument(
|
|
27
|
+
async function queryEveryDocument(query, options) {
|
|
28
|
+
return returnJsonApiDocument(await repository.queryEveryDocument(query, repositoryCallOptions(options)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// forUpdate locks the record in the call's transaction; see the repository's getDocumentById.
|
|
32
|
+
async function getDocumentById(recordId, query, options = {}) {
|
|
33
|
+
return returnJsonApiDocument(requireDocument(await repository.getDocumentById(recordId, query, {
|
|
34
|
+
...repositoryCallOptions(options),
|
|
35
|
+
forUpdate: options.forUpdate
|
|
36
|
+
})));
|
|
29
37
|
}
|
|
30
38
|
|
|
31
39
|
async function createDocument(payload, options) {
|
|
@@ -42,6 +50,7 @@ function createCrudJsonApiService({ repository }) {
|
|
|
42
50
|
|
|
43
51
|
return Object.freeze({
|
|
44
52
|
queryDocuments,
|
|
53
|
+
queryEveryDocument,
|
|
45
54
|
getDocumentById,
|
|
46
55
|
createDocument,
|
|
47
56
|
patchDocumentById,
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import knexLib from "knex";
|
|
4
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
|
+
import {
|
|
6
|
+
createJsonRestApiHost,
|
|
7
|
+
createJsonRestResourceScopeOptions
|
|
8
|
+
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
9
|
+
import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
|
|
10
|
+
|
|
11
|
+
// People in teams, parents owned by people, and children of parents, each read
|
|
12
|
+
// through a row policy for the context's team, as a real application's are.
|
|
13
|
+
const resources = {
|
|
14
|
+
people: {
|
|
15
|
+
tableName: "people",
|
|
16
|
+
schema: { id: { type: "id", primary: true }, name: { type: "string" }, team: { type: "string" } }
|
|
17
|
+
},
|
|
18
|
+
parents: {
|
|
19
|
+
tableName: "parents",
|
|
20
|
+
schema: {
|
|
21
|
+
id: { type: "id", primary: true },
|
|
22
|
+
title: { type: "string" },
|
|
23
|
+
ownerId: { type: "id", belongsTo: "people", as: "owner" }
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
children: {
|
|
27
|
+
tableName: "children",
|
|
28
|
+
schema: {
|
|
29
|
+
id: { type: "id", primary: true },
|
|
30
|
+
parentId: { type: "id", belongsTo: "parents", as: "parent" },
|
|
31
|
+
authorId: { type: "id", belongsTo: "people", as: "author" },
|
|
32
|
+
title: { type: "string" }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
async function createFixture(t) {
|
|
38
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
39
|
+
t.after(() => knex.destroy());
|
|
40
|
+
await knex.schema.createTable("people", (table) => { table.increments("id"); table.string("name"); table.string("team"); });
|
|
41
|
+
await knex.schema.createTable("parents", (table) => { table.increments("id"); table.string("title"); table.integer("owner_id"); });
|
|
42
|
+
await knex.schema.createTable("children", (table) => {
|
|
43
|
+
table.increments("id"); table.integer("parent_id"); table.integer("author_id"); table.string("title");
|
|
44
|
+
});
|
|
45
|
+
await knex("people").insert([{ name: "Ada", team: "a" }, { name: "Bea", team: "b" }]);
|
|
46
|
+
await knex("parents").insert([{ title: "Visible", owner_id: 1 }, { title: "Hidden", owner_id: 2 }]);
|
|
47
|
+
|
|
48
|
+
const policyRuns = [];
|
|
49
|
+
const team = (context) => context?.team || "__none__";
|
|
50
|
+
const policies = {
|
|
51
|
+
people: ({ query, context, column }) => {
|
|
52
|
+
query.where(column("team"), team(context));
|
|
53
|
+
return true;
|
|
54
|
+
},
|
|
55
|
+
parents: ({ query, context, column }) => {
|
|
56
|
+
query.whereExists(function visibleOwner() {
|
|
57
|
+
this.select(1).from("people as owner").whereRaw("owner.id = ??", [column("ownerId")]).where("owner.team", team(context));
|
|
58
|
+
});
|
|
59
|
+
return true;
|
|
60
|
+
},
|
|
61
|
+
children: ({ query, context, column }) => {
|
|
62
|
+
query.whereExists(function visibleParent() {
|
|
63
|
+
this.select(1).from("parents as parent").join("people as owner", "owner.id", "parent.owner_id")
|
|
64
|
+
.whereRaw("parent.id = ??", [column("parentId")]).where("owner.team", team(context));
|
|
65
|
+
});
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const api = await createJsonRestApiHost({ knex, logger: silentLogger });
|
|
70
|
+
for (const [name, resource] of Object.entries(resources)) {
|
|
71
|
+
await api.addResource(name, createJsonRestResourceScopeOptions(resource, {
|
|
72
|
+
rowPolicy: (args) => {
|
|
73
|
+
policyRuns.push(`${name}:${args.queryPurpose}`);
|
|
74
|
+
return policies[name](args);
|
|
75
|
+
}
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
const children = createCrudJsonApiRepository({ api, resource: resources.children, resourceScopeName: "children" });
|
|
79
|
+
|
|
80
|
+
// Statements and row-policy runs of one operation; BEGIN and COMMIT counted apart.
|
|
81
|
+
async function measure(run) {
|
|
82
|
+
const counts = { statements: 0, transactionStatements: 0, policy: {} };
|
|
83
|
+
const onQuery = ({ sql }) => {
|
|
84
|
+
if (/^(begin|commit|rollback|savepoint|release)/iu.test(sql.trim())) {
|
|
85
|
+
counts.transactionStatements += 1;
|
|
86
|
+
} else {
|
|
87
|
+
counts.statements += 1;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
policyRuns.length = 0;
|
|
91
|
+
knex.on("query", onQuery);
|
|
92
|
+
try {
|
|
93
|
+
counts.result = await run();
|
|
94
|
+
} finally {
|
|
95
|
+
knex.removeListener("query", onQuery);
|
|
96
|
+
}
|
|
97
|
+
for (const run of policyRuns) {
|
|
98
|
+
counts.policy[run] = (counts.policy[run] || 0) + 1;
|
|
99
|
+
}
|
|
100
|
+
return counts;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { knex, api, children, measure };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const context = Object.freeze({ team: "a" });
|
|
107
|
+
const childPayloads = (count) => Array.from({ length: count }, (_, index) => ({ parentId: 1, authorId: 1, title: `Child ${index}` }));
|
|
108
|
+
|
|
109
|
+
test("createDocuments writes a batch in one transaction and reads no record back", async (t) => {
|
|
110
|
+
const { knex, children, measure } = await createFixture(t);
|
|
111
|
+
const small = await measure(() => children.createDocuments(childPayloads(10), { context }));
|
|
112
|
+
const large = await measure(() => children.createDocuments(childPayloads(100), { context }));
|
|
113
|
+
|
|
114
|
+
assert.deepEqual(large.result.slice(0, 2), [
|
|
115
|
+
{ data: { type: "children", id: "11" } },
|
|
116
|
+
{ data: { type: "children", id: "12" } }
|
|
117
|
+
]);
|
|
118
|
+
assert.equal(await knex("children").count({ count: "*" }).first().then(({ count }) => Number(count)), 110);
|
|
119
|
+
for (const batch of [small, large]) {
|
|
120
|
+
// One owned transaction for the whole batch, whatever its size.
|
|
121
|
+
assert.equal(batch.transactionStatements, 2);
|
|
122
|
+
// No read-back: no get preflight and no visibility check of the new rows' links.
|
|
123
|
+
assert.equal(batch.policy["children:relationship-identifiers"], undefined);
|
|
124
|
+
assert.equal(batch.policy["parents:relationship-identifiers"], undefined);
|
|
125
|
+
assert.equal(batch.policy["people:relationship-identifiers"], undefined);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("returning minimal or none skips the read-back that returning full pays per created row", async (t) => {
|
|
130
|
+
const { children, measure } = await createFixture(t);
|
|
131
|
+
const perRow = {};
|
|
132
|
+
for (const returning of ["full", "minimal", "none"]) {
|
|
133
|
+
const counts = [];
|
|
134
|
+
for (const size of [10, 50]) {
|
|
135
|
+
const measured = await measure(() => children.withTransaction(async (trx) => {
|
|
136
|
+
for (const payload of childPayloads(size)) {
|
|
137
|
+
await children.createDocument(payload, { trx, context, returning });
|
|
138
|
+
}
|
|
139
|
+
}));
|
|
140
|
+
counts.push(measured);
|
|
141
|
+
}
|
|
142
|
+
// Per-row cost: the difference between 50 and 10 rows, over 40 rows.
|
|
143
|
+
perRow[returning] = (counts[1].statements - counts[0].statements) / 40;
|
|
144
|
+
const linkageRuns = Object.entries(counts[1].policy)
|
|
145
|
+
.filter(([run]) => run.endsWith(":relationship-identifiers"))
|
|
146
|
+
.reduce((sum, [, runs]) => sum + runs, 0);
|
|
147
|
+
assert.equal(linkageRuns, returning === "full" ? 100 : 0, `${returning} linkage checks`);
|
|
148
|
+
}
|
|
149
|
+
// The read-back is a get: its preflight, its read and one visibility check per linked type.
|
|
150
|
+
assert.ok(perRow.full - perRow.minimal >= 4, JSON.stringify(perRow));
|
|
151
|
+
assert.equal(perRow.minimal, perRow.none, JSON.stringify(perRow));
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("createDocuments results follow the payloads, and a failing payload leaves none created", async (t) => {
|
|
155
|
+
const { knex, children } = await createFixture(t);
|
|
156
|
+
const full = await children.createDocuments(childPayloads(2), { context, returning: "full" });
|
|
157
|
+
assert.deepEqual(full.map((document) => document.data.attributes.title), ["Child 0", "Child 1"]);
|
|
158
|
+
assert.deepEqual(await children.createDocuments(childPayloads(2), { context, returning: "none" }), [undefined, undefined]);
|
|
159
|
+
|
|
160
|
+
// The second payload links a parent the reader cannot see, so the batch rolls back.
|
|
161
|
+
await assert.rejects(
|
|
162
|
+
() => children.createDocuments([{ parentId: 1, authorId: 1, title: "Kept?" }, { parentId: 2, authorId: 1, title: "Hidden parent" }], { context }),
|
|
163
|
+
/non-existent parents with id 2/
|
|
164
|
+
);
|
|
165
|
+
assert.equal(await knex("children").where({ title: "Kept?" }).first(), undefined);
|
|
166
|
+
await assert.rejects(() => children.createDocuments({ title: "Not a list" }), /requires an array of payloads/);
|
|
167
|
+
await assert.rejects(() => children.createDocument({ title: "x" }, { returning: "ids" }), /returning must be "full", "minimal" or "none"/);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("patchDocumentById with returning minimal answers the identifier, and null for a record out of scope", async (t) => {
|
|
171
|
+
const { children } = await createFixture(t);
|
|
172
|
+
const [{ data: created }] = await children.createDocuments(childPayloads(1), { context });
|
|
173
|
+
assert.deepEqual(
|
|
174
|
+
await children.patchDocumentById(created.id, { title: "Renamed" }, { context, returning: "minimal" }),
|
|
175
|
+
{ data: { type: "children", id: created.id } }
|
|
176
|
+
);
|
|
177
|
+
assert.deepEqual(
|
|
178
|
+
await children.patchDocumentById(created.id, {}, { context, returning: "minimal" }),
|
|
179
|
+
{ data: { type: "children", id: created.id } }
|
|
180
|
+
);
|
|
181
|
+
assert.equal(await children.patchDocumentById(created.id, { title: "Other team" }, { context: { team: "b" }, returning: "none" }), null);
|
|
182
|
+
assert.equal((await children.getDocumentById(created.id, {}, { context })).data.attributes.title, "Renamed");
|
|
183
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import knexLib from "knex";
|
|
4
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
|
+
import {
|
|
6
|
+
createJsonRestApiHost,
|
|
7
|
+
createJsonRestResourceScopeOptions
|
|
8
|
+
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
9
|
+
import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
|
|
10
|
+
import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
|
|
11
|
+
import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
|
|
12
|
+
import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
|
|
13
|
+
import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
|
|
14
|
+
|
|
15
|
+
// 250 notes by 30 authors, in teams "a" and "b", read through json-rest-api's default page cap (100).
|
|
16
|
+
async function createFixture(t) {
|
|
17
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
18
|
+
t.after(() => knex.destroy());
|
|
19
|
+
await knex.schema.createTable("authors", (table) => {
|
|
20
|
+
table.increments("id");
|
|
21
|
+
table.string("name").notNullable();
|
|
22
|
+
});
|
|
23
|
+
await knex.schema.createTable("notes", (table) => {
|
|
24
|
+
table.increments("id");
|
|
25
|
+
table.integer("author_id").notNullable();
|
|
26
|
+
table.string("team").notNullable();
|
|
27
|
+
table.string("title").notNullable();
|
|
28
|
+
});
|
|
29
|
+
await knex.batchInsert("authors", Array.from({ length: 30 }, (_, index) => ({ name: `Author ${index + 1}` })), 100);
|
|
30
|
+
await knex.batchInsert("notes", Array.from({ length: 250 }, (_, index) => ({
|
|
31
|
+
author_id: (index % 30) + 1,
|
|
32
|
+
team: index % 2 === 0 ? "a" : "b",
|
|
33
|
+
title: `Note ${index + 1}`
|
|
34
|
+
})), 100);
|
|
35
|
+
|
|
36
|
+
const authors = defineCrudResource({
|
|
37
|
+
namespace: "authors",
|
|
38
|
+
tableName: "authors",
|
|
39
|
+
schema: { name: { type: "string", required: true } }
|
|
40
|
+
});
|
|
41
|
+
const notes = defineCrudResource({
|
|
42
|
+
namespace: "notes",
|
|
43
|
+
tableName: "notes",
|
|
44
|
+
schema: {
|
|
45
|
+
authorId: { type: "id", required: true, column: "author_id", belongsTo: "authors", as: "author" },
|
|
46
|
+
team: { type: "string", required: true, search: true },
|
|
47
|
+
title: { type: "string", required: true }
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
const api = await createJsonRestApiHost({ knex, logger: silentLogger });
|
|
51
|
+
await api.addResource("authors", createJsonRestResourceScopeOptions(authors));
|
|
52
|
+
await api.addResource("notes", createJsonRestResourceScopeOptions(notes));
|
|
53
|
+
return {
|
|
54
|
+
knex,
|
|
55
|
+
resource: notes,
|
|
56
|
+
repository: createCrudJsonApiRepository({ api, resource: notes, resourceScopeName: "notes" })
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const sortedIds = (rows) => rows.map((row) => Number(row.id)).sort((left, right) => left - right);
|
|
61
|
+
|
|
62
|
+
test("queryDocuments refuses a limit above queryMaxLimit and names queryEveryDocument", async (t) => {
|
|
63
|
+
const { repository } = await createFixture(t);
|
|
64
|
+
assert.equal(repository.queryMaxLimit(), 100);
|
|
65
|
+
|
|
66
|
+
const page = await repository.queryDocuments({ limit: 100 });
|
|
67
|
+
assert.equal(page.data.length, 100);
|
|
68
|
+
assert.equal(page.meta.pagination.hasMore, true);
|
|
69
|
+
assert.equal((await repository.queryDocuments({ limit: "100" })).data.length, 100);
|
|
70
|
+
|
|
71
|
+
for (const limit of [101, "250", 500]) {
|
|
72
|
+
await assert.rejects(
|
|
73
|
+
() => repository.queryDocuments({ limit }),
|
|
74
|
+
(error) => error instanceof TypeError &&
|
|
75
|
+
error.message.includes(`limit ${limit} is above its queryMaxLimit (100)`) &&
|
|
76
|
+
error.message.includes("queryEveryDocument(query, options)"),
|
|
77
|
+
`limit ${limit}`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("queryEveryDocument returns every one of 250 records once, each included author once", async (t) => {
|
|
83
|
+
const { repository } = await createFixture(t);
|
|
84
|
+
|
|
85
|
+
const document = await repository.queryEveryDocument({ include: ["author"] });
|
|
86
|
+
|
|
87
|
+
assert.equal(document.data.length, 250);
|
|
88
|
+
assert.deepEqual(sortedIds(document.data), Array.from({ length: 250 }, (_, index) => index + 1));
|
|
89
|
+
assert.equal(document.included.length, 30);
|
|
90
|
+
assert.equal(new Set(document.included.map(({ type, id }) => `${type}:${id}`)).size, 30);
|
|
91
|
+
assert.ok(document.included.every(({ type }) => type === "authors"));
|
|
92
|
+
assert.deepEqual(document.data[0].relationships.author.data, { type: "authors", id: "1" });
|
|
93
|
+
|
|
94
|
+
const teamA = await repository.queryEveryDocument({ team: "a" });
|
|
95
|
+
assert.equal(teamA.data.length, 125);
|
|
96
|
+
assert.ok(teamA.data.every((record) => record.attributes.team === "a"));
|
|
97
|
+
assert.equal(Object.hasOwn(teamA, "included"), false);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("queryEveryDocument reads in the caller's transaction and refuses a limit, cursor or sort", async (t) => {
|
|
101
|
+
const { repository } = await createFixture(t);
|
|
102
|
+
await repository.withTransaction(async (trx) => {
|
|
103
|
+
await trx("notes").insert({ author_id: 1, team: "a", title: "Uncommitted" });
|
|
104
|
+
const document = await repository.queryEveryDocument({ team: "a" }, { trx });
|
|
105
|
+
assert.equal(document.data.length, 126);
|
|
106
|
+
assert.ok(document.data.some((record) => record.attributes.title === "Uncommitted"));
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
for (const query of [{ limit: 10 }, { cursor: "abc" }, { sort: ["title"] }]) {
|
|
110
|
+
const [key] = Object.keys(query);
|
|
111
|
+
await assert.rejects(
|
|
112
|
+
() => repository.queryEveryDocument(query),
|
|
113
|
+
(error) => error instanceof TypeError && error.message.includes(`its query cannot name ${key}`),
|
|
114
|
+
key
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("the list action keeps answering a larger limit with one capped page", async (t) => {
|
|
120
|
+
const { repository, resource } = await createFixture(t);
|
|
121
|
+
const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
|
|
122
|
+
namespace: "notes",
|
|
123
|
+
resource,
|
|
124
|
+
repository,
|
|
125
|
+
service: createCrudJsonApiService({ repository }),
|
|
126
|
+
surface: "admin",
|
|
127
|
+
operations: ["list"],
|
|
128
|
+
permissionForOperation: () => ({ require: "authenticated" })
|
|
129
|
+
}));
|
|
130
|
+
const list = actions.find((entry) => entry.id.split(".").at(-1) === "list");
|
|
131
|
+
|
|
132
|
+
for (const limit of [500, "250", 100]) {
|
|
133
|
+
const result = await list.execute({ limit }, {});
|
|
134
|
+
assert.equal(result.value.data.length, 100, `limit ${limit}`);
|
|
135
|
+
assert.equal(result.value.meta.pagination.pageSize, 100, `limit ${limit}`);
|
|
136
|
+
assert.equal(result.value.meta.pagination.hasMore, true, `limit ${limit}`);
|
|
137
|
+
assert.equal(typeof result.value.meta.pagination.cursor.next, "string");
|
|
138
|
+
}
|
|
139
|
+
assert.equal((await list.execute({ limit: 20 }, {})).value.data.length, 20);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// json-rest-api 2.4.0 honours pageSizeLimit, so 250 records are one page; an earlier one reads three.
|
|
143
|
+
test("queryEveryDocument reads 250 records and their authors in one page", async (t) => {
|
|
144
|
+
const { knex, repository } = await createFixture(t);
|
|
145
|
+
let statements = 0;
|
|
146
|
+
const count = () => {
|
|
147
|
+
statements++;
|
|
148
|
+
};
|
|
149
|
+
knex.on("query", count);
|
|
150
|
+
try {
|
|
151
|
+
const document = await repository.queryEveryDocument({ include: ["author"] });
|
|
152
|
+
assert.equal(document.data.length, 250);
|
|
153
|
+
assert.equal(document.included.length, 30);
|
|
154
|
+
} finally {
|
|
155
|
+
knex.removeListener("query", count);
|
|
156
|
+
}
|
|
157
|
+
assert.ok(statements <= 3, `${statements} statements for 250 records with their authors`);
|
|
158
|
+
});
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import knexLib from "knex";
|
|
4
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
|
+
import {
|
|
6
|
+
createJsonRestApiHost,
|
|
7
|
+
createJsonRestResourceScopeOptions
|
|
8
|
+
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
9
|
+
import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
|
|
10
|
+
import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
|
|
11
|
+
import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
|
|
12
|
+
|
|
13
|
+
// The PostgreSQL case runs in a disposable schema of the test database: run with DB_NAME set to
|
|
14
|
+
// TEST_DB_NAME (and the usual DB_HOST, DB_PORT, DB_USER and DB_PASSWORD) and DB_CLIENT unset or pg.
|
|
15
|
+
const TEST_DB_NAME = process.env.TEST_DB_NAME?.trim();
|
|
16
|
+
const ON_POSTGRES_TEST_DATABASE = Boolean(TEST_DB_NAME) && process.env.DB_NAME === TEST_DB_NAME &&
|
|
17
|
+
(!process.env.DB_CLIENT || process.env.DB_CLIENT === "pg");
|
|
18
|
+
|
|
19
|
+
const counters = defineCrudResource({
|
|
20
|
+
namespace: "counters",
|
|
21
|
+
tableName: "counters",
|
|
22
|
+
schema: {
|
|
23
|
+
name: { type: "string", required: true },
|
|
24
|
+
hits: { type: "number", required: true }
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
async function createRepository(knex) {
|
|
29
|
+
await knex.schema.createTable("counters", (table) => {
|
|
30
|
+
table.increments("id");
|
|
31
|
+
table.string("name").notNullable();
|
|
32
|
+
table.integer("hits").notNullable();
|
|
33
|
+
});
|
|
34
|
+
await knex("counters").insert({ name: "Drier", hits: 0 });
|
|
35
|
+
const api = await createJsonRestApiHost({ knex, logger: silentLogger });
|
|
36
|
+
await api.addResource("counters", createJsonRestResourceScopeOptions(counters));
|
|
37
|
+
return createCrudJsonApiRepository({ api, resource: counters, resourceScopeName: "counters" });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
test("getDocumentById forUpdate needs the caller's transaction and refuses anything but a boolean", async (t) => {
|
|
41
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
42
|
+
t.after(() => knex.destroy());
|
|
43
|
+
const repository = await createRepository(knex);
|
|
44
|
+
const service = createCrudJsonApiService({ repository });
|
|
45
|
+
|
|
46
|
+
await assert.rejects(
|
|
47
|
+
() => repository.getDocumentById(1, {}, { forUpdate: true }),
|
|
48
|
+
(error) => error instanceof TypeError && error.message.includes("forUpdate") && error.message.includes("options.trx")
|
|
49
|
+
);
|
|
50
|
+
await assert.rejects(() => service.getDocumentById(1, {}, { forUpdate: true }), TypeError);
|
|
51
|
+
for (const forUpdate of ["yes", 1]) {
|
|
52
|
+
await assert.rejects(
|
|
53
|
+
() => repository.getDocumentById(1, {}, { forUpdate }),
|
|
54
|
+
(error) => error instanceof TypeError && error.message.includes("must be true or false"),
|
|
55
|
+
String(forUpdate)
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const plain = await repository.getDocumentById(1);
|
|
60
|
+
await repository.withTransaction(async (trx) => {
|
|
61
|
+
assert.deepEqual(await repository.getDocumentById(1, {}, { trx, forUpdate: true }), plain);
|
|
62
|
+
assert.equal(await repository.getDocumentById(99, {}, { trx, forUpdate: true }), null);
|
|
63
|
+
assert.deepEqual((await service.getDocumentById(1, {}, { trx, forUpdate: true })).value, plain);
|
|
64
|
+
});
|
|
65
|
+
assert.deepEqual(await repository.getDocumentById(1, {}, { forUpdate: false }), plain);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// Two transactions each read the counter forUpdate, then write hits + 1. The second one's read
|
|
69
|
+
// waits on the first one's lock, so it reads the committed 1 and writes 2: no update is lost.
|
|
70
|
+
test("a forUpdate read waits for another transaction's lock on the record (PostgreSQL)", {
|
|
71
|
+
skip: ON_POSTGRES_TEST_DATABASE ? false : "not on a PostgreSQL test database (DB_NAME=$TEST_DB_NAME)"
|
|
72
|
+
}, async (t) => {
|
|
73
|
+
const schema = `crud_row_lock_test_${process.pid}_${Date.now()}`;
|
|
74
|
+
const connection = {
|
|
75
|
+
host: process.env.DB_HOST,
|
|
76
|
+
port: Number(process.env.DB_PORT) || 5432,
|
|
77
|
+
user: process.env.DB_USER,
|
|
78
|
+
password: process.env.DB_PASSWORD,
|
|
79
|
+
database: TEST_DB_NAME
|
|
80
|
+
};
|
|
81
|
+
const admin = knexLib({ client: "pg", connection });
|
|
82
|
+
await admin.raw("create schema ??", [schema]);
|
|
83
|
+
const knex = knexLib({ client: "pg", connection, searchPath: [schema], pool: { min: 0, max: 4 } });
|
|
84
|
+
t.after(async () => {
|
|
85
|
+
await knex.destroy();
|
|
86
|
+
await admin.raw("drop schema ?? cascade", [schema]);
|
|
87
|
+
await admin.destroy();
|
|
88
|
+
});
|
|
89
|
+
const repository = await createRepository(knex);
|
|
90
|
+
const hitsOf = (document) => document.data.attributes.hits;
|
|
91
|
+
|
|
92
|
+
const events = [];
|
|
93
|
+
let releaseFirst;
|
|
94
|
+
const firstHoldsLock = new Promise((resolve) => {
|
|
95
|
+
releaseFirst = resolve;
|
|
96
|
+
});
|
|
97
|
+
let firstLocked;
|
|
98
|
+
const firstLockTaken = new Promise((resolve) => {
|
|
99
|
+
firstLocked = resolve;
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const first = repository.withTransaction(async (trx) => {
|
|
103
|
+
const document = await repository.getDocumentById(1, {}, { trx, forUpdate: true });
|
|
104
|
+
events.push(`first read ${hitsOf(document)}`);
|
|
105
|
+
firstLocked();
|
|
106
|
+
await firstHoldsLock;
|
|
107
|
+
await repository.patchDocumentById(1, { hits: hitsOf(document) + 1 }, { trx, returning: "none" });
|
|
108
|
+
events.push("first commits");
|
|
109
|
+
});
|
|
110
|
+
await firstLockTaken;
|
|
111
|
+
|
|
112
|
+
const second = repository.withTransaction(async (trx) => {
|
|
113
|
+
const document = await repository.getDocumentById(1, {}, { trx, forUpdate: true });
|
|
114
|
+
events.push(`second read ${hitsOf(document)}`);
|
|
115
|
+
await repository.patchDocumentById(1, { hits: hitsOf(document) + 1 }, { trx, returning: "none" });
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// The second transaction is blocked on a row lock before the first one writes.
|
|
119
|
+
let waiting = 0;
|
|
120
|
+
for (let attempt = 0; attempt < 200 && waiting < 1; attempt++) {
|
|
121
|
+
const { rows } = await admin.raw(
|
|
122
|
+
"select count(*)::int as waiting from pg_stat_activity where datname = current_database() " +
|
|
123
|
+
"and wait_event_type = 'Lock' and query ilike '%from \"counters\"%for update%'"
|
|
124
|
+
);
|
|
125
|
+
waiting = rows[0].waiting;
|
|
126
|
+
if (waiting < 1) {
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
assert.ok(waiting >= 1, "the second forUpdate read is waiting on the lock");
|
|
131
|
+
assert.deepEqual(events, ["first read 0"]);
|
|
132
|
+
|
|
133
|
+
releaseFirst();
|
|
134
|
+
await Promise.all([first, second]);
|
|
135
|
+
assert.deepEqual(events, ["first read 0", "first commits", "second read 1"]);
|
|
136
|
+
assert.equal(hitsOf(await repository.getDocumentById(1)), 2);
|
|
137
|
+
});
|
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
// registerCrudJsonApiRoutes, for tests that call those directly with only the options they exercise.
|
|
3
3
|
|
|
4
4
|
const CRUD_OPERATIONS = Object.freeze(["list", "view", "create", "update", "delete"]);
|
|
5
|
+
// The list action caps a limit at the repository's queryMaxLimit(): json-rest-api's default, 100.
|
|
6
|
+
const DEFAULT_REPOSITORY = Object.freeze({ queryMaxLimit: () => 100 });
|
|
5
7
|
|
|
6
8
|
/** @param {object} options The options a test sets; every other option takes the feature's default. */
|
|
7
9
|
function crudJsonApiActionOptions(options) {
|
|
8
10
|
return {
|
|
11
|
+
repository: DEFAULT_REPOSITORY,
|
|
9
12
|
operations: CRUD_OPERATIONS,
|
|
10
13
|
scopeInputValidator: null,
|
|
11
14
|
scopeInputKeys: [],
|