jinaga-server 3.5.5 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/authorization/authorization-keystore.d.ts +34 -2
  2. package/dist/authorization/authorization-keystore.js +59 -4
  3. package/dist/authorization/authorization-keystore.js.map +1 -1
  4. package/dist/feeds/feed-stream-session.d.ts +84 -0
  5. package/dist/feeds/feed-stream-session.js +331 -0
  6. package/dist/feeds/feed-stream-session.js.map +1 -0
  7. package/dist/http/router.d.ts +10 -3
  8. package/dist/http/router.js +186 -184
  9. package/dist/http/router.js.map +1 -1
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +5 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/jinaga-server.d.ts +7 -0
  14. package/dist/jinaga-server.js +19 -2
  15. package/dist/jinaga-server.js.map +1 -1
  16. package/dist/memory/memory-keystore.js +1 -1
  17. package/dist/memory/memory-keystore.js.map +1 -1
  18. package/dist/postgres/query-description.d.ts +1 -0
  19. package/dist/postgres/query-description.js +34 -3
  20. package/dist/postgres/query-description.js.map +1 -1
  21. package/dist/postgres/specification-sql.js +7 -1
  22. package/dist/postgres/specification-sql.js.map +1 -1
  23. package/docs/design/feeds-persistent-proxy-plan.md +11 -1
  24. package/integration-test/jinaga-test/distribution-multi-given.test.js +184 -0
  25. package/integration-test/jinaga-test/distribution-negating-feed.test.js +202 -0
  26. package/integration-test/jinaga-test/feed-existential-input.test.js +241 -0
  27. package/integration-test/jinaga-test/feeds-endpoint.test.js +140 -0
  28. package/integration-test/jinaga-test/package-lock.json +4 -4
  29. package/integration-test/jinaga-test/package.json +3 -2
  30. package/integration-test/jinaga-test/subscription-anchor-arrival.test.js +129 -0
  31. package/integration-test/jinaga-test/subscription-helpers.js +60 -0
  32. package/integration-test/jinaga-test/subscription-late-auth.test.js +245 -0
  33. package/integration-test/jinaga-test/subscription-no-rule.test.js +137 -0
  34. package/package.json +2 -2
  35. package/src/authorization/authorization-keystore.ts +106 -5
  36. package/src/feeds/feed-stream-session.ts +386 -0
  37. package/src/http/router.ts +212 -237
  38. package/src/index.ts +2 -1
  39. package/src/jinaga-server.ts +45 -5
  40. package/src/memory/memory-keystore.ts +1 -1
  41. package/src/postgres/query-description.ts +66 -11
  42. package/src/postgres/specification-sql.ts +7 -1
  43. package/test/authorization/intermediateProjectionFeedSpec.ts +189 -0
  44. package/test/authorization/subscriptionIntersectionSpec.ts +220 -0
  45. package/test/feeds/feedStreamSessionRegressionSpec.ts +227 -0
  46. package/test/feeds/feedStreamSessionSpec.ts +351 -0
  47. package/test/http/anchorListenerSpec.ts +117 -0
  48. package/test/http/feedStreamSessionIntegrationSpec.ts +202 -0
  49. package/test/http/lateAuthRecoverySpec.ts +435 -0
  50. package/test/http/streamFeedAnchorSpec.ts +171 -0
@@ -2,6 +2,7 @@ import {
2
2
  Authorization,
3
3
  AuthorizationEngine,
4
4
  AuthorizationRules,
5
+ DistributionDenialCode,
5
6
  DistributionEngine,
6
7
  DistributionRules,
7
8
  FactEnvelope,
@@ -17,10 +18,54 @@ import {
17
18
  factReferenceEquals
18
19
  } from "jinaga";
19
20
 
21
+ export interface DistributionIntersectionBranch {
22
+ start: FactReference[];
23
+ specification: Specification;
24
+ }
25
+
26
+ // The engine failure that made a subscription reactive (authorized via
27
+ // intersection) or denied. Carried so POST /feeds can report the structured
28
+ // per-feed decision (issue #168 S1) without recomputing distribution.
29
+ export interface DistributionDenial {
30
+ reason: string;
31
+ code: DistributionDenialCode;
32
+ }
33
+
34
+ export type DistributionBranchesResult =
35
+ // Pass-through authorized when `denial` is absent; authorized-via-
36
+ // intersection (reactive) when `denial` carries the engine failure that
37
+ // triggered the intersection.
38
+ | { type: "success"; branches: DistributionIntersectionBranch[]; denial?: DistributionDenial }
39
+ | { type: "denied"; reason: string; code: DistributionDenialCode };
40
+
41
+ export type FeedResult =
42
+ | { type: "success"; feed: FactFeed }
43
+ | { type: "denied"; reason: string };
44
+
45
+ export interface SubscriptionAuthorizer {
46
+ verifyDistributionOrIntersect(
47
+ userIdentity: UserIdentity | null,
48
+ specification: Specification,
49
+ namedStart: ReferencesByName
50
+ ): Promise<DistributionBranchesResult>;
51
+ feedPreVerified(
52
+ userIdentity: UserIdentity | null,
53
+ specification: Specification,
54
+ start: FactReference[],
55
+ bookmark: string
56
+ ): Promise<FactFeed>;
57
+ feedWithDistribution(
58
+ userIdentity: UserIdentity | null,
59
+ specification: Specification,
60
+ start: FactReference[],
61
+ bookmark: string
62
+ ): Promise<FeedResult>;
63
+ }
64
+
20
65
  import { Keystore } from "../keystore";
21
66
  import { DistributedFactCache } from "./distributed-fact-cache";
22
67
 
23
- export class AuthorizationKeystore implements Authorization {
68
+ export class AuthorizationKeystore implements Authorization, SubscriptionAuthorizer {
24
69
  private authorizationEngine: AuthorizationEngine | null;
25
70
  private distributionEngine: DistributionEngine | null;
26
71
  private distributedFacts: DistributedFactCache = new DistributedFactCache();
@@ -70,6 +115,14 @@ export class AuthorizationKeystore implements Authorization {
70
115
  }
71
116
 
72
117
  async feed(userIdentity: UserIdentity | null, specification: Specification, start: FactReference[], bookmark: string): Promise<FactFeed> {
118
+ const result = await this.feedWithDistribution(userIdentity, specification, start, bookmark);
119
+ if (result.type === "denied") {
120
+ throw new Forbidden(result.reason);
121
+ }
122
+ return result.feed;
123
+ }
124
+
125
+ async feedWithDistribution(userIdentity: UserIdentity | null, specification: Specification, start: FactReference[], bookmark: string): Promise<FeedResult> {
73
126
  if (this.distributionEngine) {
74
127
  const userReference: FactReference | null = userIdentity
75
128
  ? await this.keystore.getUserFact(userIdentity)
@@ -80,18 +133,35 @@ export class AuthorizationKeystore implements Authorization {
80
133
  }), {} as ReferencesByName);
81
134
  const canDistribute = await this.distributionEngine.canDistributeToAll([specification], namedStart, userReference);
82
135
  if (canDistribute.type === "failure") {
83
- throw new Forbidden(canDistribute.reason);
136
+ return { type: "denied", reason: canDistribute.reason };
84
137
  }
85
138
  const factFeed = await this.store.feed(specification, start, bookmark);
86
139
  const factReferences = factFeed.tuples
87
140
  .flatMap(tuple => tuple.facts)
88
141
  .filter((value, index, self) => self.findIndex(factReferenceEquals(value)) === index);
89
142
  this.distributedFacts.add(factReferences, userReference);
90
- return factFeed;
143
+ return { type: "success", feed: factFeed };
91
144
  }
92
- else {
93
- return await this.store.feed(specification, start, bookmark);
145
+ return { type: "success", feed: await this.store.feed(specification, start, bookmark) };
146
+ }
147
+
148
+ async feedPreVerified(userIdentity: UserIdentity | null, specification: Specification, start: FactReference[], bookmark: string): Promise<FactFeed> {
149
+ // Caller has already established that this feed is safe to serve
150
+ // (e.g. produced by intersectForSubscribe — the spec lifts its own
151
+ // authorization condition into the matches and therefore self-
152
+ // filters). Skip the redundant per-query distribution check, but
153
+ // keep tracking the returned references so /load stays consistent.
154
+ const factFeed = await this.store.feed(specification, start, bookmark);
155
+ if (this.distributionEngine) {
156
+ const userReference: FactReference | null = userIdentity
157
+ ? await this.keystore.getUserFact(userIdentity)
158
+ : null;
159
+ const factReferences = factFeed.tuples
160
+ .flatMap(tuple => tuple.facts)
161
+ .filter((value, index, self) => self.findIndex(factReferenceEquals(value)) === index);
162
+ this.distributedFacts.add(factReferences, userReference);
94
163
  }
164
+ return factFeed;
95
165
  }
96
166
 
97
167
  async load(userIdentity: UserIdentity, references: FactReference[]) {
@@ -165,4 +235,35 @@ export class AuthorizationKeystore implements Authorization {
165
235
  throw new Forbidden(canDistribute.reason);
166
236
  }
167
237
  }
238
+
239
+ async verifyDistributionOrIntersect(
240
+ userIdentity: UserIdentity | null,
241
+ specification: Specification,
242
+ namedStart: ReferencesByName
243
+ ): Promise<DistributionBranchesResult> {
244
+ const start = specification.given.map(g => namedStart[g.label.name]);
245
+ if (!this.distributionEngine) {
246
+ return { type: "success", branches: [{ start, specification }] };
247
+ }
248
+ const userReference: FactReference | null = userIdentity
249
+ ? await this.keystore.getUserFact(userIdentity)
250
+ : null;
251
+ const targetFeeds = buildFeeds(specification);
252
+ const canDistribute = await this.distributionEngine.canDistributeToAll(targetFeeds, namedStart, userReference);
253
+ if (canDistribute.type === "success") {
254
+ return { type: "success", branches: [{ start, specification }] };
255
+ }
256
+ // Preserve the structured engine failure so the caller can classify
257
+ // the feed (issue #168 S1). `canDistribute` is narrowed to a failure
258
+ // here, so `code`/`reason` are available.
259
+ const denial: DistributionDenial = { reason: canDistribute.reason, code: canDistribute.code };
260
+ const result = await this.distributionEngine.intersectForSubscribe(start, specification, userReference);
261
+ if (!result.intersected) {
262
+ return { type: "denied", reason: denial.reason, code: denial.code };
263
+ }
264
+ // Authorized via intersection: the spec is denied for this user right
265
+ // now (denial carries why) but self-heals once the authorizing fact
266
+ // arrives. The router reports this as `reactive`.
267
+ return { type: "success", branches: result.branches, denial };
268
+ }
168
269
  }
@@ -0,0 +1,386 @@
1
+ import {
2
+ computeTupleSubsetHash,
3
+ FactManager,
4
+ FactReference,
5
+ FeedObject,
6
+ FeedResponse,
7
+ invertSpecification,
8
+ ProjectedResult,
9
+ Specification,
10
+ SpecificationListener,
11
+ Trace
12
+ } from "jinaga";
13
+ import { FeedResult } from "../authorization/authorization-keystore";
14
+ import { Stream } from "../http/stream";
15
+
16
+ /**
17
+ * A function that queries the feed for the next page of tuples, starting
18
+ * from the supplied bookmark. Returns a {@link FeedResult} so the session
19
+ * can keep the stream alive when distribution is denied at query time.
20
+ */
21
+ export type FeedQuery = (bookmark: string) => Promise<FeedResult>;
22
+
23
+ export interface FeedStreamSessionConfig {
24
+ /** Maximum number of pages to stream before giving up (infinite-loop guard). */
25
+ maxInitialPages: number;
26
+ /** Maximum number of references the waitlist may hold before the stream is dropped. */
27
+ waitlistCap: number;
28
+ /** Insert a small delay every N pages to avoid overwhelming the database. */
29
+ pageDelayEvery: number;
30
+ /** Length of the delay inserted by {@link pageDelayEvery}, in milliseconds. */
31
+ pageDelayMs: number;
32
+ }
33
+
34
+ export const defaultFeedStreamSessionConfig: FeedStreamSessionConfig = {
35
+ maxInitialPages: 1000,
36
+ waitlistCap: 50000,
37
+ pageDelayEvery: 10,
38
+ pageDelayMs: 10
39
+ };
40
+
41
+ interface FeedStreamSessionTelemetry {
42
+ initialPages: number;
43
+ referencesStreamed: number;
44
+ cycles: number;
45
+ syncFrames: number;
46
+ waitlistRestarts: number;
47
+ waitlistHighWater: number;
48
+ }
49
+
50
+ function referenceKey(reference: FactReference): string {
51
+ return `${reference.type}:${reference.hash}`;
52
+ }
53
+
54
+ function dedupeReferences(references: FactReference[]): FactReference[] {
55
+ const seen = new Set<string>();
56
+ const result: FactReference[] = [];
57
+ for (const reference of references) {
58
+ const key = referenceKey(reference);
59
+ if (!seen.has(key)) {
60
+ seen.add(key);
61
+ result.push(reference);
62
+ }
63
+ }
64
+ return result;
65
+ }
66
+
67
+ /**
68
+ * Per-connection proxy for a streaming feed subscription.
69
+ *
70
+ * The session funnels every fetch and stream operation through a single
71
+ * "query cycle" driven by the current bookmark. Inverse observers never
72
+ * fetch or stream directly; they only enqueue fact references onto a
73
+ * waitlist and wake the cycle. This serialization removes the race between
74
+ * listener callbacks and bookmark mutation, guarantees tuple completeness,
75
+ * and ensures no update is lost when facts arrive between pages.
76
+ *
77
+ * See docs/design/feeds-persistent-proxy-plan.md for the full design.
78
+ */
79
+ export class FeedStreamSession {
80
+ private bookmark: string;
81
+ private readonly config: FeedStreamSessionConfig;
82
+
83
+ // Waitlist of fact references surfaced by inverse observers, keyed by
84
+ // "{type}:{hash}" so duplicates collapse. A reference stays on the
85
+ // waitlist until the tuple that contains it is streamed, preserving
86
+ // tuple completeness.
87
+ private readonly waitlist = new Map<string, FactReference>();
88
+
89
+ // Single-cycle execution guard. Only one runCycle() executes at a time;
90
+ // wake-ups that arrive while a cycle runs set needsCycle so the loop
91
+ // re-evaluates before returning.
92
+ private activeCycle = false;
93
+ private needsCycle = false;
94
+ private shuttingDown = false;
95
+
96
+ private listeners: SpecificationListener[] = [];
97
+ private readonly telemetry: FeedStreamSessionTelemetry = {
98
+ initialPages: 0,
99
+ referencesStreamed: 0,
100
+ cycles: 0,
101
+ syncFrames: 0,
102
+ waitlistRestarts: 0,
103
+ waitlistHighWater: 0
104
+ };
105
+
106
+ constructor(
107
+ private readonly query: FeedQuery,
108
+ private readonly factManager: FactManager,
109
+ private readonly feedDefinition: FeedObject,
110
+ private readonly startReferences: FactReference[],
111
+ private readonly givenHash: string,
112
+ private readonly stream: Stream<FeedResponse>,
113
+ initialBookmark: string,
114
+ private readonly connectionId: string = Math.random().toString(36).substring(2, 10),
115
+ config: Partial<FeedStreamSessionConfig> = {}
116
+ ) {
117
+ this.bookmark = initialBookmark;
118
+ this.config = { ...defaultFeedStreamSessionConfig, ...config };
119
+ }
120
+
121
+ /** Current number of references on the waitlist (observability/testing). */
122
+ get waitlistSize(): number {
123
+ return this.waitlist.size;
124
+ }
125
+
126
+ /**
127
+ * Register inverse and anchor observers, then kick off the initial
128
+ * paginated backfill. Resolves once the observers are registered; the
129
+ * cycle continues to run asynchronously, feeding the stream.
130
+ */
131
+ start(): void {
132
+ this.registerInverseListeners();
133
+ this.registerAnchorListeners();
134
+ // Kick off the initial backfill. Errors are isolated so a failed
135
+ // cycle never rejects the caller's setup path.
136
+ this.wake();
137
+ }
138
+
139
+ /**
140
+ * Tear down all observers and prevent any further cycles. Idempotent.
141
+ */
142
+ dispose(): void {
143
+ if (this.shuttingDown) {
144
+ return;
145
+ }
146
+ this.shuttingDown = true;
147
+ for (const listener of this.listeners) {
148
+ try {
149
+ this.factManager.removeSpecificationListener(listener);
150
+ } catch (error) {
151
+ Trace.error(error);
152
+ }
153
+ }
154
+ this.listeners = [];
155
+ // Use a stable metric name so a metrics backend does not see
156
+ // unbounded cardinality from per-connection IDs. The connection ID
157
+ // is logged separately for correlation.
158
+ Trace.info(`Feed stream session ${this.connectionId} closed`);
159
+ Trace.metric("Feed stream session closed", {
160
+ initialPages: this.telemetry.initialPages,
161
+ referencesStreamed: this.telemetry.referencesStreamed,
162
+ cycles: this.telemetry.cycles,
163
+ syncFrames: this.telemetry.syncFrames,
164
+ waitlistRestarts: this.telemetry.waitlistRestarts,
165
+ waitlistHighWater: this.telemetry.waitlistHighWater
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Add fact references to the waitlist and wake the cycle. Called by the
171
+ * inverse observers; never fetches or streams directly.
172
+ */
173
+ onInverseMatch(references: FactReference[]): void {
174
+ if (this.shuttingDown) {
175
+ return;
176
+ }
177
+ for (const reference of references) {
178
+ this.waitlist.set(referenceKey(reference), reference);
179
+ }
180
+ if (this.waitlist.size > this.telemetry.waitlistHighWater) {
181
+ this.telemetry.waitlistHighWater = this.waitlist.size;
182
+ }
183
+ if (this.waitlist.size > this.config.waitlistCap) {
184
+ Trace.warn(`Feed stream session ${this.connectionId} waitlist exceeded cap ` +
185
+ `(${this.waitlist.size} > ${this.config.waitlistCap}); closing stream.`);
186
+ this.dispose();
187
+ this.stream.close();
188
+ return;
189
+ }
190
+ this.wake();
191
+ }
192
+
193
+ /**
194
+ * Start a cycle if one is not already running. If a cycle is active,
195
+ * mark that another pass is needed once it completes.
196
+ */
197
+ private wake(): void {
198
+ if (this.shuttingDown) {
199
+ return;
200
+ }
201
+ if (this.activeCycle) {
202
+ this.needsCycle = true;
203
+ return;
204
+ }
205
+ // Run the cycle without awaiting; isolate failures.
206
+ void this.runCycle().catch(error => Trace.error(error));
207
+ }
208
+
209
+ /**
210
+ * The single serialized query cycle. Pages through the feed until both
211
+ * the query returns no tuples and the waitlist is empty, then emits a
212
+ * SYNC frame. Guarded by activeCycle so no two cycles run concurrently.
213
+ */
214
+ private async runCycle(): Promise<void> {
215
+ if (this.activeCycle) {
216
+ this.needsCycle = true;
217
+ return;
218
+ }
219
+ this.activeCycle = true;
220
+ this.telemetry.cycles++;
221
+ try {
222
+ let pagesThisCycle = 0;
223
+ let keepGoing = true;
224
+ while (keepGoing && !this.shuttingDown) {
225
+ this.needsCycle = false;
226
+
227
+ const result = await this.query(this.bookmark);
228
+ if (this.shuttingDown) {
229
+ break;
230
+ }
231
+ if (result.type === "denied") {
232
+ // Distribution denied at query time. Keep the stream
233
+ // alive (an authorizing fact may arrive later and wake a
234
+ // new cycle) but stop the loop without emitting SYNC,
235
+ // since we are not actually caught up.
236
+ Trace.info(`Feed stream session ${this.connectionId} query denied: ${result.reason}`);
237
+ break;
238
+ }
239
+
240
+ const feed = result.feed;
241
+ if (feed.tuples.length > 0) {
242
+ const references = dedupeReferences(feed.tuples.flatMap(t => t.facts));
243
+ this.streamPage(references, feed.bookmark);
244
+ this.removeFromWaitlist(references);
245
+ pagesThisCycle++;
246
+ this.telemetry.initialPages++;
247
+
248
+ if (feed.bookmark === this.bookmark) {
249
+ // The store returned results but the bookmark did not
250
+ // advance, meaning it cannot paginate further (e.g.
251
+ // MemoryStore returns the full result set on every
252
+ // call). Everything available has been delivered, so
253
+ // treat this as caught-up: drop any waitlist entries
254
+ // that the full page did not satisfy and emit SYNC.
255
+ // Re-querying with the same bookmark would loop
256
+ // forever re-delivering identical tuples.
257
+ this.waitlist.clear();
258
+ this.streamSync();
259
+ keepGoing = false;
260
+ }
261
+ else {
262
+ this.bookmark = feed.bookmark;
263
+ if (pagesThisCycle >= this.config.maxInitialPages) {
264
+ Trace.warn(`Feed stream session ${this.connectionId} hit max page limit ` +
265
+ `(${this.config.maxInitialPages}); ending cycle.`);
266
+ break;
267
+ }
268
+ if (this.config.pageDelayEvery > 0 &&
269
+ pagesThisCycle % this.config.pageDelayEvery === 0) {
270
+ await this.delay(this.config.pageDelayMs);
271
+ }
272
+ // Continue paging.
273
+ }
274
+ }
275
+ else {
276
+ // No tuples this query.
277
+ if (this.waitlist.size === 0) {
278
+ this.streamSync();
279
+ keepGoing = false;
280
+ }
281
+ else if (this.needsCycle) {
282
+ // A wake arrived during this query; re-run so the
283
+ // just-arrived facts get a chance to produce tuples.
284
+ this.telemetry.waitlistRestarts++;
285
+ }
286
+ else {
287
+ // The waitlist holds references whose tuples are not
288
+ // completable at the current bookmark (e.g. a missing
289
+ // predecessor). They cannot produce a tuple now, so
290
+ // drop them to avoid spinning and emit SYNC. A later
291
+ // trigger will re-add them once they are completable.
292
+ this.waitlist.clear();
293
+ this.streamSync();
294
+ keepGoing = false;
295
+ }
296
+ }
297
+ }
298
+ } finally {
299
+ this.activeCycle = false;
300
+ // A wake that arrived as the loop exited must start a fresh
301
+ // cycle, since this one already cleared activeCycle.
302
+ if (this.needsCycle && !this.shuttingDown) {
303
+ this.needsCycle = false;
304
+ this.wake();
305
+ }
306
+ }
307
+ }
308
+
309
+ private streamPage(references: FactReference[], bookmark: string): void {
310
+ const response: FeedResponse = { references, bookmark };
311
+ this.telemetry.referencesStreamed += references.length;
312
+ this.stream.feed(response);
313
+ }
314
+
315
+ private streamSync(): void {
316
+ const response: FeedResponse = { references: [], bookmark: this.bookmark };
317
+ this.telemetry.syncFrames++;
318
+ this.stream.feed(response);
319
+ }
320
+
321
+ private removeFromWaitlist(references: FactReference[]): void {
322
+ for (const reference of references) {
323
+ this.waitlist.delete(referenceKey(reference));
324
+ }
325
+ }
326
+
327
+ private delay(ms: number): Promise<void> {
328
+ return new Promise(resolve => setTimeout(resolve, ms));
329
+ }
330
+
331
+ private registerInverseListeners(): void {
332
+ const inverses = invertSpecification(this.feedDefinition.feed);
333
+ for (const inverse of inverses) {
334
+ const listener = this.factManager.addSpecificationListener(
335
+ inverse.inverseSpecification,
336
+ async (results: ProjectedResult[]) => {
337
+ if (this.shuttingDown) {
338
+ return;
339
+ }
340
+ // Only enqueue results whose given subset matches this
341
+ // subscription's given.
342
+ const matching = results.filter(pr =>
343
+ this.givenHash === computeTupleSubsetHash(pr.tuple, inverse.givenSubset));
344
+ if (matching.length === 0) {
345
+ return;
346
+ }
347
+ const references = dedupeReferences(
348
+ matching.flatMap(pr => Object.values(pr.tuple)));
349
+ this.onInverseMatch(references);
350
+ });
351
+ this.listeners.push(listener);
352
+ }
353
+ }
354
+
355
+ private registerAnchorListeners(): void {
356
+ // Anchor listeners (jinaga.js#129): the inverse-listener path only
357
+ // fires when a descendant of the given arrives. If the given fact
358
+ // itself isn't yet in the store when the client subscribes, no
359
+ // inverse can deliver results until the given is recorded. Register
360
+ // a listener per unique anchor that wakes the cycle the moment a
361
+ // saved fact matches the anchor's (type, hash). The anchor itself is
362
+ // not added to the waitlist; the query will surface its descendants.
363
+ const uniqueAnchors = this.startReferences.filter((s, i, arr) =>
364
+ arr.findIndex(other => other.type === s.type && other.hash === s.hash) === i);
365
+ for (const anchor of uniqueAnchors) {
366
+ const anchorSpec: Specification = {
367
+ given: [{ label: { name: "x", type: anchor.type }, conditions: [] }],
368
+ matches: [],
369
+ projection: { type: "fact", label: "x" }
370
+ };
371
+ const listener = this.factManager.addSpecificationListener(anchorSpec, async (results: ProjectedResult[]) => {
372
+ if (this.shuttingDown) {
373
+ return;
374
+ }
375
+ const matched = results.some(pr => {
376
+ const ref = pr.tuple && (pr.tuple as any).x;
377
+ return ref && ref.type === anchor.type && ref.hash === anchor.hash;
378
+ });
379
+ if (matched) {
380
+ this.wake();
381
+ }
382
+ });
383
+ this.listeners.push(listener);
384
+ }
385
+ }
386
+ }