@coasys/ad4m 0.13.0-test-5 → 0.13.0-test-6
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 +610 -337
- package/lib/index.js +608 -338
- package/lib/src/Ad4mClient.d.ts +1 -1
- package/lib/src/Ad4mClient.js +2 -1
- package/lib/src/agent/AgentClient.d.ts +16 -0
- package/lib/src/agent/AgentClient.js +74 -4
- package/lib/src/cache/PersistentCache.d.ts +40 -0
- package/lib/src/cache/PersistentCache.js +139 -0
- package/lib/src/expression/ExpressionClient.d.ts +8 -0
- package/lib/src/expression/ExpressionClient.js +113 -5
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.js +29 -57
- package/lib/src/model/Ad4mModel.test.js +688 -1434
- package/lib/src/model/ModelQueryBuilder.js +0 -9
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/query-surreal.d.ts +44 -0
- package/lib/src/model/query-surreal.js +249 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/surreal-utils.d.ts +42 -0
- package/lib/src/model/surreal-utils.js +128 -0
- package/lib/src/model/types.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveClient.js +5 -13
- package/lib/src/perspectives/PerspectiveProxy.js +0 -3
- package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveResolver.js +11 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
- package/lib/src/runtime/RuntimeResolver.js +4 -197
- package/lib/src/schema.gql +1 -27
- package/lib/src/shacl/SHACLShape.test.js +0 -82
- package/package.json +1 -1
- package/src/Ad4mClient.test.ts +14 -4
- package/src/Ad4mClient.ts +2 -1
- package/src/agent/AgentClient.ts +84 -2
- package/src/cache/PersistentCache.ts +145 -0
- package/src/cache/cache.test.ts +713 -0
- package/src/expression/ExpressionClient.ts +137 -3
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.test.ts +1 -61
- package/src/model/Ad4mModel.ts +31 -57
- package/src/model/ModelQueryBuilder.ts +0 -6
- package/src/model/types.ts +1 -1
- package/src/perspectives/PerspectiveClient.ts +7 -17
- package/src/perspectives/PerspectiveProxy.ts +0 -3
- package/lib/src/model/hydration-batch.d.ts +0 -34
- package/lib/src/model/hydration-batch.js +0 -147
- package/lib/src/model/hydration-batching.test.d.ts +0 -7
- package/lib/src/model/hydration-batching.test.js +0 -456
- package/lib/src/model/model-manifest.d.ts +0 -41
- package/lib/src/model/model-manifest.js +0 -11
- package/lib/src/model/query-cache.test.d.ts +0 -1
- package/lib/src/model/query-cache.test.js +0 -43
- package/lib/src/model/query-sparql-batch.d.ts +0 -17
- package/lib/src/model/query-sparql-batch.js +0 -260
- package/lib/src/model/query-sparql.test.d.ts +0 -1
- package/lib/src/model/query-sparql.test.js +0 -312
- package/lib/src/model/subscription-delta.test.d.ts +0 -24
- package/lib/src/model/subscription-delta.test.js +0 -180
- package/lib/src/model/subscription-pool.d.ts +0 -39
- package/lib/src/model/subscription-pool.js +0 -165
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
|
@@ -2,16 +2,36 @@ import { ApiClient } from "../apiClient";
|
|
|
2
2
|
import { InteractionCall, InteractionMeta } from "../language/Language";
|
|
3
3
|
import { ExpressionRendered } from "./Expression";
|
|
4
4
|
import { Literal } from "../Literal";
|
|
5
|
+
import { PersistentCache, createPersistentCache } from "../cache/PersistentCache";
|
|
5
6
|
import type { CreateExpressionRequest, ExpressionManyRequest } from "../generated/api";
|
|
6
7
|
|
|
8
|
+
interface CachedExpression {
|
|
9
|
+
data: ExpressionRendered;
|
|
10
|
+
size: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
7
13
|
export class ExpressionClient {
|
|
8
14
|
#apiClient: ApiClient
|
|
9
15
|
|
|
16
|
+
// L1: in-memory LRU cache (hot path, sub-ms)
|
|
17
|
+
#memCache = new Map<string, CachedExpression>();
|
|
18
|
+
#inflight = new Map<string, Promise<ExpressionRendered>>();
|
|
19
|
+
/** Maximum number of entries in the L1 memory cache. */
|
|
20
|
+
static MAX_MEM_ENTRIES = 200;
|
|
21
|
+
/** Maximum total size (in bytes) of L1 memory cache values. */
|
|
22
|
+
static MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
|
|
23
|
+
#totalMemBytes = 0;
|
|
24
|
+
|
|
25
|
+
// L2: persistent cache (IndexedDB in browser, NullCache in Node)
|
|
26
|
+
#persistent: PersistentCache<ExpressionRendered>;
|
|
27
|
+
|
|
10
28
|
constructor(baseUrl: string, token?: string, sharedApiClient?: ApiClient) {
|
|
11
29
|
this.#apiClient = sharedApiClient || new ApiClient(baseUrl, token)
|
|
30
|
+
this.#persistent = createPersistentCache<ExpressionRendered>('ad4m-expression-cache', 'expressions');
|
|
12
31
|
}
|
|
13
32
|
|
|
14
33
|
async get(url: string, alwaysGet: boolean = false): Promise<ExpressionRendered> {
|
|
34
|
+
// Existing literal fast-path
|
|
15
35
|
if(!alwaysGet){
|
|
16
36
|
try {
|
|
17
37
|
let literalValue = Literal.fromUrl(url).get();
|
|
@@ -23,11 +43,120 @@ export class ExpressionClient {
|
|
|
23
43
|
} catch(e) {}
|
|
24
44
|
}
|
|
25
45
|
|
|
26
|
-
|
|
46
|
+
// L1: memory hit
|
|
47
|
+
if (!alwaysGet) {
|
|
48
|
+
const memHit = this.#memCache.get(url);
|
|
49
|
+
if (memHit) return memHit.data;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Deduplicate in-flight requests
|
|
53
|
+
if (!alwaysGet) {
|
|
54
|
+
const existing = this.#inflight.get(url);
|
|
55
|
+
if (existing) return existing;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// L2 check + L3 network
|
|
59
|
+
const promise = (async () => {
|
|
60
|
+
if (!alwaysGet) {
|
|
61
|
+
const persisted = await this.#persistent.get(url);
|
|
62
|
+
if (persisted) {
|
|
63
|
+
this.#memCacheResult(url, persisted); // promote to L1
|
|
64
|
+
return persisted;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// L3: network fetch
|
|
69
|
+
const result = await this.#apiClient.call<ExpressionRendered>('expression.get', { url });
|
|
70
|
+
this.#memCacheResult(url, result);
|
|
71
|
+
this.#persistent.put(url, result); // fire-and-forget write to L2
|
|
72
|
+
return result;
|
|
73
|
+
})();
|
|
74
|
+
|
|
75
|
+
this.#inflight.set(url, promise);
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
return await promise;
|
|
79
|
+
} finally {
|
|
80
|
+
this.#inflight.delete(url);
|
|
81
|
+
}
|
|
27
82
|
}
|
|
28
83
|
|
|
29
84
|
async getMany(urls: string[]): Promise<ExpressionRendered[]> {
|
|
30
|
-
|
|
85
|
+
// Check L1 first
|
|
86
|
+
const results: (ExpressionRendered | null)[] = urls.map(
|
|
87
|
+
u => this.#memCache.get(u)?.data ?? null
|
|
88
|
+
);
|
|
89
|
+
let uncachedIndices = results
|
|
90
|
+
.map((r, i) => r === null ? i : -1)
|
|
91
|
+
.filter(i => i >= 0);
|
|
92
|
+
|
|
93
|
+
if (uncachedIndices.length === 0) return results as ExpressionRendered[];
|
|
94
|
+
|
|
95
|
+
// Check L2 for remaining misses
|
|
96
|
+
const l2Results = await Promise.all(
|
|
97
|
+
uncachedIndices.map(i => this.#persistent.get(urls[i]))
|
|
98
|
+
);
|
|
99
|
+
const stillMissing: number[] = [];
|
|
100
|
+
for (let j = 0; j < uncachedIndices.length; j++) {
|
|
101
|
+
const idx = uncachedIndices[j];
|
|
102
|
+
if (l2Results[j]) {
|
|
103
|
+
results[idx] = l2Results[j]!;
|
|
104
|
+
this.#memCacheResult(urls[idx], l2Results[j]!); // promote to L1
|
|
105
|
+
} else {
|
|
106
|
+
stillMissing.push(idx);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (stillMissing.length === 0) return results as ExpressionRendered[];
|
|
111
|
+
|
|
112
|
+
// L3: fetch only truly uncached URLs
|
|
113
|
+
const uncachedUrls = stillMissing.map(i => urls[i]);
|
|
114
|
+
const fetched = await this.#apiClient.call<ExpressionRendered[]>(
|
|
115
|
+
'expression.getMany', { urls: uncachedUrls }
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
for (let i = 0; i < stillMissing.length; i++) {
|
|
119
|
+
const idx = stillMissing[i];
|
|
120
|
+
results[idx] = fetched[i];
|
|
121
|
+
if (fetched[i]) {
|
|
122
|
+
this.#memCacheResult(uncachedUrls[i], fetched[i]);
|
|
123
|
+
this.#persistent.put(uncachedUrls[i], fetched[i]); // fire-and-forget
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return results as ExpressionRendered[];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Insert a result into L1 memory cache with LRU eviction.
|
|
132
|
+
*/
|
|
133
|
+
#memCacheResult(url: string, data: ExpressionRendered): void {
|
|
134
|
+
const size = JSON.stringify(data).length;
|
|
135
|
+
|
|
136
|
+
// Evict oldest entries if we'd exceed limits
|
|
137
|
+
while (
|
|
138
|
+
this.#memCache.size >= ExpressionClient.MAX_MEM_ENTRIES ||
|
|
139
|
+
this.#totalMemBytes + size > ExpressionClient.MAX_MEM_BYTES
|
|
140
|
+
) {
|
|
141
|
+
const oldest = this.#memCache.keys().next().value;
|
|
142
|
+
if (!oldest) break;
|
|
143
|
+
const entry = this.#memCache.get(oldest)!;
|
|
144
|
+
this.#totalMemBytes -= entry.size;
|
|
145
|
+
this.#memCache.delete(oldest);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
this.#memCache.set(url, { data, size });
|
|
149
|
+
this.#totalMemBytes += size;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Clear both L1 (memory) and L2 (persistent) expression caches.
|
|
154
|
+
*/
|
|
155
|
+
clearCache(): void {
|
|
156
|
+
this.#memCache.clear();
|
|
157
|
+
this.#inflight.clear();
|
|
158
|
+
this.#totalMemBytes = 0;
|
|
159
|
+
this.#persistent.clear(); // fire-and-forget
|
|
31
160
|
}
|
|
32
161
|
|
|
33
162
|
async getRaw(url: string): Promise<string> {
|
|
@@ -44,6 +173,11 @@ export class ExpressionClient {
|
|
|
44
173
|
}
|
|
45
174
|
|
|
46
175
|
async interact(url: string, interactionCall: InteractionCall): Promise<string|null> {
|
|
47
|
-
|
|
176
|
+
const result = await this.#apiClient.call<string|null>('expression.interact', { url, interactionCall });
|
|
177
|
+
// Interactions can mutate the expression — invalidate cache so next get() fetches fresh
|
|
178
|
+
this.#memCache.delete(url);
|
|
179
|
+
this.#inflight.delete(url);
|
|
180
|
+
this.#persistent.delete(url); // fire-and-forget
|
|
181
|
+
return result;
|
|
48
182
|
}
|
|
49
183
|
}
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from "./Ad4mClient"
|
|
|
2
2
|
export * from "./Address";
|
|
3
3
|
export * from "./agent/Agent";
|
|
4
4
|
export * from "./agent/AgentStatus";
|
|
5
|
+
export * from "./cache/PersistentCache";
|
|
5
6
|
export * from "./Exception";
|
|
6
7
|
export * from "./expression/Expression";
|
|
7
8
|
export * from "./expression/ExpressionRef";
|
|
@@ -1424,66 +1424,6 @@ describe("ModelQueryBuilder paginateSubscribe", () => {
|
|
|
1424
1424
|
expect(queryJson.offset).toBe(0);
|
|
1425
1425
|
});
|
|
1426
1426
|
|
|
1427
|
-
it("paginateSubscribe should skip isInit messages from subscription", async () => {
|
|
1428
|
-
const mockSubscriptionId = "paginate-init-sub";
|
|
1429
|
-
let capturedCallback: ((result: any) => void) | null = null;
|
|
1430
|
-
|
|
1431
|
-
const mockClient = {
|
|
1432
|
-
modelSubscribe: jest.fn().mockResolvedValue({
|
|
1433
|
-
subscriptionId: mockSubscriptionId,
|
|
1434
|
-
result: { instances: [], totalCount: 0 },
|
|
1435
|
-
}),
|
|
1436
|
-
subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
|
|
1437
|
-
capturedCallback = cb;
|
|
1438
|
-
return () => {};
|
|
1439
|
-
}),
|
|
1440
|
-
keepAliveQuery: jest.fn().mockResolvedValue(true),
|
|
1441
|
-
disposeQuerySubscription: jest.fn().mockResolvedValue(true),
|
|
1442
|
-
};
|
|
1443
|
-
|
|
1444
|
-
let modelQueryCallCount = 0;
|
|
1445
|
-
const mockPerspective = {
|
|
1446
|
-
uuid: "test-uuid",
|
|
1447
|
-
client: mockClient,
|
|
1448
|
-
modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
|
|
1449
|
-
return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
|
|
1450
|
-
}),
|
|
1451
|
-
modelQuery: jest.fn().mockImplementation(async () => {
|
|
1452
|
-
modelQueryCallCount++;
|
|
1453
|
-
return { instances: [], totalCount: 0 };
|
|
1454
|
-
}),
|
|
1455
|
-
} as any;
|
|
1456
|
-
|
|
1457
|
-
const { Ad4mModel, Model, Flag, Property } = require("./index");
|
|
1458
|
-
|
|
1459
|
-
@Model({ name: "InitGuardTest" })
|
|
1460
|
-
class InitGuardTest extends Ad4mModel {
|
|
1461
|
-
@Flag({ through: "test://type", value: "test://init" })
|
|
1462
|
-
type: string = "test://init";
|
|
1463
|
-
@Property({ through: "test://name" })
|
|
1464
|
-
name: string = "";
|
|
1465
|
-
}
|
|
1466
|
-
|
|
1467
|
-
const userCallback = jest.fn();
|
|
1468
|
-
const builder = InitGuardTest.query(mockPerspective);
|
|
1469
|
-
await builder.paginateSubscribe(10, 1, userCallback);
|
|
1470
|
-
|
|
1471
|
-
// Reset the count after initial fetch
|
|
1472
|
-
const initialCallCount = modelQueryCallCount;
|
|
1473
|
-
|
|
1474
|
-
// Simulate an isInit message from subscription
|
|
1475
|
-
expect(capturedCallback).not.toBeNull();
|
|
1476
|
-
capturedCallback!({ isInit: true });
|
|
1477
|
-
|
|
1478
|
-
// Wait for any async processing
|
|
1479
|
-
await new Promise(r => setTimeout(r, 50));
|
|
1480
|
-
|
|
1481
|
-
// modelQuery should NOT have been called again (isInit was filtered)
|
|
1482
|
-
expect(modelQueryCallCount).toBe(initialCallCount);
|
|
1483
|
-
// User callback should NOT have been invoked by isInit
|
|
1484
|
-
expect(userCallback).not.toHaveBeenCalled();
|
|
1485
|
-
});
|
|
1486
|
-
|
|
1487
1427
|
it("paginateSubscribe should re-fetch on real subscription updates", async () => {
|
|
1488
1428
|
const mockSubscriptionId = "paginate-update-sub";
|
|
1489
1429
|
let capturedCallback: ((result: any) => void) | null = null;
|
|
@@ -1530,7 +1470,7 @@ describe("ModelQueryBuilder paginateSubscribe", () => {
|
|
|
1530
1470
|
|
|
1531
1471
|
const initialCallCount = modelQueryCallCount;
|
|
1532
1472
|
|
|
1533
|
-
// Simulate a
|
|
1473
|
+
// Simulate a subscription update
|
|
1534
1474
|
capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
|
|
1535
1475
|
|
|
1536
1476
|
// Wait for async processing
|
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -857,7 +857,11 @@ export class Ad4mModel {
|
|
|
857
857
|
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
858
858
|
}
|
|
859
859
|
|
|
860
|
-
// Pre-compute conformance getters
|
|
860
|
+
// Pre-compute conformance getters for Rust-side evaluation.
|
|
861
|
+
// Where clauses are NOT compiled into getter SPARQL because stored
|
|
862
|
+
// property values are signed expression envelopes (literal:json:...),
|
|
863
|
+
// not simple literal:string:X values. Instead, where clauses are
|
|
864
|
+
// attached as metadata for Rust-side post-evaluation filtering.
|
|
861
865
|
{
|
|
862
866
|
const allRelMeta = getRelationsMetadata(this as any);
|
|
863
867
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
@@ -869,41 +873,30 @@ export class Ad4mModel {
|
|
|
869
873
|
const TargetClass = meta.target();
|
|
870
874
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
871
875
|
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
876
|
+
if (filter) {
|
|
877
|
+
rel.getter = filter.getter;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// Attach where-clause metadata for Rust-side post-getter filtering
|
|
877
881
|
if (rel.where) {
|
|
878
882
|
try {
|
|
879
883
|
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
880
|
-
let allSparqlFilterable = true;
|
|
881
884
|
if (targetMetadata) {
|
|
885
|
+
const predicates: Record<string, string> = {};
|
|
882
886
|
for (const propName of Object.keys(rel.where)) {
|
|
883
887
|
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
884
888
|
const propMeta = targetMetadata.properties[propName];
|
|
885
|
-
if (propMeta?.
|
|
886
|
-
|
|
887
|
-
break;
|
|
889
|
+
if (propMeta?.predicate) {
|
|
890
|
+
predicates[propName] = propMeta.predicate;
|
|
888
891
|
}
|
|
889
892
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
+
if (Object.keys(predicates).length > 0) {
|
|
894
|
+
rel.whereFilter = rel.where;
|
|
895
|
+
rel.wherePredicates = predicates;
|
|
896
|
+
}
|
|
893
897
|
}
|
|
894
898
|
} catch (_) {}
|
|
895
899
|
}
|
|
896
|
-
|
|
897
|
-
if (filter) {
|
|
898
|
-
let getter = filter.getter;
|
|
899
|
-
if (whereConditions.length > 0) {
|
|
900
|
-
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
901
|
-
}
|
|
902
|
-
rel.getter = getter;
|
|
903
|
-
} else if (whereConditions.length > 0) {
|
|
904
|
-
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
905
|
-
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
906
|
-
}
|
|
907
900
|
} catch (_) {}
|
|
908
901
|
}
|
|
909
902
|
}
|
|
@@ -1044,43 +1037,32 @@ export class Ad4mModel {
|
|
|
1044
1037
|
const TargetClass = meta.target();
|
|
1045
1038
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1046
1039
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1040
|
+
if (filter) {
|
|
1041
|
+
rel.getter = filter.getter;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// Attach where-clause metadata for Rust-side post-getter filtering.
|
|
1045
|
+
// Property values are signed expression envelopes (literal:json:...)
|
|
1046
|
+
// and cannot be matched by SPARQL FILTER on the raw IRI.
|
|
1052
1047
|
if (rel.where) {
|
|
1053
1048
|
try {
|
|
1054
1049
|
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
1055
|
-
let allSparqlFilterable = true;
|
|
1056
1050
|
if (targetMetadata) {
|
|
1051
|
+
const predicates: Record<string, string> = {};
|
|
1057
1052
|
for (const propName of Object.keys(rel.where)) {
|
|
1058
1053
|
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
1059
1054
|
const propMeta = targetMetadata.properties[propName];
|
|
1060
|
-
if (propMeta?.
|
|
1061
|
-
|
|
1062
|
-
break;
|
|
1055
|
+
if (propMeta?.predicate) {
|
|
1056
|
+
predicates[propName] = propMeta.predicate;
|
|
1063
1057
|
}
|
|
1064
1058
|
}
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1059
|
+
if (Object.keys(predicates).length > 0) {
|
|
1060
|
+
rel.whereFilter = rel.where;
|
|
1061
|
+
rel.wherePredicates = predicates;
|
|
1062
|
+
}
|
|
1068
1063
|
}
|
|
1069
1064
|
} catch (_) { /* target metadata unavailable */ }
|
|
1070
1065
|
}
|
|
1071
|
-
|
|
1072
|
-
if (filter) {
|
|
1073
|
-
let getter = filter.getter;
|
|
1074
|
-
if (whereConditions.length > 0) {
|
|
1075
|
-
// Append where conditions before the closing }
|
|
1076
|
-
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
1077
|
-
}
|
|
1078
|
-
rel.getter = getter;
|
|
1079
|
-
} else if (whereConditions.length > 0) {
|
|
1080
|
-
// No conformance filter but where clause exists — build getter from where alone
|
|
1081
|
-
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
1082
|
-
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
1083
|
-
}
|
|
1084
1066
|
} catch (e) {
|
|
1085
1067
|
// Target class may not be available; skip silently
|
|
1086
1068
|
}
|
|
@@ -1093,14 +1075,6 @@ export class Ad4mModel {
|
|
|
1093
1075
|
const shapeJson = JSON.stringify(metadata);
|
|
1094
1076
|
const queryJson = JSON.stringify(queryInput);
|
|
1095
1077
|
|
|
1096
|
-
// TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
|
|
1097
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1098
|
-
const rel = relMeta as any;
|
|
1099
|
-
if (rel.where) {
|
|
1100
|
-
console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
|
|
1104
1078
|
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1105
1079
|
|
|
1106
1080
|
// Convert JSON instances to model class instances, recursively constructing
|
|
@@ -409,10 +409,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
409
409
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
|
|
410
410
|
subscriptionId,
|
|
411
411
|
(rawResult: any) => {
|
|
412
|
-
// Skip delayed #init# messages — initial data was already returned
|
|
413
|
-
// synchronously from modelSubscribe(). Late init messages contain stale
|
|
414
|
-
// data that would overwrite real subscription updates.
|
|
415
|
-
if (rawResult && rawResult.isInit) return;
|
|
416
412
|
try {
|
|
417
413
|
const results = parseResults(rawResult);
|
|
418
414
|
const fp = buildFingerprint(results);
|
|
@@ -537,7 +533,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
537
533
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
|
|
538
534
|
subscriptionId,
|
|
539
535
|
(rawResult: any) => {
|
|
540
|
-
if (rawResult && rawResult.isInit) return;
|
|
541
536
|
try {
|
|
542
537
|
callback(parseCount(rawResult));
|
|
543
538
|
} catch (e) {
|
|
@@ -674,7 +669,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
674
669
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
|
|
675
670
|
subscriptionId,
|
|
676
671
|
(rawResult: any) => {
|
|
677
|
-
if (rawResult && rawResult.isInit) return;
|
|
678
672
|
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
679
673
|
},
|
|
680
674
|
);
|
package/src/model/types.ts
CHANGED
|
@@ -160,7 +160,7 @@ export type GetOptions = Pick<Query, 'include' | 'properties'>;
|
|
|
160
160
|
// Result types
|
|
161
161
|
// ---------------------------------------------------------------------------
|
|
162
162
|
|
|
163
|
-
export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number
|
|
163
|
+
export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number };
|
|
164
164
|
export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
|
|
165
165
|
export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
|
|
166
166
|
|
|
@@ -16,14 +16,8 @@ export type UuidCallback = (uuid: string) => null
|
|
|
16
16
|
export type LinkCallback = (link: LinkExpression) => null
|
|
17
17
|
export type SyncStateChangeCallback = (state: PerspectiveState) => null
|
|
18
18
|
|
|
19
|
-
function normalizeQueryResult(raw: unknown, errorContext: string):
|
|
19
|
+
function normalizeQueryResult(raw: unknown, errorContext: string): AllInstancesResult {
|
|
20
20
|
let finalResult: unknown = raw
|
|
21
|
-
let isInit = false
|
|
22
|
-
|
|
23
|
-
if (typeof finalResult === 'string' && finalResult.startsWith('#init#')) {
|
|
24
|
-
finalResult = finalResult.substring(6)
|
|
25
|
-
isInit = true
|
|
26
|
-
}
|
|
27
21
|
|
|
28
22
|
if (typeof finalResult === 'string') {
|
|
29
23
|
try {
|
|
@@ -33,11 +27,7 @@ function normalizeQueryResult(raw: unknown, errorContext: string): { result: All
|
|
|
33
27
|
}
|
|
34
28
|
}
|
|
35
29
|
|
|
36
|
-
|
|
37
|
-
(finalResult as Record<string, unknown>).isInit = true
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return { result: finalResult as AllInstancesResult, isInit }
|
|
30
|
+
return finalResult as AllInstancesResult
|
|
41
31
|
}
|
|
42
32
|
|
|
43
33
|
export class PerspectiveClient {
|
|
@@ -131,13 +121,13 @@ export class PerspectiveClient {
|
|
|
131
121
|
return JSON.parse(result)
|
|
132
122
|
}
|
|
133
123
|
|
|
134
|
-
async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult
|
|
124
|
+
async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult }> {
|
|
135
125
|
const response = await this.#apiClient.call<{ subscriptionId: string, result: unknown }>(
|
|
136
126
|
'perspective.subscribeQuery', { uuid, query }
|
|
137
127
|
)
|
|
138
128
|
const { subscriptionId, result } = response
|
|
139
|
-
const
|
|
140
|
-
return { subscriptionId, result:
|
|
129
|
+
const parsed = normalizeQueryResult(result, 'Error parsing subscribeQuery result:')
|
|
130
|
+
return { subscriptionId, result: parsed }
|
|
141
131
|
}
|
|
142
132
|
|
|
143
133
|
async perspectiveKeepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean> {
|
|
@@ -161,8 +151,8 @@ export class PerspectiveClient {
|
|
|
161
151
|
const eventSubscriptionId = event.subscriptionId || event.subscription_id
|
|
162
152
|
if (eventSubscriptionId !== subscriptionId) return
|
|
163
153
|
|
|
164
|
-
const
|
|
165
|
-
onData(
|
|
154
|
+
const parsed = normalizeQueryResult(event.result, 'Error parsing query subscription:')
|
|
155
|
+
onData(parsed)
|
|
166
156
|
}
|
|
167
157
|
)
|
|
168
158
|
this.#querySubscriptionUnsubscribers.set(subscriptionId, unsub)
|
|
@@ -171,9 +171,6 @@ export class QuerySubscriptionProxy {
|
|
|
171
171
|
this.#initReject = undefined;
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
// Skip duplicate init messages
|
|
175
|
-
if (updateResult.isInit && this.#latestResult) return;
|
|
176
|
-
|
|
177
174
|
this.#latestResult = updateResult;
|
|
178
175
|
this.#notifyCallbacks(updateResult);
|
|
179
176
|
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Batch hydration for SPARQL batch query results.
|
|
3
|
-
*
|
|
4
|
-
* Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
|
|
5
|
-
* with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
|
|
6
|
-
* model instances.
|
|
7
|
-
*
|
|
8
|
-
* @module
|
|
9
|
-
*/
|
|
10
|
-
import type { IncludeMap } from "./types";
|
|
11
|
-
/**
|
|
12
|
-
* A row returned by the batch SPARQL query.
|
|
13
|
-
*/
|
|
14
|
-
interface BatchRow {
|
|
15
|
-
depth: string;
|
|
16
|
-
parentBase: string;
|
|
17
|
-
relationName: string;
|
|
18
|
-
source: string;
|
|
19
|
-
predicate: string;
|
|
20
|
-
target: string;
|
|
21
|
-
author: string;
|
|
22
|
-
timestamp: string;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Hydrate batch SPARQL results into a tree of model instances.
|
|
26
|
-
*
|
|
27
|
-
* @param rows - Flat rows from the batch SPARQL query
|
|
28
|
-
* @param rootClass - The root model class (extends Ad4mModel)
|
|
29
|
-
* @param includeMap - The include specification from the query
|
|
30
|
-
* @param perspective - The PerspectiveProxy for creating instances
|
|
31
|
-
* @returns Array of hydrated root instances with relations populated
|
|
32
|
-
*/
|
|
33
|
-
export declare function hydrateBatchResult<T>(rows: BatchRow[], rootClass: any, includeMap: IncludeMap, perspective: any): Promise<T[]>;
|
|
34
|
-
export {};
|