@jskit-ai/resource-runtime 0.2.36 → 0.2.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.3.0 exactly (from 3.2.0): `aggregate({ measures, filters }, { ...txOptions, lockMode })`, with `lockMode` `"share"`, `"update"` or `"noKeyUpdate"`, reads one row of totals from one statement with that row lock on the rows they read, held until the transaction ends, so a save that checks a count or a sum keeps it as read: an update or delete of a counted row waits until commit (on MySQL and MariaDB an insert the totals would count waits too, as InnoDB locks the index range read; on PostgreSQL it goes on, and json-rest-api reads the totals again until no row joined them while it waited). No row is read into the application, however many match (json-rest-api totals 2,000 rows exactly in the statements it takes for 3), where `lockWhere` and a count read every id and stop at 1,000. With `lockMode`, `groupBy` or `page` is a `TypeError` (total each group with a measure's `where`) and a call outside a transaction is `RestApiLockOutsideTransactionError`, before any statement; json-rest-api refuses a filter on another table's field or a row policy that joins another table (rule `lock_single_table`) and, on MySQL and MariaDB, a read with no index that starts with the ownership columns, as `lockWhere` does. Its single-table refusal of every lock and claim (`lock_single_table`) now names the fix: filter on the resource's own fields, and have a row policy test another table in a subquery, not a join.
6
+ - A request's user scope is the signed-in user on every route, as its workspace is: the user scope reads the context's `scopeValues.userId`, the route's visibility user and now the signed-in user (`resolveActorId`: the context's actor, else the request's user). So a `workspace` route (a CRUD feature that names `visibility: "workspace"`, a hand route's `callOptions()`, an action) reaches the signed-in member's own rows of a `user` or `workspace_user` table, and stamps them on its creates, where it threw `MissingScopeError` and an application set `scopeValues.userId` by hand; a `workspace_user` route reached them already. The input never names the user: an owner value in it that differs is refused, a signed-out request still names no user (`MissingScopeError`, whose message now says that a request reaches the signed-in user's own rows), and a job context from `forUser` or `forWorkspaceUser` is signed in as no one. Sources that name two different users throw the safety invariant, as the scope value and the visibility user did.
5
7
  - Depends on json-rest-api 3.2.0 exactly (from 3.1.11): a row policy's `ownTable(name)` reader and a `joinSource()`'s `query` take `forceIndex(...names)` on MySQL and MariaDB, which makes the table the read reads (the owner's table inside a join source's derived tables) use the named indexes. A lock's row policy nests its reads in SELECTs that lock every row their plan examines, so a nested read the planner would answer by scanning a shared table, another workspace's rows included, names the index that leads with the owner's columns and examines only the caller's range. It takes plain index names only, sets the hint once, and throws a `TypeError` on PostgreSQL and SQLite, which have no index hints; the builders stay read-only.
6
8
  - A row policy's `caller` for a user's context that says why it was made carries the reason: `{ kind: "user", userId, reason }`, as for the context `workspaces.roleContext` builds for installer and seed work. The reason grants nothing: the same read answers the same rows, refuses the same hidden fields and keeps the request row limits. A reason that is no text is none, and a context with a reason but no user is still anonymous.
7
9
  - `lockPages(filters, { ...txOptions, pageBy })` pages by a list filter's column, then the id: `pageBy` names a filter of the call whose search entry says `filterOperator: "in"`, on the table's own column, given a list. Each page locks up to `pageSize` rows of the values no page has passed, in that column's order, and the rest of the last value's rows follow in id order, that value alone, so on MySQL and MariaDB every statement reads one value's range after another of an index that holds the column after the ownership columns and the filters' other fixed columns, and examines and holds only the listed values' rows, where id order walks, and holds, every row of the owner it passes. Ten listed actions among 30 and among 300 send the same statements. A `pageBy` that names no such filter, or a filter given no list, is a TypeError before any statement; a value given otherwise than the column stores it throws rather than paging forever. Needs json-rest-api 3.1.11, whose `lockWhere` counts a list filter given one value as an equality when it picks its index.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.36",
3
+ "version": "0.2.38",
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.217",
19
- "@jskit-ai/resource-crud-core": "0.1.219",
20
- "json-rest-api": "3.2.0"
18
+ "@jskit-ai/resource-core": "0.1.218",
19
+ "@jskit-ai/resource-crud-core": "0.1.220",
20
+ "json-rest-api": "3.3.0"
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.275",
68
- "@jskit-ai/kernel": "0.2.26"
67
+ "@jskit-ai/database-runtime": "0.1.276",
68
+ "@jskit-ai/kernel": "0.2.27"
69
69
  }
70
70
  }
@@ -13,7 +13,8 @@ class MissingScopeError extends TypeError {
13
13
  constructor(resourceName, owner) {
14
14
  super(
15
15
  (owner
16
- ? `${resourceName} rows each belong to a ${owner}, and this context names no ${owner}, so the ownership scope cannot be applied. `
16
+ ? `${resourceName} rows each belong to a ${owner}, and this context names no ${owner}, so the ownership scope cannot be applied. ` +
17
+ (owner === "user" ? "A request reaches the signed-in user's own rows, so a request with no one signed in reaches none. " : "")
17
18
  : `${resourceName} needs options.context, so the ownership scope can be applied. `) +
18
19
  "Pass on the options your function received. Only a background job of a feature with systemScope uses " +
19
20
  "systemContext(reason).forWorkspace(id); never use it to make a request work."
@@ -1,3 +1,4 @@
1
+ import { RestApiLockOutsideTransactionError } from "json-rest-api";
1
2
  import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
2
3
  import { isJobContext } from "./contexts.js";
3
4
  import { RowLimitError } from "./errors.js";
@@ -11,10 +12,10 @@ import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
11
12
  // reference it (a foreign key's check takes FOR KEY SHARE); MySQL, MariaDB and SQLite have no weaker exclusive lock and
12
13
  // lock as for "update".
13
14
  const LOCK_MODES = Object.freeze(["update", "noKeyUpdate"]);
14
- // lock, lockMany and lockWhere also take "share": FOR SHARE (LOCK IN SHARE MODE on MySQL and MariaDB), which other
15
- // reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows must not change until
16
- // the transaction ends. A row held shared is never written in the same transaction: two transactions that each hold it
17
- // shared and then write it deadlock.
15
+ // lock, lockMany, lockWhere and a locking aggregate() also take "share": FOR SHARE (LOCK IN SHARE MODE on MySQL and
16
+ // MariaDB), which other reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows
17
+ // must not change until the transaction ends. A row held shared is never written in the same transaction: two
18
+ // transactions that each hold it shared and then write it deadlock.
18
19
  const SHARED_LOCK_MODES = Object.freeze([...LOCK_MODES, "share"]);
19
20
  // Why the methods that take or write their rows refuse "share".
20
21
  const NO_SHARE = Object.freeze({
@@ -46,6 +47,33 @@ function lockModeOf(name, caller, lockMode) {
46
47
  return { lockMode };
47
48
  }
48
49
 
50
+ /**
51
+ * The transaction of an aggregate() read, `{ transaction }`, with its lock when `options.lockMode` names one: then it reads
52
+ * one row of totals with that row lock on the rows they read, held until the transaction ends, for a save that checks a
53
+ * count or sum that must stay as read, and no row is read into the application however many there are. "share" lets
54
+ * other transactions' checks share the rows while their writes wait; "update" or "noKeyUpdate" hold them exclusively. An
55
+ * insert of a new matching row waits on MySQL and MariaDB (InnoDB locks the index range) and goes on on PostgreSQL. With
56
+ * a lock mode, groupBy and page are a TypeError and a call outside a transaction is RestApiLockOutsideTransactionError
57
+ * (json-rest-api refuses it too, but filters that match no row answer without asking it), before any statement.
58
+ * @param {string} name The resource's name.
59
+ * @param {{ groupBy?: unknown, page?: unknown }} spec The aggregate's groupBy and page.
60
+ * @param {{ trx?: object | null, lockMode?: unknown }} options
61
+ * @returns {{ transaction: object | undefined, lockMode?: string }}
62
+ */
63
+ function aggregateTransactionOf(name, { groupBy, page }, options) {
64
+ const mode = lockModeOf(name, "aggregate", options.lockMode);
65
+ if (mode.lockMode !== undefined && ((Array.isArray(groupBy) && groupBy.length > 0) || page !== undefined)) {
66
+ throw new TypeError(
67
+ `${name}.aggregate() with lockMode reads one row of totals and takes no groupBy or page: total each group with a ` +
68
+ 'measure with a where ({ open: { count: "*", where: { status: "open" } } }), or lock the rows with lockWhere().'
69
+ );
70
+ }
71
+ if (mode.lockMode !== undefined && !options.trx) {
72
+ throw new RestApiLockOutsideTransactionError({ resourceType: name, operation: "aggregate" });
73
+ }
74
+ return { ...mode, transaction: options.trx || undefined };
75
+ }
76
+
49
77
  // The most rows one read of the locked rows' links names, as the lock itself reads its ids in chunks of 1,000.
50
78
  const LINKS_PER_READ = 1000;
51
79
 
@@ -443,4 +471,4 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
443
471
  });
444
472
  }
445
473
 
446
- export { createLockReads, lockModeOf };
474
+ export { aggregateTransactionOf, createLockReads, lockModeOf };
@@ -6,7 +6,7 @@ import { createJsonRestContext } from "./contexts.js";
6
6
  import { checkBlobReads, checkBlobValues, namedBlobs, refuseBlobsInJson } from "./handleBlobs.js";
7
7
  import { createEveryRowReads } from "./handleEveryRow.js";
8
8
  import { createHiddenFieldReads, createJoinSource, markHandleFunctions } from "./handleHidden.js";
9
- import { createLockReads, lockModeOf } from "./handleLocks.js";
9
+ import { aggregateTransactionOf, createLockReads, lockModeOf } from "./handleLocks.js";
10
10
  import { withCallOptions } from "./filterJoinSources.js";
11
11
  import { requireHandleTransaction, trackHandleTransaction } from "./handleTransactions.js";
12
12
  import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
@@ -306,15 +306,16 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
306
306
  * One statement answers at most pageLimits().request groups: a grouped aggregate without `page` answers every group
307
307
  * or, when there are more, throws GroupLimitError rather than answer part of them. `page: { size, number }` (number
308
308
  * from 1) answers one page of groups as query() does, `{ rows, page: { size, number, hasMore, next } }`: read the
309
- * next while `page.hasMore`.
309
+ * next while `page.hasMore`. With `lockMode` the rows of one row of totals stay locked: see aggregateTransactionOf().
310
310
  * @param {{ measures: object, groupBy?: Array<string | object>, filters?: object, sort?: string[], page?: { size: number, number?: number } }} spec
311
- * @param {{ context?: object | null, trx?: object | null }} [options]
311
+ * @param {{ context?: object | null, trx?: object | null, lockMode?: "update" | "noKeyUpdate" | "share" }} [options]
312
312
  */
313
313
  async function aggregate({ measures, groupBy, filters, sort, page }, options = {}) {
314
314
  requireDefinedFilters(name, "aggregate", filters);
315
315
  if (page !== undefined && page?.size == null) {
316
316
  throw new TypeError(`${name}.aggregate() page needs size (at most pageLimits().request) and takes number from 1: page: { size, number }.`);
317
317
  }
318
+ const transaction = aggregateTransactionOf(name, { groupBy, page }, options);
318
319
  const context = contextOf(options);
319
320
  if (matchesNoRow(filters, jsonRest().vars.schemaInfo)) {
320
321
  return aggregateAnswer(noRowsAggregate(measures, groupBy), page, false);
@@ -331,7 +332,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
331
332
  ...(page === undefined ? {} : { page }),
332
333
  ...(groupLimit === undefined ? {} : { page: { size: groupLimit } })
333
334
  },
334
- transaction: options.trx || undefined
335
+ ...transaction
335
336
  },
336
337
  context
337
338
  );
@@ -22,7 +22,7 @@ import {
22
22
  normalizeJsonApiFieldsets
23
23
  } from "@jskit-ai/kernel/shared/support/jsonApiFieldsets";
24
24
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
25
- import { resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
25
+ import { resolveActorId, resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
26
26
  import { ROUTE_VISIBILITY_WORKSPACE, ROUTE_VISIBILITY_WORKSPACE_USER } from "@jskit-ai/kernel/shared/support/visibility";
27
27
  import { createJsonRestContext } from "./contexts.js";
28
28
  import { blobFields } from "./handleBlobs.js";
@@ -562,15 +562,30 @@ function resolveWorkspaceScopeValue(context = null) {
562
562
  return workspaceId;
563
563
  }
564
564
 
565
+ /**
566
+ * The id of the user a context acts for; null when it names none. It reads, in this order:
567
+ * 1. the `userId` scope value (`context.scopeValues.userId`), which a job context derived for a user names;
568
+ * 2. the user of the route's visibility (`context.visibilityContext.userId`), on a `user` or `workspace_user` route;
569
+ * 3. the signed-in user (the context's actor, else the request's user: resolveActorId), so a request reaches its own
570
+ * rows of a `user` or `workspace_user` table on any route, a `workspace` route's included, as the workspace is read
571
+ * from the request on any route. A job context is signed in as no one, and a signed-out request names no user.
572
+ * Never an id from the request's input. One execution acts for one user, so the sources it finds must agree: two
573
+ * different ids throw.
574
+ * @param {object | null} [context]
575
+ * @returns {string | null}
576
+ */
565
577
  function resolveUserScopeValue(context = null) {
566
- const scopedUserId = normalizeScopeValue(context?.scopeValues?.userId);
567
- const visibleUserId = normalizeScopeValue(context?.visibilityContext?.userId);
568
- if (scopedUserId && visibleUserId && scopedUserId !== visibleUserId) {
569
- throw new Error(
570
- `safety invariant: a context names two users (${scopedUserId}, ${visibleUserId}); one execution acts for one user.`
571
- );
578
+ const userIds = [
579
+ context?.scopeValues?.userId,
580
+ context?.visibilityContext?.userId,
581
+ resolveActorId(context)
582
+ ].map(normalizeScopeValue).filter(Boolean);
583
+ const [userId = null] = userIds;
584
+ const otherUserId = userIds.find((id) => id !== userId);
585
+ if (otherUserId) {
586
+ throw new Error(`safety invariant: a context names two users (${userId}, ${otherUserId}); one execution acts for one user.`);
572
587
  }
573
- return scopedUserId || visibleUserId;
588
+ return userId;
574
589
  }
575
590
 
576
591
  function isJsonRestResourceMissingError(error = null) {
@@ -883,6 +883,18 @@ test("scope resolvers understand explicit scopeValues and JSKIT visibilityContex
883
883
  }
884
884
  }), null);
885
885
  assert.equal(resolveUserScopeValue(null), null);
886
+
887
+ // The signed-in user (the actor, else the request's user) is the user of a context whose route names none.
888
+ assert.equal(resolveUserScopeValue({ actor: { id: 7 } }), "7");
889
+ assert.equal(resolveUserScopeValue({ requestMeta: { request: { user: { id: "7" } } } }), "7");
890
+ assert.equal(resolveUserScopeValue({ actor: { id: "7" }, visibilityContext: { userId: "7" }, scopeValues: { userId: "7" } }), "7");
891
+ assert.throws(() => resolveUserScopeValue({ actor: { id: "7" }, visibilityContext: { userId: "8" } }),
892
+ /safety invariant: a context names two users \(8, 7\)/u);
893
+ assert.throws(() => resolveUserScopeValue({ actor: { id: "7" }, scopeValues: { userId: "8" } }),
894
+ /safety invariant: a context names two users \(8, 7\)/u);
895
+ // Background work acts for its user without being signed in as anyone; the request's input never names the user.
896
+ assert.equal(resolveUserScopeValue({ onBehalfOf: { id: "7" } }), null);
897
+ assert.equal(resolveUserScopeValue({ requestMeta: { request: { body: { userId: "7" }, query: { userId: "7" } } } }), null);
886
898
  });
887
899
 
888
900
  test("json-rest-api's fixed-English errors render from the resource-runtime catalog", async () => {
@@ -10,6 +10,7 @@ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
10
10
  // are locking reads, so they read what was committed whatever that snapshot holds.
11
11
 
12
12
  const WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
13
+ const OTHER_WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "2" }) }) });
13
14
 
14
15
  const seatResource = defineTableResource({
15
16
  name: "seats",
@@ -190,3 +191,48 @@ test("lock, lockMany and lockWhere with lockMode share let another transaction s
190
191
  assert.deepEqual(outcomes, { lock: shared, lockMany: shared, lockWhere: shared });
191
192
  assert.deepEqual((await bookings.queryAll({}, WORKSPACE)).map(({ guest }) => guest), ["first"]);
192
193
  });
194
+
195
+ test("aggregate with lockMode share holds what its totals read until commit: a delete and an insert the totals would count wait, and so does a write or exclusive lock of a column they read", async (t) => {
196
+ const { seats, bookings } = await database(t, "da_lr_aggregate");
197
+ const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
198
+ const [first] = await bookings.createMany([{ seatId, guest: "first" }, { seatId, guest: "second" }], { ...WORKSPACE, returning: "ids" });
199
+ const [theirs] = await bookings.createMany([{ seatId, guest: "theirs" }], { ...OTHER_WORKSPACE, returning: "ids" });
200
+ // What another transaction does meanwhile: it gives up after 1 s (ER_LOCK_WAIT_TIMEOUT) when it would wait.
201
+ const meanwhile = (work) => bookings.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
202
+ await tx.trx.raw("SET SESSION innodb_lock_wait_timeout = 1");
203
+ await work(tx);
204
+ }).then(() => "proceeds", (error) => error.code);
205
+ const others = {
206
+ "shared lock": (tx) => bookings.lock(first, { ...tx, lockMode: "share" }),
207
+ "exclusive lock": (tx) => bookings.lock(first, tx),
208
+ "write of guest": (tx) => tx.trx("bookings").where({ id: first }).update({ guest: "other" }),
209
+ delete: (tx) => tx.trx("bookings").where({ id: first }).delete(),
210
+ insert: (tx) => tx.trx("bookings").insert({ workspace_id: 1, seat_id: seatId, guest: "late" }),
211
+ "another workspace's write": (tx) => tx.trx("bookings").where({ id: theirs }).update({ guest: "other" })
212
+ };
213
+ // A count reads the ownership index alone; a distinct count of guests reads each row too.
214
+ const totals = {
215
+ count: { measures: { bookings: { count: "*" } } },
216
+ guests: { measures: { bookings: { count: "*" }, guests: { countDistinct: "guest" } } }
217
+ };
218
+ const outcomes = {};
219
+ for (const [name, spec] of Object.entries(totals)) {
220
+ outcomes[name] = await bookings.withTransaction(WORKSPACE, async (tx) => {
221
+ const [read] = await bookings.aggregate(spec, { ...tx, lockMode: "share" });
222
+ assert.equal(read.bookings, 2, name);
223
+ const seen = {};
224
+ for (const [what, work] of Object.entries(others)) {
225
+ seen[what] = await meanwhile(work);
226
+ }
227
+ assert.deepEqual(await bookings.aggregate(spec, { ...tx, lockMode: "share" }), [read], `${name}: the totals hold`);
228
+ return seen;
229
+ });
230
+ }
231
+ const held = "ER_LOCK_WAIT_TIMEOUT";
232
+ const always = { "shared lock": "proceeds", delete: held, insert: held, "another workspace's write": "proceeds" };
233
+ assert.deepEqual(outcomes, {
234
+ count: { ...always, "exclusive lock": "proceeds", "write of guest": "proceeds" },
235
+ guests: { ...always, "exclusive lock": held, "write of guest": held }
236
+ });
237
+ assert.deepEqual((await bookings.queryAll({}, WORKSPACE)).map(({ guest }) => guest).sort(), ["other", "second"]);
238
+ });
@@ -344,6 +344,51 @@ test("a lock or patchWhere with lockMode noKeyUpdate lets another transaction ad
344
344
  assert.equal(Number((await knex("entries").count({ count: "*" }).first()).count), 6);
345
345
  });
346
346
 
347
+ test("aggregate with lockMode share holds the rows it totals: another transaction reads and share-locks them while its writes and exclusive locks wait; an insert goes on, as do other workspaces' rows", { skip }, async (t) => {
348
+ const { knex, slots } = await database(t);
349
+ const [counted] = (await slots.createMany([{ code: "a" }, { code: "b" }, { code: "c", status: "done" }], { ...WORKSPACE, returning: "ids" })).map(String);
350
+ const [theirs] = (await slots.createMany([{ code: "z" }], { ...OTHER_WORKSPACE, returning: "ids" })).map(String);
351
+ // What another transaction does while the rows are held: it gives up after 500 ms (55P03) when it would wait.
352
+ const meanwhile = async (work) => {
353
+ const { error } = await settle(() => knex.transaction(async (trx) => {
354
+ await trx.raw("SET LOCAL lock_timeout = '500ms'");
355
+ await work(trx);
356
+ }));
357
+ return error ? error.code : "proceeds";
358
+ };
359
+ const others = {
360
+ read: (trx) => trx("slots").where({ id: counted }),
361
+ "shared lock": (trx) => trx("slots").where({ id: counted }).forShare(),
362
+ "exclusive lock": (trx) => trx("slots").where({ id: counted }).forUpdate(),
363
+ write: (trx) => trx("slots").where({ id: counted }).update({ taken_by: "other" }),
364
+ insert: (trx) => trx("slots").insert({ workspace_id: 1, code: "d", status: "open" }),
365
+ "another workspace's write": (trx) => trx("slots").where({ id: theirs }).update({ taken_by: "other" })
366
+ };
367
+ const spec = { measures: { open: { count: "*" } }, filters: { status: "open" } };
368
+ const statements = [];
369
+ const recorded = ({ sql }) => statements.push(sql);
370
+ const outcome = await slots.withTransaction(WORKSPACE, async (txOptions) => {
371
+ knex.on("query", recorded);
372
+ let totals;
373
+ try {
374
+ totals = await slots.aggregate(spec, { ...txOptions, lockMode: "share" });
375
+ } finally {
376
+ knex.off("query", recorded);
377
+ }
378
+ assert.deepEqual(totals, [{ open: 2 }]);
379
+ assert.ok(statements.some((sql) => /\bcount\(/iu.test(sql) && /\bfor share\b/iu.test(sql)), statements.join(" | "));
380
+ const seen = {};
381
+ for (const [what, work] of Object.entries(others)) {
382
+ seen[what] = await meanwhile(work);
383
+ }
384
+ // FOR SHARE holds the rows that exist: the insert committed meanwhile, and the next read counts it.
385
+ assert.deepEqual(await slots.aggregate(spec, { ...txOptions, lockMode: "share" }), [{ open: 3 }]);
386
+ return seen;
387
+ });
388
+ assert.deepEqual(outcome, { read: "proceeds", "shared lock": "proceeds", "exclusive lock": "55P03", write: "55P03", insert: "proceeds", "another workspace's write": "proceeds" });
389
+ assert.equal((await knex("slots").where({ id: counted }).first()).taken_by, null);
390
+ });
391
+
347
392
  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
393
  const { knex, slots } = await database(t);
349
394
  const [slot] = (await slots.createMany([{ status: "open" }], { ...WORKSPACE, returning: "ids" })).map(String);
@@ -136,9 +136,11 @@ test("a hand route's callOptions() scope user, workspace and workspace_user tabl
136
136
  }
137
137
 
138
138
  const member = { user: { id: "7" }, workspace: { id: "1" } };
139
+ // The signed-in user's own rows are reached on every route, as the request's workspace is: a workspace route, whose
140
+ // visibility names no user, reaches user 7's bookmarks and pins too.
139
141
  const expected = {
140
142
  user: [{ user: member.user }, { bookmarks: ["7's"], notes: "refused", pins: "refused" }],
141
- workspace: [member, { bookmarks: "refused", notes: ["in 1"], pins: "refused" }],
143
+ workspace: [member, { bookmarks: ["7's"], notes: ["in 1"], pins: ["7's in 1"] }],
142
144
  workspace_user: [member, { bookmarks: ["7's"], notes: ["in 1"], pins: ["7's in 1"] }]
143
145
  };
144
146
  for (const visibility of VISIBILITIES) {
@@ -150,6 +152,7 @@ test("a hand route's callOptions() scope user, workspace and workspace_user tabl
150
152
  const anonymous = await call(`/hand/${visibility}`, {});
151
153
  assert.deepEqual(anonymous, await call(`/action/${visibility}`, {}), `${visibility} route, signed out`);
152
154
  assert.equal(anonymous.reads.bookmarks, "refused");
155
+ assert.equal(anonymous.reads.pins, "refused");
153
156
  assert.equal(anonymous.visibilityContext.userId ?? null, null);
154
157
  }
155
158
  });
@@ -1012,6 +1012,40 @@ test("aggregate() totals the caller's rows", async (t) => {
1012
1012
  assert.deepEqual(rows, [{ status: "done", count: 2 }, { status: "open", count: 1 }]);
1013
1013
  });
1014
1014
 
1015
+ test("aggregate() with lockMode totals the caller's rows inside its transaction; outside one, with groupBy or page, or with another mode it is refused before any statement", async (t) => {
1016
+ const { knex, notes } = await createFixture(t);
1017
+ await notes.createMany([{ title: "a", status: "queued" }, { title: "b", status: "queued" }, { title: "c", status: "done" }], { context: WORKSPACE_A });
1018
+ await notes.createMany([{ title: "other", status: "queued" }], { context: WORKSPACE_B });
1019
+ const spec = { measures: { notes: { count: "*" }, queued: { count: "*", where: { status: "queued" } } } };
1020
+ const statements = [];
1021
+ const counted = ({ sql }) => statements.push(sql);
1022
+ await notes.withTransaction({ context: WORKSPACE_A }, async (txOptions) => {
1023
+ for (const lockMode of ["share", "update", "noKeyUpdate"]) {
1024
+ assert.deepEqual(await notes.aggregate(spec, { ...txOptions, lockMode }), [{ notes: 3, queued: 2 }], lockMode);
1025
+ }
1026
+ assert.deepEqual(await notes.aggregate({ ...spec, filters: { status: "done" } }, { ...txOptions, lockMode: "share" }), [{ notes: 1, queued: 0 }]);
1027
+ knex.on("query", counted);
1028
+ const shared = { ...txOptions, lockMode: "share" };
1029
+ const oneRow = 'notes.aggregate() with lockMode reads one row of totals and takes no groupBy or page: total each group with a ' +
1030
+ 'measure with a where ({ open: { count: "*", where: { status: "open" } } }), or lock the rows with lockWhere().';
1031
+ await assert.rejects(notes.aggregate({ ...spec, groupBy: ["status"] }, shared), { name: "TypeError", message: oneRow });
1032
+ await assert.rejects(notes.aggregate({ ...spec, page: { size: 10 } }, shared), { name: "TypeError", message: oneRow });
1033
+ await assert.rejects(notes.aggregate(spec, { ...txOptions, lockMode: "exclusive" }), {
1034
+ name: "TypeError",
1035
+ message: 'notes.aggregate() lockMode is "update" (the default), "noKeyUpdate" or "share". Received: "exclusive"'
1036
+ });
1037
+ knex.off("query", counted);
1038
+ });
1039
+ // Outside a transaction a lock ends at once, so it is refused, also for filters that match no row.
1040
+ knex.on("query", counted);
1041
+ for (const filters of [undefined, { id: [] }]) {
1042
+ await assert.rejects(notes.aggregate({ ...spec, filters }, { context: WORKSPACE_A, lockMode: "share" }), (error) =>
1043
+ error instanceof RestApiLockOutsideTransactionError && error.message === "aggregate on 'notes' needs a transaction from api.transaction");
1044
+ }
1045
+ knex.off("query", counted);
1046
+ assert.deepEqual(statements, []);
1047
+ });
1048
+
1015
1049
  test("aggregate() counts a table's ids, distinct or not, as its rows, on a schema that declares no id field", async (t) => {
1016
1050
  const { visits, options } = await createVisitFixture(t);
1017
1051
  const [totals] = await visits.aggregate({