@coasys/ad4m 0.10.1-release-candidate-5 → 0.11.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.
@@ -155,6 +155,26 @@ export class PerspectiveClient {
155
155
  return JSON.parse(perspectiveQueryProlog)
156
156
  }
157
157
 
158
+ /**
159
+ * Executes a read-only SurrealQL query against a perspective's link cache.
160
+ *
161
+ * Security: Only SELECT, RETURN, and other read-only queries are permitted.
162
+ * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
163
+ *
164
+ * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
165
+ * as generated from Rust method "perspective_query_surreal_db"
166
+ */
167
+ async querySurrealDB(uuid: string, query: string): Promise<any> {
168
+ const { perspectiveQuerySurrealDb } = unwrapApolloResult(await this.#apolloClient.query({
169
+ query: gql`query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
170
+ perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
171
+ }`,
172
+ variables: { uuid, query }
173
+ }))
174
+
175
+ return JSON.parse(perspectiveQuerySurrealDb)
176
+ }
177
+
158
178
  async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult, isInit?: boolean }> {
159
179
  const { perspectiveSubscribeQuery } = unwrapApolloResult(await this.#apolloClient.mutate({
160
180
  mutation: gql`mutation perspectiveSubscribeQuery($uuid: String!, $query: String!) {
@@ -180,6 +200,53 @@ export class PerspectiveClient {
180
200
  return { subscriptionId, result: finalResult, isInit }
181
201
  }
182
202
 
203
+ async perspectiveSubscribeSurrealQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult, isInit?: boolean }> {
204
+ const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await this.#apolloClient.mutate({
205
+ mutation: gql`mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
206
+ perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
207
+ subscriptionId
208
+ result
209
+ }
210
+ }`,
211
+ variables: { uuid, query }
212
+ }))
213
+ const { subscriptionId, result } = perspectiveSubscribeSurrealQuery
214
+ let finalResult = result;
215
+ let isInit = false;
216
+ if(finalResult.startsWith("#init#")) {
217
+ finalResult = finalResult.substring(6)
218
+ isInit = true;
219
+ }
220
+ try {
221
+ finalResult = JSON.parse(finalResult)
222
+ } catch (e) {
223
+ console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e)
224
+ }
225
+ return { subscriptionId, result: finalResult, isInit }
226
+ }
227
+
228
+ async perspectiveKeepAliveSurrealQuery(uuid: string, subscriptionId: string): Promise<boolean> {
229
+ const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await this.#apolloClient.mutate({
230
+ mutation: gql`mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
231
+ perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
232
+ }`,
233
+ variables: { uuid, subscriptionId }
234
+ }))
235
+
236
+ return perspectiveKeepAliveSurrealQuery
237
+ }
238
+
239
+ async perspectiveDisposeSurrealQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean> {
240
+ const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await this.#apolloClient.mutate({
241
+ mutation: gql`mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
242
+ perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
243
+ }`,
244
+ variables: { uuid, subscriptionId }
245
+ }))
246
+
247
+ return perspectiveDisposeSurrealQuerySubscription
248
+ }
249
+
183
250
  subscribeToQueryUpdates(subscriptionId: string, onData: (result: AllInstancesResult) => void): () => void {
184
251
  const subscription = this.#apolloClient.subscribe({
185
252
  query: gql`
@@ -64,8 +64,11 @@ export class QuerySubscriptionProxy {
64
64
  #latestResult: AllInstancesResult|null;
65
65
  #disposed: boolean = false;
66
66
  #initialized: Promise<boolean>;
67
+ #initResolve?: (value: boolean) => void;
68
+ #initReject?: (reason?: any) => void;
67
69
  #initTimeoutId?: NodeJS.Timeout;
68
70
  #query: string;
71
+ isSurrealDB: boolean = false;
69
72
 
70
73
  /** Creates a new query subscription
71
74
  * @param uuid - The UUID of the perspective
@@ -78,56 +81,119 @@ export class QuerySubscriptionProxy {
78
81
  this.#client = client;
79
82
  this.#callbacks = new Set();
80
83
  this.#latestResult = null;
84
+
85
+ // Create the promise once and store its resolve/reject
86
+ this.#initialized = new Promise<boolean>((resolve, reject) => {
87
+ this.#initResolve = resolve;
88
+ this.#initReject = reject;
89
+ });
81
90
  }
82
91
 
83
92
  async subscribe() {
84
- // initialize the query subscription
85
- const result = await this.#client.subscribeQuery(this.#uuid, this.#query);
86
- this.#subscriptionId = result.subscriptionId;
87
- // Subscribe to query updates
88
- this.#initialized = new Promise<boolean>((resolve, reject) => {
89
- // Add timeout to prevent hanging promises
93
+ // Clean up previous subscription attempt if retrying
94
+ if (this.#unsubscribe) {
95
+ this.#unsubscribe();
96
+ this.#unsubscribe = undefined;
97
+ }
98
+
99
+ // Clear any existing timeout
100
+ if (this.#initTimeoutId) {
101
+ clearTimeout(this.#initTimeoutId);
102
+ this.#initTimeoutId = undefined;
103
+ }
104
+
105
+ // Clear any existing keepalive timer to prevent accumulation
106
+ if (this.#keepaliveTimer) {
107
+ clearTimeout(this.#keepaliveTimer);
108
+ this.#keepaliveTimer = undefined;
109
+ }
110
+
111
+ try {
112
+ // Initialize the query subscription
113
+ let initialResult;
114
+ if (this.isSurrealDB) {
115
+ initialResult = await this.#client.perspectiveSubscribeSurrealQuery(this.#uuid, this.#query);
116
+ } else {
117
+ initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
118
+ }
119
+ this.#subscriptionId = initialResult.subscriptionId;
120
+
121
+ // Process the initial result immediately for fast UX
122
+ if (initialResult.result) {
123
+ this.#latestResult = initialResult.result;
124
+ this.#notifyCallbacks(initialResult.result);
125
+ } else {
126
+ console.warn('⚠️ No initial result returned from subscribeQuery!');
127
+ }
128
+
129
+ // Set up timeout for retry
90
130
  this.#initTimeoutId = setTimeout(() => {
91
- reject(new Error('Subscription initialization timed out after 30 seconds. Resubscribing...'));
92
- this.subscribe();
93
- }, 30000); // 30 seconds timeout
131
+ console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
132
+ // Recursively retry subscription, catching any errors
133
+ this.subscribe().catch(error => {
134
+ console.error('Error during subscription retry after timeout:', error);
135
+ });
136
+ }, 30000);
94
137
 
95
138
  // Subscribe to query updates
96
139
  this.#unsubscribe = this.#client.subscribeToQueryUpdates(
97
140
  this.#subscriptionId,
98
- (result) => {
141
+ (updateResult) => {
142
+ // Clear timeout on first message
99
143
  if (this.#initTimeoutId) {
100
144
  clearTimeout(this.#initTimeoutId);
101
145
  this.#initTimeoutId = undefined;
102
146
  }
103
- resolve(true);
104
-
105
- // if the result is one of those repeated initialization results
106
- // and we got a result before, we don't notify the callbacks
107
- // so they don't get confused (we could have gotten another
108
- // more recent result in between)
109
- if(result.isInit && this.#latestResult) {
110
- return
147
+
148
+ // Resolve the initialization promise (only resolves once)
149
+ if (this.#initResolve) {
150
+ this.#initResolve(true);
151
+ this.#initResolve = undefined; // Prevent double-resolve
152
+ this.#initReject = undefined;
111
153
  }
112
154
 
113
- this.#latestResult = result;
114
- this.#notifyCallbacks(result);
155
+ // Skip duplicate init messages
156
+ if (updateResult.isInit && this.#latestResult) return;
157
+
158
+ this.#latestResult = updateResult;
159
+ this.#notifyCallbacks(updateResult);
115
160
  }
116
161
  );
117
- });
162
+ } catch (error) {
163
+ console.error('Error setting up subscription:', error);
164
+
165
+ // Reject the promise if this is the first attempt
166
+ if (this.#initReject) {
167
+ this.#initReject(error);
168
+ this.#initResolve = undefined;
169
+ this.#initReject = undefined;
170
+ }
171
+
172
+ throw error; // Re-throw so caller knows it failed
173
+ }
118
174
 
119
175
  // Start keepalive loop using platform-agnostic setTimeout
120
176
  const keepaliveLoop = async () => {
121
177
  if (this.#disposed) return;
122
178
 
123
179
  try {
124
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
180
+ if (this.isSurrealDB) {
181
+ await this.#client.perspectiveKeepAliveSurrealQuery(this.#uuid, this.#subscriptionId);
182
+ } else {
183
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
184
+ }
125
185
  } catch (e) {
126
186
  console.error('Error in keepalive:', e);
127
187
  // try to reinitialize the subscription
128
188
  console.log('Reinitializing subscription for query:', this.#query);
129
- await this.subscribe();
130
- console.log('Subscription reinitialized');
189
+ try {
190
+ await this.subscribe();
191
+ console.log('Subscription reinitialized');
192
+ } catch (resubscribeError) {
193
+ console.error('Error during resubscription from keepalive:', resubscribeError);
194
+ // Don't schedule another keepalive on resubscribe failure
195
+ return;
196
+ }
131
197
  }
132
198
 
133
199
  // Schedule next keepalive if not disposed
@@ -152,15 +218,17 @@ export class QuerySubscriptionProxy {
152
218
  return this.#subscriptionId;
153
219
  }
154
220
 
155
- /** Promise that resolves when the subscription has received its first result
156
- * through the subscription channel. This ensures the subscription is fully
157
- * set up before allowing access to results or updates.
158
- *
159
- * The promise will reject if no result is received within 30 seconds.
160
- *
161
- * Note: You typically don't need to await this directly since the subscription
162
- * creation methods (like subscribeInfer) already wait for initialization.
163
- */
221
+ /** Promise that resolves when the subscription has received its first result
222
+ * through the subscription channel. This ensures the subscription is fully
223
+ * set up before allowing access to results or updates.
224
+ *
225
+ * If no result is received within 30 seconds, the subscription will automatically
226
+ * retry. The promise will remain pending until a subscription message successfully
227
+ * arrives, or until a fatal error occurs during subscription setup.
228
+ *
229
+ * Note: You typically don't need to await this directly since the subscription
230
+ * creation methods (like subscribeInfer) already wait for initialization.
231
+ */
164
232
  get initialized(): Promise<boolean> {
165
233
  return this.#initialized;
166
234
  }
@@ -237,8 +305,13 @@ export class QuerySubscriptionProxy {
237
305
 
238
306
  // Tell the backend to dispose of the subscription
239
307
  if (this.#subscriptionId) {
240
- this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
241
- .catch(e => console.error('Error disposing query subscription:', e));
308
+ if (this.isSurrealDB) {
309
+ this.#client.perspectiveDisposeSurrealQuerySubscription(this.#uuid, this.#subscriptionId)
310
+ .catch(e => console.error('Error disposing surreal query subscription:', e));
311
+ } else {
312
+ this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
313
+ .catch(e => console.error('Error disposing query subscription:', e));
314
+ }
242
315
  }
243
316
  }
244
317
  }
@@ -451,6 +524,37 @@ export class PerspectiveProxy {
451
524
  return await this.#client.queryProlog(this.#handle.uuid, query)
452
525
  }
453
526
 
527
+ /**
528
+ * Executes a SurrealQL query against the perspective's link cache.
529
+ * This allows powerful SQL-like queries on the link data stored in SurrealDB.
530
+ *
531
+ * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
532
+ * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
533
+ * blocked for security reasons. Use the perspective's add/remove methods to modify links.
534
+ *
535
+ * @param query - SurrealQL query string (read-only operations only)
536
+ * @returns Query results as parsed JSON
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * // Get all links
541
+ * const links = await perspective.querySurrealDB('SELECT * FROM link');
542
+ *
543
+ * // Filter links by predicate
544
+ * const follows = await perspective.querySurrealDB(
545
+ * "SELECT * FROM link WHERE predicate = 'follows'"
546
+ * );
547
+ *
548
+ * // Complex aggregation query
549
+ * const stats = await perspective.querySurrealDB(
550
+ * "SELECT predicate, count() as total FROM link GROUP BY predicate"
551
+ * );
552
+ * ```
553
+ */
554
+ async querySurrealDB(query: string): Promise<any> {
555
+ return await this.#client.querySurrealDB(this.#handle.uuid, query)
556
+ }
557
+
454
558
  /**
455
559
  * Adds a new link to the perspective.
456
560
  *
@@ -1255,4 +1359,40 @@ export class PerspectiveProxy {
1255
1359
  return subscriptionProxy;
1256
1360
  }
1257
1361
 
1362
+ /**
1363
+ * Creates a subscription for a SurrealQL query that updates in real-time.
1364
+ *
1365
+ * This method:
1366
+ * 1. Creates the subscription on the Rust side
1367
+ * 2. Sets up the subscription callback
1368
+ * 3. Waits for the initial result to come through the subscription channel
1369
+ * 4. Returns a fully initialized QuerySubscriptionProxy
1370
+ *
1371
+ * The returned subscription is guaranteed to be ready to receive updates,
1372
+ * as this method waits for the initialization process to complete.
1373
+ *
1374
+ * The subscription will be automatically cleaned up on both frontend and backend
1375
+ * when dispose() is called. Make sure to call dispose() when you're done to
1376
+ * prevent memory leaks and ensure proper cleanup of resources.
1377
+ *
1378
+ * @param query - SurrealQL query string
1379
+ * @returns Initialized QuerySubscriptionProxy instance
1380
+ */
1381
+ async subscribeSurrealDB(query: string): Promise<QuerySubscriptionProxy> {
1382
+ const subscriptionProxy = new QuerySubscriptionProxy(
1383
+ this.uuid,
1384
+ query,
1385
+ this.#client
1386
+ );
1387
+ subscriptionProxy.isSurrealDB = true;
1388
+
1389
+ // Start the subscription on the Rust side first to get the real subscription ID
1390
+ await subscriptionProxy.subscribe();
1391
+
1392
+ // Wait for the initial result
1393
+ await subscriptionProxy.initialized;
1394
+
1395
+ return subscriptionProxy;
1396
+ }
1397
+
1258
1398
  }
@@ -90,6 +90,14 @@ export default class PerspectiveResolver {
90
90
  return `[{"X": 1}]`
91
91
  }
92
92
 
93
+ @Query(returns => String)
94
+ async perspectiveQuerySurrealDB(
95
+ @Arg('uuid') uuid: string,
96
+ @Arg('query') query: string
97
+ ): Promise<string> {
98
+ return `[]`
99
+ }
100
+
93
101
  @Mutation(returns => QuerySubscription)
94
102
  async perspectiveSubscribeQuery(
95
103
  @Arg('uuid') uuid: string,