@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -3,6 +3,7 @@ import { Link, LinkExpression } from '../links/Links';
3
3
  import { LinkQuery } from './LinkQuery';
4
4
  import { Literal } from '../Literal';
5
5
  import { SHACLFlow } from '../shacl/SHACLFlow';
6
+ import { clearQueryCache } from '../model/query-cache';
6
7
 
7
8
  function createProxy(client: any): PerspectiveProxy {
8
9
  return new PerspectiveProxy(
@@ -12,415 +13,47 @@ function createProxy(client: any): PerspectiveProxy {
12
13
  }
13
14
 
14
15
  describe('QuerySubscriptionProxy', () => {
15
- it('treats the initial subscribeQuery() result as a completed initialization', async () => {
16
- const initialResult = [
17
- {
18
- source: 'literal:string:test-channel',
19
- predicate: 'flux://has_channel_name',
20
- target: 'literal:string:Runtime Fix Channel',
21
- },
22
- ];
23
-
24
- const unsubscribe = jest.fn();
25
- const mockClient = {
26
- subscribeQuery: jest.fn().mockResolvedValue({
27
- subscriptionId: 'sub-1',
28
- result: initialResult,
29
- }),
30
- subscribeToQueryUpdates: jest.fn().mockReturnValue(unsubscribe),
31
- keepAliveQuery: jest.fn().mockResolvedValue(true),
32
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
33
- } as any;
34
-
35
- const subscription = new QuerySubscriptionProxy('perspective-1', 'SELECT * WHERE { ?s ?p ?o }', mockClient);
36
-
37
- await subscription.subscribe();
38
-
39
- const initialized = await Promise.race([
40
- subscription.initialized.then(() => 'resolved'),
41
- new Promise<string>((resolve) => setTimeout(() => resolve('timeout'), 25)),
42
- ]);
43
-
44
- expect(initialized).toBe('resolved');
45
- expect(subscription.result).toEqual(initialResult);
46
- expect(mockClient.subscribeQuery).toHaveBeenCalledWith('perspective-1', 'SELECT * WHERE { ?s ?p ?o }');
47
- expect(mockClient.subscribeToQueryUpdates).toHaveBeenCalledWith('sub-1', expect.any(Function));
48
-
49
- subscription.dispose();
50
- expect(unsubscribe).toHaveBeenCalled();
51
- });
52
-
53
- // Subscribers of the same query share one executor subscription id, and each
54
- // disposeQuerySubscription releases one hold on it. Every hold this proxy
55
- // acquires must be released exactly once.
56
- describe('executor hold', () => {
57
- function holdClient(ids: string[]) {
58
- let next = 0;
59
- return {
60
- subscribeQuery: jest.fn(async () => ({ subscriptionId: ids[next++], result: [] })),
61
- subscribeToQueryUpdates: jest.fn(() => jest.fn()),
62
- keepAliveQuery: jest.fn().mockResolvedValue(true),
63
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
64
- } as any;
65
- }
66
-
67
- it('dispose() releases the hold once, even when called twice', async () => {
68
- const mockClient = holdClient(['shared-sub']);
69
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
70
- await subscription.subscribe();
71
-
72
- subscription.dispose();
73
- subscription.dispose();
74
-
75
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledTimes(1);
76
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledWith('p-1', 'shared-sub');
77
- });
78
-
79
- it('a retried subscribe() releases the hold it replaces', async () => {
80
- // The executor returns the same id while the entry is alive, so the
81
- // retry adds a second hold on it; the first must be released.
82
- const mockClient = holdClient(['shared-sub', 'shared-sub']);
83
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
84
- await subscription.subscribe();
85
- await subscription.subscribe();
86
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledTimes(1);
87
-
88
- subscription.dispose();
89
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledTimes(2);
90
- expect(mockClient.disposeQuerySubscription).toHaveBeenNthCalledWith(2, 'p-1', 'shared-sub');
91
- });
92
-
93
- it('a reconnect swap releases the hold it replaces', async () => {
94
- let reconnectCallback: (() => Promise<void>) | undefined;
95
- const mockClient = holdClient(['sub-1', 'sub-2']);
96
- mockClient.onReconnect = jest.fn((cb: () => Promise<void>) => {
97
- reconnectCallback = cb;
98
- return jest.fn();
99
- });
100
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
101
- await subscription.subscribe();
102
-
103
- await reconnectCallback!();
104
- expect(subscription.id).toBe('sub-2');
105
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledTimes(1);
106
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledWith('p-1', 'sub-1');
107
-
108
- subscription.dispose();
109
- subscription.dispose();
110
- expect(mockClient.disposeQuerySubscription).toHaveBeenCalledTimes(2);
111
- expect(mockClient.disposeQuerySubscription).toHaveBeenNthCalledWith(2, 'p-1', 'sub-2');
112
- });
113
- });
114
-
115
- it('re-subscribes immediately when onReconnect fires', async () => {
116
- let reconnectCallback: (() => void) | undefined;
117
- const initialUnsubscribe = jest.fn();
118
- const reconnectUnsubscribe = jest.fn();
119
- let subscribeToUpdatesCall = 0;
120
- const unsubReconnect = jest.fn();
121
- const mockClient = {
122
- subscribeQuery: jest.fn().mockResolvedValue({
123
- subscriptionId: 'sub-1',
124
- result: [{ s: 'a', p: 'b', o: 'c' }],
125
- }),
126
- subscribeToQueryUpdates: jest.fn(() => {
127
- subscribeToUpdatesCall++;
128
- return subscribeToUpdatesCall === 1 ? initialUnsubscribe : reconnectUnsubscribe;
129
- }),
130
- keepAliveQuery: jest.fn().mockResolvedValue(true),
131
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
132
- onReconnect: jest.fn((cb: () => void) => {
133
- reconnectCallback = cb;
134
- return unsubReconnect;
135
- }),
136
- } as any;
137
-
138
- const subscription = new QuerySubscriptionProxy('perspective-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
139
- await subscription.subscribe();
140
-
141
- // onReconnect should have been registered
142
- expect(mockClient.onReconnect).toHaveBeenCalledTimes(1);
143
- expect(reconnectCallback).toBeDefined();
144
-
145
- // Reset call counts to isolate the reconnect re-subscribe — but do NOT
146
- // reset the monotonic counter: the mock must keep returning DISTINCT
147
- // unsubscribers so the assertions below can tell "old callback disposed"
148
- // apart from "new callback disposed" (they'd be the same jest.fn if the
149
- // counter restarted at 1).
150
- mockClient.subscribeQuery.mockClear();
151
- mockClient.subscribeToQueryUpdates.mockClear();
152
-
153
- // Return a fresh subscriptionId on reconnect
154
- mockClient.subscribeQuery.mockResolvedValue({
155
- subscriptionId: 'sub-2',
156
- result: [{ s: 'x', p: 'y', o: 'z' }],
157
- });
158
-
159
- // Simulate reconnect
160
- reconnectCallback!();
161
- // Allow the async swap to settle
162
- await new Promise((r) => setTimeout(r, 10));
163
-
164
- // Should have re-established the server-side subscription with a fresh ID
165
- // and swapped the client-side callback in place — NEW callback registered
166
- // BEFORE the old one is disposed (so the WS never dips to 0 subscribers).
167
- expect(mockClient.subscribeQuery).toHaveBeenCalledWith('perspective-1', 'SELECT ?x WHERE { ?x ?p ?o }');
168
- expect(mockClient.subscribeToQueryUpdates).toHaveBeenCalledWith('sub-2', expect.any(Function));
169
- // The OLD callback was disposed, the NEW one was not.
170
- expect(initialUnsubscribe).toHaveBeenCalledTimes(1);
171
- expect(reconnectUnsubscribe).not.toHaveBeenCalled();
172
-
173
- subscription.dispose();
174
- // dispose() tears down the callback that is live at that point — the
175
- // reconnect-registered one.
176
- expect(reconnectUnsubscribe).toHaveBeenCalledTimes(1);
177
- });
178
-
179
- it('cleans up reconnect listener on dispose', async () => {
180
- const unsubReconnect = jest.fn();
181
- const mockClient = {
182
- subscribeQuery: jest.fn().mockResolvedValue({
183
- subscriptionId: 'sub-1',
184
- result: [],
185
- }),
186
- subscribeToQueryUpdates: jest.fn().mockReturnValue(jest.fn()),
187
- keepAliveQuery: jest.fn().mockResolvedValue(true),
188
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
189
- onReconnect: jest.fn(() => unsubReconnect),
190
- } as any;
191
-
192
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
193
- await subscription.subscribe();
194
-
195
- expect(unsubReconnect).not.toHaveBeenCalled();
196
- subscription.dispose();
197
- expect(unsubReconnect).toHaveBeenCalledTimes(1);
198
- });
199
-
200
- // Regression for CodeRabbit review on PR #899 AND for the follow-on
201
- // integration-tests-mcp failure the first fix exposed.
202
- //
203
- // CodeRabbit warned about the "final-subscriber" loop: when this query
204
- // owns the LAST `_handlers` entry in ApiClient, calling `#unsubscribe`
205
- // inside a reconnect-driven `subscribe()` closes the WebSocket
206
- // (the release ApiClient.on() returns: "if no more handlers and no pending
207
- // calls, close the socket"). The subsequent `subscribeQuery` reopens the
208
- // socket, whose fresh `onopen` fires every registered reconnect callback
209
- // → recursion.
210
- //
211
- // The current fix avoids the loop AND the collateral damage by NOT
212
- // calling `subscribe()` from the reconnect handler at all. Instead it
213
- // swap-in-place: get a new server-side subscription ID via
214
- // `subscribeQuery`, register the new client-side callback FIRST, then
215
- // dispose the old callback. `_handlers.size` never dips to 0 across
216
- // the swap, so the socket stays open, no `onopen` re-fires, no
217
- // cross-proxy RPCs die with 503 (the mcp-http.test.ts "should fire
218
- // onWake when mention uses agent DID" failure).
219
- //
220
- // This test models the invariant the swap guarantees.
221
- it('reconnect handler swaps subscriptions without dropping to zero WS callbacks (regression)', async () => {
222
- // Real Set so we can observe the swap ordering.
223
- const reconnectCallbacks = new Set<() => void>();
224
- // Count of live client-side callback subscriptions (proxy analogue of
225
- // ApiClient._handlers.size). Bumped by subscribeToQueryUpdates, and
226
- // decremented by the returned unsubscribe. If this ever drops to 0
227
- // during the swap, ApiClient would close the socket — which is
228
- // exactly the loop CodeRabbit flagged.
229
- let liveCallbacks = 0;
230
- let minLiveDuringSwap = Number.POSITIVE_INFINITY;
231
- let subscribeQueryCount = 0;
232
- let subscribeToUpdatesCount = 0;
233
-
234
- const mockClient = {
235
- subscribeQuery: jest.fn(async (_uuid: string, _query: string) => {
236
- subscribeQueryCount++;
237
- return {
238
- subscriptionId: `sub-${subscribeQueryCount}`,
239
- result: [{ s: 'a', p: 'b', o: 'c' }],
240
- };
241
- }),
242
- subscribeToQueryUpdates: jest.fn(() => {
243
- subscribeToUpdatesCount++;
244
- liveCallbacks++;
245
- // Sample the invariant after each mutation.
246
- if (liveCallbacks < minLiveDuringSwap) minLiveDuringSwap = liveCallbacks;
247
- return jest.fn(() => {
248
- liveCallbacks--;
249
- if (liveCallbacks < minLiveDuringSwap) minLiveDuringSwap = liveCallbacks;
250
- });
251
- }),
252
- keepAliveQuery: jest.fn().mockResolvedValue(true),
16
+ function liveClient(subscribeQuery: jest.Mock) {
17
+ const client = {
18
+ subscribeQuery,
19
+ onQueryUpdate: () => () => {},
20
+ onReconnect: () => () => {},
253
21
  disposeQuerySubscription: jest.fn().mockResolvedValue(true),
254
- onReconnect: jest.fn((cb: () => void) => {
255
- reconnectCallbacks.add(cb);
256
- return () => { reconnectCallbacks.delete(cb); };
257
- }),
258
- } as any;
259
-
260
- const subscription = new QuerySubscriptionProxy(
261
- 'perspective-1',
262
- 'SELECT ?x WHERE { ?x ?p ?o }',
263
- mockClient,
264
- );
265
-
266
- // Initial subscribe — one server subscription, one live callback.
267
- await subscription.subscribe();
268
- expect(subscribeQueryCount).toBe(1);
269
- expect(subscribeToUpdatesCount).toBe(1);
270
- expect(liveCallbacks).toBe(1);
271
- expect(reconnectCallbacks.size).toBe(1);
272
- // Reset the low-water mark to the post-init steady state so we only
273
- // measure what the reconnect handler does.
274
- minLiveDuringSwap = liveCallbacks;
275
-
276
- // Fire one genuine reconnect. The handler should:
277
- // (a) call subscribeQuery (new server-side sub id: sub-2)
278
- // (b) call subscribeToQueryUpdates for sub-2 → liveCallbacks 1 → 2
279
- // (c) THEN invoke the old unsubscribe → liveCallbacks 2 → 1
280
- // At no point should liveCallbacks reach 0. And the fresh listener
281
- // installed at the top of the initial subscribe() must NOT itself
282
- // re-enter subscribe() from this reconnect.
283
- for (const cb of Array.from(reconnectCallbacks)) cb();
284
- // Let the async swap settle.
285
- await new Promise((r) => setTimeout(r, 20));
286
-
287
- expect(subscribeQueryCount).toBe(2);
288
- expect(subscribeToUpdatesCount).toBe(2);
289
- // The critical assertion: the swap never let the callback set go to 0.
290
- // A zero here would mean the socket got closed → reopened → onopen
291
- // fires reconnect callbacks again → the loop CodeRabbit warned about.
292
- expect(minLiveDuringSwap).toBeGreaterThanOrEqual(1);
293
- // One reconnect fired → exactly one server-side re-establish. NOT a
294
- // recursive cascade.
295
- expect(reconnectCallbacks.size).toBe(1);
296
- expect(liveCallbacks).toBe(1);
297
-
298
- subscription.dispose();
299
- // Dispose drops both the live callback and the reconnect listener.
300
- expect(liveCallbacks).toBe(0);
301
- expect(reconnectCallbacks.size).toBe(0);
302
- });
303
-
304
- // Regression for the review-blocker on PR #899: a failed full resubscribe
305
- // (the keepalive / init-timeout retry path) used to remove the reconnect
306
- // listener at the top of subscribe() and only re-register on success —
307
- // one subscribeQuery failure during a network flap left the proxy
308
- // permanently dead (keepalive loop stops itself on resubscribe failure,
309
- // no listener left to retry). The catch block must install a recovery
310
- // listener so the next reconnect retries the full subscribe.
311
- it('keeps reconnect recovery alive after a failed resubscribe attempt', async () => {
312
- let reconnectCallback: (() => void) | undefined;
313
- const mockClient = {
314
- subscribeQuery: jest.fn()
315
- .mockResolvedValueOnce({ subscriptionId: 'sub-1', result: [] }) // initial subscribe OK
316
- .mockRejectedValueOnce(new Error('flap')) // resubscribe attempt fails
317
- .mockResolvedValueOnce({ subscriptionId: 'sub-2', result: [] }), // recovery succeeds
318
- subscribeToQueryUpdates: jest.fn().mockReturnValue(jest.fn()),
319
- keepAliveQuery: jest.fn().mockResolvedValue(true),
320
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
321
- onReconnect: jest.fn((cb: () => void) => {
322
- reconnectCallback = cb;
323
- return jest.fn();
324
- }),
325
22
  } as any;
23
+ return { client };
24
+ }
326
25
 
327
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
26
+ it('resolves initialized with the first result', async () => {
27
+ const { client } = liveClient(jest.fn().mockResolvedValue({ subscriptionId: 'sub-1', result: [{ s: 'a' }], revision: 0 }));
28
+ const subscription = new QuerySubscriptionProxy('perspective-1', 'SELECT * WHERE { ?s ?p ?o }', client);
328
29
  await subscription.subscribe();
30
+ await expect(subscription.initialized).resolves.toBe(true);
31
+ expect(subscription.result).toEqual([{ s: 'a' }]);
329
32
  expect(subscription.id).toBe('sub-1');
330
-
331
- // A retry-subscribe fails (this is what the keepalive path does when
332
- // the server subscription died).
333
- await expect(subscription.subscribe()).rejects.toThrow('flap');
334
-
335
- // The failure must have installed a recovery listener — total listener
336
- // registrations: initial subscribe + failure recovery.
337
- expect(mockClient.onReconnect).toHaveBeenCalledTimes(2);
338
- expect(reconnectCallback).toBeDefined();
339
-
340
- // A reconnect arrives → the recovery listener runs a full subscribe()
341
- // and the proxy comes back to life on a fresh server subscription.
342
- reconnectCallback!();
343
- await new Promise((r) => setTimeout(r, 10));
344
-
345
- expect(mockClient.subscribeQuery).toHaveBeenCalledTimes(3);
346
- expect(subscription.id).toBe('sub-2');
347
-
348
- subscription.dispose();
33
+ expect(client.subscribeQuery).toHaveBeenCalledWith('perspective-1', 'SELECT * WHERE { ?s ?p ?o }');
349
34
  });
350
35
 
351
- // Regression for the concurrent-writers race flagged in the PR #899
352
- // review: the reconnect swap handler, the keepalive-retry subscribe() and
353
- // the init-timeout retry subscribe() all write `#unsubscribe` /
354
- // `#subscriptionId`. Without the generation guard, a swap handler parked
355
- // on its subscribeQuery while a full subscribe() ran could register a
356
- // client-side callback that the subscribe() then overwrote WITHOUT
357
- // disposing — leaking the callback in ApiClient._handlers for the
358
- // client lifetime (holding the socket open and firing into a dead
359
- // subscription). The stale writer must back out and release its
360
- // server-side subscription instead.
361
- it('a reconnect swap superseded by a concurrent resubscribe backs out without leaking callbacks', async () => {
362
- let reconnectCallback: (() => void) | undefined;
363
- // Deferred subscribeQuery responses so the test controls interleaving.
364
- const deferreds: Array<{ resolve: (v: any) => void }> = [];
365
- let subCounter = 0;
366
- let liveCallbacks = 0;
367
- const disposedServerSubs: string[] = [];
368
-
369
- const mockClient = {
370
- subscribeQuery: jest.fn(() => new Promise((resolve) => {
371
- deferreds.push({ resolve });
372
- })),
373
- subscribeToQueryUpdates: jest.fn(() => {
374
- liveCallbacks++;
375
- return jest.fn(() => { liveCallbacks--; });
376
- }),
377
- keepAliveQuery: jest.fn().mockResolvedValue(true),
378
- disposeQuerySubscription: jest.fn((_uuid: string, subId: string) => {
379
- disposedServerSubs.push(subId);
380
- return Promise.resolve(true);
381
- }),
382
- onReconnect: jest.fn((cb: () => void) => {
383
- reconnectCallback = cb;
384
- return jest.fn();
385
- }),
386
- } as any;
36
+ it('rejects initialized when the subscribe call fails', async () => {
37
+ const { client } = liveClient(jest.fn().mockRejectedValue(new Error('locked')));
38
+ const subscription = new QuerySubscriptionProxy('p', 'SELECT ?x WHERE { ?x ?p ?o }', client);
39
+ const initialized = subscription.initialized;
40
+ await expect(subscription.subscribe()).rejects.toThrow('locked');
41
+ await expect(initialized).rejects.toThrow('locked');
42
+ });
387
43
 
388
- const subscription = new QuerySubscriptionProxy('p-1', 'SELECT ?x WHERE { ?x ?p ?o }', mockClient);
389
-
390
- // Initial subscribe.
391
- const initial = subscription.subscribe();
392
- deferreds[0].resolve({ subscriptionId: `sub-${++subCounter}`, result: [] });
393
- await initial;
394
- expect(liveCallbacks).toBe(1);
395
-
396
- // 1. Reconnect fires; the swap handler parks on its subscribeQuery.
397
- reconnectCallback!();
398
- expect(deferreds.length).toBe(2);
399
-
400
- // 2. While the handler is parked, a full resubscribe runs (keepalive
401
- // retry analogue) and parks on ITS subscribeQuery.
402
- const retry = subscription.subscribe();
403
- expect(deferreds.length).toBe(3);
404
-
405
- // 3. The handler's subscribeQuery resolves FIRST — the handler is now
406
- // stale (the full subscribe superseded it) and must back out.
407
- deferreds[1].resolve({ subscriptionId: 'sub-stale', result: [] });
408
- await new Promise((r) => setTimeout(r, 5));
409
-
410
- // 4. The full subscribe's subscribeQuery resolves and completes.
411
- deferreds[2].resolve({ subscriptionId: `sub-${++subCounter}`, result: [] });
412
- await retry;
413
-
414
- // Exactly ONE live client-side callback — the stale handler must not
415
- // have left an orphaned one behind (nor disposed the winner's).
416
- expect(liveCallbacks).toBe(1);
417
- // The winner's subscription is active…
418
- expect(subscription.id).toBe('sub-2');
419
- // …and the stale handler released its orphaned server-side subscription.
420
- expect(disposedServerSubs).toContain('sub-stale');
421
-
422
- subscription.dispose();
423
- expect(liveCallbacks).toBe(0);
44
+ it('leaves no unhandled rejection when the caller never reads initialized', async () => {
45
+ const unhandled: unknown[] = [];
46
+ const record = (reason: unknown) => unhandled.push(reason);
47
+ process.on('unhandledRejection', record);
48
+ try {
49
+ const { client } = liveClient(jest.fn().mockRejectedValue(new Error('refused')));
50
+ const subscription = new QuerySubscriptionProxy('p', 'not sparql', client);
51
+ await expect(subscription.subscribe()).rejects.toThrow('refused');
52
+ await new Promise(resolve => setImmediate(resolve));
53
+ expect(unhandled).toEqual([]);
54
+ } finally {
55
+ process.off('unhandledRejection', record);
56
+ }
424
57
  });
425
58
  });
426
59
 
@@ -805,3 +438,54 @@ describe('PerspectiveProxy.addFlow replace', () => {
805
438
  expect((await proxy.getFlow('Todo'))?.flowUri).toBe(todoFlow(2, 'new://').flowUri);
806
439
  });
807
440
  });
441
+
442
+ // A read right after an awaited write must not be served from the query
443
+ // cache: `updateSubject` and `removeSubject` through an abstract class (#1435)
444
+ // write in the executor, so they invalidate it like the other writes.
445
+ describe('PerspectiveProxy write RPCs invalidate the query cache', () => {
446
+ const query = 'SELECT ?v WHERE { <ad4m://m/1> <test://text> ?v }';
447
+
448
+ function client() {
449
+ const marker = new LinkExpression();
450
+ marker.data = new Link({ source: 'test://ReadableShape', predicate: 'ad4m://abstract', target: 'literal:true' });
451
+ return {
452
+ querySparql: jest.fn()
453
+ .mockResolvedValueOnce([{ v: 'old' }])
454
+ .mockResolvedValueOnce([{ v: 'new' }]),
455
+ updateSubject: jest.fn().mockResolvedValue(true),
456
+ removeSubject: jest.fn().mockResolvedValue(true),
457
+ queryLinks: jest.fn().mockResolvedValue([marker]),
458
+ } as any;
459
+ }
460
+
461
+ beforeEach(() => clearQueryCache());
462
+
463
+ it('after updateSubject', async () => {
464
+ const proxy = createProxy(client());
465
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'old' }]);
466
+ await proxy.updateSubject('Readable', 'ad4m://m/1', { text: 'new' });
467
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'new' }]);
468
+ });
469
+
470
+ it('after removeSubject through an abstract class', async () => {
471
+ const c = client();
472
+ const proxy = createProxy(c);
473
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'old' }]);
474
+ await proxy.removeSubject('Readable', 'ad4m://m/1');
475
+ expect(c.removeSubject).toHaveBeenCalledWith('test-uuid', 'Readable', 'ad4m://m/1', undefined);
476
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'new' }]);
477
+ });
478
+
479
+ it('after delete of a built-in TextContent row', async () => {
480
+ const now = Date.now();
481
+ jest.spyOn(Date, 'now').mockReturnValue(now);
482
+ const c = client();
483
+ const proxy = createProxy(c);
484
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'old' }]);
485
+ const row = { constructor: { builtinUri: 'ad4m://TextContent' } };
486
+ await proxy.removeSubject(row, 'ad4m://m/1');
487
+ expect(c.removeSubject).toHaveBeenCalledWith('test-uuid', 'ad4m://TextContent', 'ad4m://m/1', undefined);
488
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'new' }]);
489
+ jest.spyOn(Date, 'now').mockRestore();
490
+ });
491
+ });