@coasys/ad4m 0.13.0-test-2 → 0.13.0-test-3
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/lib/index.cjs +1060 -147
- package/lib/index.js +1054 -147
- package/lib/src/index.d.ts +0 -1
- package/lib/src/index.js +0 -1
- package/lib/src/language/Language.d.ts +26 -214
- package/lib/src/language/Language.js +28 -2
- package/lib/src/model/Ad4mModel.d.ts +25 -1
- package/lib/src/model/Ad4mModel.js +139 -30
- package/lib/src/model/Ad4mModel.test.js +214 -32
- package/lib/src/model/ModelQueryBuilder.d.ts +19 -0
- package/lib/src/model/ModelQueryBuilder.js +62 -18
- package/lib/src/model/hydration-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/hydration.d.ts +1 -0
- package/lib/src/model/hydration.js +279 -70
- package/lib/src/model/query-sparql.d.ts +78 -1
- package/lib/src/model/query-sparql.js +447 -16
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +495 -0
- package/lib/src/model/query-utils.js +4 -0
- package/lib/src/model/subscription-delta.test.d.ts +24 -0
- package/lib/src/model/subscription-delta.test.js +180 -0
- package/lib/src/model/subscription-pool.js +48 -2
- package/lib/src/model/types.d.ts +49 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +2 -0
- package/lib/src/perspectives/PerspectiveClient.js +37 -9
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +3 -0
- package/lib/src/perspectives/PerspectiveProxy.js +15 -0
- package/package.json +1 -1
- package/src/Ad4mClient.test.ts +56 -1
- package/src/index.ts +0 -1
- package/src/language/Language.ts +54 -275
- package/src/model/Ad4mModel.test.ts +222 -35
- package/src/model/Ad4mModel.ts +144 -30
- package/src/model/ModelQueryBuilder.ts +66 -18
- package/src/model/hydration-batching.test.ts +563 -0
- package/src/model/hydration.ts +249 -47
- package/src/model/query-sparql.test.ts +568 -0
- package/src/model/query-sparql.ts +473 -16
- package/src/model/query-utils.ts +4 -0
- package/src/model/subscription-delta.test.ts +207 -0
- package/src/model/subscription-pool.ts +50 -2
- package/src/model/types.ts +50 -1
- package/src/perspectives/PerspectiveClient.test.ts +204 -0
- package/src/perspectives/PerspectiveClient.ts +36 -7
- package/src/perspectives/PerspectiveProxy.ts +18 -0
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/lib/src/model/surreal-utils.d.ts +0 -42
- package/lib/src/model/surreal-utils.js +0 -128
- package/src/language/LanguageContext.ts +0 -37
- package/tsconfig-browser.json +0 -82
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the delta fast-path logic used in subscription-pool.ts.
|
|
3
|
+
*
|
|
4
|
+
* The delta optimisation in pooledSubscribe's onResult handler:
|
|
5
|
+
* 1. Checks if new rows are a strict superset of previous rows
|
|
6
|
+
* 2. Extracts added rows (new triples not in prev set)
|
|
7
|
+
* 3. Verifies ALL added rows have source URIs not already in previous results
|
|
8
|
+
* 4. If condition 3 fails (existing source got new links), falls back to full rehydration
|
|
9
|
+
*
|
|
10
|
+
* These tests validate the detection logic in isolation.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
type Row = { source: string; predicate: string; target: string };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Replicates the delta-path eligibility check from subscription-pool.ts
|
|
17
|
+
*/
|
|
18
|
+
function detectDeltaPath(prevArr: Row[], newArr: Row[]): {
|
|
19
|
+
useDelta: boolean;
|
|
20
|
+
addedRows: Row[];
|
|
21
|
+
reason?: string;
|
|
22
|
+
} {
|
|
23
|
+
if (newArr.length <= prevArr.length) {
|
|
24
|
+
return { useDelta: false, addedRows: [], reason: 'no growth' };
|
|
25
|
+
}
|
|
26
|
+
if (newArr.length - prevArr.length > 5) {
|
|
27
|
+
return { useDelta: false, addedRows: [], reason: 'delta too large' };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const prevSources = new Set(prevArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
|
|
31
|
+
const addedRows = newArr.filter(r => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
32
|
+
|
|
33
|
+
const newSources = new Set(newArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
|
|
34
|
+
const removedRows = prevArr.filter(r => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
35
|
+
|
|
36
|
+
if (removedRows.length > 0) {
|
|
37
|
+
return { useDelta: false, addedRows, reason: 'rows removed' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Key check: all added rows must have NEW source URIs
|
|
41
|
+
const prevSourceIds = new Set(prevArr.map(r => r.source));
|
|
42
|
+
const allNewSources = addedRows.every(r => !prevSourceIds.has(r.source));
|
|
43
|
+
|
|
44
|
+
if (!allNewSources) {
|
|
45
|
+
return { useDelta: false, addedRows, reason: 'existing source got new links' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return { useDelta: true, addedRows };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
describe('delta fast-path detection', () => {
|
|
52
|
+
const prev: Row[] = [
|
|
53
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
54
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
55
|
+
{ source: 'b', predicate: 'p1', target: 't3' },
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
it('appends genuinely new items via delta path', () => {
|
|
59
|
+
const next: Row[] = [
|
|
60
|
+
...prev,
|
|
61
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
62
|
+
];
|
|
63
|
+
const result = detectDeltaPath(prev, next);
|
|
64
|
+
expect(result.useDelta).toBe(true);
|
|
65
|
+
expect(result.addedRows).toHaveLength(1);
|
|
66
|
+
expect(result.addedRows[0].source).toBe('c');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('falls back when existing source gets new links', () => {
|
|
70
|
+
const next: Row[] = [
|
|
71
|
+
...prev,
|
|
72
|
+
{ source: 'a', predicate: 'p3', target: 't5' }, // source 'a' already exists
|
|
73
|
+
];
|
|
74
|
+
const result = detectDeltaPath(prev, next);
|
|
75
|
+
expect(result.useDelta).toBe(false);
|
|
76
|
+
expect(result.reason).toBe('existing source got new links');
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('falls back when rows are removed (even if new ones added)', () => {
|
|
80
|
+
const next: Row[] = [
|
|
81
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
82
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
83
|
+
// source 'b' row removed, two new sources added so length grows
|
|
84
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
85
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
86
|
+
];
|
|
87
|
+
const result = detectDeltaPath(prev, next);
|
|
88
|
+
expect(result.useDelta).toBe(false);
|
|
89
|
+
expect(result.reason).toBe('rows removed');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('falls back when delta is too large (>5 new rows)', () => {
|
|
93
|
+
const next: Row[] = [
|
|
94
|
+
...prev,
|
|
95
|
+
...Array.from({ length: 6 }, (_, i) => ({
|
|
96
|
+
source: `new${i}`, predicate: 'p1', target: `t${10 + i}`,
|
|
97
|
+
})),
|
|
98
|
+
];
|
|
99
|
+
const result = detectDeltaPath(prev, next);
|
|
100
|
+
expect(result.useDelta).toBe(false);
|
|
101
|
+
expect(result.reason).toBe('delta too large');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('falls back when no growth', () => {
|
|
105
|
+
const result = detectDeltaPath(prev, prev);
|
|
106
|
+
expect(result.useDelta).toBe(false);
|
|
107
|
+
expect(result.reason).toBe('no growth');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('handles multiple new sources in one delta', () => {
|
|
111
|
+
const next: Row[] = [
|
|
112
|
+
...prev,
|
|
113
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
114
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
115
|
+
];
|
|
116
|
+
const result = detectDeltaPath(prev, next);
|
|
117
|
+
expect(result.useDelta).toBe(true);
|
|
118
|
+
expect(result.addedRows).toHaveLength(2);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// ── Test #8: Rapid successive additions ──
|
|
122
|
+
it('handles 10 items added in quick succession without duplicates', () => {
|
|
123
|
+
let current = [...prev];
|
|
124
|
+
for (let i = 0; i < 10; i++) {
|
|
125
|
+
const next = [...current, { source: `rapid-${i}`, predicate: 'p1', target: `t-rapid-${i}` }];
|
|
126
|
+
const result = detectDeltaPath(current, next);
|
|
127
|
+
// Each individual addition should be eligible for delta
|
|
128
|
+
expect(result.useDelta).toBe(true);
|
|
129
|
+
expect(result.addedRows).toHaveLength(1);
|
|
130
|
+
expect(result.addedRows[0].source).toBe(`rapid-${i}`);
|
|
131
|
+
current = next;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// ── Test #9: Addition + removal in same batch ──
|
|
136
|
+
it('falls back when one item added and another removed simultaneously', () => {
|
|
137
|
+
const next: Row[] = [
|
|
138
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
139
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
140
|
+
// source 'b' removed, source 'c' added
|
|
141
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
142
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
143
|
+
];
|
|
144
|
+
const result = detectDeltaPath(prev, next);
|
|
145
|
+
expect(result.useDelta).toBe(false);
|
|
146
|
+
expect(result.reason).toBe('rows removed');
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// ── Test #10: Delta with nested relations (detection only) ──
|
|
150
|
+
it('delta path detects new items correctly even when sources have complex URIs', () => {
|
|
151
|
+
const next: Row[] = [
|
|
152
|
+
...prev,
|
|
153
|
+
{ source: 'flux://post/123/comment/456', predicate: 'flux://belongs_to', target: 'flux://post/123' },
|
|
154
|
+
];
|
|
155
|
+
const result = detectDeltaPath(prev, next);
|
|
156
|
+
expect(result.useDelta).toBe(true);
|
|
157
|
+
expect(result.addedRows).toHaveLength(1);
|
|
158
|
+
expect(result.addedRows[0].source).toBe('flux://post/123/comment/456');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// ── Test #11: Empty previous result + new items ──
|
|
162
|
+
it('handles empty previous array with new items arriving', () => {
|
|
163
|
+
const empty: Row[] = [];
|
|
164
|
+
const next: Row[] = [
|
|
165
|
+
{ source: 'x', predicate: 'p1', target: 't1' },
|
|
166
|
+
];
|
|
167
|
+
const result = detectDeltaPath(empty, next);
|
|
168
|
+
expect(result.useDelta).toBe(true);
|
|
169
|
+
expect(result.addedRows).toHaveLength(1);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('handles empty previous with no new items', () => {
|
|
173
|
+
const result = detectDeltaPath([], []);
|
|
174
|
+
expect(result.useDelta).toBe(false);
|
|
175
|
+
expect(result.reason).toBe('no growth');
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// ── Test #12: Source URI with special characters ──
|
|
179
|
+
it('handles URIs with encoded characters, fragments, and query params', () => {
|
|
180
|
+
const specialPrev: Row[] = [
|
|
181
|
+
{ source: 'flux://item%20one', predicate: 'p1', target: 't1' },
|
|
182
|
+
{ source: 'flux://item#section', predicate: 'p2', target: 't2' },
|
|
183
|
+
{ source: 'flux://item?key=val&foo=bar', predicate: 'p3', target: 't3' },
|
|
184
|
+
];
|
|
185
|
+
const specialNext: Row[] = [
|
|
186
|
+
...specialPrev,
|
|
187
|
+
{ source: 'flux://new%C3%A9item', predicate: 'p1', target: 't4' },
|
|
188
|
+
];
|
|
189
|
+
const result = detectDeltaPath(specialPrev, specialNext);
|
|
190
|
+
expect(result.useDelta).toBe(true);
|
|
191
|
+
expect(result.addedRows).toHaveLength(1);
|
|
192
|
+
expect(result.addedRows[0].source).toBe('flux://new%C3%A9item');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('correctly identifies existing source with special chars getting new links', () => {
|
|
196
|
+
const specialPrev: Row[] = [
|
|
197
|
+
{ source: 'flux://item#section', predicate: 'p1', target: 't1' },
|
|
198
|
+
];
|
|
199
|
+
const specialNext: Row[] = [
|
|
200
|
+
...specialPrev,
|
|
201
|
+
{ source: 'flux://item#section', predicate: 'p2', target: 't2' },
|
|
202
|
+
];
|
|
203
|
+
const result = detectDeltaPath(specialPrev, specialNext);
|
|
204
|
+
expect(result.useDelta).toBe(false);
|
|
205
|
+
expect(result.reason).toBe('existing source got new links');
|
|
206
|
+
});
|
|
207
|
+
});
|
|
@@ -97,14 +97,62 @@ export async function pooledSubscribe(
|
|
|
97
97
|
|
|
98
98
|
pool.set(key, newEntry);
|
|
99
99
|
|
|
100
|
-
// Set up shared result handler
|
|
100
|
+
// Set up shared result handler with delta optimization
|
|
101
101
|
subscription.onResult(async (rawResult: any) => {
|
|
102
|
+
const prevRaw = newEntry.latestRaw;
|
|
102
103
|
newEntry.latestRaw = rawResult;
|
|
103
104
|
newEntry.hydrating = true;
|
|
104
105
|
try {
|
|
105
|
-
// Hydrate ONCE using the first subscriber's hydrate function
|
|
106
106
|
const firstSub = newEntry.callbacks.values().next().value;
|
|
107
107
|
if (firstSub) {
|
|
108
|
+
// Delta optimization: if the new result is strictly an addition
|
|
109
|
+
// (all previous rows still present + new rows), only hydrate the
|
|
110
|
+
// new rows and append them to the cached hydrated result.
|
|
111
|
+
const prevArr = Array.isArray(prevRaw) ? prevRaw : [];
|
|
112
|
+
const newArr = Array.isArray(rawResult) ? rawResult : [];
|
|
113
|
+
const prevHydrated = newEntry.latestHydrated;
|
|
114
|
+
|
|
115
|
+
if (
|
|
116
|
+
prevHydrated &&
|
|
117
|
+
Array.isArray(prevHydrated) &&
|
|
118
|
+
newArr.length > prevArr.length &&
|
|
119
|
+
newArr.length - prevArr.length <= 5 // small delta — worth optimizing
|
|
120
|
+
) {
|
|
121
|
+
// Build a set of source URIs from previous results for quick lookup
|
|
122
|
+
const prevSources = new Set(prevArr.map((r: any) => `${r.source}|${r.predicate}|${r.target}`));
|
|
123
|
+
const addedRows = newArr.filter((r: any) => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
124
|
+
|
|
125
|
+
// Check that no rows were removed (pure addition)
|
|
126
|
+
const newSources = new Set(newArr.map((r: any) => `${r.source}|${r.predicate}|${r.target}`));
|
|
127
|
+
const removedRows = prevArr.filter((r: any) => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
128
|
+
|
|
129
|
+
if (removedRows.length === 0 && addedRows.length > 0) {
|
|
130
|
+
// Verify ALL added rows have sources not in previous results.
|
|
131
|
+
// If any added row's source matches an existing source, it means
|
|
132
|
+
// an existing instance got new links — we need full rehydration.
|
|
133
|
+
const prevSourceIds = new Set(prevArr.map((r: any) => r.source));
|
|
134
|
+
const allNewSources = addedRows.every((r: any) => !prevSourceIds.has(r.source));
|
|
135
|
+
|
|
136
|
+
if (allNewSources) {
|
|
137
|
+
// Pure addition of new instances — hydrate only the new rows
|
|
138
|
+
try {
|
|
139
|
+
const deltaHydrated = await firstSub.hydrate(addedRows);
|
|
140
|
+
if (Array.isArray(deltaHydrated)) {
|
|
141
|
+
const merged = [...prevHydrated, ...deltaHydrated];
|
|
142
|
+
newEntry.latestHydrated = merged;
|
|
143
|
+
for (const cb of newEntry.callbacks) {
|
|
144
|
+
try { cb.onResult(merged); } catch (e) { /* subscriber error */ }
|
|
145
|
+
}
|
|
146
|
+
return; // Delta path succeeded
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
// Delta hydration failed — fall through to full hydration
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Full hydration fallback
|
|
108
156
|
const hydrated = await firstSub.hydrate(rawResult);
|
|
109
157
|
newEntry.latestHydrated = hydrated;
|
|
110
158
|
// Distribute to all callbacks
|
package/src/model/types.ts
CHANGED
|
@@ -41,12 +41,48 @@ export type ParentScope =
|
|
|
41
41
|
| { model: typeof Ad4mModel; id: string; field?: string }
|
|
42
42
|
| { id: string; predicate: string };
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Descriptor for a user-named projection — a derived field computed from a
|
|
46
|
+
* relation that is attached to the parent instance under a custom `$`-prefixed
|
|
47
|
+
* key in the `IncludeMap`.
|
|
48
|
+
*
|
|
49
|
+
* The `from` field must name a declared relation on the model.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* include: {
|
|
54
|
+
* $signalCount: { from: 'signals', count: true },
|
|
55
|
+
* $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 },
|
|
56
|
+
* $likeSignals: { from: 'signals', where: { signalTypeId: 'like' } },
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export interface IncludeProjection {
|
|
61
|
+
/** Declared relation name on the model to derive the projection from. */
|
|
62
|
+
from: string;
|
|
63
|
+
/**
|
|
64
|
+
* When true, the projection result is the count of matching instances
|
|
65
|
+
* as a `number`. All other options (`where`, `limit`) are still applied
|
|
66
|
+
* before counting. `count: true` → result type is `number`.
|
|
67
|
+
*/
|
|
68
|
+
count?: true;
|
|
69
|
+
/** Filter applied to the related instances before the projection result is produced. */
|
|
70
|
+
where?: Where;
|
|
71
|
+
/**
|
|
72
|
+
* Maximum number of results to include.
|
|
73
|
+
* When `limit` is `1`, the result type is `T | null` (unwrapped single instance)
|
|
74
|
+
* rather than `T[]`.
|
|
75
|
+
*/
|
|
76
|
+
limit?: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
44
79
|
/**
|
|
45
80
|
* Describes which relations to eager-load when querying.
|
|
46
81
|
*
|
|
47
82
|
* Each value is either:
|
|
48
83
|
* - `true` — hydrate the relation one level deep
|
|
49
84
|
* - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
|
|
85
|
+
* - An `IncludeProjection` — user-named derived field (count, filtered subset, single item)
|
|
50
86
|
*
|
|
51
87
|
* @example
|
|
52
88
|
* ```typescript
|
|
@@ -58,10 +94,13 @@ export type ParentScope =
|
|
|
58
94
|
*
|
|
59
95
|
* // Nested eager-load
|
|
60
96
|
* { comments: { include: { author: true } } }
|
|
97
|
+
*
|
|
98
|
+
* // Projection: count + filtered single item
|
|
99
|
+
* { $signalCount: { from: 'signals', count: true }, $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 } }
|
|
61
100
|
* ```
|
|
62
101
|
*/
|
|
63
102
|
export interface IncludeMap {
|
|
64
|
-
[relation: string]: boolean | RelationSubQuery;
|
|
103
|
+
[relation: string]: boolean | RelationSubQuery | IncludeProjection;
|
|
65
104
|
}
|
|
66
105
|
|
|
67
106
|
export type Query = {
|
|
@@ -74,6 +113,16 @@ export type Query = {
|
|
|
74
113
|
offset?: number;
|
|
75
114
|
limit?: number;
|
|
76
115
|
count?: boolean;
|
|
116
|
+
/**
|
|
117
|
+
* When true, SPARQL property getters (@Property with `getter`) ARE evaluated
|
|
118
|
+
* during collection hydration. By default, collection queries skip getter
|
|
119
|
+
* evaluation for performance — getters run only on single-instance get().
|
|
120
|
+
*
|
|
121
|
+
* Use this when you need getter-backed properties (e.g. `replyingTo`,
|
|
122
|
+
* `isPopular`) in a list query. For most list/feed UIs, leave this off
|
|
123
|
+
* and use `Ad4mModel.evaluateGetters()` on visible items only.
|
|
124
|
+
*/
|
|
125
|
+
deepQuery?: boolean;
|
|
77
126
|
};
|
|
78
127
|
|
|
79
128
|
/**
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { ApolloClient, InMemoryCache, gql } from "@apollo/client/core"
|
|
2
|
+
import { PerspectiveClient } from "./PerspectiveClient"
|
|
3
|
+
import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Focused unit tests for PerspectiveClient proxy cache behaviour.
|
|
7
|
+
* Uses a mock Apollo client to isolate cache logic from network.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
// Minimal mock Apollo client that returns controllable results
|
|
11
|
+
function createMockApolloClient(overrides: {
|
|
12
|
+
query?: (opts: any) => any,
|
|
13
|
+
mutate?: (opts: any) => any,
|
|
14
|
+
subscribe?: (opts: any) => any,
|
|
15
|
+
} = {}) {
|
|
16
|
+
return {
|
|
17
|
+
query: overrides.query || jest.fn().mockResolvedValue({ data: {} }),
|
|
18
|
+
mutate: overrides.mutate || jest.fn().mockResolvedValue({ data: {} }),
|
|
19
|
+
subscribe: overrides.subscribe || jest.fn().mockReturnValue({
|
|
20
|
+
subscribe: jest.fn()
|
|
21
|
+
}),
|
|
22
|
+
} as unknown as ApolloClient<any>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function makeHandle(uuid: string, name: string, state = PerspectiveState.Private): PerspectiveHandle {
|
|
26
|
+
const h = new PerspectiveHandle(uuid, name, state)
|
|
27
|
+
return h
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
describe('PerspectiveClient proxy cache', () => {
|
|
31
|
+
it('byUUID returns the same proxy reference on cache hit', async () => {
|
|
32
|
+
const handle = makeHandle('uuid-1', 'Test')
|
|
33
|
+
const mockClient = createMockApolloClient({
|
|
34
|
+
query: jest.fn().mockResolvedValue({
|
|
35
|
+
data: { perspective: handle }
|
|
36
|
+
}),
|
|
37
|
+
})
|
|
38
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
39
|
+
|
|
40
|
+
const p1 = await client.byUUID('uuid-1')
|
|
41
|
+
const p2 = await client.byUUID('uuid-1')
|
|
42
|
+
expect(p1).toBe(p2)
|
|
43
|
+
// Only one query should have been made (second is cache hit)
|
|
44
|
+
expect(mockClient.query).toHaveBeenCalledTimes(1)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('byUUID returns null for non-existent perspectives', async () => {
|
|
48
|
+
const mockClient = createMockApolloClient({
|
|
49
|
+
query: jest.fn().mockResolvedValue({
|
|
50
|
+
data: { perspective: null }
|
|
51
|
+
}),
|
|
52
|
+
})
|
|
53
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
54
|
+
const p = await client.byUUID('non-existent')
|
|
55
|
+
expect(p).toBeNull()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('all() populates cache so subsequent byUUID is a hit', async () => {
|
|
59
|
+
const handles = [
|
|
60
|
+
makeHandle('uuid-a', 'A'),
|
|
61
|
+
makeHandle('uuid-b', 'B'),
|
|
62
|
+
]
|
|
63
|
+
const queryFn = jest.fn()
|
|
64
|
+
.mockResolvedValueOnce({ data: { perspectives: handles } })
|
|
65
|
+
const mockClient = createMockApolloClient({ query: queryFn })
|
|
66
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
67
|
+
|
|
68
|
+
const all = await client.all()
|
|
69
|
+
expect(all.length).toBe(2)
|
|
70
|
+
|
|
71
|
+
// byUUID should be a cache hit — no additional query
|
|
72
|
+
const pa = await client.byUUID('uuid-a')
|
|
73
|
+
expect(pa).toBe(all[0])
|
|
74
|
+
expect(queryFn).toHaveBeenCalledTimes(1) // only the all() query
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('add() populates cache', async () => {
|
|
78
|
+
const handle = makeHandle('uuid-new', 'New')
|
|
79
|
+
const mockClient = createMockApolloClient({
|
|
80
|
+
mutate: jest.fn().mockResolvedValue({
|
|
81
|
+
data: { perspectiveAdd: handle }
|
|
82
|
+
}),
|
|
83
|
+
})
|
|
84
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
85
|
+
|
|
86
|
+
const added = await client.add('New')
|
|
87
|
+
expect(added.uuid).toBe('uuid-new')
|
|
88
|
+
|
|
89
|
+
// byUUID should hit cache
|
|
90
|
+
const fetched = await client.byUUID('uuid-new')
|
|
91
|
+
expect(fetched).toBe(added)
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
it('update() evicts and recreates cached proxy', async () => {
|
|
95
|
+
const originalHandle = makeHandle('uuid-u', 'Original')
|
|
96
|
+
const updatedHandle = makeHandle('uuid-u', 'Updated')
|
|
97
|
+
const queryFn = jest.fn().mockResolvedValue({
|
|
98
|
+
data: { perspective: originalHandle }
|
|
99
|
+
})
|
|
100
|
+
const mutateFn = jest.fn().mockResolvedValue({
|
|
101
|
+
data: { perspectiveUpdate: updatedHandle }
|
|
102
|
+
})
|
|
103
|
+
const mockClient = createMockApolloClient({
|
|
104
|
+
query: queryFn,
|
|
105
|
+
mutate: mutateFn,
|
|
106
|
+
})
|
|
107
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
108
|
+
|
|
109
|
+
const original = await client.byUUID('uuid-u')
|
|
110
|
+
expect(original.name).toBe('Original')
|
|
111
|
+
|
|
112
|
+
const updated = await client.update('uuid-u', 'Updated')
|
|
113
|
+
expect(updated).not.toBe(original) // new reference after eviction
|
|
114
|
+
expect(updated.name).toBe('Updated')
|
|
115
|
+
expect(original.name).toBe('Original') // old reference retains stale data
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('remove() evicts from cache', async () => {
|
|
119
|
+
const handle = makeHandle('uuid-r', 'ToRemove')
|
|
120
|
+
const queryFn = jest.fn().mockResolvedValue({
|
|
121
|
+
data: { perspective: handle }
|
|
122
|
+
})
|
|
123
|
+
const mutateFn = jest.fn().mockResolvedValue({
|
|
124
|
+
data: { perspectiveRemove: true }
|
|
125
|
+
})
|
|
126
|
+
const mockClient = createMockApolloClient({
|
|
127
|
+
query: queryFn,
|
|
128
|
+
mutate: mutateFn,
|
|
129
|
+
})
|
|
130
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
131
|
+
|
|
132
|
+
const p = await client.byUUID('uuid-r')
|
|
133
|
+
expect(p).toBeTruthy()
|
|
134
|
+
expect(queryFn).toHaveBeenCalledTimes(1)
|
|
135
|
+
|
|
136
|
+
await client.remove('uuid-r')
|
|
137
|
+
|
|
138
|
+
// byUUID should miss cache and query again
|
|
139
|
+
const handle2 = makeHandle('uuid-r', 'Recreated')
|
|
140
|
+
queryFn.mockResolvedValueOnce({ data: { perspective: handle2 } })
|
|
141
|
+
|
|
142
|
+
const p2 = await client.byUUID('uuid-r')
|
|
143
|
+
expect(p2).not.toBe(p)
|
|
144
|
+
expect(p2.name).toBe('Recreated')
|
|
145
|
+
expect(queryFn).toHaveBeenCalledTimes(2)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it('getOrCreateProxy does not re-register listeners on cache hit', async () => {
|
|
149
|
+
// Verify that getting the same proxy twice does not create duplicate subscriptions
|
|
150
|
+
const handle = makeHandle('uuid-dup', 'NoDuplicates')
|
|
151
|
+
const subscribeCalls: string[] = []
|
|
152
|
+
const subscribeFn = jest.fn().mockImplementation((opts) => {
|
|
153
|
+
// Track subscription query names
|
|
154
|
+
const queryStr = opts.query?.loc?.source?.body || ''
|
|
155
|
+
subscribeCalls.push(queryStr)
|
|
156
|
+
return {
|
|
157
|
+
subscribe: jest.fn()
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
const queryFn = jest.fn()
|
|
161
|
+
.mockResolvedValueOnce({ data: { perspectives: [handle] } })
|
|
162
|
+
const mockClient = createMockApolloClient({
|
|
163
|
+
query: queryFn,
|
|
164
|
+
subscribe: subscribeFn,
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
168
|
+
const all = await client.all()
|
|
169
|
+
const firstProxy = all[0]
|
|
170
|
+
|
|
171
|
+
// Record how many subscribe calls happened from PerspectiveProxy constructor
|
|
172
|
+
const callsAfterFirst = subscribeFn.mock.calls.length
|
|
173
|
+
|
|
174
|
+
// Get same proxy again via all() — should be cache hit, no new constructor call
|
|
175
|
+
queryFn.mockResolvedValueOnce({ data: { perspectives: [handle] } })
|
|
176
|
+
const all2 = await client.all()
|
|
177
|
+
const secondProxy = all2[0]
|
|
178
|
+
|
|
179
|
+
expect(secondProxy).toBe(firstProxy)
|
|
180
|
+
// No additional subscribe calls should have been made
|
|
181
|
+
expect(subscribeFn.mock.calls.length).toBe(callsAfterFirst)
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
it('all() updates existing cached proxies with fresh data', async () => {
|
|
185
|
+
const handle1 = makeHandle('uuid-f', 'OldName')
|
|
186
|
+
const handle2 = makeHandle('uuid-f', 'FreshName')
|
|
187
|
+
|
|
188
|
+
const queryFn = jest.fn()
|
|
189
|
+
.mockResolvedValueOnce({ data: { perspective: handle1 } })
|
|
190
|
+
.mockResolvedValueOnce({ data: { perspectives: [handle2] } })
|
|
191
|
+
const mockClient = createMockApolloClient({ query: queryFn })
|
|
192
|
+
const client = new PerspectiveClient(mockClient, false)
|
|
193
|
+
|
|
194
|
+
const original = await client.byUUID('uuid-f')
|
|
195
|
+
expect(original.name).toBe('OldName')
|
|
196
|
+
|
|
197
|
+
const all = await client.all()
|
|
198
|
+
const refreshed = all.find(p => p.uuid === 'uuid-f')
|
|
199
|
+
|
|
200
|
+
expect(refreshed).toBe(original) // same reference
|
|
201
|
+
expect(refreshed.name).toBe('FreshName') // updated in-place
|
|
202
|
+
expect(original.name).toBe('FreshName') // original ref also updated
|
|
203
|
+
})
|
|
204
|
+
})
|
|
@@ -57,6 +57,7 @@ export class PerspectiveClient {
|
|
|
57
57
|
#expressionClient?: ExpressionClient
|
|
58
58
|
#neighbourhoodClient?: NeighbourhoodClient
|
|
59
59
|
#aiClient?: AIClient
|
|
60
|
+
#proxyCache: Map<string, PerspectiveProxy> = new Map()
|
|
60
61
|
|
|
61
62
|
constructor(client: ApolloClient<any>, subscribe: boolean = true) {
|
|
62
63
|
this.#apolloClient = client
|
|
@@ -72,6 +73,18 @@ export class PerspectiveClient {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/** Get or create a proxy for a UUID. If the proxy exists in cache, update its handle and return it. */
|
|
77
|
+
private getOrCreateProxy(handle: PerspectiveHandle): PerspectiveProxy {
|
|
78
|
+
const existing = this.#proxyCache.get(handle.uuid)
|
|
79
|
+
if (existing) {
|
|
80
|
+
existing.updateHandle(handle)
|
|
81
|
+
return existing
|
|
82
|
+
}
|
|
83
|
+
const proxy = new PerspectiveProxy(handle, this)
|
|
84
|
+
this.#proxyCache.set(handle.uuid, proxy)
|
|
85
|
+
return proxy
|
|
86
|
+
}
|
|
87
|
+
|
|
75
88
|
setExpressionClient(client: ExpressionClient) {
|
|
76
89
|
this.#expressionClient = client
|
|
77
90
|
}
|
|
@@ -96,10 +109,13 @@ export class PerspectiveClient {
|
|
|
96
109
|
}
|
|
97
110
|
}`
|
|
98
111
|
}))
|
|
99
|
-
return perspectives.map(handle =>
|
|
112
|
+
return perspectives.map(handle => this.getOrCreateProxy(handle))
|
|
100
113
|
}
|
|
101
114
|
|
|
102
115
|
async byUUID(uuid: string): Promise<PerspectiveProxy|null> {
|
|
116
|
+
const cached = this.#proxyCache.get(uuid)
|
|
117
|
+
if (cached) return cached
|
|
118
|
+
|
|
103
119
|
const { perspective } = unwrapApolloResult(await this.#apolloClient.query({
|
|
104
120
|
query: gql`query perspective($uuid: String!) {
|
|
105
121
|
perspective(uuid: $uuid) {
|
|
@@ -109,7 +125,7 @@ export class PerspectiveClient {
|
|
|
109
125
|
variables: { uuid }
|
|
110
126
|
}))
|
|
111
127
|
if(!perspective) return null
|
|
112
|
-
return
|
|
128
|
+
return this.getOrCreateProxy(perspective)
|
|
113
129
|
}
|
|
114
130
|
|
|
115
131
|
async snapshotByUUID(uuid: string): Promise<Perspective|null> {
|
|
@@ -259,7 +275,7 @@ export class PerspectiveClient {
|
|
|
259
275
|
}`,
|
|
260
276
|
variables: { name }
|
|
261
277
|
}))
|
|
262
|
-
return
|
|
278
|
+
return this.getOrCreateProxy(perspectiveAdd)
|
|
263
279
|
}
|
|
264
280
|
|
|
265
281
|
async update(uuid: string, name: string): Promise<PerspectiveProxy> {
|
|
@@ -271,10 +287,13 @@ export class PerspectiveClient {
|
|
|
271
287
|
}`,
|
|
272
288
|
variables: { uuid, name }
|
|
273
289
|
}))
|
|
274
|
-
|
|
290
|
+
// Evict stale proxy — getOrCreateProxy will create a fresh one with updated handle
|
|
291
|
+
this.#proxyCache.delete(uuid)
|
|
292
|
+
return this.getOrCreateProxy(perspectiveUpdate)
|
|
275
293
|
}
|
|
276
294
|
|
|
277
295
|
async remove(uuid: string): Promise<{perspectiveRemove: boolean}> {
|
|
296
|
+
this.#proxyCache.delete(uuid)
|
|
278
297
|
return unwrapApolloResult(await this.#apolloClient.mutate({
|
|
279
298
|
mutation: gql`mutation perspectiveRemove($uuid: String!) {
|
|
280
299
|
perspectiveRemove(uuid: $uuid)
|
|
@@ -441,9 +460,12 @@ export class PerspectiveClient {
|
|
|
441
460
|
}
|
|
442
461
|
`}).subscribe({
|
|
443
462
|
next: result => {
|
|
463
|
+
const handle = result.data.perspectiveAdded
|
|
444
464
|
this.#perspectiveAddedCallbacks.forEach(cb => {
|
|
445
|
-
cb(
|
|
465
|
+
cb(handle)
|
|
446
466
|
})
|
|
467
|
+
// Populate cache so subsequent byUUID() calls get a hit
|
|
468
|
+
this.getOrCreateProxy(handle)
|
|
447
469
|
},
|
|
448
470
|
error: (e) => console.error(e)
|
|
449
471
|
})
|
|
@@ -460,9 +482,13 @@ export class PerspectiveClient {
|
|
|
460
482
|
}
|
|
461
483
|
`}).subscribe({
|
|
462
484
|
next: result => {
|
|
485
|
+
const handle = result.data.perspectiveUpdated
|
|
463
486
|
this.#perspectiveUpdatedCallbacks.forEach(cb => {
|
|
464
|
-
cb(
|
|
487
|
+
cb(handle)
|
|
465
488
|
})
|
|
489
|
+
// Evict stale proxy and create fresh one with updated handle
|
|
490
|
+
this.#proxyCache.delete(handle.uuid)
|
|
491
|
+
this.getOrCreateProxy(handle)
|
|
466
492
|
},
|
|
467
493
|
error: (e) => console.error(e)
|
|
468
494
|
})
|
|
@@ -500,9 +526,12 @@ export class PerspectiveClient {
|
|
|
500
526
|
}
|
|
501
527
|
`}).subscribe({
|
|
502
528
|
next: result => {
|
|
529
|
+
const uuid = result.data.perspectiveRemoved
|
|
503
530
|
this.#perspectiveRemovedCallbacks.forEach(cb => {
|
|
504
|
-
cb(
|
|
531
|
+
cb(uuid)
|
|
505
532
|
})
|
|
533
|
+
// Evict from cache
|
|
534
|
+
this.#proxyCache.delete(uuid)
|
|
506
535
|
},
|
|
507
536
|
error: (e) => console.error(e)
|
|
508
537
|
})
|