@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,180 @@
|
|
|
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
|
+
* Replicates the delta-path eligibility check from subscription-pool.ts
|
|
14
|
+
*/
|
|
15
|
+
function detectDeltaPath(prevArr, newArr) {
|
|
16
|
+
if (newArr.length <= prevArr.length) {
|
|
17
|
+
return { useDelta: false, addedRows: [], reason: 'no growth' };
|
|
18
|
+
}
|
|
19
|
+
if (newArr.length - prevArr.length > 5) {
|
|
20
|
+
return { useDelta: false, addedRows: [], reason: 'delta too large' };
|
|
21
|
+
}
|
|
22
|
+
const prevSources = new Set(prevArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
|
|
23
|
+
const addedRows = newArr.filter(r => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
24
|
+
const newSources = new Set(newArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
|
|
25
|
+
const removedRows = prevArr.filter(r => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
26
|
+
if (removedRows.length > 0) {
|
|
27
|
+
return { useDelta: false, addedRows, reason: 'rows removed' };
|
|
28
|
+
}
|
|
29
|
+
// Key check: all added rows must have NEW source URIs
|
|
30
|
+
const prevSourceIds = new Set(prevArr.map(r => r.source));
|
|
31
|
+
const allNewSources = addedRows.every(r => !prevSourceIds.has(r.source));
|
|
32
|
+
if (!allNewSources) {
|
|
33
|
+
return { useDelta: false, addedRows, reason: 'existing source got new links' };
|
|
34
|
+
}
|
|
35
|
+
return { useDelta: true, addedRows };
|
|
36
|
+
}
|
|
37
|
+
describe('delta fast-path detection', () => {
|
|
38
|
+
const prev = [
|
|
39
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
40
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
41
|
+
{ source: 'b', predicate: 'p1', target: 't3' },
|
|
42
|
+
];
|
|
43
|
+
it('appends genuinely new items via delta path', () => {
|
|
44
|
+
const next = [
|
|
45
|
+
...prev,
|
|
46
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
47
|
+
];
|
|
48
|
+
const result = detectDeltaPath(prev, next);
|
|
49
|
+
expect(result.useDelta).toBe(true);
|
|
50
|
+
expect(result.addedRows).toHaveLength(1);
|
|
51
|
+
expect(result.addedRows[0].source).toBe('c');
|
|
52
|
+
});
|
|
53
|
+
it('falls back when existing source gets new links', () => {
|
|
54
|
+
const next = [
|
|
55
|
+
...prev,
|
|
56
|
+
{ source: 'a', predicate: 'p3', target: 't5' }, // source 'a' already exists
|
|
57
|
+
];
|
|
58
|
+
const result = detectDeltaPath(prev, next);
|
|
59
|
+
expect(result.useDelta).toBe(false);
|
|
60
|
+
expect(result.reason).toBe('existing source got new links');
|
|
61
|
+
});
|
|
62
|
+
it('falls back when rows are removed (even if new ones added)', () => {
|
|
63
|
+
const next = [
|
|
64
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
65
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
66
|
+
// source 'b' row removed, two new sources added so length grows
|
|
67
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
68
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
69
|
+
];
|
|
70
|
+
const result = detectDeltaPath(prev, next);
|
|
71
|
+
expect(result.useDelta).toBe(false);
|
|
72
|
+
expect(result.reason).toBe('rows removed');
|
|
73
|
+
});
|
|
74
|
+
it('falls back when delta is too large (>5 new rows)', () => {
|
|
75
|
+
const next = [
|
|
76
|
+
...prev,
|
|
77
|
+
...Array.from({ length: 6 }, (_, i) => ({
|
|
78
|
+
source: `new${i}`, predicate: 'p1', target: `t${10 + i}`,
|
|
79
|
+
})),
|
|
80
|
+
];
|
|
81
|
+
const result = detectDeltaPath(prev, next);
|
|
82
|
+
expect(result.useDelta).toBe(false);
|
|
83
|
+
expect(result.reason).toBe('delta too large');
|
|
84
|
+
});
|
|
85
|
+
it('falls back when no growth', () => {
|
|
86
|
+
const result = detectDeltaPath(prev, prev);
|
|
87
|
+
expect(result.useDelta).toBe(false);
|
|
88
|
+
expect(result.reason).toBe('no growth');
|
|
89
|
+
});
|
|
90
|
+
it('handles multiple new sources in one delta', () => {
|
|
91
|
+
const next = [
|
|
92
|
+
...prev,
|
|
93
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
94
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
95
|
+
];
|
|
96
|
+
const result = detectDeltaPath(prev, next);
|
|
97
|
+
expect(result.useDelta).toBe(true);
|
|
98
|
+
expect(result.addedRows).toHaveLength(2);
|
|
99
|
+
});
|
|
100
|
+
// ── Test #8: Rapid successive additions ──
|
|
101
|
+
it('handles 10 items added in quick succession without duplicates', () => {
|
|
102
|
+
let current = [...prev];
|
|
103
|
+
for (let i = 0; i < 10; i++) {
|
|
104
|
+
const next = [...current, { source: `rapid-${i}`, predicate: 'p1', target: `t-rapid-${i}` }];
|
|
105
|
+
const result = detectDeltaPath(current, next);
|
|
106
|
+
// Each individual addition should be eligible for delta
|
|
107
|
+
expect(result.useDelta).toBe(true);
|
|
108
|
+
expect(result.addedRows).toHaveLength(1);
|
|
109
|
+
expect(result.addedRows[0].source).toBe(`rapid-${i}`);
|
|
110
|
+
current = next;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
// ── Test #9: Addition + removal in same batch ──
|
|
114
|
+
it('falls back when one item added and another removed simultaneously', () => {
|
|
115
|
+
const next = [
|
|
116
|
+
{ source: 'a', predicate: 'p1', target: 't1' },
|
|
117
|
+
{ source: 'a', predicate: 'p2', target: 't2' },
|
|
118
|
+
// source 'b' removed, source 'c' added
|
|
119
|
+
{ source: 'c', predicate: 'p1', target: 't4' },
|
|
120
|
+
{ source: 'd', predicate: 'p1', target: 't5' },
|
|
121
|
+
];
|
|
122
|
+
const result = detectDeltaPath(prev, next);
|
|
123
|
+
expect(result.useDelta).toBe(false);
|
|
124
|
+
expect(result.reason).toBe('rows removed');
|
|
125
|
+
});
|
|
126
|
+
// ── Test #10: Delta with nested relations (detection only) ──
|
|
127
|
+
it('delta path detects new items correctly even when sources have complex URIs', () => {
|
|
128
|
+
const next = [
|
|
129
|
+
...prev,
|
|
130
|
+
{ source: 'flux://post/123/comment/456', predicate: 'flux://belongs_to', target: 'flux://post/123' },
|
|
131
|
+
];
|
|
132
|
+
const result = detectDeltaPath(prev, next);
|
|
133
|
+
expect(result.useDelta).toBe(true);
|
|
134
|
+
expect(result.addedRows).toHaveLength(1);
|
|
135
|
+
expect(result.addedRows[0].source).toBe('flux://post/123/comment/456');
|
|
136
|
+
});
|
|
137
|
+
// ── Test #11: Empty previous result + new items ──
|
|
138
|
+
it('handles empty previous array with new items arriving', () => {
|
|
139
|
+
const empty = [];
|
|
140
|
+
const next = [
|
|
141
|
+
{ source: 'x', predicate: 'p1', target: 't1' },
|
|
142
|
+
];
|
|
143
|
+
const result = detectDeltaPath(empty, next);
|
|
144
|
+
expect(result.useDelta).toBe(true);
|
|
145
|
+
expect(result.addedRows).toHaveLength(1);
|
|
146
|
+
});
|
|
147
|
+
it('handles empty previous with no new items', () => {
|
|
148
|
+
const result = detectDeltaPath([], []);
|
|
149
|
+
expect(result.useDelta).toBe(false);
|
|
150
|
+
expect(result.reason).toBe('no growth');
|
|
151
|
+
});
|
|
152
|
+
// ── Test #12: Source URI with special characters ──
|
|
153
|
+
it('handles URIs with encoded characters, fragments, and query params', () => {
|
|
154
|
+
const specialPrev = [
|
|
155
|
+
{ source: 'flux://item%20one', predicate: 'p1', target: 't1' },
|
|
156
|
+
{ source: 'flux://item#section', predicate: 'p2', target: 't2' },
|
|
157
|
+
{ source: 'flux://item?key=val&foo=bar', predicate: 'p3', target: 't3' },
|
|
158
|
+
];
|
|
159
|
+
const specialNext = [
|
|
160
|
+
...specialPrev,
|
|
161
|
+
{ source: 'flux://new%C3%A9item', predicate: 'p1', target: 't4' },
|
|
162
|
+
];
|
|
163
|
+
const result = detectDeltaPath(specialPrev, specialNext);
|
|
164
|
+
expect(result.useDelta).toBe(true);
|
|
165
|
+
expect(result.addedRows).toHaveLength(1);
|
|
166
|
+
expect(result.addedRows[0].source).toBe('flux://new%C3%A9item');
|
|
167
|
+
});
|
|
168
|
+
it('correctly identifies existing source with special chars getting new links', () => {
|
|
169
|
+
const specialPrev = [
|
|
170
|
+
{ source: 'flux://item#section', predicate: 'p1', target: 't1' },
|
|
171
|
+
];
|
|
172
|
+
const specialNext = [
|
|
173
|
+
...specialPrev,
|
|
174
|
+
{ source: 'flux://item#section', predicate: 'p2', target: 't2' },
|
|
175
|
+
];
|
|
176
|
+
const result = detectDeltaPath(specialPrev, specialNext);
|
|
177
|
+
expect(result.useDelta).toBe(false);
|
|
178
|
+
expect(result.reason).toBe('existing source got new links');
|
|
179
|
+
});
|
|
180
|
+
});
|
|
@@ -55,14 +55,60 @@ export async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResul
|
|
|
55
55
|
refCount: 1,
|
|
56
56
|
};
|
|
57
57
|
pool.set(key, newEntry);
|
|
58
|
-
// Set up shared result handler
|
|
58
|
+
// Set up shared result handler with delta optimization
|
|
59
59
|
subscription.onResult(async (rawResult) => {
|
|
60
|
+
const prevRaw = newEntry.latestRaw;
|
|
60
61
|
newEntry.latestRaw = rawResult;
|
|
61
62
|
newEntry.hydrating = true;
|
|
62
63
|
try {
|
|
63
|
-
// Hydrate ONCE using the first subscriber's hydrate function
|
|
64
64
|
const firstSub = newEntry.callbacks.values().next().value;
|
|
65
65
|
if (firstSub) {
|
|
66
|
+
// Delta optimization: if the new result is strictly an addition
|
|
67
|
+
// (all previous rows still present + new rows), only hydrate the
|
|
68
|
+
// new rows and append them to the cached hydrated result.
|
|
69
|
+
const prevArr = Array.isArray(prevRaw) ? prevRaw : [];
|
|
70
|
+
const newArr = Array.isArray(rawResult) ? rawResult : [];
|
|
71
|
+
const prevHydrated = newEntry.latestHydrated;
|
|
72
|
+
if (prevHydrated &&
|
|
73
|
+
Array.isArray(prevHydrated) &&
|
|
74
|
+
newArr.length > prevArr.length &&
|
|
75
|
+
newArr.length - prevArr.length <= 5 // small delta — worth optimizing
|
|
76
|
+
) {
|
|
77
|
+
// Build a set of source URIs from previous results for quick lookup
|
|
78
|
+
const prevSources = new Set(prevArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
|
|
79
|
+
const addedRows = newArr.filter((r) => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
80
|
+
// Check that no rows were removed (pure addition)
|
|
81
|
+
const newSources = new Set(newArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
|
|
82
|
+
const removedRows = prevArr.filter((r) => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
|
|
83
|
+
if (removedRows.length === 0 && addedRows.length > 0) {
|
|
84
|
+
// Verify ALL added rows have sources not in previous results.
|
|
85
|
+
// If any added row's source matches an existing source, it means
|
|
86
|
+
// an existing instance got new links — we need full rehydration.
|
|
87
|
+
const prevSourceIds = new Set(prevArr.map((r) => r.source));
|
|
88
|
+
const allNewSources = addedRows.every((r) => !prevSourceIds.has(r.source));
|
|
89
|
+
if (allNewSources) {
|
|
90
|
+
// Pure addition of new instances — hydrate only the new rows
|
|
91
|
+
try {
|
|
92
|
+
const deltaHydrated = await firstSub.hydrate(addedRows);
|
|
93
|
+
if (Array.isArray(deltaHydrated)) {
|
|
94
|
+
const merged = [...prevHydrated, ...deltaHydrated];
|
|
95
|
+
newEntry.latestHydrated = merged;
|
|
96
|
+
for (const cb of newEntry.callbacks) {
|
|
97
|
+
try {
|
|
98
|
+
cb.onResult(merged);
|
|
99
|
+
}
|
|
100
|
+
catch (e) { /* subscriber error */ }
|
|
101
|
+
}
|
|
102
|
+
return; // Delta path succeeded
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// Delta hydration failed — fall through to full hydration
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// Full hydration fallback
|
|
66
112
|
const hydrated = await firstSub.hydrate(rawResult);
|
|
67
113
|
newEntry.latestHydrated = hydrated;
|
|
68
114
|
// Distribute to all callbacks
|
package/lib/src/model/types.d.ts
CHANGED
|
@@ -41,12 +41,47 @@ export type ParentScope = {
|
|
|
41
41
|
id: string;
|
|
42
42
|
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
|
+
}
|
|
44
78
|
/**
|
|
45
79
|
* Describes which relations to eager-load when querying.
|
|
46
80
|
*
|
|
47
81
|
* Each value is either:
|
|
48
82
|
* - `true` — hydrate the relation one level deep
|
|
49
83
|
* - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
|
|
84
|
+
* - An `IncludeProjection` — user-named derived field (count, filtered subset, single item)
|
|
50
85
|
*
|
|
51
86
|
* @example
|
|
52
87
|
* ```typescript
|
|
@@ -58,10 +93,13 @@ export type ParentScope = {
|
|
|
58
93
|
*
|
|
59
94
|
* // Nested eager-load
|
|
60
95
|
* { comments: { include: { author: true } } }
|
|
96
|
+
*
|
|
97
|
+
* // Projection: count + filtered single item
|
|
98
|
+
* { $signalCount: { from: 'signals', count: true }, $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 } }
|
|
61
99
|
* ```
|
|
62
100
|
*/
|
|
63
101
|
export interface IncludeMap {
|
|
64
|
-
[relation: string]: boolean | RelationSubQuery;
|
|
102
|
+
[relation: string]: boolean | RelationSubQuery | IncludeProjection;
|
|
65
103
|
}
|
|
66
104
|
export type Query = {
|
|
67
105
|
/** Filter to instances that are the target of a link from a given parent. */
|
|
@@ -73,6 +111,16 @@ export type Query = {
|
|
|
73
111
|
offset?: number;
|
|
74
112
|
limit?: number;
|
|
75
113
|
count?: boolean;
|
|
114
|
+
/**
|
|
115
|
+
* When true, SPARQL property getters (@Property with `getter`) ARE evaluated
|
|
116
|
+
* during collection hydration. By default, collection queries skip getter
|
|
117
|
+
* evaluation for performance — getters run only on single-instance get().
|
|
118
|
+
*
|
|
119
|
+
* Use this when you need getter-backed properties (e.g. `replyingTo`,
|
|
120
|
+
* `isPopular`) in a list query. For most list/feed UIs, leave this off
|
|
121
|
+
* and use `Ad4mModel.evaluateGetters()` on visible items only.
|
|
122
|
+
*/
|
|
123
|
+
deepQuery?: boolean;
|
|
76
124
|
};
|
|
77
125
|
/**
|
|
78
126
|
* Sub-query options for a specific relation inside an `IncludeMap`.
|
|
@@ -17,6 +17,8 @@ export type SyncStateChangeCallback = (state: PerspectiveState) => null;
|
|
|
17
17
|
export declare class PerspectiveClient {
|
|
18
18
|
#private;
|
|
19
19
|
constructor(client: ApolloClient<any>, subscribe?: boolean);
|
|
20
|
+
/** Get or create a proxy for a UUID. If the proxy exists in cache, update its handle and return it. */
|
|
21
|
+
private getOrCreateProxy;
|
|
20
22
|
setExpressionClient(client: ExpressionClient): void;
|
|
21
23
|
setNeighbourhoodClient(client: NeighbourhoodClient): void;
|
|
22
24
|
setAIClient(client: AIClient): void;
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _PerspectiveClient_apolloClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient;
|
|
12
|
+
var _PerspectiveClient_apolloClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_proxyCache;
|
|
13
13
|
import { gql } from "@apollo/client/core";
|
|
14
14
|
import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
|
|
15
15
|
import unwrapApolloResult from "../unwrapApolloResult";
|
|
@@ -53,6 +53,7 @@ export class PerspectiveClient {
|
|
|
53
53
|
_PerspectiveClient_expressionClient.set(this, void 0);
|
|
54
54
|
_PerspectiveClient_neighbourhoodClient.set(this, void 0);
|
|
55
55
|
_PerspectiveClient_aiClient.set(this, void 0);
|
|
56
|
+
_PerspectiveClient_proxyCache.set(this, new Map());
|
|
56
57
|
__classPrivateFieldSet(this, _PerspectiveClient_apolloClient, client, "f");
|
|
57
58
|
__classPrivateFieldSet(this, _PerspectiveClient_perspectiveAddedCallbacks, [], "f");
|
|
58
59
|
__classPrivateFieldSet(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], "f");
|
|
@@ -64,6 +65,17 @@ export class PerspectiveClient {
|
|
|
64
65
|
this.subscribePerspectiveRemoved();
|
|
65
66
|
}
|
|
66
67
|
}
|
|
68
|
+
/** Get or create a proxy for a UUID. If the proxy exists in cache, update its handle and return it. */
|
|
69
|
+
getOrCreateProxy(handle) {
|
|
70
|
+
const existing = __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").get(handle.uuid);
|
|
71
|
+
if (existing) {
|
|
72
|
+
existing.updateHandle(handle);
|
|
73
|
+
return existing;
|
|
74
|
+
}
|
|
75
|
+
const proxy = new PerspectiveProxy(handle, this);
|
|
76
|
+
__classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").set(handle.uuid, proxy);
|
|
77
|
+
return proxy;
|
|
78
|
+
}
|
|
67
79
|
setExpressionClient(client) {
|
|
68
80
|
__classPrivateFieldSet(this, _PerspectiveClient_expressionClient, client, "f");
|
|
69
81
|
}
|
|
@@ -84,9 +96,12 @@ export class PerspectiveClient {
|
|
|
84
96
|
}
|
|
85
97
|
}`
|
|
86
98
|
}));
|
|
87
|
-
return perspectives.map(handle =>
|
|
99
|
+
return perspectives.map(handle => this.getOrCreateProxy(handle));
|
|
88
100
|
}
|
|
89
101
|
async byUUID(uuid) {
|
|
102
|
+
const cached = __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").get(uuid);
|
|
103
|
+
if (cached)
|
|
104
|
+
return cached;
|
|
90
105
|
const { perspective } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
|
|
91
106
|
query: gql `query perspective($uuid: String!) {
|
|
92
107
|
perspective(uuid: $uuid) {
|
|
@@ -97,7 +112,7 @@ export class PerspectiveClient {
|
|
|
97
112
|
}));
|
|
98
113
|
if (!perspective)
|
|
99
114
|
return null;
|
|
100
|
-
return
|
|
115
|
+
return this.getOrCreateProxy(perspective);
|
|
101
116
|
}
|
|
102
117
|
async snapshotByUUID(uuid) {
|
|
103
118
|
const { perspectiveSnapshot } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
|
|
@@ -235,7 +250,7 @@ export class PerspectiveClient {
|
|
|
235
250
|
}`,
|
|
236
251
|
variables: { name }
|
|
237
252
|
}));
|
|
238
|
-
return
|
|
253
|
+
return this.getOrCreateProxy(perspectiveAdd);
|
|
239
254
|
}
|
|
240
255
|
async update(uuid, name) {
|
|
241
256
|
const { perspectiveUpdate } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
@@ -246,9 +261,12 @@ export class PerspectiveClient {
|
|
|
246
261
|
}`,
|
|
247
262
|
variables: { uuid, name }
|
|
248
263
|
}));
|
|
249
|
-
|
|
264
|
+
// Evict stale proxy — getOrCreateProxy will create a fresh one with updated handle
|
|
265
|
+
__classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
|
|
266
|
+
return this.getOrCreateProxy(perspectiveUpdate);
|
|
250
267
|
}
|
|
251
268
|
async remove(uuid) {
|
|
269
|
+
__classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
|
|
252
270
|
return unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
253
271
|
mutation: gql `mutation perspectiveRemove($uuid: String!) {
|
|
254
272
|
perspectiveRemove(uuid: $uuid)
|
|
@@ -401,9 +419,12 @@ export class PerspectiveClient {
|
|
|
401
419
|
`
|
|
402
420
|
}).subscribe({
|
|
403
421
|
next: result => {
|
|
422
|
+
const handle = result.data.perspectiveAdded;
|
|
404
423
|
__classPrivateFieldGet(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").forEach(cb => {
|
|
405
|
-
cb(
|
|
424
|
+
cb(handle);
|
|
406
425
|
});
|
|
426
|
+
// Populate cache so subsequent byUUID() calls get a hit
|
|
427
|
+
this.getOrCreateProxy(handle);
|
|
407
428
|
},
|
|
408
429
|
error: (e) => console.error(e)
|
|
409
430
|
});
|
|
@@ -419,9 +440,13 @@ export class PerspectiveClient {
|
|
|
419
440
|
`
|
|
420
441
|
}).subscribe({
|
|
421
442
|
next: result => {
|
|
443
|
+
const handle = result.data.perspectiveUpdated;
|
|
422
444
|
__classPrivateFieldGet(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").forEach(cb => {
|
|
423
|
-
cb(
|
|
445
|
+
cb(handle);
|
|
424
446
|
});
|
|
447
|
+
// Evict stale proxy and create fresh one with updated handle
|
|
448
|
+
__classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(handle.uuid);
|
|
449
|
+
this.getOrCreateProxy(handle);
|
|
425
450
|
},
|
|
426
451
|
error: (e) => console.error(e)
|
|
427
452
|
});
|
|
@@ -456,9 +481,12 @@ export class PerspectiveClient {
|
|
|
456
481
|
`
|
|
457
482
|
}).subscribe({
|
|
458
483
|
next: result => {
|
|
484
|
+
const uuid = result.data.perspectiveRemoved;
|
|
459
485
|
__classPrivateFieldGet(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").forEach(cb => {
|
|
460
|
-
cb(
|
|
486
|
+
cb(uuid);
|
|
461
487
|
});
|
|
488
|
+
// Evict from cache
|
|
489
|
+
__classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
|
|
462
490
|
},
|
|
463
491
|
error: (e) => console.error(e)
|
|
464
492
|
});
|
|
@@ -556,4 +584,4 @@ export class PerspectiveClient {
|
|
|
556
584
|
return perspectiveCommitBatch;
|
|
557
585
|
}
|
|
558
586
|
}
|
|
559
|
-
_PerspectiveClient_apolloClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap();
|
|
587
|
+
_PerspectiveClient_apolloClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_proxyCache = new WeakMap();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { PerspectiveClient } from "./PerspectiveClient";
|
|
2
|
+
import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
|
|
3
|
+
/**
|
|
4
|
+
* Focused unit tests for PerspectiveClient proxy cache behaviour.
|
|
5
|
+
* Uses a mock Apollo client to isolate cache logic from network.
|
|
6
|
+
*/
|
|
7
|
+
// Minimal mock Apollo client that returns controllable results
|
|
8
|
+
function createMockApolloClient(overrides = {}) {
|
|
9
|
+
return {
|
|
10
|
+
query: overrides.query || jest.fn().mockResolvedValue({ data: {} }),
|
|
11
|
+
mutate: overrides.mutate || jest.fn().mockResolvedValue({ data: {} }),
|
|
12
|
+
subscribe: overrides.subscribe || jest.fn().mockReturnValue({
|
|
13
|
+
subscribe: jest.fn()
|
|
14
|
+
}),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function makeHandle(uuid, name, state = PerspectiveState.Private) {
|
|
18
|
+
const h = new PerspectiveHandle(uuid, name, state);
|
|
19
|
+
return h;
|
|
20
|
+
}
|
|
21
|
+
describe('PerspectiveClient proxy cache', () => {
|
|
22
|
+
it('byUUID returns the same proxy reference on cache hit', async () => {
|
|
23
|
+
const handle = makeHandle('uuid-1', 'Test');
|
|
24
|
+
const mockClient = createMockApolloClient({
|
|
25
|
+
query: jest.fn().mockResolvedValue({
|
|
26
|
+
data: { perspective: handle }
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
30
|
+
const p1 = await client.byUUID('uuid-1');
|
|
31
|
+
const p2 = await client.byUUID('uuid-1');
|
|
32
|
+
expect(p1).toBe(p2);
|
|
33
|
+
// Only one query should have been made (second is cache hit)
|
|
34
|
+
expect(mockClient.query).toHaveBeenCalledTimes(1);
|
|
35
|
+
});
|
|
36
|
+
it('byUUID returns null for non-existent perspectives', async () => {
|
|
37
|
+
const mockClient = createMockApolloClient({
|
|
38
|
+
query: jest.fn().mockResolvedValue({
|
|
39
|
+
data: { perspective: null }
|
|
40
|
+
}),
|
|
41
|
+
});
|
|
42
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
43
|
+
const p = await client.byUUID('non-existent');
|
|
44
|
+
expect(p).toBeNull();
|
|
45
|
+
});
|
|
46
|
+
it('all() populates cache so subsequent byUUID is a hit', async () => {
|
|
47
|
+
const handles = [
|
|
48
|
+
makeHandle('uuid-a', 'A'),
|
|
49
|
+
makeHandle('uuid-b', 'B'),
|
|
50
|
+
];
|
|
51
|
+
const queryFn = jest.fn()
|
|
52
|
+
.mockResolvedValueOnce({ data: { perspectives: handles } });
|
|
53
|
+
const mockClient = createMockApolloClient({ query: queryFn });
|
|
54
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
55
|
+
const all = await client.all();
|
|
56
|
+
expect(all.length).toBe(2);
|
|
57
|
+
// byUUID should be a cache hit — no additional query
|
|
58
|
+
const pa = await client.byUUID('uuid-a');
|
|
59
|
+
expect(pa).toBe(all[0]);
|
|
60
|
+
expect(queryFn).toHaveBeenCalledTimes(1); // only the all() query
|
|
61
|
+
});
|
|
62
|
+
it('add() populates cache', async () => {
|
|
63
|
+
const handle = makeHandle('uuid-new', 'New');
|
|
64
|
+
const mockClient = createMockApolloClient({
|
|
65
|
+
mutate: jest.fn().mockResolvedValue({
|
|
66
|
+
data: { perspectiveAdd: handle }
|
|
67
|
+
}),
|
|
68
|
+
});
|
|
69
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
70
|
+
const added = await client.add('New');
|
|
71
|
+
expect(added.uuid).toBe('uuid-new');
|
|
72
|
+
// byUUID should hit cache
|
|
73
|
+
const fetched = await client.byUUID('uuid-new');
|
|
74
|
+
expect(fetched).toBe(added);
|
|
75
|
+
});
|
|
76
|
+
it('update() evicts and recreates cached proxy', async () => {
|
|
77
|
+
const originalHandle = makeHandle('uuid-u', 'Original');
|
|
78
|
+
const updatedHandle = makeHandle('uuid-u', 'Updated');
|
|
79
|
+
const queryFn = jest.fn().mockResolvedValue({
|
|
80
|
+
data: { perspective: originalHandle }
|
|
81
|
+
});
|
|
82
|
+
const mutateFn = jest.fn().mockResolvedValue({
|
|
83
|
+
data: { perspectiveUpdate: updatedHandle }
|
|
84
|
+
});
|
|
85
|
+
const mockClient = createMockApolloClient({
|
|
86
|
+
query: queryFn,
|
|
87
|
+
mutate: mutateFn,
|
|
88
|
+
});
|
|
89
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
90
|
+
const original = await client.byUUID('uuid-u');
|
|
91
|
+
expect(original.name).toBe('Original');
|
|
92
|
+
const updated = await client.update('uuid-u', 'Updated');
|
|
93
|
+
expect(updated).not.toBe(original); // new reference after eviction
|
|
94
|
+
expect(updated.name).toBe('Updated');
|
|
95
|
+
expect(original.name).toBe('Original'); // old reference retains stale data
|
|
96
|
+
});
|
|
97
|
+
it('remove() evicts from cache', async () => {
|
|
98
|
+
const handle = makeHandle('uuid-r', 'ToRemove');
|
|
99
|
+
const queryFn = jest.fn().mockResolvedValue({
|
|
100
|
+
data: { perspective: handle }
|
|
101
|
+
});
|
|
102
|
+
const mutateFn = jest.fn().mockResolvedValue({
|
|
103
|
+
data: { perspectiveRemove: true }
|
|
104
|
+
});
|
|
105
|
+
const mockClient = createMockApolloClient({
|
|
106
|
+
query: queryFn,
|
|
107
|
+
mutate: mutateFn,
|
|
108
|
+
});
|
|
109
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
110
|
+
const p = await client.byUUID('uuid-r');
|
|
111
|
+
expect(p).toBeTruthy();
|
|
112
|
+
expect(queryFn).toHaveBeenCalledTimes(1);
|
|
113
|
+
await client.remove('uuid-r');
|
|
114
|
+
// byUUID should miss cache and query again
|
|
115
|
+
const handle2 = makeHandle('uuid-r', 'Recreated');
|
|
116
|
+
queryFn.mockResolvedValueOnce({ data: { perspective: handle2 } });
|
|
117
|
+
const p2 = await client.byUUID('uuid-r');
|
|
118
|
+
expect(p2).not.toBe(p);
|
|
119
|
+
expect(p2.name).toBe('Recreated');
|
|
120
|
+
expect(queryFn).toHaveBeenCalledTimes(2);
|
|
121
|
+
});
|
|
122
|
+
it('getOrCreateProxy does not re-register listeners on cache hit', async () => {
|
|
123
|
+
// Verify that getting the same proxy twice does not create duplicate subscriptions
|
|
124
|
+
const handle = makeHandle('uuid-dup', 'NoDuplicates');
|
|
125
|
+
const subscribeCalls = [];
|
|
126
|
+
const subscribeFn = jest.fn().mockImplementation((opts) => {
|
|
127
|
+
// Track subscription query names
|
|
128
|
+
const queryStr = opts.query?.loc?.source?.body || '';
|
|
129
|
+
subscribeCalls.push(queryStr);
|
|
130
|
+
return {
|
|
131
|
+
subscribe: jest.fn()
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
const queryFn = jest.fn()
|
|
135
|
+
.mockResolvedValueOnce({ data: { perspectives: [handle] } });
|
|
136
|
+
const mockClient = createMockApolloClient({
|
|
137
|
+
query: queryFn,
|
|
138
|
+
subscribe: subscribeFn,
|
|
139
|
+
});
|
|
140
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
141
|
+
const all = await client.all();
|
|
142
|
+
const firstProxy = all[0];
|
|
143
|
+
// Record how many subscribe calls happened from PerspectiveProxy constructor
|
|
144
|
+
const callsAfterFirst = subscribeFn.mock.calls.length;
|
|
145
|
+
// Get same proxy again via all() — should be cache hit, no new constructor call
|
|
146
|
+
queryFn.mockResolvedValueOnce({ data: { perspectives: [handle] } });
|
|
147
|
+
const all2 = await client.all();
|
|
148
|
+
const secondProxy = all2[0];
|
|
149
|
+
expect(secondProxy).toBe(firstProxy);
|
|
150
|
+
// No additional subscribe calls should have been made
|
|
151
|
+
expect(subscribeFn.mock.calls.length).toBe(callsAfterFirst);
|
|
152
|
+
});
|
|
153
|
+
it('all() updates existing cached proxies with fresh data', async () => {
|
|
154
|
+
const handle1 = makeHandle('uuid-f', 'OldName');
|
|
155
|
+
const handle2 = makeHandle('uuid-f', 'FreshName');
|
|
156
|
+
const queryFn = jest.fn()
|
|
157
|
+
.mockResolvedValueOnce({ data: { perspective: handle1 } })
|
|
158
|
+
.mockResolvedValueOnce({ data: { perspectives: [handle2] } });
|
|
159
|
+
const mockClient = createMockApolloClient({ query: queryFn });
|
|
160
|
+
const client = new PerspectiveClient(mockClient, false);
|
|
161
|
+
const original = await client.byUUID('uuid-f');
|
|
162
|
+
expect(original.name).toBe('OldName');
|
|
163
|
+
const all = await client.all();
|
|
164
|
+
const refreshed = all.find(p => p.uuid === 'uuid-f');
|
|
165
|
+
expect(refreshed).toBe(original); // same reference
|
|
166
|
+
expect(refreshed.name).toBe('FreshName'); // updated in-place
|
|
167
|
+
expect(original.name).toBe('FreshName'); // original ref also updated
|
|
168
|
+
});
|
|
169
|
+
});
|
|
@@ -180,6 +180,9 @@ export declare class PerspectiveProxy {
|
|
|
180
180
|
* Note: Don't create this directly, use ad4m.perspective.add() instead.
|
|
181
181
|
*/
|
|
182
182
|
constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient);
|
|
183
|
+
/** Update the proxy's internal handle and public fields in-place.
|
|
184
|
+
* Keeps the same object reference so all holders see the update. */
|
|
185
|
+
updateHandle(handle: PerspectiveHandle): void;
|
|
183
186
|
/**
|
|
184
187
|
* Escapes special regex characters in a string to prevent ReDoS attacks
|
|
185
188
|
* and regex injection when building dynamic regular expressions.
|
|
@@ -351,6 +351,21 @@ export class PerspectiveProxy {
|
|
|
351
351
|
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
|
|
352
352
|
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
|
|
353
353
|
}
|
|
354
|
+
/** Update the proxy's internal handle and public fields in-place.
|
|
355
|
+
* Keeps the same object reference so all holders see the update. */
|
|
356
|
+
updateHandle(handle) {
|
|
357
|
+
if (handle.uuid !== __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid) {
|
|
358
|
+
throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid}" but received handle with UUID "${handle.uuid}". ` +
|
|
359
|
+
`This would silently diverge from listeners registered under the original UUID.`);
|
|
360
|
+
}
|
|
361
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_handle, handle, "f");
|
|
362
|
+
this.uuid = handle.uuid;
|
|
363
|
+
this.name = handle.name;
|
|
364
|
+
this.owners = handle.owners;
|
|
365
|
+
this.sharedUrl = handle.sharedUrl;
|
|
366
|
+
this.neighbourhood = handle.neighbourhood;
|
|
367
|
+
this.state = handle.state;
|
|
368
|
+
}
|
|
354
369
|
/**
|
|
355
370
|
* Escapes special regex characters in a string to prevent ReDoS attacks
|
|
356
371
|
* and regex injection when building dynamic regular expressions.
|