bunsane 0.3.0 → 0.3.2
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/.claude/scheduled_tasks.lock +1 -0
- package/CHANGELOG.md +104 -0
- package/CLAUDE.md +20 -0
- package/config/cache.config.ts +35 -1
- package/core/App.ts +24 -1060
- package/core/ArcheType.ts +78 -2110
- package/core/Entity.ts +136 -41
- package/core/RequestContext.ts +85 -36
- package/core/RequestLoaders.ts +89 -31
- package/core/SchedulerManager.ts +13 -13
- package/core/app/bootstrap.ts +133 -0
- package/core/app/cors.ts +94 -0
- package/core/app/graphqlSetup.ts +56 -0
- package/core/app/healthEndpoints.ts +31 -0
- package/core/app/metricsCollector.ts +27 -0
- package/core/app/preparedStatementWarmup.ts +55 -0
- package/core/app/processHandlers.ts +43 -0
- package/core/app/requestRouter.ts +309 -0
- package/core/app/restRegistry.ts +72 -0
- package/core/app/shutdown.ts +97 -0
- package/core/app/studioRouter.ts +83 -0
- package/core/archetype/customTypes.ts +100 -0
- package/core/archetype/decorators.ts +171 -0
- package/core/archetype/fieldResolvers.ts +621 -0
- package/core/archetype/helpers.ts +29 -0
- package/core/archetype/relationLoader.ts +118 -0
- package/core/archetype/schemaBuilder.ts +141 -0
- package/core/archetype/weaver.ts +218 -0
- package/core/archetype/zodSchemaBuilder.ts +527 -0
- package/core/cache/CacheManager.ts +144 -9
- package/core/components/BaseComponent.ts +12 -2
- package/core/middleware/AccessLog.ts +8 -1
- package/database/PreparedStatementCache.ts +17 -16
- package/database/cancellable.ts +22 -0
- package/database/instrumentedDb.ts +141 -0
- package/docs/RFC_APP_REFACTOR.md +248 -0
- package/docs/RFC_REFACTOR_TARGETS.md +251 -0
- package/package.json +1 -1
- package/query/ComponentInclusionNode.ts +5 -5
- package/query/Query.ts +65 -48
- package/service/ServiceRegistry.ts +7 -1
- package/service/index.ts +4 -2
- package/tests/integration/loaders/RequestLoaders.abort.test.ts +82 -0
- package/tests/integration/query/Query.abort.test.ts +66 -0
- package/tests/unit/cache/CacheManager.test.ts +152 -1
- package/tests/unit/database/cancellable.test.ts +81 -0
- package/tests/unit/database/instrumentedDb.test.ts +160 -0
- package/tests/unit/entity/Entity.components.test.ts +73 -0
- package/tests/unit/entity/Entity.drainSideEffects.test.ts +51 -0
- package/tests/unit/entity/Entity.reload.test.ts +63 -0
- package/tests/unit/entity/Entity.requireComponents.test.ts +72 -0
- package/tests/unit/query/Query.emptyString.test.ts +69 -0
- package/tests/unit/query/Query.test.ts +6 -4
- package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +95 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for `database/cancellable.ts` — the shared `runWithSignal`
|
|
3
|
+
* helper extracted from Entity.ts so every framework call-site uses the
|
|
4
|
+
* same abort-on-cancel pattern.
|
|
5
|
+
*/
|
|
6
|
+
import { describe, test, expect } from 'bun:test';
|
|
7
|
+
import { runWithSignal } from '../../../database/cancellable';
|
|
8
|
+
|
|
9
|
+
function makeFakeQuery<T>(opts: { delayMs?: number; value?: T; rejectWith?: Error }) {
|
|
10
|
+
let cancelFn: () => void = () => {};
|
|
11
|
+
const promise: any = new Promise<T>((resolve, reject) => {
|
|
12
|
+
const handle = setTimeout(() => {
|
|
13
|
+
if (opts.rejectWith) reject(opts.rejectWith);
|
|
14
|
+
else resolve(opts.value as T);
|
|
15
|
+
}, opts.delayMs ?? 1);
|
|
16
|
+
cancelFn = () => {
|
|
17
|
+
clearTimeout(handle);
|
|
18
|
+
promise.cancelled = true;
|
|
19
|
+
reject(Object.assign(new Error('Query cancelled'), { name: 'AbortError' }));
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
// Swallow unhandled rejection when the helper throws on pre-abort before
|
|
23
|
+
// awaiting `q`. Real Bun SQL Query objects don't surface this as an
|
|
24
|
+
// unhandled rejection because the runtime captures the cancel reason.
|
|
25
|
+
promise.catch(() => {});
|
|
26
|
+
promise.cancel = cancelFn;
|
|
27
|
+
promise.cancelled = false;
|
|
28
|
+
return promise;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe('runWithSignal', () => {
|
|
32
|
+
test('resolves normally without signal', async () => {
|
|
33
|
+
const q = makeFakeQuery({ value: [1, 2, 3] });
|
|
34
|
+
const r = await runWithSignal<number[]>(q);
|
|
35
|
+
expect(r).toEqual([1, 2, 3]);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('resolves normally when signal never fires', async () => {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const q = makeFakeQuery({ value: 'done' });
|
|
41
|
+
const r = await runWithSignal<string>(q, controller.signal);
|
|
42
|
+
expect(r).toBe('done');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('rejects immediately when signal is pre-aborted', async () => {
|
|
46
|
+
const controller = new AbortController();
|
|
47
|
+
controller.abort(new Error('pre-aborted'));
|
|
48
|
+
const q = makeFakeQuery({ delayMs: 5000 });
|
|
49
|
+
await expect(runWithSignal(q, controller.signal)).rejects.toBeDefined();
|
|
50
|
+
// Cancelling the underlying query is best-effort; verify cancel ran.
|
|
51
|
+
expect(q.cancelled).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('cancels query mid-flight when signal aborts', async () => {
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const q = makeFakeQuery({ delayMs: 5000 });
|
|
57
|
+
queueMicrotask(() => controller.abort(new Error('mid-flight')));
|
|
58
|
+
|
|
59
|
+
await expect(runWithSignal(q, controller.signal)).rejects.toBeDefined();
|
|
60
|
+
expect(q.cancelled).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('removes abort listener on success', async () => {
|
|
64
|
+
const controller = new AbortController();
|
|
65
|
+
let listenerCount = 0;
|
|
66
|
+
const origAdd = controller.signal.addEventListener.bind(controller.signal);
|
|
67
|
+
const origRemove = controller.signal.removeEventListener.bind(controller.signal);
|
|
68
|
+
controller.signal.addEventListener = ((...args: any[]) => {
|
|
69
|
+
listenerCount++;
|
|
70
|
+
return (origAdd as any)(...args);
|
|
71
|
+
}) as any;
|
|
72
|
+
controller.signal.removeEventListener = ((...args: any[]) => {
|
|
73
|
+
listenerCount--;
|
|
74
|
+
return (origRemove as any)(...args);
|
|
75
|
+
}) as any;
|
|
76
|
+
|
|
77
|
+
const q = makeFakeQuery({ value: 1 });
|
|
78
|
+
await runWithSignal(q, controller.signal);
|
|
79
|
+
expect(listenerCount).toBe(0);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for database/instrumentedDb.ts.
|
|
3
|
+
*
|
|
4
|
+
* Uses a fake `db` that returns a `cancel()`able promise-like to exercise
|
|
5
|
+
* the timing + abort path without a real Postgres backend.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, test, expect, beforeEach } from 'bun:test';
|
|
8
|
+
import {
|
|
9
|
+
timedUnsafe,
|
|
10
|
+
incrementDataLoaderCall,
|
|
11
|
+
getDbStats,
|
|
12
|
+
resetDbStats,
|
|
13
|
+
type PerRequestCounters,
|
|
14
|
+
} from '../../../database/instrumentedDb';
|
|
15
|
+
|
|
16
|
+
interface FakeQuery<T> extends Promise<T> {
|
|
17
|
+
cancel(): void;
|
|
18
|
+
cancelled: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function makeFakeDb(opts: { delayMs?: number; rejectWith?: Error; rows?: any[] } = {}) {
|
|
22
|
+
return {
|
|
23
|
+
unsafe(_sql: string, _params: any[]): FakeQuery<any[]> {
|
|
24
|
+
let cancelFn: () => void = () => {};
|
|
25
|
+
const promise: any = new Promise<any[]>((resolve, reject) => {
|
|
26
|
+
const handle = setTimeout(() => {
|
|
27
|
+
if (opts.rejectWith) reject(opts.rejectWith);
|
|
28
|
+
else resolve(opts.rows ?? []);
|
|
29
|
+
}, opts.delayMs ?? 1);
|
|
30
|
+
cancelFn = () => {
|
|
31
|
+
clearTimeout(handle);
|
|
32
|
+
promise.cancelled = true;
|
|
33
|
+
reject(Object.assign(new Error('Query cancelled'), { name: 'AbortError' }));
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
// Swallow unhandled rejection on pre-abort cancel path.
|
|
37
|
+
promise.catch(() => {});
|
|
38
|
+
promise.cancel = cancelFn;
|
|
39
|
+
promise.cancelled = false;
|
|
40
|
+
return promise as FakeQuery<any[]>;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('timedUnsafe', () => {
|
|
46
|
+
beforeEach(() => resetDbStats());
|
|
47
|
+
|
|
48
|
+
test('records totalCount and totalMs on success', async () => {
|
|
49
|
+
const db = makeFakeDb({ rows: [{ id: 1 }], delayMs: 5 });
|
|
50
|
+
const result = await timedUnsafe(db as any, 'SELECT 1', []);
|
|
51
|
+
expect(result).toEqual([{ id: 1 }]);
|
|
52
|
+
|
|
53
|
+
const stats = getDbStats();
|
|
54
|
+
expect(stats.totalCount).toBe(1);
|
|
55
|
+
expect(stats.totalMs).toBeGreaterThanOrEqual(1);
|
|
56
|
+
expect(stats.maxMs).toBeGreaterThanOrEqual(1);
|
|
57
|
+
expect(stats.abortedCount).toBe(0);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('increments dbQueryCount on perRequest counters', async () => {
|
|
61
|
+
const db = makeFakeDb();
|
|
62
|
+
const perReq: PerRequestCounters = { dbQueryCount: 0 };
|
|
63
|
+
await timedUnsafe(db as any, 'SELECT 1', [], undefined, perReq);
|
|
64
|
+
await timedUnsafe(db as any, 'SELECT 1', [], undefined, perReq);
|
|
65
|
+
expect(perReq.dbQueryCount).toBe(2);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('aborted query rejects with AbortError and records abortedCount', async () => {
|
|
69
|
+
const db = makeFakeDb({ delayMs: 1000 });
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
const promise = timedUnsafe(db as any, 'SELECT pg_sleep(10)', [], controller.signal);
|
|
72
|
+
|
|
73
|
+
queueMicrotask(() => controller.abort(new Error('test abort')));
|
|
74
|
+
|
|
75
|
+
await expect(promise).rejects.toBeDefined();
|
|
76
|
+
|
|
77
|
+
const stats = getDbStats();
|
|
78
|
+
expect(stats.totalCount).toBe(1);
|
|
79
|
+
expect(stats.abortedCount).toBe(1);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('pre-aborted signal cancels before await', async () => {
|
|
83
|
+
const db = makeFakeDb({ delayMs: 1000 });
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
controller.abort(new Error('pre-aborted'));
|
|
86
|
+
|
|
87
|
+
const promise = timedUnsafe(db as any, 'SELECT 1', [], controller.signal);
|
|
88
|
+
await expect(promise).rejects.toBeDefined();
|
|
89
|
+
|
|
90
|
+
const stats = getDbStats();
|
|
91
|
+
expect(stats.abortedCount).toBe(1);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('slow query above threshold increments slowCount', async () => {
|
|
95
|
+
// Slow threshold defaults to 500ms; we cannot reasonably wait that long
|
|
96
|
+
// in a unit test, so we override via env at module load — fall back to
|
|
97
|
+
// asserting the slow path is reachable by passing a tiny synthetic
|
|
98
|
+
// delay larger than zero and checking that the slowCount path triggers
|
|
99
|
+
// only when over threshold. Direct assertion: with default threshold,
|
|
100
|
+
// a 5ms query should NOT mark slow.
|
|
101
|
+
const db = makeFakeDb({ delayMs: 5 });
|
|
102
|
+
await timedUnsafe(db as any, 'SELECT 1', []);
|
|
103
|
+
const stats = getDbStats();
|
|
104
|
+
expect(stats.slowCount).toBe(0);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe('incrementDataLoaderCall', () => {
|
|
109
|
+
beforeEach(() => resetDbStats());
|
|
110
|
+
|
|
111
|
+
test('increments per-kind global stats', () => {
|
|
112
|
+
incrementDataLoaderCall('entity');
|
|
113
|
+
incrementDataLoaderCall('component');
|
|
114
|
+
incrementDataLoaderCall('component');
|
|
115
|
+
incrementDataLoaderCall('relation');
|
|
116
|
+
|
|
117
|
+
const stats = getDbStats();
|
|
118
|
+
expect(stats.dataLoaderCalls.entity).toBe(1);
|
|
119
|
+
expect(stats.dataLoaderCalls.component).toBe(2);
|
|
120
|
+
expect(stats.dataLoaderCalls.relation).toBe(1);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('increments perRequest.dataLoaderCalls when supplied', () => {
|
|
124
|
+
const perReq = {
|
|
125
|
+
dbQueryCount: 0,
|
|
126
|
+
dataLoaderCalls: { entity: 0, component: 0, relation: 0 },
|
|
127
|
+
};
|
|
128
|
+
incrementDataLoaderCall('entity', perReq);
|
|
129
|
+
incrementDataLoaderCall('component', perReq);
|
|
130
|
+
incrementDataLoaderCall('component', perReq);
|
|
131
|
+
expect(perReq.dataLoaderCalls.entity).toBe(1);
|
|
132
|
+
expect(perReq.dataLoaderCalls.component).toBe(2);
|
|
133
|
+
expect(perReq.dataLoaderCalls.relation).toBe(0);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
describe('getDbStats', () => {
|
|
138
|
+
beforeEach(() => resetDbStats());
|
|
139
|
+
|
|
140
|
+
test('reports avgMs as totalMs / totalCount', async () => {
|
|
141
|
+
const db = makeFakeDb({ delayMs: 4 });
|
|
142
|
+
await timedUnsafe(db as any, 'SELECT 1', []);
|
|
143
|
+
await timedUnsafe(db as any, 'SELECT 1', []);
|
|
144
|
+
const stats = getDbStats();
|
|
145
|
+
expect(stats.totalCount).toBe(2);
|
|
146
|
+
// avgMs is rounded to 2 decimals while totalMs is integer-rounded,
|
|
147
|
+
// so allow ±0.5ms tolerance against the unrounded computation.
|
|
148
|
+
expect(Math.abs(stats.avgMs - stats.totalMs / 2)).toBeLessThan(1);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('returns zero state after reset', () => {
|
|
152
|
+
const stats = getDbStats();
|
|
153
|
+
expect(stats.totalCount).toBe(0);
|
|
154
|
+
expect(stats.totalMs).toBe(0);
|
|
155
|
+
expect(stats.maxMs).toBe(0);
|
|
156
|
+
expect(stats.slowCount).toBe(0);
|
|
157
|
+
expect(stats.abortedCount).toBe(0);
|
|
158
|
+
expect(stats.dataLoaderCalls).toEqual({ entity: 0, component: 0, relation: 0 });
|
|
159
|
+
});
|
|
160
|
+
});
|
|
@@ -187,6 +187,79 @@ describe('Entity Component Management', () => {
|
|
|
187
187
|
|
|
188
188
|
expect(data?.createdAt).toBe('2024-01-15T10:30:00.000Z');
|
|
189
189
|
});
|
|
190
|
+
|
|
191
|
+
test('serializableData throws descriptive error on invalid Date', () => {
|
|
192
|
+
const entity = new Entity();
|
|
193
|
+
entity.add(TestOrder, {
|
|
194
|
+
orderNumber: 'ORD-002',
|
|
195
|
+
total: 50,
|
|
196
|
+
status: 'pending',
|
|
197
|
+
createdAt: new Date('not-a-date')
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const component = entity.getInMemory(TestOrder);
|
|
201
|
+
expect(() => component?.serializableData()).toThrow(
|
|
202
|
+
/Invalid Date for property 'createdAt' on component 'TestOrder'/
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test('serializableData throws on Date type mismatch', () => {
|
|
207
|
+
const entity = new Entity();
|
|
208
|
+
entity.add(TestOrder, {
|
|
209
|
+
orderNumber: 'ORD-003',
|
|
210
|
+
total: 50,
|
|
211
|
+
status: 'pending',
|
|
212
|
+
createdAt: '2024-01-15' as any
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const component = entity.getInMemory(TestOrder);
|
|
216
|
+
expect(() => component?.serializableData()).toThrow(
|
|
217
|
+
/Type mismatch for property 'createdAt' on component 'TestOrder': expected Date, got string/
|
|
218
|
+
);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test('serializableData throws on NaN number', () => {
|
|
222
|
+
const entity = new Entity();
|
|
223
|
+
entity.add(TestOrder, {
|
|
224
|
+
orderNumber: 'ORD-004',
|
|
225
|
+
total: NaN,
|
|
226
|
+
status: 'pending',
|
|
227
|
+
createdAt: new Date()
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const component = entity.getInMemory(TestOrder);
|
|
231
|
+
expect(() => component?.serializableData()).toThrow(
|
|
232
|
+
/Invalid number for property 'total' on component 'TestOrder'/
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test('serializableData throws on Infinity number', () => {
|
|
237
|
+
const entity = new Entity();
|
|
238
|
+
entity.add(TestOrder, {
|
|
239
|
+
orderNumber: 'ORD-005',
|
|
240
|
+
total: Infinity,
|
|
241
|
+
status: 'pending',
|
|
242
|
+
createdAt: new Date()
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
const component = entity.getInMemory(TestOrder);
|
|
246
|
+
expect(() => component?.serializableData()).toThrow(
|
|
247
|
+
/Invalid number for property 'total' on component 'TestOrder'/
|
|
248
|
+
);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
test('serializableData allows null/undefined for nullable Date/Number', () => {
|
|
252
|
+
const entity = new Entity();
|
|
253
|
+
entity.add(TestOrder, {
|
|
254
|
+
orderNumber: 'ORD-006',
|
|
255
|
+
total: 0,
|
|
256
|
+
status: 'pending',
|
|
257
|
+
createdAt: null as any
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const component = entity.getInMemory(TestOrder);
|
|
261
|
+
expect(() => component?.serializableData()).not.toThrow();
|
|
262
|
+
});
|
|
190
263
|
});
|
|
191
264
|
|
|
192
265
|
describe('component state', () => {
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BUNSANE-001 defensive harness: verify Entity.drainPendingSideEffects()
|
|
3
|
+
* awaits post-commit work scheduled via queueMicrotask from save(), so
|
|
4
|
+
* tests under PGlite can settle prior-file background work before
|
|
5
|
+
* asserting against freshly-committed state.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, test, expect, beforeAll } from 'bun:test';
|
|
8
|
+
import { Entity } from '../../../core/Entity';
|
|
9
|
+
import { BaseComponent } from '../../../core/components/BaseComponent';
|
|
10
|
+
import { Component, CompData } from '../../../core/components/Decorators';
|
|
11
|
+
import { ensureComponentsRegistered } from '../../utils';
|
|
12
|
+
|
|
13
|
+
@Component
|
|
14
|
+
class DrainMarker extends BaseComponent {
|
|
15
|
+
@CompData()
|
|
16
|
+
value: string = '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe('Entity.drainPendingSideEffects', () => {
|
|
20
|
+
beforeAll(async () => {
|
|
21
|
+
await ensureComponentsRegistered(DrainMarker);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('no-op when nothing is pending', async () => {
|
|
25
|
+
await expect(Entity.drainPendingSideEffects(100)).resolves.toBeUndefined();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('awaits post-commit side effects scheduled by save()', async () => {
|
|
29
|
+
const saved = Entity.Create();
|
|
30
|
+
saved.add(DrainMarker, { value: 'pending' });
|
|
31
|
+
await saved.save();
|
|
32
|
+
|
|
33
|
+
// runPostCommitSideEffects is queued as a microtask. drain() must
|
|
34
|
+
// settle it before returning.
|
|
35
|
+
await Entity.drainPendingSideEffects(2_000);
|
|
36
|
+
|
|
37
|
+
// A second drain is a no-op.
|
|
38
|
+
await Entity.drainPendingSideEffects(100);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('bounded by timeout, returns even if drain exceeds it', async () => {
|
|
42
|
+
const saved = Entity.Create();
|
|
43
|
+
saved.add(DrainMarker, { value: 'bounded' });
|
|
44
|
+
await saved.save();
|
|
45
|
+
|
|
46
|
+
const start = Date.now();
|
|
47
|
+
await Entity.drainPendingSideEffects(1);
|
|
48
|
+
const elapsed = Date.now() - start;
|
|
49
|
+
expect(elapsed).toBeLessThan(500);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for Entity.reload (BUNSANE-006).
|
|
3
|
+
* Ensures in-memory component state is discarded and re-hydrated from DB.
|
|
4
|
+
*/
|
|
5
|
+
import { describe, test, expect, beforeAll } from 'bun:test';
|
|
6
|
+
import { Entity } from '../../../core/Entity';
|
|
7
|
+
import { BaseComponent } from '../../../core/components/BaseComponent';
|
|
8
|
+
import { Component, CompData } from '../../../core/components/Decorators';
|
|
9
|
+
import { ensureComponentsRegistered } from '../../utils';
|
|
10
|
+
import db from '../../../database';
|
|
11
|
+
|
|
12
|
+
@Component
|
|
13
|
+
class ReloadStatus extends BaseComponent {
|
|
14
|
+
@CompData()
|
|
15
|
+
value: string = '';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('Entity.reload', () => {
|
|
19
|
+
beforeAll(async () => {
|
|
20
|
+
await ensureComponentsRegistered(ReloadStatus);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('no-op on entity without a valid id', async () => {
|
|
24
|
+
const entity = new Entity('');
|
|
25
|
+
await expect(entity.reload()).resolves.toBe(entity);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('refreshes in-memory data after raw-SQL write', async () => {
|
|
29
|
+
const saved = Entity.Create();
|
|
30
|
+
saved.add(ReloadStatus, { value: 'before' });
|
|
31
|
+
await saved.save();
|
|
32
|
+
|
|
33
|
+
const typeId = new ReloadStatus().getTypeID();
|
|
34
|
+
|
|
35
|
+
// Write new value via raw SQL — bypasses entity cache invalidation.
|
|
36
|
+
await db.unsafe(
|
|
37
|
+
`UPDATE components SET data = data || '{"value":"after"}'::jsonb
|
|
38
|
+
WHERE entity_id = $1 AND type_id = $2`,
|
|
39
|
+
[saved.id, typeId]
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
// In-memory copy still holds stale value.
|
|
43
|
+
expect(saved.getInMemory(ReloadStatus)?.value).toBe('before');
|
|
44
|
+
|
|
45
|
+
const returned = await saved.reload();
|
|
46
|
+
expect(returned).toBe(saved);
|
|
47
|
+
expect(saved.getInMemory(ReloadStatus)?.value).toBe('after');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('hydrates a bare Entity instance from DB', async () => {
|
|
51
|
+
const saved = Entity.Create();
|
|
52
|
+
saved.add(ReloadStatus, { value: 'hydrated' });
|
|
53
|
+
await saved.save();
|
|
54
|
+
|
|
55
|
+
const bare = new Entity(saved.id);
|
|
56
|
+
expect(bare.componentList().length).toBe(0);
|
|
57
|
+
|
|
58
|
+
await bare.reload();
|
|
59
|
+
|
|
60
|
+
expect(bare.hasInMemory(ReloadStatus)).toBe(true);
|
|
61
|
+
expect(bare.getInMemory(ReloadStatus)?.value).toBe('hydrated');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for Entity.requireComponents (BUNSANE-003).
|
|
3
|
+
* Ensures ComponentTargetHook includeComponents matching sees tag
|
|
4
|
+
* components that weren't eagerly loaded.
|
|
5
|
+
*/
|
|
6
|
+
import { describe, test, expect, beforeAll } from 'bun:test';
|
|
7
|
+
import { Entity } from '../../../core/Entity';
|
|
8
|
+
import { BaseComponent } from '../../../core/components/BaseComponent';
|
|
9
|
+
import { Component, CompData } from '../../../core/components/Decorators';
|
|
10
|
+
import { TestUser } from '../../fixtures/components';
|
|
11
|
+
import { ensureComponentsRegistered } from '../../utils';
|
|
12
|
+
|
|
13
|
+
@Component
|
|
14
|
+
class ReqTag extends BaseComponent {}
|
|
15
|
+
|
|
16
|
+
@Component
|
|
17
|
+
class ReqData extends BaseComponent {
|
|
18
|
+
@CompData()
|
|
19
|
+
value: string = '';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('Entity.requireComponents', () => {
|
|
23
|
+
beforeAll(async () => {
|
|
24
|
+
await ensureComponentsRegistered(TestUser, ReqTag, ReqData);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('no-op for empty list', async () => {
|
|
28
|
+
const entity = Entity.Create();
|
|
29
|
+
await expect(entity.requireComponents([])).resolves.toBeUndefined();
|
|
30
|
+
expect(entity.componentList().length).toBe(0);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('does nothing when components already in memory', async () => {
|
|
34
|
+
const entity = Entity.Create();
|
|
35
|
+
entity.add(ReqTag);
|
|
36
|
+
const before = entity.componentList().length;
|
|
37
|
+
await entity.requireComponents([ReqTag]);
|
|
38
|
+
expect(entity.componentList().length).toBe(before);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('hydrates missing components from DB after save', async () => {
|
|
42
|
+
const saved = Entity.Create();
|
|
43
|
+
saved.add(ReqTag);
|
|
44
|
+
saved.add(ReqData, { value: 'hello' });
|
|
45
|
+
await saved.save();
|
|
46
|
+
|
|
47
|
+
const loaded = new Entity(saved.id);
|
|
48
|
+
expect(loaded.componentList().length).toBe(0);
|
|
49
|
+
|
|
50
|
+
await loaded.requireComponents([ReqTag, ReqData]);
|
|
51
|
+
|
|
52
|
+
expect(loaded.hasInMemory(ReqTag)).toBe(true);
|
|
53
|
+
expect(loaded.hasInMemory(ReqData)).toBe(true);
|
|
54
|
+
expect(loaded.getInMemory(ReqData)?.value).toBe('hello');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('only fetches missing components, not already-loaded ones', async () => {
|
|
58
|
+
const saved = Entity.Create();
|
|
59
|
+
saved.add(ReqTag);
|
|
60
|
+
saved.add(ReqData, { value: 'mix' });
|
|
61
|
+
await saved.save();
|
|
62
|
+
|
|
63
|
+
const loaded = new Entity(saved.id);
|
|
64
|
+
await loaded.requireComponents([ReqData]);
|
|
65
|
+
expect(loaded.hasInMemory(ReqData)).toBe(true);
|
|
66
|
+
expect(loaded.hasInMemory(ReqTag)).toBe(false);
|
|
67
|
+
|
|
68
|
+
await loaded.requireComponents([ReqTag, ReqData]);
|
|
69
|
+
expect(loaded.hasInMemory(ReqTag)).toBe(true);
|
|
70
|
+
expect(loaded.getInMemory(ReqData)?.value).toBe('mix');
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Empty-string filter support. JSONB text extraction (c.data->>'field')
|
|
3
|
+
* returns text, so `= ''` / `!= ''` / LIKE against empty string are
|
|
4
|
+
* legitimate. UUID-cast path is gated on a regex that empty cannot match.
|
|
5
|
+
*/
|
|
6
|
+
import { describe, test, expect, beforeAll } from 'bun:test';
|
|
7
|
+
import { Entity } from '../../../core/Entity';
|
|
8
|
+
import { BaseComponent } from '../../../core/components/BaseComponent';
|
|
9
|
+
import { Component, CompData } from '../../../core/components/Decorators';
|
|
10
|
+
import { Query, FilterOp } from '../../../query/Query';
|
|
11
|
+
import { ensureComponentsRegistered } from '../../utils';
|
|
12
|
+
|
|
13
|
+
@Component
|
|
14
|
+
class EmptyableNote extends BaseComponent {
|
|
15
|
+
@CompData()
|
|
16
|
+
value: string = '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe('Query empty-string filter', () => {
|
|
20
|
+
beforeAll(async () => {
|
|
21
|
+
await ensureComponentsRegistered(EmptyableNote);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('Query.filter accepts empty-string value without throwing', () => {
|
|
25
|
+
expect(() => Query.filter('value', FilterOp.EQ, '')).not.toThrow();
|
|
26
|
+
const f = Query.filter('value', FilterOp.EQ, '');
|
|
27
|
+
expect(f.value).toBe('');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('Query.filter accepts whitespace-only value without throwing', () => {
|
|
31
|
+
expect(() => Query.filter('value', FilterOp.EQ, ' ')).not.toThrow();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('.with(C, filter EQ "") executes and returns matching rows', async () => {
|
|
35
|
+
const withEmpty = Entity.Create();
|
|
36
|
+
withEmpty.add(EmptyableNote, { value: '' });
|
|
37
|
+
await withEmpty.save();
|
|
38
|
+
|
|
39
|
+
const withData = Entity.Create();
|
|
40
|
+
withData.add(EmptyableNote, { value: 'not empty' });
|
|
41
|
+
await withData.save();
|
|
42
|
+
|
|
43
|
+
const rows = await new Query()
|
|
44
|
+
.with(EmptyableNote, Query.filters(Query.filter('value', FilterOp.EQ, '')))
|
|
45
|
+
.exec();
|
|
46
|
+
|
|
47
|
+
const ids = rows.map(e => e.id);
|
|
48
|
+
expect(ids).toContain(withEmpty.id);
|
|
49
|
+
expect(ids).not.toContain(withData.id);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('.with(C, filter != "") excludes rows with empty value', async () => {
|
|
53
|
+
const withEmpty = Entity.Create();
|
|
54
|
+
withEmpty.add(EmptyableNote, { value: '' });
|
|
55
|
+
await withEmpty.save();
|
|
56
|
+
|
|
57
|
+
const withData = Entity.Create();
|
|
58
|
+
withData.add(EmptyableNote, { value: 'populated' });
|
|
59
|
+
await withData.save();
|
|
60
|
+
|
|
61
|
+
const rows = await new Query()
|
|
62
|
+
.with(EmptyableNote, Query.filters(Query.filter('value', FilterOp.NEQ, '')))
|
|
63
|
+
.exec();
|
|
64
|
+
|
|
65
|
+
const ids = rows.map(e => e.id);
|
|
66
|
+
expect(ids).toContain(withData.id);
|
|
67
|
+
expect(ids).not.toContain(withEmpty.id);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
@@ -192,12 +192,14 @@ describe('Query', () => {
|
|
|
192
192
|
expect(filter.value).toBe('John');
|
|
193
193
|
});
|
|
194
194
|
|
|
195
|
-
test('
|
|
196
|
-
|
|
195
|
+
test('accepts empty string value', () => {
|
|
196
|
+
const filter = Query.filter('name', FilterOp.EQ, '');
|
|
197
|
+
expect(filter.value).toBe('');
|
|
197
198
|
});
|
|
198
199
|
|
|
199
|
-
test('
|
|
200
|
-
|
|
200
|
+
test('accepts whitespace value', () => {
|
|
201
|
+
const filter = Query.filter('name', FilterOp.EQ, ' ');
|
|
202
|
+
expect(filter.value).toBe(' ');
|
|
201
203
|
});
|
|
202
204
|
});
|
|
203
205
|
|