@ultimat3/testing 31.9.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-checks.ts +12 -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-measures.ts +166 -0
- package/src/entity-conformance-version-lock.ts +204 -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,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;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Entity conformance · FILTERED aggregates: `countBy(col, { where })` counts only the rows the filter
|
|
2
|
+
// passes yet keeps every group the chain matched (with 0 — what makes it no `andWhere`), and
|
|
3
|
+
// `aggregate({ name: measure })` answers several measures, each under its own filter, over exactly
|
|
4
|
+
// the rows `count()` counts: a count is 0 on nothing, a sum is null, money stays money.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { Database } from '@ultimat3/entity';
|
|
8
|
+
import { entity, integer, money, 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 reactions = remember(
|
|
14
|
+
entity('ec_m_reactions', {
|
|
15
|
+
columns: {
|
|
16
|
+
id: uuid().primaryKey(),
|
|
17
|
+
orgId: uuid().tenant(),
|
|
18
|
+
postId: uuid().nullable(),
|
|
19
|
+
kind: text({ max: 10 }),
|
|
20
|
+
weight: integer(),
|
|
21
|
+
tip: money(),
|
|
22
|
+
deletedAt: timestamp().nullable(),
|
|
23
|
+
},
|
|
24
|
+
}),
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
const SET = { reactions };
|
|
28
|
+
type Db = Database<typeof SET>;
|
|
29
|
+
type Reaction = typeof reactions.$row;
|
|
30
|
+
const [ORG, OTHER_ORG] = [idAt('9a'), idAt('9b')];
|
|
31
|
+
const [POST_A, POST_B, POST_C] = [idAt('9aa'), idAt('9bb'), idAt('9cc')];
|
|
32
|
+
const eur = (minor: number) => ({ minor, currency: 'EUR' });
|
|
33
|
+
|
|
34
|
+
const reaction = (index: number, over: Partial<Reaction>): Reaction => ({
|
|
35
|
+
id: idAt(9000 + index),
|
|
36
|
+
orgId: ORG,
|
|
37
|
+
postId: POST_A,
|
|
38
|
+
kind: 'like',
|
|
39
|
+
weight: 1,
|
|
40
|
+
tip: eur(0),
|
|
41
|
+
deletedAt: null,
|
|
42
|
+
...over,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/** A: like, like, love · B: like · C: love · none: love — then a deleted love and another org's. */
|
|
46
|
+
const SEED: readonly Reaction[] = [
|
|
47
|
+
reaction(1, { weight: 2, tip: eur(100) }),
|
|
48
|
+
reaction(2, { weight: 3, tip: eur(50) }),
|
|
49
|
+
reaction(3, { kind: 'love', weight: 5, tip: eur(25) }),
|
|
50
|
+
reaction(4, { postId: POST_B, weight: 7 }),
|
|
51
|
+
reaction(5, { postId: POST_C, kind: 'love', weight: 11 }),
|
|
52
|
+
reaction(6, { postId: null, kind: 'love', weight: 13 }),
|
|
53
|
+
reaction(7, { kind: 'love', weight: 1000, deletedAt: new Date('2026-02-02T00:00:00.000Z') }),
|
|
54
|
+
reaction(8, { kind: 'love', weight: 1000, orgId: OTHER_ORG }),
|
|
55
|
+
];
|
|
56
|
+
|
|
57
|
+
const seeded = async (db: Db): Promise<void> => {
|
|
58
|
+
await db.reactions.insertAll(SEED);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const COUNT_BY = ['aggregate:countBy'] as const;
|
|
62
|
+
|
|
63
|
+
const countBy: readonly EntityDriverCheck[] = [
|
|
64
|
+
checkOver(
|
|
65
|
+
SET,
|
|
66
|
+
'countBy with a where counts the rows it passes, and keeps every matched group at 0',
|
|
67
|
+
async (db) => {
|
|
68
|
+
await seeded(db);
|
|
69
|
+
const loves = await inOrg(ORG, () =>
|
|
70
|
+
db.reactions.where({ orgId: ORG }).countBy('postId', { where: [['kind', 'eq', 'love']] }),
|
|
71
|
+
);
|
|
72
|
+
expect([...loves].sort(([a], [b]) => String(a).localeCompare(String(b)))).toEqual([
|
|
73
|
+
[POST_A, 1],
|
|
74
|
+
[POST_B, 0],
|
|
75
|
+
[POST_C, 1],
|
|
76
|
+
[null, 1],
|
|
77
|
+
]);
|
|
78
|
+
// The chain still decides which groups exist: the filter narrows counts, never groups.
|
|
79
|
+
const heavy = await inOrg(ORG, () =>
|
|
80
|
+
db.reactions
|
|
81
|
+
.andWhere('postId', 'in', [POST_A, POST_B])
|
|
82
|
+
.countBy('postId', { where: [['weight', 'gte', 3]] }),
|
|
83
|
+
);
|
|
84
|
+
expect([heavy.get(POST_A), heavy.get(POST_B), heavy.has(POST_C)]).toEqual([2, 1, false]);
|
|
85
|
+
},
|
|
86
|
+
COUNT_BY,
|
|
87
|
+
),
|
|
88
|
+
checkOver(
|
|
89
|
+
SET,
|
|
90
|
+
'a countBy filter naming no column of the entity is refused, never ignored',
|
|
91
|
+
async (db) => {
|
|
92
|
+
await seeded(db);
|
|
93
|
+
const refused = await inOrg(ORG, () =>
|
|
94
|
+
codeOf(() =>
|
|
95
|
+
db.reactions.countBy('postId', { where: [['nope' as never, 'eq', 'x' as never]] }),
|
|
96
|
+
),
|
|
97
|
+
);
|
|
98
|
+
expect(refused).toBe('X_AGGREGATE_UNSUPPORTED');
|
|
99
|
+
},
|
|
100
|
+
COUNT_BY,
|
|
101
|
+
),
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
const measures: readonly EntityDriverCheck[] = [
|
|
105
|
+
checkOver(
|
|
106
|
+
SET,
|
|
107
|
+
'aggregate answers every measure under its own filter, over the rows count() counts',
|
|
108
|
+
async (db) => {
|
|
109
|
+
await seeded(db);
|
|
110
|
+
const answer = await inOrg(ORG, () =>
|
|
111
|
+
db.reactions.where({ orgId: ORG }).aggregate({
|
|
112
|
+
all: { fn: 'count' },
|
|
113
|
+
loves: { fn: 'count', where: [['kind', 'eq', 'love']] },
|
|
114
|
+
weight: { fn: 'sum', column: 'weight' },
|
|
115
|
+
loveWeight: { fn: 'sum', column: 'weight', where: [['kind', 'eq', 'love']] },
|
|
116
|
+
heaviest: { fn: 'max', column: 'weight', where: [['kind', 'eq', 'like']] },
|
|
117
|
+
tips: { fn: 'sum', column: 'tip', where: [['postId', 'eq', POST_A]] },
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
expect(answer).toEqual({
|
|
121
|
+
all: 6,
|
|
122
|
+
loves: 3,
|
|
123
|
+
weight: '41',
|
|
124
|
+
loveWeight: '29',
|
|
125
|
+
heaviest: 7,
|
|
126
|
+
tips: eur(175),
|
|
127
|
+
});
|
|
128
|
+
expect(await inOrg(ORG, () => db.reactions.count())).toBe(answer.all);
|
|
129
|
+
},
|
|
130
|
+
['aggregate:sum', 'aggregate:max'],
|
|
131
|
+
),
|
|
132
|
+
checkOver(
|
|
133
|
+
SET,
|
|
134
|
+
'a measure whose filter passes nothing is 0 for a count and null for the rest',
|
|
135
|
+
async (db) => {
|
|
136
|
+
await seeded(db);
|
|
137
|
+
const none = [['kind', 'eq', 'nope']] as const;
|
|
138
|
+
const answer = await inOrg(ORG, () =>
|
|
139
|
+
db.reactions.aggregate({
|
|
140
|
+
n: { fn: 'count', where: none },
|
|
141
|
+
sum: { fn: 'sum', column: 'weight', where: none },
|
|
142
|
+
avg: { fn: 'avg', column: 'weight', where: none },
|
|
143
|
+
min: { fn: 'min', column: 'weight', where: none },
|
|
144
|
+
tips: { fn: 'sum', column: 'tip', where: none },
|
|
145
|
+
}),
|
|
146
|
+
);
|
|
147
|
+
expect(answer).toEqual({ n: 0, sum: null, avg: null, min: null, tips: null });
|
|
148
|
+
},
|
|
149
|
+
['aggregate:sum', 'aggregate:avg', 'aggregate:min'],
|
|
150
|
+
),
|
|
151
|
+
checkOver(
|
|
152
|
+
SET,
|
|
153
|
+
'counts alone need no aggregate capability; with no actor on a tenant table they are refused',
|
|
154
|
+
async (db) => {
|
|
155
|
+
await seeded(db);
|
|
156
|
+
const counts = {
|
|
157
|
+
n: { fn: 'count' },
|
|
158
|
+
loves: { fn: 'count', where: [['kind', 'eq', 'love']] },
|
|
159
|
+
} as const;
|
|
160
|
+
expect(await inOrg(ORG, () => db.reactions.aggregate(counts))).toEqual({ n: 6, loves: 3 });
|
|
161
|
+
expect(await codeOf(() => db.reactions.aggregate(counts))).toBe('X_TENANCY_UNSCOPED');
|
|
162
|
+
},
|
|
163
|
+
),
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
export const MEASURE_CHECKS: readonly EntityDriverCheck[] = [...countBy, ...measures];
|