@ultimat3/testing 31.8.0 → 31.10.0
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/package.json +22 -22
- package/src/auth-adapter-conformance-sessions.ts +19 -0
- package/src/entity-conformance-chain-writes.ts +350 -0
- package/src/entity-conformance-checks.ts +22 -0
- package/src/entity-conformance-contains.ts +145 -0
- package/src/entity-conformance-counted-in.ts +229 -0
- package/src/entity-conformance-latest-by.ts +242 -0
- package/src/entity-conformance-lock-keys.ts +206 -0
- package/src/entity-conformance-matrix-writes.ts +75 -0
- package/src/entity-conformance-matrix.ts +5 -5
- package/src/entity-conformance-measures.ts +166 -0
- package/src/entity-conformance-page-bytes.ts +57 -0
- package/src/entity-conformance-tenancy.ts +46 -1
- package/src/entity-conformance-unreturned.ts +355 -0
- package/src/entity-conformance-update-many.ts +359 -0
- package/src/entity-conformance-version-lock.ts +204 -0
- package/src/entity-conformance-write-entities.ts +71 -0
- package/src/entity-conformance-write-support.ts +40 -0
- package/src/entity-driver-conformance.ts +10 -0
- package/src/plan-sweep-fix.ts +18 -0
- package/src/plan-sweep-report.ts +5 -2
- package/src/plan-trigram.ts +21 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// Entity conformance · a `countedIn` counter is a write to its PARENT, and the row observer says so:
|
|
2
|
+
// a child insert, delete or re-parent reports `entity.row` for each parent whose count moved, its
|
|
3
|
+
// `before` and `after` the stored row; a bulk child write pinned to one parent reports that row, one
|
|
4
|
+
// spanning several a bulk count — never silence, and never a change a rolled-back write did not make.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { EntityRowEvent } from '@ultimat3/core';
|
|
8
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
9
|
+
import type { Database } from '@ultimat3/entity';
|
|
10
|
+
import { entity, integer, text, uuid } from '@ultimat3/entity';
|
|
11
|
+
import { remember } from './entity-conformance-entities';
|
|
12
|
+
import { codeOf, handleOf, idAt } from './entity-conformance-support';
|
|
13
|
+
import { accountedFor, heard } from './entity-conformance-write-support';
|
|
14
|
+
import type { EntityDriverCheck, EntityDriverRun } from './entity-driver-conformance';
|
|
15
|
+
|
|
16
|
+
const posts = remember(
|
|
17
|
+
entity('ec_ci_posts', {
|
|
18
|
+
columns: { id: uuid().primaryKey(), title: text({ max: 20 }), likeCount: integer().default(0) },
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
const likes = remember(
|
|
23
|
+
entity('ec_ci_likes', {
|
|
24
|
+
columns: {
|
|
25
|
+
id: uuid().primaryKey(),
|
|
26
|
+
postId: uuid().references(() => posts.id, { countedIn: () => posts.likeCount }),
|
|
27
|
+
reaction: text({ max: 20 }),
|
|
28
|
+
},
|
|
29
|
+
}),
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
const SET = { posts, likes };
|
|
33
|
+
type Db = Database<typeof SET>;
|
|
34
|
+
const PARENT = 'ec_ci_posts';
|
|
35
|
+
const [P1, P2] = [idAt('f1'), idAt('f2')];
|
|
36
|
+
const [L1, L2, L3] = [idAt('f11'), idAt('f12'), idAt('f13')];
|
|
37
|
+
|
|
38
|
+
const seedPosts = async (db: Db): Promise<void> => {
|
|
39
|
+
await db.posts.insertAll([
|
|
40
|
+
{ id: P1, title: 'one', likeCount: 0 },
|
|
41
|
+
{ id: P2, title: 'two', likeCount: 0 },
|
|
42
|
+
]);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A row event as the three facts that matter: which parent, and its count before and after. */
|
|
46
|
+
const moved = (event: EntityRowEvent) => [
|
|
47
|
+
event.op,
|
|
48
|
+
event.after?.['id'] ?? event.before?.['id'],
|
|
49
|
+
event.before?.['likeCount'] ?? null,
|
|
50
|
+
event.after?.['likeCount'] ?? null,
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
const stored = async (db: Db) =>
|
|
54
|
+
(await db.posts.orderBy('id').all()).map((row) => [row.id, row.likeCount]);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A check over a store that keeps the counter. One that does not (`defineDriver`: no lifecycle
|
|
58
|
+
* hook) refuses the counted child's repository outright, so there is no handle to build and no
|
|
59
|
+
* parent change to report: its claim is the refusal check below, never these.
|
|
60
|
+
*/
|
|
61
|
+
const counted = (
|
|
62
|
+
name: string,
|
|
63
|
+
run: (db: Db, raw: EntityDriverRun) => Promise<void>,
|
|
64
|
+
needs: EntityDriverCheck['needs'] = [],
|
|
65
|
+
): EntityDriverCheck => ({
|
|
66
|
+
name,
|
|
67
|
+
entities: Object.values(SET),
|
|
68
|
+
needs,
|
|
69
|
+
run: async (raw) => {
|
|
70
|
+
if (!raw.counters) return;
|
|
71
|
+
await run(handleOf(SET, raw.driver), raw);
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/** `[code, capability]` a build refused with, or `'built'`. */
|
|
76
|
+
const builds = (build: () => unknown): unknown => {
|
|
77
|
+
try {
|
|
78
|
+
build();
|
|
79
|
+
return 'built';
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return isUltimateError(error) ? [error.code, error.meta?.['capability']] : String(error);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const refusal: readonly EntityDriverCheck[] = [
|
|
86
|
+
{
|
|
87
|
+
name: 'a store that keeps no counter refuses the counted child, never a count left stale',
|
|
88
|
+
entities: Object.values(SET),
|
|
89
|
+
run: async (raw) => {
|
|
90
|
+
const child = builds(() => raw.driver.repo(likes));
|
|
91
|
+
// The parent declares no counter of its own: every store builds it.
|
|
92
|
+
expect([child, builds(() => raw.driver.repo(posts))]).toEqual([
|
|
93
|
+
raw.counters ? 'built' : ['X_DRIVER_UNSUPPORTED', 'countedIn'],
|
|
94
|
+
'built',
|
|
95
|
+
]);
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
const rows: readonly EntityDriverCheck[] = [
|
|
101
|
+
counted(
|
|
102
|
+
'a counted child insert and delete each report the parent row, its count before and after',
|
|
103
|
+
async (db) => {
|
|
104
|
+
await seedPosts(db);
|
|
105
|
+
const insert = await heard(PARENT, () =>
|
|
106
|
+
db.likes.insert({ id: L1, postId: P1, reaction: 'up' }),
|
|
107
|
+
);
|
|
108
|
+
const again = await heard(PARENT, () =>
|
|
109
|
+
db.likes.insert({ id: L2, postId: P1, reaction: 'up' }),
|
|
110
|
+
);
|
|
111
|
+
const remove = await heard(PARENT, () => db.likes.delete(L1));
|
|
112
|
+
expect([insert, again, remove].map((each) => each.heard.rows.map(moved))).toEqual([
|
|
113
|
+
[['update', P1, 0, 1]],
|
|
114
|
+
[['update', P1, 1, 2]],
|
|
115
|
+
[['update', P1, 2, 1]],
|
|
116
|
+
]);
|
|
117
|
+
expect([insert, again, remove].map((each) => each.heard.bulk)).toEqual([[], [], []]);
|
|
118
|
+
expect(await stored(db)).toEqual([
|
|
119
|
+
[P1, 1],
|
|
120
|
+
[P2, 0],
|
|
121
|
+
]);
|
|
122
|
+
},
|
|
123
|
+
),
|
|
124
|
+
counted(
|
|
125
|
+
'a re-parenting update reports both parents: the one it left and the one it joined',
|
|
126
|
+
async (db) => {
|
|
127
|
+
await seedPosts(db);
|
|
128
|
+
await db.likes.insert({ id: L1, postId: P1, reaction: 'up' });
|
|
129
|
+
const { heard: told } = await heard(PARENT, () => db.likes.update(L1, { postId: P2 }));
|
|
130
|
+
expect(told.rows.map(moved).sort((a, b) => String(a[1]).localeCompare(String(b[1])))).toEqual(
|
|
131
|
+
[
|
|
132
|
+
['update', P1, 1, 0],
|
|
133
|
+
['update', P2, 0, 1],
|
|
134
|
+
],
|
|
135
|
+
);
|
|
136
|
+
expect(await stored(db)).toEqual([
|
|
137
|
+
[P1, 0],
|
|
138
|
+
[P2, 1],
|
|
139
|
+
]);
|
|
140
|
+
},
|
|
141
|
+
),
|
|
142
|
+
counted('an update leaving the counted key alone reports no parent change', async (db) => {
|
|
143
|
+
await seedPosts(db);
|
|
144
|
+
await db.likes.insert({ id: L1, postId: P1, reaction: 'up' });
|
|
145
|
+
const { heard: told } = await heard(PARENT, () => db.likes.update(L1, { reaction: 'down' }));
|
|
146
|
+
expect([told.rows.map(moved), told.bulk]).toEqual([[], []]);
|
|
147
|
+
}),
|
|
148
|
+
];
|
|
149
|
+
|
|
150
|
+
const bulk: readonly EntityDriverCheck[] = [
|
|
151
|
+
counted(
|
|
152
|
+
'a bulk child delete pinned to one parent reports that parent row, by filter or by chain',
|
|
153
|
+
async (db) => {
|
|
154
|
+
await seedPosts(db);
|
|
155
|
+
const three = () =>
|
|
156
|
+
db.likes.insertAll([
|
|
157
|
+
{ id: L1, postId: P1, reaction: 'up' },
|
|
158
|
+
{ id: L2, postId: P1, reaction: 'up' },
|
|
159
|
+
{ id: L3, postId: P2, reaction: 'up' },
|
|
160
|
+
]);
|
|
161
|
+
await three();
|
|
162
|
+
const filter = await heard(PARENT, () => db.likes.deleteWhere({ postId: P1 }));
|
|
163
|
+
await db.likes.deleteWhere({ postId: P2 });
|
|
164
|
+
await three();
|
|
165
|
+
const chain = await heard(PARENT, () =>
|
|
166
|
+
db.likes.where({ postId: P1, reaction: 'up' }).deleteAll(),
|
|
167
|
+
);
|
|
168
|
+
// Pinned, the parent is known and re-read; by how much is not, so `before` is unknown (null).
|
|
169
|
+
for (const [how, pinned] of [
|
|
170
|
+
['deleteWhere', filter],
|
|
171
|
+
['chain deleteAll', chain],
|
|
172
|
+
] as const) {
|
|
173
|
+
expect([how, pinned.answer, pinned.heard.rows.map(moved), pinned.heard.bulk]).toEqual([
|
|
174
|
+
how,
|
|
175
|
+
2,
|
|
176
|
+
[['update', P1, null, 0]],
|
|
177
|
+
[],
|
|
178
|
+
]);
|
|
179
|
+
}
|
|
180
|
+
expect(await stored(db)).toEqual([
|
|
181
|
+
[P1, 0],
|
|
182
|
+
[P2, 1],
|
|
183
|
+
]);
|
|
184
|
+
},
|
|
185
|
+
),
|
|
186
|
+
counted(
|
|
187
|
+
'a bulk child delete across parents reports a bulk count for the parent table, never silence',
|
|
188
|
+
async (db) => {
|
|
189
|
+
await seedPosts(db);
|
|
190
|
+
await db.likes.insertAll([
|
|
191
|
+
{ id: L1, postId: P1, reaction: 'up' },
|
|
192
|
+
{ id: L2, postId: P1, reaction: 'up' },
|
|
193
|
+
{ id: L3, postId: P2, reaction: 'up' },
|
|
194
|
+
]);
|
|
195
|
+
const spread = await heard(PARENT, () => db.likes.where({ reaction: 'up' }).deleteAll());
|
|
196
|
+
expect(spread.answer).toBe(3);
|
|
197
|
+
expect(spread.heard.bulk.map((each) => [each.entity, each.op])).toEqual([[PARENT, 'update']]);
|
|
198
|
+
// Two parents moved: a count a subscriber re-reads on may be wider, never narrower.
|
|
199
|
+
expect(accountedFor(spread.heard)).toBeGreaterThanOrEqual(2);
|
|
200
|
+
expect(await stored(db)).toEqual([
|
|
201
|
+
[P1, 0],
|
|
202
|
+
[P2, 0],
|
|
203
|
+
]);
|
|
204
|
+
},
|
|
205
|
+
),
|
|
206
|
+
counted(
|
|
207
|
+
'a counted child write rolled back with its transaction reports no parent change',
|
|
208
|
+
async (db, { driver }) => {
|
|
209
|
+
await seedPosts(db);
|
|
210
|
+
await db.likes.insert({ id: L1, postId: P1, reaction: 'up' });
|
|
211
|
+
const { answer, heard: told } = await heard(PARENT, () =>
|
|
212
|
+
codeOf(() =>
|
|
213
|
+
driver.transactor().run(async () => {
|
|
214
|
+
await db.likes.insert({ id: L2, postId: P1, reaction: 'up' });
|
|
215
|
+
await db.likes.insert({ id: L1, postId: P2, reaction: 'dup' });
|
|
216
|
+
}),
|
|
217
|
+
),
|
|
218
|
+
);
|
|
219
|
+
expect([answer, told.rows.map(moved), told.bulk]).toEqual(['X_DB_UNIQUE_VIOLATION', [], []]);
|
|
220
|
+
expect(await stored(db)).toEqual([
|
|
221
|
+
[P1, 1],
|
|
222
|
+
[P2, 0],
|
|
223
|
+
]);
|
|
224
|
+
},
|
|
225
|
+
['transactions'],
|
|
226
|
+
),
|
|
227
|
+
];
|
|
228
|
+
|
|
229
|
+
export const COUNTED_IN_CHECKS: readonly EntityDriverCheck[] = [...refusal, ...rows, ...bulk];
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Entity conformance · newest row per group: `latestBy(group, { order })` answers one row per group
|
|
2
|
+
// the chain matches — ordered by the group with `null` last, ties to the primary key, under the
|
|
3
|
+
// read's tenancy and soft delete, refused past its bound and beside a page — and
|
|
4
|
+
// `preload(rel, { perParent })` attaches each parent its newest n children, `[]` for none.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { Database } from '@ultimat3/entity';
|
|
8
|
+
import { entity, text, timestamp, uuid } from '@ultimat3/entity';
|
|
9
|
+
import { remember } from './entity-conformance-entities';
|
|
10
|
+
import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
|
|
11
|
+
import type { EntityDriverCheck } from './entity-driver-conformance';
|
|
12
|
+
|
|
13
|
+
const threads = remember(
|
|
14
|
+
entity('ec_lb_threads', {
|
|
15
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), title: text({ max: 20 }) },
|
|
16
|
+
}),
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
const messages = remember(
|
|
20
|
+
entity('ec_lb_messages', {
|
|
21
|
+
columns: {
|
|
22
|
+
id: uuid().primaryKey(),
|
|
23
|
+
orgId: uuid().tenant(),
|
|
24
|
+
threadId: uuid()
|
|
25
|
+
.references(() => threads.id)
|
|
26
|
+
.nullable(),
|
|
27
|
+
body: text({ max: 20 }),
|
|
28
|
+
sentAt: timestamp(),
|
|
29
|
+
deletedAt: timestamp().nullable(),
|
|
30
|
+
},
|
|
31
|
+
}),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const SET = { threads, messages };
|
|
35
|
+
type Db = Database<typeof SET>;
|
|
36
|
+
type Message = typeof messages.$row;
|
|
37
|
+
const [ORG, OTHER_ORG] = [idAt('e1'), idAt('e2')];
|
|
38
|
+
const [T1, T2, T3] = [idAt('e11'), idAt('e12'), idAt('e13')];
|
|
39
|
+
/** The `hasMany` from a thread to its messages: named for the entity the rows come from. */
|
|
40
|
+
const MESSAGES = 'ec_lb_messages';
|
|
41
|
+
const at = (minute: number): Date => new Date(Date.UTC(2026, 0, 1, 0, minute));
|
|
42
|
+
|
|
43
|
+
/** A message in thread one of our org; its id from its body, so every row's id is its own. */
|
|
44
|
+
const message = (over: Partial<Message> & Pick<Message, 'body' | 'sentAt'>): Message => ({
|
|
45
|
+
id: idAt(Bun.hash(over.body).toString(16).slice(0, 12)),
|
|
46
|
+
orgId: ORG,
|
|
47
|
+
threadId: T1,
|
|
48
|
+
deletedAt: null,
|
|
49
|
+
...over,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const seedThreads = (db: Db) =>
|
|
53
|
+
db.threads.insertAll([
|
|
54
|
+
{ id: T1, orgId: ORG, title: 'one' },
|
|
55
|
+
{ id: T2, orgId: ORG, title: 'two' },
|
|
56
|
+
{ id: T3, orgId: ORG, title: 'three' },
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
const bodies = (rows: readonly { readonly body: string }[]) => rows.map((row) => row.body);
|
|
60
|
+
const latest = (db: Db, options: { direction?: 'asc' | 'desc' } = {}) =>
|
|
61
|
+
inOrg(ORG, () =>
|
|
62
|
+
db.messages.where({ orgId: ORG }).latestBy('threadId', { order: 'sentAt', ...options }),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const reads: readonly EntityDriverCheck[] = [
|
|
66
|
+
checkOver(
|
|
67
|
+
SET,
|
|
68
|
+
'latestBy answers the newest row of every group, ordered by the group, null last',
|
|
69
|
+
async (db) => {
|
|
70
|
+
await seedThreads(db);
|
|
71
|
+
await db.messages.insertAll([
|
|
72
|
+
message({ threadId: T2, body: 't2 old', sentAt: at(1) }),
|
|
73
|
+
message({ threadId: T1, body: 't1 mid', sentAt: at(3) }),
|
|
74
|
+
message({ threadId: null, body: 'loose new', sentAt: at(9) }),
|
|
75
|
+
message({ threadId: T1, body: 't1 new', sentAt: at(5) }),
|
|
76
|
+
message({ threadId: T2, body: 't2 new', sentAt: at(2) }),
|
|
77
|
+
message({ threadId: T1, body: 't1 old', sentAt: at(0) }),
|
|
78
|
+
message({ threadId: null, body: 'loose old', sentAt: at(4) }),
|
|
79
|
+
]);
|
|
80
|
+
expect(bodies(await latest(db))).toEqual(['t1 new', 't2 new', 'loose new']);
|
|
81
|
+
expect(bodies(await latest(db, { direction: 'asc' }))).toEqual([
|
|
82
|
+
't1 old',
|
|
83
|
+
't2 old',
|
|
84
|
+
'loose old',
|
|
85
|
+
]);
|
|
86
|
+
},
|
|
87
|
+
),
|
|
88
|
+
checkOver(
|
|
89
|
+
SET,
|
|
90
|
+
'a tie on the order goes to the primary key, in the same direction',
|
|
91
|
+
async (db) => {
|
|
92
|
+
await seedThreads(db);
|
|
93
|
+
// Inserted high id first, so an answer in insertion order is not mistaken for the tiebreak.
|
|
94
|
+
await db.messages.insertAll([
|
|
95
|
+
message({ id: idAt('e9b'), body: 'high', sentAt: at(7) }),
|
|
96
|
+
message({ id: idAt('e9a'), body: 'low', sentAt: at(7) }),
|
|
97
|
+
]);
|
|
98
|
+
expect([bodies(await latest(db)), bodies(await latest(db, { direction: 'asc' }))]).toEqual([
|
|
99
|
+
['high'],
|
|
100
|
+
['low'],
|
|
101
|
+
]);
|
|
102
|
+
},
|
|
103
|
+
),
|
|
104
|
+
checkOver(
|
|
105
|
+
SET,
|
|
106
|
+
'latestBy reads what the chain reads: its filter, the actor’s tenant, never a deleted row',
|
|
107
|
+
async (db) => {
|
|
108
|
+
await seedThreads(db);
|
|
109
|
+
await db.messages.insertAll([
|
|
110
|
+
message({ threadId: T1, body: 'kept', sentAt: at(1) }),
|
|
111
|
+
message({ threadId: T1, body: 'deleted', sentAt: at(8), deletedAt: at(9) }),
|
|
112
|
+
// Another org's: a same-tenant key cannot point it at our thread, so it waits in the null group.
|
|
113
|
+
message({ threadId: null, body: 'theirs', sentAt: at(9), orgId: OTHER_ORG }),
|
|
114
|
+
message({ threadId: T2, body: 't2 filtered out', sentAt: at(9) }),
|
|
115
|
+
message({ threadId: T2, body: 't2', sentAt: at(2) }),
|
|
116
|
+
]);
|
|
117
|
+
const rows = await inOrg(ORG, () =>
|
|
118
|
+
db.messages
|
|
119
|
+
.andWhere('body', 'neq', 't2 filtered out')
|
|
120
|
+
.latestBy('threadId', { order: 'sentAt' }),
|
|
121
|
+
);
|
|
122
|
+
expect(bodies(rows)).toEqual(['kept', 't2']);
|
|
123
|
+
expect(await codeOf(() => db.messages.latestBy('threadId', { order: 'sentAt' }))).toBe(
|
|
124
|
+
'X_TENANCY_UNSCOPED',
|
|
125
|
+
);
|
|
126
|
+
},
|
|
127
|
+
),
|
|
128
|
+
checkOver(
|
|
129
|
+
SET,
|
|
130
|
+
'latestBy beside orderBy(), limit() or after() is refused; one row per group is the shape',
|
|
131
|
+
async (db) => {
|
|
132
|
+
await seedThreads(db);
|
|
133
|
+
await db.messages.insert(message({ body: 'only', sentAt: at(1) }));
|
|
134
|
+
const chain = () => db.messages.where({ orgId: ORG });
|
|
135
|
+
const refusals = await inOrg(ORG, async () => [
|
|
136
|
+
await codeOf(() => chain().orderBy('sentAt').latestBy('threadId', { order: 'sentAt' })),
|
|
137
|
+
await codeOf(() => chain().limit(1).latestBy('threadId', { order: 'sentAt' })),
|
|
138
|
+
await codeOf(() => chain().after('cursor').latestBy('threadId', { order: 'sentAt' })),
|
|
139
|
+
]);
|
|
140
|
+
expect(refusals).toEqual([
|
|
141
|
+
'X_INVARIANT_VIOLATED',
|
|
142
|
+
'X_INVARIANT_VIOLATED',
|
|
143
|
+
'X_INVARIANT_VIOLATED',
|
|
144
|
+
]);
|
|
145
|
+
},
|
|
146
|
+
),
|
|
147
|
+
];
|
|
148
|
+
|
|
149
|
+
/** `MAX_LATEST_GROUPS` (`countBy`'s `MAX_GROUPS`): past it refused, never cut. */
|
|
150
|
+
const MAX_GROUPS = 1000;
|
|
151
|
+
|
|
152
|
+
const bound: readonly EntityDriverCheck[] = [
|
|
153
|
+
checkOver(
|
|
154
|
+
{ threads, messages },
|
|
155
|
+
`latestBy over ${MAX_GROUPS} groups answers each; one more group is refused`,
|
|
156
|
+
async (db) => {
|
|
157
|
+
const many = Array.from({ length: MAX_GROUPS + 1 }, (_, index) => ({
|
|
158
|
+
id: idAt(50_000 + index),
|
|
159
|
+
orgId: ORG,
|
|
160
|
+
title: `t${index}`,
|
|
161
|
+
}));
|
|
162
|
+
await db.threads.insertAll(many);
|
|
163
|
+
await db.messages.insertAll(
|
|
164
|
+
many
|
|
165
|
+
.slice(0, MAX_GROUPS)
|
|
166
|
+
.map((thread, index) =>
|
|
167
|
+
message({ id: idAt(60_000 + index), threadId: thread.id, body: 'm', sentAt: at(1) }),
|
|
168
|
+
),
|
|
169
|
+
);
|
|
170
|
+
expect((await latest(db)).length).toBe(MAX_GROUPS);
|
|
171
|
+
await db.messages.insert(
|
|
172
|
+
message({
|
|
173
|
+
id: idAt(70_000),
|
|
174
|
+
threadId: many[MAX_GROUPS]?.id ?? null,
|
|
175
|
+
body: 'm',
|
|
176
|
+
sentAt: at(1),
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
expect(await codeOf(() => latest(db))).toBe('X_INVARIANT_VIOLATED');
|
|
180
|
+
},
|
|
181
|
+
),
|
|
182
|
+
];
|
|
183
|
+
|
|
184
|
+
const perParent: readonly EntityDriverCheck[] = [
|
|
185
|
+
checkOver(
|
|
186
|
+
SET,
|
|
187
|
+
'preload perParent attaches each parent its newest n children in order, [] for none',
|
|
188
|
+
async (db) => {
|
|
189
|
+
await seedThreads(db);
|
|
190
|
+
await db.messages.insertAll([
|
|
191
|
+
message({ threadId: T1, body: 't1 a', sentAt: at(1) }),
|
|
192
|
+
message({ threadId: T1, body: 't1 c', sentAt: at(3) }),
|
|
193
|
+
message({ threadId: T1, body: 't1 b', sentAt: at(2) }),
|
|
194
|
+
message({ threadId: T2, body: 't2 a', sentAt: at(4) }),
|
|
195
|
+
message({ threadId: T1, body: 't1 deleted', sentAt: at(9), deletedAt: at(9) }),
|
|
196
|
+
]);
|
|
197
|
+
const rows = await inOrg(ORG, () =>
|
|
198
|
+
db.threads
|
|
199
|
+
.where({ orgId: ORG })
|
|
200
|
+
.orderBy('id')
|
|
201
|
+
.preload(MESSAGES, { perParent: 2, order: 'sentAt' })
|
|
202
|
+
.all(),
|
|
203
|
+
);
|
|
204
|
+
const attached = rows.map((row) =>
|
|
205
|
+
bodies((row as unknown as Record<string, readonly Message[]>)[MESSAGES] ?? []),
|
|
206
|
+
);
|
|
207
|
+
expect(attached).toEqual([['t1 c', 't1 b'], ['t2 a'], []]);
|
|
208
|
+
const oldest = await inOrg(ORG, () =>
|
|
209
|
+
db.threads
|
|
210
|
+
.where({ id: T1 })
|
|
211
|
+
.preload(MESSAGES, { perParent: 1, order: 'sentAt', direction: 'asc' })
|
|
212
|
+
.one(),
|
|
213
|
+
);
|
|
214
|
+
expect(
|
|
215
|
+
bodies((oldest as unknown as Record<string, readonly Message[]>)[MESSAGES] ?? []),
|
|
216
|
+
).toEqual(['t1 a']);
|
|
217
|
+
},
|
|
218
|
+
),
|
|
219
|
+
checkOver(
|
|
220
|
+
SET,
|
|
221
|
+
'a perParent past a whole number from 1, on a belongsTo, or an order without it is refused',
|
|
222
|
+
async (db) => {
|
|
223
|
+
const threadChain = () => db.threads.where({ orgId: ORG });
|
|
224
|
+
const asked = [
|
|
225
|
+
...[0, -1, 1.5, Number.NaN].map(
|
|
226
|
+
(perParent) => () => threadChain().preload(MESSAGES, { perParent, order: 'sentAt' }),
|
|
227
|
+
),
|
|
228
|
+
// A belongsTo attaches one row already; an order alone names no "first n".
|
|
229
|
+
() => db.messages.where({ orgId: ORG }).preload('thread', { perParent: 1 }),
|
|
230
|
+
() => threadChain().preload(MESSAGES, { order: 'sentAt' }),
|
|
231
|
+
];
|
|
232
|
+
const answers = await Promise.all(asked.map((ask) => codeOf(ask)));
|
|
233
|
+
expect(answers).toEqual(asked.map(() => 'X_INVARIANT_VIOLATED'));
|
|
234
|
+
// The same chain with a whole perParent is accepted: the refusals are about the value.
|
|
235
|
+
expect(await codeOf(() => threadChain().preload(MESSAGES, { perParent: 1 }))).toBe(
|
|
236
|
+
'resolved',
|
|
237
|
+
);
|
|
238
|
+
},
|
|
239
|
+
),
|
|
240
|
+
];
|
|
241
|
+
|
|
242
|
+
export const LATEST_BY_CHECKS: readonly EntityDriverCheck[] = [...reads, ...bound, ...perParent];
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Entity conformance · `lockKeys(keys, fn)`: several keys held for one callback in one transaction,
|
|
2
|
+
// taken in sorted order so two callers naming them in opposite orders never deadlock, each key the
|
|
3
|
+
// very lock `lockKey` takes (one holder blocks the other), an org's keys never another org's, a
|
|
4
|
+
// throw undoing what the callback wrote, and the read path's scope and the blank-key refusal kept.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { Database, Tx } from '@ultimat3/entity';
|
|
8
|
+
import { entity, integer, text, uuid } from '@ultimat3/entity';
|
|
9
|
+
import { remember } from './entity-conformance-entities';
|
|
10
|
+
import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
|
|
11
|
+
import type { EntityDriverCheck, EntityDriverRun } from './entity-driver-conformance';
|
|
12
|
+
|
|
13
|
+
const tallies = remember(
|
|
14
|
+
entity('ec_lk_tallies', {
|
|
15
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), hits: integer() },
|
|
16
|
+
}),
|
|
17
|
+
);
|
|
18
|
+
const shared = remember(
|
|
19
|
+
entity('ec_lk_shared', { columns: { id: uuid().primaryKey(), label: text({ max: 10 }) } }),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
const SET = { tallies, shared };
|
|
23
|
+
type Db = Database<typeof SET>;
|
|
24
|
+
const [ORG_A, ORG_B] = [idAt('ba'), idAt('bb')];
|
|
25
|
+
const LOCK = ['lock'] as const;
|
|
26
|
+
const LOCK_TX = ['lock', 'transactions'] as const;
|
|
27
|
+
const RACERS = 20;
|
|
28
|
+
|
|
29
|
+
// A foreign failure handed to the subject: test input, never its verdict.
|
|
30
|
+
const CALLBACK_FAILED = new Error('the callback failed');
|
|
31
|
+
|
|
32
|
+
/** A turn of the event loop, so a read-modify-write has a window if the lock does not close it. */
|
|
33
|
+
const yieldNow = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 1));
|
|
34
|
+
|
|
35
|
+
const tally = (db: Db, id: string, hits = 0) => db.tallies.insert({ id, orgId: ORG_A, hits });
|
|
36
|
+
const hitsOf = async (db: Db, id: string) =>
|
|
37
|
+
(await db.tallies.where({ id, orgId: ORG_A }).one())?.hits;
|
|
38
|
+
|
|
39
|
+
/** Read, yield, write: loses updates unless every caller is held out of the window. */
|
|
40
|
+
const bump = async (db: Db, id: string, tx: Tx): Promise<void> => {
|
|
41
|
+
const row = await db.tallies.where({ id }).one();
|
|
42
|
+
await yieldNow();
|
|
43
|
+
await db.tallies.update(id, { hits: (row?.hits ?? 0) + 1 }, { tx });
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Until `settled()` or a contender is queued on a lock — what the driver REPORTS, never a clock. A
|
|
48
|
+
* check that stopped on a window of its own let a slow contender look like a blocked one.
|
|
49
|
+
*/
|
|
50
|
+
const queuedOr = async (waiters: () => number | Promise<number>, settled: () => boolean) => {
|
|
51
|
+
while (!settled() && (await waiters()) < 1) {
|
|
52
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const hold = (raw: EntityDriverRun) => raw.lockWaiters;
|
|
57
|
+
|
|
58
|
+
const checks: readonly EntityDriverCheck[] = [
|
|
59
|
+
checkOver(
|
|
60
|
+
SET,
|
|
61
|
+
`lockKeys: ${RACERS} racers naming two keys in opposite orders end at ${RACERS}, no deadlock`,
|
|
62
|
+
async (db) => {
|
|
63
|
+
await tally(db, idAt('b1'));
|
|
64
|
+
await inOrg(ORG_A, () =>
|
|
65
|
+
Promise.all(
|
|
66
|
+
Array.from({ length: RACERS }, (_, index) =>
|
|
67
|
+
db.tallies.lockKeys(index % 2 === 0 ? ['left', 'right'] : ['right', 'left'], (tx) =>
|
|
68
|
+
bump(db, idAt('b1'), tx),
|
|
69
|
+
),
|
|
70
|
+
),
|
|
71
|
+
),
|
|
72
|
+
);
|
|
73
|
+
expect(await hitsOf(db, idAt('b1'))).toBe(RACERS);
|
|
74
|
+
},
|
|
75
|
+
LOCK_TX,
|
|
76
|
+
),
|
|
77
|
+
checkOver(
|
|
78
|
+
SET,
|
|
79
|
+
'lockKeys answers the callback’s answer, and a throw rolls back all it wrote',
|
|
80
|
+
async (db) => {
|
|
81
|
+
await tally(db, idAt('b2'), 3);
|
|
82
|
+
await tally(db, idAt('b3'), 3);
|
|
83
|
+
const answer = await inOrg(ORG_A, () => db.tallies.lockKeys(['a', 'b'], () => 'held'));
|
|
84
|
+
const thrown = await inOrg(ORG_A, () =>
|
|
85
|
+
db.tallies
|
|
86
|
+
.lockKeys(['a', 'b'], async (tx) => {
|
|
87
|
+
await db.tallies.update(idAt('b2'), { hits: 4 }, { tx });
|
|
88
|
+
await db.tallies.update(idAt('b3'), { hits: 4 }, { tx });
|
|
89
|
+
throw CALLBACK_FAILED;
|
|
90
|
+
})
|
|
91
|
+
.then(
|
|
92
|
+
() => 'resolved',
|
|
93
|
+
(error: unknown) => error,
|
|
94
|
+
),
|
|
95
|
+
);
|
|
96
|
+
expect([answer, thrown]).toEqual(['held', CALLBACK_FAILED]);
|
|
97
|
+
expect([await hitsOf(db, idAt('b2')), await hitsOf(db, idAt('b3'))]).toEqual([3, 3]);
|
|
98
|
+
},
|
|
99
|
+
LOCK_TX,
|
|
100
|
+
),
|
|
101
|
+
checkOver(
|
|
102
|
+
SET,
|
|
103
|
+
'every key lockKeys names is the lock lockKey takes: a holder of either set waits the other',
|
|
104
|
+
async (db, raw) => {
|
|
105
|
+
const waiters = hold(raw);
|
|
106
|
+
// PGlite: one connection, so a contender waits on the client where no query sees it.
|
|
107
|
+
if (waiters === undefined) return;
|
|
108
|
+
for (const [holder, contender] of [
|
|
109
|
+
['lockKeys', 'lockKey'],
|
|
110
|
+
['lockKey', 'lockKeys'],
|
|
111
|
+
] as const) {
|
|
112
|
+
const order: string[] = [];
|
|
113
|
+
const entered = Promise.withResolvers<void>();
|
|
114
|
+
let contenderRan = false;
|
|
115
|
+
const take = (which: 'lockKey' | 'lockKeys', fn: () => unknown) =>
|
|
116
|
+
which === 'lockKey'
|
|
117
|
+
? db.tallies.lockKey('second', fn)
|
|
118
|
+
: db.tallies.lockKeys(['first', 'second'], fn);
|
|
119
|
+
await inOrg(ORG_A, () =>
|
|
120
|
+
Promise.all([
|
|
121
|
+
take(holder, async () => {
|
|
122
|
+
entered.resolve();
|
|
123
|
+
await queuedOr(waiters, () => contenderRan);
|
|
124
|
+
order.push('holder ending');
|
|
125
|
+
}),
|
|
126
|
+
(async () => {
|
|
127
|
+
await entered.promise;
|
|
128
|
+
await take(contender, () => {
|
|
129
|
+
contenderRan = true;
|
|
130
|
+
order.push('contender ran');
|
|
131
|
+
});
|
|
132
|
+
})(),
|
|
133
|
+
]),
|
|
134
|
+
);
|
|
135
|
+
expect([holder, order]).toEqual([holder, ['holder ending', 'contender ran']]);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
LOCK,
|
|
139
|
+
),
|
|
140
|
+
checkOver(
|
|
141
|
+
SET,
|
|
142
|
+
'org A holding its keys never blocks org B naming the same keys',
|
|
143
|
+
async (db, raw) => {
|
|
144
|
+
const waiters = hold(raw);
|
|
145
|
+
if (waiters === undefined) return;
|
|
146
|
+
const order: string[] = [];
|
|
147
|
+
const entered = Promise.withResolvers<void>();
|
|
148
|
+
let otherRan = false;
|
|
149
|
+
await Promise.all([
|
|
150
|
+
inOrg(ORG_A, () =>
|
|
151
|
+
db.tallies.lockKeys(['same', 'keys'], async () => {
|
|
152
|
+
entered.resolve();
|
|
153
|
+
await queuedOr(waiters, () => otherRan);
|
|
154
|
+
order.push('org A ending');
|
|
155
|
+
}),
|
|
156
|
+
),
|
|
157
|
+
(async () => {
|
|
158
|
+
await entered.promise;
|
|
159
|
+
await inOrg(ORG_B, () =>
|
|
160
|
+
db.tallies.lockKeys(['keys', 'same'], () => {
|
|
161
|
+
otherRan = true;
|
|
162
|
+
order.push('org B ran');
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
})(),
|
|
166
|
+
]);
|
|
167
|
+
expect(order).toEqual(['org B ran', 'org A ending']);
|
|
168
|
+
},
|
|
169
|
+
LOCK,
|
|
170
|
+
),
|
|
171
|
+
checkOver(
|
|
172
|
+
SET,
|
|
173
|
+
'lockKeys is scoped as a read; no key, a blank key or past 64 distinct keys is refused',
|
|
174
|
+
async (db) => {
|
|
175
|
+
let ran = 0;
|
|
176
|
+
const fn = () => {
|
|
177
|
+
ran += 1;
|
|
178
|
+
};
|
|
179
|
+
const keys = (n: number) => Array.from({ length: n }, (_, index) => `k${index}`);
|
|
180
|
+
const answers = [
|
|
181
|
+
await codeOf(() => db.tallies.lockKeys(['k'], fn)),
|
|
182
|
+
await codeOf(() => db.tallies.lockKeys(['k'], fn, { orgId: ORG_A })),
|
|
183
|
+
await codeOf(() => db.shared.lockKeys(['k', 'j', 'k'], fn)),
|
|
184
|
+
await codeOf(() => db.shared.lockKeys([...keys(64), 'k0'], fn)),
|
|
185
|
+
await codeOf(() => db.shared.lockKeys([], fn)),
|
|
186
|
+
await codeOf(() => db.shared.lockKeys(['k', ' '], fn)),
|
|
187
|
+
await codeOf(() => db.shared.lockKeys(keys(65), fn)),
|
|
188
|
+
];
|
|
189
|
+
expect([answers, ran]).toEqual([
|
|
190
|
+
[
|
|
191
|
+
'X_TENANCY_UNSCOPED',
|
|
192
|
+
'resolved',
|
|
193
|
+
'resolved',
|
|
194
|
+
'resolved',
|
|
195
|
+
'X_INVARIANT',
|
|
196
|
+
'X_INVARIANT',
|
|
197
|
+
'X_INVARIANT',
|
|
198
|
+
],
|
|
199
|
+
3,
|
|
200
|
+
]);
|
|
201
|
+
},
|
|
202
|
+
LOCK,
|
|
203
|
+
),
|
|
204
|
+
];
|
|
205
|
+
|
|
206
|
+
export const LOCK_KEYS_CHECKS: readonly EntityDriverCheck[] = checks;
|