@jskit-ai/resource-runtime 0.2.17 → 0.2.19
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 +14 -0
- package/locales/en.json +3 -1
- package/package.json +6 -6
- package/src/server/errors.js +29 -5
- package/src/server/filterJoinSources.js +177 -0
- package/src/server/handleBlobs.js +139 -0
- package/src/server/handleEveryRow.js +188 -0
- package/src/server/handleHidden.js +46 -4
- package/src/server/handleLocks.js +173 -19
- package/src/server/handleRecords.js +16 -3
- package/src/server/index.js +1 -0
- package/src/server/manyRowChannel.js +44 -0
- package/src/server/resourceHandle.js +64 -52
- package/src/server/resourceHost.js +5 -5
- package/src/server/resourceRuntime.js +67 -20
- package/src/server/types.js +5 -0
- package/src/test/expectFlatQueries.js +23 -11
- package/src/test/index.js +2 -2
- package/test/blobFields.mysql.test.js +8 -0
- package/test/blobFields.test.js +8 -0
- package/test/crossTableFilters.mysql.test.js +8 -0
- package/test/crossTableFilters.test.js +8 -0
- package/test/filterJoinSources.mysql.test.js +8 -0
- package/test/filterJoinSources.test.js +8 -0
- package/test/hiddenFields.test.js +41 -0
- package/test/lockIncludes.mysql.test.js +8 -0
- package/test/lockIncludes.test.js +8 -0
- package/test/lockedReads.mysql.test.js +156 -0
- package/test/pagedReads.mysql.test.js +8 -0
- package/test/pagedReads.test.js +8 -0
- package/test/reportsAcrossOwners.mysql.test.js +8 -0
- package/test/reportsAcrossOwners.test.js +8 -0
- package/test/resourceRuntime.test.js +55 -2
- package/test/support/blobFieldsCases.js +226 -0
- package/test/support/crossTableFiltersCases.js +180 -0
- package/test/support/filterJoinSourcesCases.js +256 -0
- package/test/support/lockIncludesCases.js +158 -0
- package/test/support/mysqlDatabase.js +35 -0
- package/test/support/pagedReadsCases.js +168 -0
- package/test/support/reportsAcrossOwnersCases.js +201 -0
- package/test/testHelpers.test.js +128 -3
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { createPackageTestKnex } from "../src/test/index.js";
|
|
3
|
+
import { crossTableFiltersCases } from "./support/crossTableFiltersCases.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 crossTableFiltersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { filterJoinSourcesCases } from "./support/filterJoinSourcesCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of filterJoinSourcesCases(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 { filterJoinSourcesCases } from "./support/filterJoinSourcesCases.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 filterJoinSourcesCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
2
3
|
import test from "node:test";
|
|
3
4
|
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
5
|
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
@@ -229,6 +230,46 @@ test("withoutHiddenFields refuses a hidden field named through any method, and s
|
|
|
229
230
|
assert.deepEqual(await exposed.cardsTitled({ context: system.forWorkspace("2") }, { title: "Kit" }), [{ id: "3", title: "Kit", publicToken: "t3" }]);
|
|
230
231
|
});
|
|
231
232
|
|
|
233
|
+
test("withoutHiddenFields strips the hidden fields from each page queryPages() hands another feature, and refuses one its fields names", async (t) => {
|
|
234
|
+
const { cards, resource, system, options } = await createCardFixture(t);
|
|
235
|
+
const owner = Object.freeze({
|
|
236
|
+
...cards,
|
|
237
|
+
tokenPages: (callOptions) => cards.queryPages({ fields: ["title", "publicToken"] }, callOptions),
|
|
238
|
+
// An owner's method of another name that forwards the caller's params to queryPages().
|
|
239
|
+
eachCard: (params, callOptions) => cards.queryPages(params, callOptions),
|
|
240
|
+
// A stream of the owner's own, which passes as it is.
|
|
241
|
+
exportStream: () => Readable.from(["Rex\n", "Bo\n"])
|
|
242
|
+
});
|
|
243
|
+
const exposed = withoutHiddenFields(owner, resource);
|
|
244
|
+
const pagesOf = async (pages) => {
|
|
245
|
+
const read = [];
|
|
246
|
+
for await (const records of pages) {
|
|
247
|
+
read.push(records);
|
|
248
|
+
}
|
|
249
|
+
return read;
|
|
250
|
+
};
|
|
251
|
+
assert.deepEqual(await pagesOf(exposed.tokenPages(options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
|
|
252
|
+
assert.deepEqual(await pagesOf(exposed.queryPages({ fields: ["title"] }, options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
|
|
253
|
+
await assert.rejects(pagesOf(exposed.queryPages({ fields: ["title", "publicToken"] }, options)), /cards\.queryPages\(\) fields names the hidden field "publicToken"/u);
|
|
254
|
+
assert.deepEqual(await pagesOf(exposed.tokenPages({ context: system.forWorkspace("2") })), [[{ id: "3", title: "Kit", publicToken: "t3" }]]);
|
|
255
|
+
|
|
256
|
+
// A refusal is pages that throw and a rejected promise at once, whatever the method's name, and leaves no rejection
|
|
257
|
+
// unhandled when only iterated.
|
|
258
|
+
const unhandled = [];
|
|
259
|
+
const onUnhandled = (reason) => unhandled.push(reason);
|
|
260
|
+
process.on("unhandledRejection", onUnhandled);
|
|
261
|
+
t.after(() => process.off("unhandledRejection", onUnhandled));
|
|
262
|
+
assert.deepEqual(await pagesOf(exposed.eachCard({ fields: ["title"] }, options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
|
|
263
|
+
await assert.rejects(pagesOf(exposed.eachCard({ fields: ["title", "publicToken"] }, options)), /cards\.eachCard\(\) fields names the hidden field "publicToken"/u);
|
|
264
|
+
await assert.rejects(exposed.eachCard({ fields: ["publicToken"] }, options), /cards\.eachCard\(\) fields names the hidden field/u);
|
|
265
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
266
|
+
assert.deepEqual(unhandled, []);
|
|
267
|
+
const stream = exposed.exportStream();
|
|
268
|
+
assert.equal(stream instanceof Readable, true);
|
|
269
|
+
assert.equal(typeof stream.pipe, "function");
|
|
270
|
+
assert.deepEqual(await stream.toArray(), ["Rex\n", "Bo\n"]);
|
|
271
|
+
});
|
|
272
|
+
|
|
232
273
|
test("withoutHiddenFields refuses a field one owned table hides and another shows, since it strips hidden fields by name", () => {
|
|
233
274
|
const cards = defineTableResource({
|
|
234
275
|
name: "cards",
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { lockIncludesCases } from "./support/lockIncludesCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of lockIncludesCases(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 { lockIncludesCases } from "./support/lockIncludesCases.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 lockIncludesCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { createTestResourceRuntime } from "../src/test/index.js";
|
|
5
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
6
|
+
|
|
7
|
+
// What a lock's caller reads after the lock on MySQL and MariaDB, under InnoDB's REPEATABLE READ. A plain read inside a
|
|
8
|
+
// transaction sees the snapshot of the transaction's first plain read: a transaction that locks first reads what the
|
|
9
|
+
// lock's previous holder committed, one that read before its lock does not. A lock and the records its include names
|
|
10
|
+
// are locking reads, so they read what was committed whatever that snapshot holds.
|
|
11
|
+
|
|
12
|
+
const WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
|
|
13
|
+
|
|
14
|
+
const seatResource = defineTableResource({
|
|
15
|
+
name: "seats",
|
|
16
|
+
tableName: "seats",
|
|
17
|
+
ownership: "workspace",
|
|
18
|
+
schema: {
|
|
19
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
20
|
+
code: { type: "string", required: true }
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
const ticketResource = defineTableResource({
|
|
24
|
+
name: "tickets",
|
|
25
|
+
tableName: "tickets",
|
|
26
|
+
ownership: "workspace",
|
|
27
|
+
schema: {
|
|
28
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
29
|
+
number: { type: "string", required: true }
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
const bookingResource = defineTableResource({
|
|
33
|
+
name: "bookings",
|
|
34
|
+
tableName: "bookings",
|
|
35
|
+
ownership: "workspace",
|
|
36
|
+
searchSchema: { seatIds: { type: "array", actualField: "seatId", filterOperator: "in" } },
|
|
37
|
+
schema: {
|
|
38
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
39
|
+
seatId: { type: "id", required: true, storage: { column: "seat_id" } },
|
|
40
|
+
ticketId: { type: "id", nullable: true, belongsTo: "tickets", as: "ticket", storage: { column: "ticket_id" } },
|
|
41
|
+
guest: { type: "string", required: true }
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
async function database(t, suffix) {
|
|
46
|
+
const knex = await ownMysqlDatabase(t, suffix);
|
|
47
|
+
await knex.schema.createTable("seats", (table) => {
|
|
48
|
+
table.increments("id");
|
|
49
|
+
table.integer("workspace_id").nullable();
|
|
50
|
+
table.string("code").notNullable();
|
|
51
|
+
});
|
|
52
|
+
await knex.schema.createTable("tickets", (table) => {
|
|
53
|
+
table.increments("id");
|
|
54
|
+
table.integer("workspace_id").nullable();
|
|
55
|
+
table.string("number").notNullable();
|
|
56
|
+
});
|
|
57
|
+
await knex.schema.createTable("bookings", (table) => {
|
|
58
|
+
table.increments("id");
|
|
59
|
+
table.integer("workspace_id").nullable();
|
|
60
|
+
table.integer("seat_id").notNullable().index();
|
|
61
|
+
table.integer("ticket_id").nullable();
|
|
62
|
+
table.string("guest").notNullable();
|
|
63
|
+
// lockWhere on MySQL reads through an index that starts with the ownership column.
|
|
64
|
+
table.index(["workspace_id", "seat_id"]);
|
|
65
|
+
});
|
|
66
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
67
|
+
return runtime.own("seats.feature", [seatResource, ticketResource, bookingResource]);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One transaction holds a seat's lock and adds a booking for it; a second, the reader, locks the seat (waiting for
|
|
72
|
+
* the holder's commit) and then reads the seat's bookings. With `readFirst` the reader makes a plain read before the
|
|
73
|
+
* holder commits. Answers the reader's bookings before (readFirst only) and after its lock.
|
|
74
|
+
*/
|
|
75
|
+
async function readAfterLock(t, suffix, { readFirst }) {
|
|
76
|
+
const { seats, bookings } = await database(t, suffix);
|
|
77
|
+
const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
|
|
78
|
+
const guestsOf = (tx) => bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"] }, tx);
|
|
79
|
+
let commit;
|
|
80
|
+
const committing = new Promise((resolve) => {
|
|
81
|
+
commit = resolve;
|
|
82
|
+
});
|
|
83
|
+
let holding;
|
|
84
|
+
const held = new Promise((resolve) => {
|
|
85
|
+
holding = resolve;
|
|
86
|
+
});
|
|
87
|
+
const holder = seats.withTransaction(WORKSPACE, async (tx) => {
|
|
88
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
89
|
+
await bookings.create({ seatId, guest: "first" }, { ...tx, returning: "none" });
|
|
90
|
+
holding();
|
|
91
|
+
await committing;
|
|
92
|
+
});
|
|
93
|
+
await held;
|
|
94
|
+
const reader = seats.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
95
|
+
try {
|
|
96
|
+
await assert.rejects(seats.lock(seatId, { ...tx, include: ["bookings"] }), /seats\.lock\(\) includes "bookings", which is no belongs-to relationship of seats/u);
|
|
97
|
+
const before = readFirst ? await guestsOf(tx) : null;
|
|
98
|
+
// The holder commits only once the reader has made its plain read, or is about to lock.
|
|
99
|
+
commit();
|
|
100
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
101
|
+
return { before, after: await guestsOf(tx) };
|
|
102
|
+
} finally {
|
|
103
|
+
// A failed step still lets the holder finish, so the test fails rather than waits.
|
|
104
|
+
commit();
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
const [, read] = await Promise.all([holder, reader]);
|
|
108
|
+
return { before: read.before?.map(({ guest }) => guest) ?? null, after: read.after.map(({ guest }) => guest) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
test("a transaction that locks first reads, after its lock, the rows the lock's previous holder committed", async (t) => {
|
|
112
|
+
assert.deepEqual(await readAfterLock(t, "da_lr_lock", { readFirst: false }), { before: null, after: ["first"] });
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("a transaction that made a plain read before its lock still reads that read's snapshot after the lock", async (t) => {
|
|
116
|
+
assert.deepEqual(await readAfterLock(t, "da_lr_read", { readFirst: true }), { before: [], after: [] });
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("a lock's include reads the records committed after the transaction's snapshot, which a plain read after the lock misses", async (t) => {
|
|
120
|
+
const { seats, tickets, bookings } = await database(t, "da_lr_include");
|
|
121
|
+
const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
|
|
122
|
+
let commit;
|
|
123
|
+
const committing = new Promise((resolve) => {
|
|
124
|
+
commit = resolve;
|
|
125
|
+
});
|
|
126
|
+
let holding;
|
|
127
|
+
const held = new Promise((resolve) => {
|
|
128
|
+
holding = resolve;
|
|
129
|
+
});
|
|
130
|
+
// The holder locks the seat, then adds a ticket and a booking that names it.
|
|
131
|
+
const holder = seats.withTransaction(WORKSPACE, async (tx) => {
|
|
132
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
133
|
+
const ticket = await tickets.create({ number: "T1" }, { ...tx, returning: "id" });
|
|
134
|
+
await bookings.create({ seatId, ticketId: ticket, guest: "first" }, { ...tx, returning: "none" });
|
|
135
|
+
holding();
|
|
136
|
+
await committing;
|
|
137
|
+
});
|
|
138
|
+
await held;
|
|
139
|
+
// The reader's plain read takes its snapshot before the holder commits; its lock waits for the commit.
|
|
140
|
+
const reader = seats.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
141
|
+
try {
|
|
142
|
+
const before = await bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"], include: ["ticket"] }, tx);
|
|
143
|
+
commit();
|
|
144
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
145
|
+
const locked = await bookings.lockWhere({ seatIds: [seatId] }, { ...tx, fields: ["guest"], include: ["ticket"] });
|
|
146
|
+
const after = await bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"], include: ["ticket"] }, tx);
|
|
147
|
+
return { before, locked, after };
|
|
148
|
+
} finally {
|
|
149
|
+
commit();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
const [, read] = await Promise.all([holder, reader]);
|
|
153
|
+
assert.deepEqual(read.before, []);
|
|
154
|
+
assert.deepEqual(read.locked.map(({ guest, ticketId, ticket }) => [guest, ticketId !== null && ticketId === ticket?.id, ticket?.number ?? null]), [["first", true, "T1"]]);
|
|
155
|
+
assert.deepEqual(read.after, []);
|
|
156
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { pagedReadsCases } from "./support/pagedReadsCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of pagedReadsCases(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 { pagedReadsCases } from "./support/pagedReadsCases.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 pagedReadsCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { reportsAcrossOwnersCases } from "./support/reportsAcrossOwnersCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of reportsAcrossOwnersCases(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 { reportsAcrossOwnersCases } from "./support/reportsAcrossOwnersCases.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 reportsAcrossOwnersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -196,7 +196,7 @@ test("query() pages with page.size and page.after, and refuses an unpaged or ove
|
|
|
196
196
|
assert.deepEqual(second.records.map(({ title }) => title), ["n2", "n3"]);
|
|
197
197
|
const filtered = await notes.query({ filters: { title: "n4" }, page: { size: 2 } }, { context: WORKSPACE_A });
|
|
198
198
|
assert.deepEqual(filtered.records.map(({ title }) => title), ["n4"]);
|
|
199
|
-
assert.deepEqual(notes.pageLimits(), { request: 20, server: 1000 });
|
|
199
|
+
assert.deepEqual(notes.pageLimits(), { request: 20, server: 1000, requestRows: 10000 });
|
|
200
200
|
});
|
|
201
201
|
|
|
202
202
|
test("query() serves a numbered page in one statement, with no count, and refuses page.number with page.after", async (t) => {
|
|
@@ -330,6 +330,28 @@ test("many-row writes run per chunk in the caller's workspace, and answer nothin
|
|
|
330
330
|
assert.deepEqual(await knex("notes").pluck("title"), ["other"]);
|
|
331
331
|
});
|
|
332
332
|
|
|
333
|
+
test("a many-row write refuses a chunk of fewer than 100 rows before any statement, and takes 100 or more", async (t) => {
|
|
334
|
+
const { notes, knex } = await createFixture(t);
|
|
335
|
+
const options = { context: WORKSPACE_A };
|
|
336
|
+
const [id] = await notes.createMany([{ title: "a" }], { ...options, returning: "ids" });
|
|
337
|
+
for (const chunkSize of [1, 99, 0, 150.5, -100, "200", null]) {
|
|
338
|
+
for (const [operation, call] of [
|
|
339
|
+
["createMany", () => notes.createMany([{ title: "b" }], { ...options, chunkSize })],
|
|
340
|
+
["patchMany", () => notes.patchMany([{ id, title: "b" }], { ...options, chunkSize })],
|
|
341
|
+
["patchWhere", () => notes.patchWhere({ id }, { title: "b" }, { ...options, chunkSize })],
|
|
342
|
+
["deleteWhere", () => notes.deleteWhere({ id }, { ...options, chunkSize })]
|
|
343
|
+
]) {
|
|
344
|
+
const refused = new RegExp(`^TypeError: notes\\.${operation}\\(\\) chunkSize is a whole number of at least 100 rows \\(500 when left out\\)`, "u");
|
|
345
|
+
const { count } = await countQueries(knex, () => assert.rejects(call(), refused, `${operation} with chunkSize ${chunkSize}`));
|
|
346
|
+
assert.equal(count, 0, `${operation} with chunkSize ${chunkSize} sends nothing`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
assert.deepEqual(await knex("notes").pluck("title"), ["a"]);
|
|
350
|
+
const { count } = await countQueries(knex, () => notes.createMany(Array.from({ length: 250 }, (_, index) => ({ title: `c${index}` })), { ...options, chunkSize: 100 }));
|
|
351
|
+
assert.ok(count >= 3, `250 rows in chunks of 100 are 3 inserts, in ${count} statements`);
|
|
352
|
+
assert.equal((await knex("notes").pluck("id")).length, 251);
|
|
353
|
+
});
|
|
354
|
+
|
|
333
355
|
test("a table keyed by a uuid or a string takes its ids as text without its own normalizeId", async (t) => {
|
|
334
356
|
const tokens = defineTableResource({
|
|
335
357
|
name: "tokens",
|
|
@@ -816,7 +838,7 @@ test("locks need a transaction and take only the caller's rows", async (t) => {
|
|
|
816
838
|
assert.deepEqual((await notes.lockMany([a.id, other.id], { ...txOptions, missing: "skip" })).map(({ title }) => title), ["a"]);
|
|
817
839
|
assert.deepEqual((await notes.lockWhere({ status: "queued" }, txOptions)).map(({ title }) => title), ["b"]);
|
|
818
840
|
assert.deepEqual((await notes.claim({ filters: { status: "queued" }, take: 5 }, txOptions)).map(({ id }) => String(id)), [String(b.id)]);
|
|
819
|
-
await assert.rejects(notes.claim({ status: "queued" }, { limit: 5 }, txOptions), /takes \(\{ filters, sort, take \}, options\)/u);
|
|
841
|
+
await assert.rejects(notes.claim({ status: "queued" }, { limit: 5 }, txOptions), /takes \(\{ filters, sort, take, include \}, options\)/u);
|
|
820
842
|
});
|
|
821
843
|
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, (txOptions) => notes.lock(other.id, txOptions)), notFound);
|
|
822
844
|
});
|
|
@@ -1792,6 +1814,37 @@ test("lock, lockMany, lockWhere and claim read only the fields they name, so a r
|
|
|
1792
1814
|
assert.deepEqual(locked, [{ id: ids[0], stage: "new", vetId: "1" }]);
|
|
1793
1815
|
});
|
|
1794
1816
|
|
|
1817
|
+
test("a lock includes its rows' related records as a read does, each locked after the rows; a collection is refused before any statement", async (t) => {
|
|
1818
|
+
const { visits, options, ids, selects } = await createVisitFixture(t);
|
|
1819
|
+
const refused = (method) => ({
|
|
1820
|
+
name: "TypeError",
|
|
1821
|
+
message: new RegExp(`^visits\\.${method}\\(\\) includes "notes", which is no belongs-to relationship of visits: a lock includes only the records its rows name`, "u")
|
|
1822
|
+
});
|
|
1823
|
+
const statements = await selects(() => visits.withTransaction(options, async (tx) => {
|
|
1824
|
+
const including = { ...tx, include: ["customer", "notes"] };
|
|
1825
|
+
await assert.rejects(visits.lock(ids[0], including), refused("lock"));
|
|
1826
|
+
await assert.rejects(visits.lockMany(ids, including), refused("lockMany"));
|
|
1827
|
+
await assert.rejects(visits.lockWhere({ id: ids }, including), refused("lockWhere"));
|
|
1828
|
+
await assert.rejects(visits.claim({ filters: { id: ids } }, including), refused("claim"));
|
|
1829
|
+
await assert.rejects(visits.claim({ filters: { id: ids }, include: ["notes"] }, tx), refused("claim"));
|
|
1830
|
+
}));
|
|
1831
|
+
assert.deepEqual(statements, []);
|
|
1832
|
+
// A lock's include answers what a read's include answers: the records left out by default stay out, the related
|
|
1833
|
+
// records nest under their relationships, and each included table is read once, after the lock's own rows.
|
|
1834
|
+
for (const include of [["customer"], ["customer", "vet"], "vet"]) {
|
|
1835
|
+
const read = await visits.queryAll({ filters: { id: ids }, include }, options);
|
|
1836
|
+
let locked;
|
|
1837
|
+
const tables = await selects(() => visits.withTransaction(options, async (tx) => {
|
|
1838
|
+
locked = await visits.lockMany(ids, { ...tx, include });
|
|
1839
|
+
}));
|
|
1840
|
+
assert.deepEqual(locked, read, JSON.stringify(include));
|
|
1841
|
+
assert.equal(tables[0], "visits", JSON.stringify(include));
|
|
1842
|
+
for (const table of ["customers", "vets"]) {
|
|
1843
|
+
assert.ok(tables.filter((name) => name === table).length <= 1, `${JSON.stringify(include)}: ${tables.join(", ")}`);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
});
|
|
1847
|
+
|
|
1795
1848
|
test("a patch that compares a lock version or onlyIf locks only the version, and compares onlyIf in SQL, hidden fields too", async (t) => {
|
|
1796
1849
|
const { visits, options, ids, selects } = await createVisitFixture(t);
|
|
1797
1850
|
// The patch's own locking read checks no relation: the customer it writes unchanged is checked by the write alone.
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { Buffer } from "node:buffer";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
5
|
+
import { createTestResourceRuntime, expectFlatQueries } from "../../src/test/index.js";
|
|
6
|
+
|
|
7
|
+
// A blob field on every database the runtime supports: writes take bytes within maxBytes, checked before any
|
|
8
|
+
// statement; reads answer it only when their fields name it, never as JSON, never an included table's, and never more
|
|
9
|
+
// than 16 MiB of it but one record's, so queryPages() shrinks its pages to fit. Each database's test file runs these
|
|
10
|
+
// cases on its own connection.
|
|
11
|
+
|
|
12
|
+
const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
|
|
13
|
+
// expectFlatQueries() runs only against a test database, which TEST_DB_NAME names.
|
|
14
|
+
const TEST_ENVIRONMENT = Object.freeze({ TEST_DB_NAME: "blob_test" });
|
|
15
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
16
|
+
|
|
17
|
+
const avatarResource = defineTableResource({
|
|
18
|
+
name: "avatars",
|
|
19
|
+
tableName: "avatars",
|
|
20
|
+
ownership: "workspace",
|
|
21
|
+
lockVersionField: "lockVersion",
|
|
22
|
+
schema: {
|
|
23
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
24
|
+
albumId: { type: "id", nullable: true, belongsTo: "albums", as: "album", storage: { column: "album_id" } },
|
|
25
|
+
label: { type: "string", required: true, search: true },
|
|
26
|
+
image: { type: "blob", maxBytes: MAX_BYTES, nullable: true },
|
|
27
|
+
lockVersion: { type: "integer", defaultTo: 0, storage: { column: "lock_version" } }
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const albumResource = defineTableResource({
|
|
32
|
+
name: "albums",
|
|
33
|
+
tableName: "albums",
|
|
34
|
+
ownership: "workspace",
|
|
35
|
+
relationships: { avatars: { type: "hasMany", target: "avatars", foreignKey: "albumId" } },
|
|
36
|
+
schema: {
|
|
37
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
38
|
+
title: { type: "string", required: true }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {import("knex").Knex} knex
|
|
44
|
+
* @param {{ afterWrite?: Function }} [hooks] The avatars' hooks.
|
|
45
|
+
*/
|
|
46
|
+
async function createAvatars(knex, hooks) {
|
|
47
|
+
await knex.schema.createTable("albums", (table) => {
|
|
48
|
+
table.increments("id");
|
|
49
|
+
table.integer("workspace_id").nullable();
|
|
50
|
+
table.string("title").notNullable();
|
|
51
|
+
});
|
|
52
|
+
await knex.schema.createTable("avatars", (table) => {
|
|
53
|
+
table.increments("id");
|
|
54
|
+
table.integer("workspace_id").nullable();
|
|
55
|
+
table.integer("album_id").nullable().index();
|
|
56
|
+
table.string("label").notNullable();
|
|
57
|
+
// MySQL's BLOB holds 64 KiB; a column holds the field's maxBytes.
|
|
58
|
+
if (knex.client.config.client === "mysql2") {
|
|
59
|
+
table.specificType("image", "MEDIUMBLOB").nullable();
|
|
60
|
+
} else {
|
|
61
|
+
table.binary("image").nullable();
|
|
62
|
+
}
|
|
63
|
+
table.integer("lock_version").notNullable().defaultTo(0);
|
|
64
|
+
});
|
|
65
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
66
|
+
const { avatars, albums } = await runtime.own("avatars.feature", [hooks ? { resource: avatarResource, hooks } : avatarResource, albumResource]);
|
|
67
|
+
const system = runtime.declareSystemScope("avatars.feature", "resize every workspace's avatars")("resize");
|
|
68
|
+
return { avatars, albums, system, job: { context: system.forWorkspace("1") } };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function pagesOf(pages) {
|
|
72
|
+
const read = [];
|
|
73
|
+
for await (const records of pages) {
|
|
74
|
+
read.push(records);
|
|
75
|
+
}
|
|
76
|
+
return read;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const validation = (rule) => (error) => error.code === "REST_API_VALIDATION" && error.details.violations[0].field === "image" &&
|
|
80
|
+
error.details.violations[0].rule === rule;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
84
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
85
|
+
*/
|
|
86
|
+
function blobFieldsCases(connect) {
|
|
87
|
+
return [
|
|
88
|
+
["a blob field takes bytes within maxBytes, refusing anything else before any statement, and a read answers it only when its fields name it", async (t) => {
|
|
89
|
+
const knex = await connect(t, "da_bl_values");
|
|
90
|
+
const { avatars } = await createAvatars(knex);
|
|
91
|
+
const options = { context: WORKSPACE_A };
|
|
92
|
+
const bytes = Buffer.from([0, 1, 2, 255]);
|
|
93
|
+
|
|
94
|
+
const created = await avatars.create({ label: "plain", image: bytes }, options);
|
|
95
|
+
assert.equal(Object.hasOwn(created, "image"), false);
|
|
96
|
+
const read = await avatars.get(created.id, { fields: ["label", "image"] }, options);
|
|
97
|
+
assert.equal(Buffer.isBuffer(read.image), true);
|
|
98
|
+
assert.deepEqual([...read.image], [0, 1, 2, 255]);
|
|
99
|
+
assert.equal(Object.hasOwn(await avatars.get(created.id, {}, options), "image"), false);
|
|
100
|
+
|
|
101
|
+
const viewed = await avatars.create({ label: "view", image: new Uint8Array([7, 8, 9]).subarray(1) }, { ...options, returning: "id" });
|
|
102
|
+
assert.deepEqual([...(await avatars.get(viewed, { fields: ["image"] }, options)).image], [8, 9]);
|
|
103
|
+
|
|
104
|
+
for (const [value, rule] of [["text", "blob"], [[1, 2], "blob"], [{ data: [1] }, "blob"], [Buffer.alloc(MAX_BYTES + 1), "max_bytes"]]) {
|
|
105
|
+
const refused = await countQueries(knex, () => assert.rejects(avatars.create({ label: "bad", image: value }, options), validation(rule)));
|
|
106
|
+
assert.equal(refused.count, 0);
|
|
107
|
+
}
|
|
108
|
+
await assert.rejects(avatars.createMany([{ label: "ok", image: bytes }, { label: "bad", image: "text" }], options), validation("blob"));
|
|
109
|
+
await assert.rejects(avatars.patchMany([{ id: created.id, image: Buffer.alloc(MAX_BYTES + 1) }], options), validation("max_bytes"));
|
|
110
|
+
await assert.rejects(avatars.patchWhere({ id: [created.id] }, { image: 5 }, options), validation("blob"));
|
|
111
|
+
await avatars.patch(created.id, { image: Buffer.alloc(MAX_BYTES) }, { ...options, returning: "none" });
|
|
112
|
+
assert.equal((await avatars.get(created.id, { fields: ["image"] }, options)).image.byteLength, MAX_BYTES);
|
|
113
|
+
await avatars.patch(created.id, { image: null }, { ...options, returning: "none" });
|
|
114
|
+
assert.equal((await avatars.get(created.id, { fields: ["image"] }, options)).image, null);
|
|
115
|
+
|
|
116
|
+
// One page names it; a read of every row at once, a JSON:API read and a filter lock do not.
|
|
117
|
+
const page = await avatars.query({ filters: { label: "view" }, fields: ["label", "image"], page: { size: 4 } }, options);
|
|
118
|
+
assert.deepEqual([...page.records[0].image], [8, 9]);
|
|
119
|
+
await assert.rejects(avatars.queryAll({ fields: ["label", "image"] }, options),
|
|
120
|
+
/avatars\.queryAll\(\) reads every matching row at once, so it reads no blob \(avatars\.image\): read blobs a page at a time with queryPages\(\)/u);
|
|
121
|
+
await assert.rejects(avatars.query({ fields: { avatars: "label,image" }, page: { size: 10 } }, { ...options, format: "jsonapi" }),
|
|
122
|
+
(error) => error.status === 400 && error.code === "JSON_API_FIELDSET_INVALID" && error.messageCode === "resource.blobFields" &&
|
|
123
|
+
error.messageParams.fields === "avatars.image" && /JSON holds no binary, so their fields name no blob \(avatars\.image\)/u.test(error.message));
|
|
124
|
+
await assert.rejects(avatars.get(viewed, { fields: { avatars: "image" } }, { ...options, format: "jsonapi" }), /JSON holds no binary/u);
|
|
125
|
+
const locked = await avatars.withTransaction(options, async (tx) => {
|
|
126
|
+
await assert.rejects(avatars.lockWhere({ label: "view" }, { ...tx, fields: ["image"] }), /avatars\.lockWhere\(\) reads every matching row at once, so it reads no blob/u);
|
|
127
|
+
assert.equal(Object.hasOwn(await avatars.lock(viewed, tx), "image"), false);
|
|
128
|
+
return avatars.lockMany([viewed], { ...tx, fields: ["image"] });
|
|
129
|
+
});
|
|
130
|
+
assert.deepEqual([...locked[0].image], [8, 9]);
|
|
131
|
+
}],
|
|
132
|
+
|
|
133
|
+
["queryPages() reads named blobs in pages that hold at most 16 MiB of them, and every row a page without them", async (t) => {
|
|
134
|
+
const knex = await connect(t, "da_bl_pages");
|
|
135
|
+
const { avatars, system, job } = await createAvatars(knex);
|
|
136
|
+
await avatars.createMany(Array.from({ length: 9 }, (_, index) => ({ label: `a${index}`, image: Buffer.from([index]) })), { ...job, returning: "none" });
|
|
137
|
+
const sizes = async (params) => (await pagesOf(avatars.queryPages(params, job))).map((records) => records.length);
|
|
138
|
+
// A 4 MiB blob: 4 rows a page.
|
|
139
|
+
assert.deepEqual(await sizes({ fields: ["label", "image"] }), [4, 4, 1]);
|
|
140
|
+
assert.deepEqual(await sizes({ fields: ["label"] }), [9]);
|
|
141
|
+
const last = [];
|
|
142
|
+
for await (const records of avatars.queryPages({ filters: { label: "a8" }, fields: ["image"] }, job)) {
|
|
143
|
+
last.push(...records.map(({ image }) => [...image]));
|
|
144
|
+
}
|
|
145
|
+
assert.deepEqual(last, [[8]]);
|
|
146
|
+
|
|
147
|
+
// Each later page's own statement is allowed, as a many-row write's later chunks are, so the paged read is flat.
|
|
148
|
+
let workspace = 1;
|
|
149
|
+
const seed = async (size) => {
|
|
150
|
+
workspace += 1;
|
|
151
|
+
const options = { context: system.forWorkspace(String(workspace)), returning: "none" };
|
|
152
|
+
await avatars.createMany(Array.from({ length: size }, (_, index) => ({ label: `w${index}`, image: Buffer.from([index]) })), options);
|
|
153
|
+
return String(workspace);
|
|
154
|
+
};
|
|
155
|
+
const run = async (seeded) => (await pagesOf(avatars.queryPages({ fields: ["image"] }, { context: system.forWorkspace(seeded) }))).flat().length;
|
|
156
|
+
assert.deepEqual(await expectFlatQueries({ knex, environment: TEST_ENVIRONMENT, sizes: [5, 20], seed, run }),
|
|
157
|
+
[{ size: 5, count: 2, chunkStatements: 1 }, { size: 20, count: 5, chunkStatements: 4 }]);
|
|
158
|
+
}],
|
|
159
|
+
|
|
160
|
+
["a write whose blob is wrong sends no statement, not a lock or a BEGIN, whatever the patch's conditions or the table's hooks", async (t) => {
|
|
161
|
+
const knex = await connect(t, "da_bl_first");
|
|
162
|
+
const written = [];
|
|
163
|
+
const { avatars } = await createAvatars(knex, { afterWrite: ({ operation }) => { written.push(operation); } });
|
|
164
|
+
const options = { context: WORKSPACE_A };
|
|
165
|
+
const { id, lockVersion } = await avatars.create({ label: "framed", image: Buffer.from([1]) }, options);
|
|
166
|
+
const oversize = Buffer.alloc(MAX_BYTES + 1);
|
|
167
|
+
const writes = [
|
|
168
|
+
() => avatars.patch(id, { image: oversize }, { ...options, lockVersion }),
|
|
169
|
+
() => avatars.patch(id, { image: oversize }, { ...options, onlyIf: { label: "framed" } }),
|
|
170
|
+
() => avatars.patch(id, { image: oversize }, options),
|
|
171
|
+
() => avatars.create({ label: "big", image: oversize }, options),
|
|
172
|
+
() => avatars.createMany([{ label: "big", image: oversize }], options),
|
|
173
|
+
() => avatars.patchMany([{ id, image: oversize }], options),
|
|
174
|
+
() => avatars.patchWhere({ id: [id] }, { image: oversize }, options),
|
|
175
|
+
() => avatars.findOrCreate({ id: "999", label: "big", image: oversize }, options),
|
|
176
|
+
() => avatars.lockOrCreate({ id: "999", label: "big", image: oversize }, options, () => null)
|
|
177
|
+
];
|
|
178
|
+
for (const write of writes) {
|
|
179
|
+
const refused = await countQueries(knex, () => assert.rejects(write(), validation("max_bytes")));
|
|
180
|
+
assert.equal(refused.count, 0);
|
|
181
|
+
}
|
|
182
|
+
assert.deepEqual(written, ["create"]);
|
|
183
|
+
}],
|
|
184
|
+
|
|
185
|
+
["a read holds at most 16 MiB of blobs, or one record's, and no included table's: a query page, a lockMany() list, an include and a join source", async (t) => {
|
|
186
|
+
const knex = await connect(t, "da_bl_bound");
|
|
187
|
+
const { avatars, albums, job } = await createAvatars(knex);
|
|
188
|
+
const options = { context: WORKSPACE_A };
|
|
189
|
+
const ids = await avatars.createMany(Array.from({ length: 5 }, (_, index) => ({ label: `b${index}`, image: Buffer.from([index]) })), { ...options, returning: "ids" });
|
|
190
|
+
const albumId = await albums.create({ title: "Faces" }, { ...options, returning: "id" });
|
|
191
|
+
|
|
192
|
+
// A 4 MiB blob: 4 records hold 16 MiB.
|
|
193
|
+
assert.equal((await avatars.query({ fields: ["image"], page: { size: 4 } }, options)).records.length, 4);
|
|
194
|
+
const page = await countQueries(knex, () => assert.rejects(avatars.query({ fields: ["image"], page: { size: 5 } }, options),
|
|
195
|
+
/avatars\.query\(\) reads up to 5 records, and 4 of them already hold 16 MiB of avatars\.image: read at most 4 at a time/u));
|
|
196
|
+
assert.equal(page.count, 0);
|
|
197
|
+
await avatars.withTransaction(options, async (tx) => {
|
|
198
|
+
await assert.rejects(avatars.lockMany(ids, { ...tx, fields: ["image"] }), /avatars\.lockMany\(\) reads up to 5 records/u);
|
|
199
|
+
assert.equal((await avatars.lockMany(ids.slice(0, 4), { ...tx, fields: ["image"] })).length, 4);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// An include holds any number of records, so no read names an included table's blob.
|
|
203
|
+
const faces = { include: ["avatars"], fields: { albums: "title", avatars: "label,image" } };
|
|
204
|
+
const included = /albums\.(get|query|queryPages|queryAll)\(\) fields name avatars\.image, a blob of an included table/u;
|
|
205
|
+
const reads = [
|
|
206
|
+
() => albums.get(albumId, faces, options),
|
|
207
|
+
() => albums.query({ ...faces, page: { size: 10 } }, options),
|
|
208
|
+
() => albums.queryAll(faces, options),
|
|
209
|
+
() => pagesOf(albums.queryPages(faces, job))
|
|
210
|
+
];
|
|
211
|
+
for (const read of reads) {
|
|
212
|
+
const refused = await countQueries(knex, () => assert.rejects(read(), included));
|
|
213
|
+
assert.equal(refused.count, 0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// A join source carries no blob, so a report's select of every column reads none.
|
|
217
|
+
const source = await avatars.joinSource({ alias: "a" }, options);
|
|
218
|
+
const [row] = await source.query.select("a.*").orderBy("a.id").limit(1);
|
|
219
|
+
assert.equal(Object.hasOwn(row, "image"), false);
|
|
220
|
+
assert.equal(row.label, "b0");
|
|
221
|
+
assert.throws(() => source.column("image"), /avatars\.joinSource\(\) carries no blob, so it has no column for "image"/u);
|
|
222
|
+
}]
|
|
223
|
+
];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export { blobFieldsCases };
|