@xyo-network/bridge-pub-sub 3.6.8 → 3.6.10

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.
@@ -1,12 +1,22 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __reflectGet = Reflect.get;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
11
+ if (kind && result) __defProp(target, key, result);
12
+ return result;
13
+ };
14
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
15
+ var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
3
16
 
4
17
  // src/AbstractModuleHost/AbstractModuleHost.ts
5
18
  import { Base } from "@xylabs/object";
6
19
  var AbstractModuleHost = class extends Base {
7
- static {
8
- __name(this, "AbstractModuleHost");
9
- }
10
20
  };
11
21
 
12
22
  // src/AsyncQueryBus/AsyncQueryBusClient.ts
@@ -32,9 +42,6 @@ var POLLING_FREQUENCY_MIN = 100;
32
42
  var POLLING_FREQUENCY_MAX = 6e4;
33
43
  var POLLING_FREQUENCY_DEFAULT = 1e3;
34
44
  var AsyncQueryBusBase = class extends Base2 {
35
- static {
36
- __name(this, "AsyncQueryBusBase");
37
- }
38
45
  _lastState;
39
46
  _targetConfigs = {};
40
47
  _targetQueries = {};
@@ -42,6 +49,7 @@ var AsyncQueryBusBase = class extends Base2 {
42
49
  _queriesArchivist;
43
50
  _queriesDiviner;
44
51
  _reResolveDelay = 1e3 * 5;
52
+ // 5 seconds
45
53
  _resolveMutex = new Mutex();
46
54
  _responsesArchivist;
47
55
  _responsesDiviner;
@@ -62,48 +70,57 @@ var AsyncQueryBusBase = class extends Base2 {
62
70
  return this.params.rootModule;
63
71
  }
64
72
  /**
65
- * A cache of the last offset of the Diviner process per address
66
- */
73
+ * A cache of the last offset of the Diviner process per address
74
+ */
67
75
  get lastState() {
68
- const requiredConfig = {
69
- max: 1e3,
70
- ttl: 0
71
- };
76
+ const requiredConfig = { max: 1e3, ttl: 0 };
72
77
  this._lastState = this._lastState ?? new LRUCache(requiredConfig);
73
78
  return this._lastState;
74
79
  }
75
80
  async queriesArchivist() {
76
81
  return await this._resolveMutex.runExclusive(async () => {
77
- this._queriesArchivist = this._queriesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.queries?.archivist, () => "No queries Archivist defined"), isArchivistInstance);
82
+ this._queriesArchivist = this._queriesArchivist ?? await this.resolve(
83
+ assertEx(this.config?.intersect?.queries?.archivist, () => "No queries Archivist defined"),
84
+ isArchivistInstance
85
+ );
78
86
  return this._queriesArchivist;
79
87
  });
80
88
  }
81
89
  async queriesDiviner() {
82
90
  return await this._resolveMutex.runExclusive(async () => {
83
- this._queriesDiviner = this._queriesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined"), isDivinerInstance);
91
+ this._queriesDiviner = this._queriesDiviner ?? await this.resolve(
92
+ assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined"),
93
+ isDivinerInstance
94
+ );
84
95
  return this._queriesDiviner;
85
96
  });
86
97
  }
87
98
  async responsesArchivist() {
88
99
  return await this._resolveMutex.runExclusive(async () => {
89
- this._responsesArchivist = this._responsesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.responses?.archivist, () => "No responses Archivist defined"), isArchivistInstance);
100
+ this._responsesArchivist = this._responsesArchivist ?? await this.resolve(
101
+ assertEx(this.config?.intersect?.responses?.archivist, () => "No responses Archivist defined"),
102
+ isArchivistInstance
103
+ );
90
104
  return this._responsesArchivist;
91
105
  });
92
106
  }
93
107
  async responsesDiviner() {
94
108
  return await this._resolveMutex.runExclusive(async () => {
95
- this._responsesDiviner = this._responsesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => "No responses Diviner defined"), isDivinerInstance);
109
+ this._responsesDiviner = this._responsesDiviner ?? await this.resolve(
110
+ assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => "No responses Diviner defined"),
111
+ isDivinerInstance
112
+ );
96
113
  return this._responsesDiviner;
97
114
  });
98
115
  }
99
116
  /**
100
- * Commit the internal state of the process. This is similar
101
- * to a transaction completion in a database and should only be called
102
- * when results have been successfully persisted to the appropriate
103
- * external stores.
104
- * @param address The module address to commit the state for
105
- * @param nextState The state to commit
106
- */
117
+ * Commit the internal state of the process. This is similar
118
+ * to a transaction completion in a database and should only be called
119
+ * when results have been successfully persisted to the appropriate
120
+ * external stores.
121
+ * @param address The module address to commit the state for
122
+ * @param nextState The state to commit
123
+ */
107
124
  async commitState(address, nextState) {
108
125
  await Promise.resolve();
109
126
  const lastState = this.lastState.get(address);
@@ -111,9 +128,9 @@ var AsyncQueryBusBase = class extends Base2 {
111
128
  this.lastState.set(address, nextState);
112
129
  }
113
130
  /**
114
- * Retrieves the last state of the process. Used to recover state after
115
- * preemptions, reboots, etc.
116
- */
131
+ * Retrieves the last state of the process. Used to recover state after
132
+ * preemptions, reboots, etc.
133
+ */
117
134
  async retrieveState(address) {
118
135
  await Promise.resolve();
119
136
  const state = this.lastState.get(address);
@@ -149,9 +166,6 @@ var Pending = "pending";
149
166
 
150
167
  // src/AsyncQueryBus/AsyncQueryBusClient.ts
151
168
  var AsyncQueryBusClient = class extends AsyncQueryBusBase {
152
- static {
153
- __name(this, "AsyncQueryBusClient");
154
- }
155
169
  _queryCache;
156
170
  _pollCount = 0;
157
171
  _pollId;
@@ -170,18 +184,12 @@ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
170
184
  return !!this._pollId;
171
185
  }
172
186
  /**
173
- * A cache of queries that have been issued
174
- */
187
+ * A cache of queries that have been issued
188
+ */
175
189
  get queryCache() {
176
190
  const config = this.queryCacheConfig;
177
- const requiredConfig = {
178
- noUpdateTTL: false,
179
- ttlAutopurge: true
180
- };
181
- this._queryCache = this._queryCache ?? new LRUCache2({
182
- ...config,
183
- ...requiredConfig
184
- });
191
+ const requiredConfig = { noUpdateTTL: false, ttlAutopurge: true };
192
+ this._queryCache = this._queryCache ?? new LRUCache2({ ...config, ...requiredConfig });
185
193
  return this._queryCache;
186
194
  }
187
195
  listeningAddresses() {
@@ -189,21 +197,14 @@ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
189
197
  }
190
198
  async send(address, query, payloads) {
191
199
  this.logger?.debug(`Begin issuing query to: ${address}`);
192
- const routedQuery = {
193
- ...query,
194
- $destination: [
195
- address
196
- ]
197
- };
198
- const queryArchivist = assertEx2(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
200
+ const routedQuery = { ...query, $destination: [address] };
201
+ const queryArchivist = assertEx2(
202
+ await this.queriesArchivist(),
203
+ () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`
204
+ );
199
205
  const routedQueryHash = await PayloadBuilder.dataHash(routedQuery);
200
206
  this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`);
201
- const data = payloads ? [
202
- routedQuery,
203
- ...payloads
204
- ] : [
205
- routedQuery
206
- ];
207
+ const data = payloads ? [routedQuery, ...payloads] : [routedQuery];
207
208
  const insertResult = await queryArchivist.insert?.(data);
208
209
  this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`);
209
210
  this.queryCache.set(routedQueryHash, Pending);
@@ -211,7 +212,7 @@ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
211
212
  return new Promise((resolve, reject) => {
212
213
  this.logger?.debug(`Polling for response to query: ${routedQueryHash}`);
213
214
  let nextDelay = 100;
214
- const pollForResponse = /* @__PURE__ */ __name(async () => {
215
+ const pollForResponse = async () => {
215
216
  try {
216
217
  this.start();
217
218
  let response = this.queryCache.get(routedQueryHash);
@@ -231,23 +232,21 @@ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
231
232
  message: "Timeout waiting for query response",
232
233
  query: "network.xyo.boundwitness",
233
234
  schema: "network.xyo.error.module",
234
- $sources: [
235
- routedQueryHash
236
- ]
235
+ $sources: [routedQueryHash]
237
236
  };
238
237
  reject(error);
239
238
  return;
240
239
  } finally {
241
240
  this.stop();
242
241
  }
243
- }, "pollForResponse");
242
+ };
244
243
  forget(pollForResponse());
245
244
  });
246
245
  }
247
246
  /**
248
- * Runs the background divine process on a loop with a delay
249
- * specified by the `config.pollFrequency`
250
- */
247
+ * Runs the background divine process on a loop with a delay
248
+ * specified by the `config.pollFrequency`
249
+ */
251
250
  poll() {
252
251
  this._pollId = setTimeoutEx(async () => {
253
252
  try {
@@ -262,44 +261,38 @@ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
262
261
  }, this.pollFrequency);
263
262
  }
264
263
  /**
265
- * Background process for processing incoming responses to previously issued queries
266
- */
267
- processIncomingResponses = /* @__PURE__ */ __name(async () => {
264
+ * Background process for processing incoming responses to previously issued queries
265
+ */
266
+ processIncomingResponses = async () => {
268
267
  const responseArchivist = await this.responsesArchivist();
269
268
  if (responseArchivist) {
270
269
  const responseBoundWitnessDiviner = await this.responsesDiviner();
271
270
  if (responseBoundWitnessDiviner) {
272
- const pendingCommands = [
273
- ...this.queryCache.entries()
274
- ].filter(([_, status]) => status === Pending);
275
- await Promise.allSettled(pendingCommands.map(async ([sourceQuery, status]) => {
276
- if (status === Pending) {
277
- const divinerQuery = {
278
- limit: 1,
279
- order: "desc",
280
- schema: BoundWitnessDivinerQuerySchema,
281
- sourceQuery
282
- };
283
- const result = await responseBoundWitnessDiviner.divine([
284
- divinerQuery
285
- ]);
286
- if (result && result.length > 0) {
287
- const response = result.find(isBoundWitness);
288
- if (response && response?.$sourceQuery === sourceQuery) {
289
- this.logger?.debug(`Found response to query: ${sourceQuery}`);
290
- const payloads = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : [];
291
- this.queryCache.set(sourceQuery, [
292
- response,
293
- payloads,
294
- []
295
- ]);
271
+ const pendingCommands = [...this.queryCache.entries()].filter(([_, status]) => status === Pending);
272
+ await Promise.allSettled(
273
+ pendingCommands.map(async ([sourceQuery, status]) => {
274
+ if (status === Pending) {
275
+ const divinerQuery = {
276
+ limit: 1,
277
+ order: "desc",
278
+ schema: BoundWitnessDivinerQuerySchema,
279
+ sourceQuery
280
+ };
281
+ const result = await responseBoundWitnessDiviner.divine([divinerQuery]);
282
+ if (result && result.length > 0) {
283
+ const response = result.find(isBoundWitness);
284
+ if (response && response?.$sourceQuery === sourceQuery) {
285
+ this.logger?.debug(`Found response to query: ${sourceQuery}`);
286
+ const payloads = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : [];
287
+ this.queryCache.set(sourceQuery, [response, payloads, []]);
288
+ }
296
289
  }
297
290
  }
298
- }
299
- }));
291
+ })
292
+ );
300
293
  }
301
294
  }
302
- }, "processIncomingResponses");
295
+ };
303
296
  start() {
304
297
  if (this._pollCount === 0) {
305
298
  this.poll();
@@ -323,9 +316,16 @@ import { clearTimeoutEx as clearTimeoutEx2, setTimeoutEx as setTimeoutEx2 } from
323
316
  import { isQueryBoundWitnessWithStorageMeta } from "@xyo-network/boundwitness-model";
324
317
  import { isBridgeInstance } from "@xyo-network/bridge-model";
325
318
  import { BoundWitnessDivinerQuerySchema as BoundWitnessDivinerQuerySchema2 } from "@xyo-network/diviner-boundwitness-model";
326
- import { asModuleInstance, ModuleConfigSchema, resolveAddressToInstance, ResolveHelper as ResolveHelper2 } from "@xyo-network/module-model";
319
+ import {
320
+ asModuleInstance,
321
+ ModuleConfigSchema,
322
+ resolveAddressToInstance,
323
+ ResolveHelper as ResolveHelper2
324
+ } from "@xyo-network/module-model";
327
325
  import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
328
- import { SequenceConstants as SequenceConstants2 } from "@xyo-network/payload-model";
326
+ import {
327
+ SequenceConstants as SequenceConstants2
328
+ } from "@xyo-network/payload-model";
329
329
  var IDLE_POLLING_FREQUENCY_RATIO_MIN = 4;
330
330
  var IDLE_POLLING_FREQUENCY_RATIO_MAX = 64;
331
331
  var IDLE_POLLING_FREQUENCY_RATIO_DEFAULT = 16;
@@ -333,9 +333,6 @@ var IDLE_THRESHOLD_RATIO_MIN = 4;
333
333
  var IDLE_THRESHOLD_RATIO_MAX = 64;
334
334
  var IDLE_THRESHOLD_RATIO_DEFAULT = 16;
335
335
  var AsyncQueryBusHost = class extends AsyncQueryBusBase {
336
- static {
337
- __name(this, "AsyncQueryBusHost");
338
- }
339
336
  _exposedAddresses = /* @__PURE__ */ new Set();
340
337
  _exposeOptions = {};
341
338
  _idle = false;
@@ -380,19 +377,19 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
380
377
  } else {
381
378
  assertEx3(!failOnAlreadyExposed || !this._exposedAddresses.has(mod.address), () => `Address already exposed: ${mod.id} [${mod.address}]`);
382
379
  this._exposedAddresses.add(mod.address);
383
- this._exposeOptions[mod.address] = {
384
- ...options
385
- };
380
+ this._exposeOptions[mod.address] = { ...options };
386
381
  this.logger?.debug(`${mod.id} exposed [${mod.address}]`);
387
382
  return mod;
388
383
  }
389
384
  }
390
385
  async listeningModules() {
391
- const exposedModules = [
392
- ...this.config?.listeningModules ?? [],
393
- ...this.exposedAddresses.values()
394
- ];
395
- return await Promise.all(exposedModules.map(async (exposedModule) => assertEx3(asModuleInstance(await resolveAddressToInstance(this.rootModule, exposedModule)), () => `Unable to resolve listeningModule [${exposedModule}]`)));
386
+ const exposedModules = [...this.config?.listeningModules ?? [], ...this.exposedAddresses.values()];
387
+ return await Promise.all(
388
+ exposedModules.map(async (exposedModule) => assertEx3(
389
+ asModuleInstance(await resolveAddressToInstance(this.rootModule, exposedModule)),
390
+ () => `Unable to resolve listeningModule [${exposedModule}]`
391
+ ))
392
+ );
396
393
  }
397
394
  start() {
398
395
  if (this.started) {
@@ -408,9 +405,7 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
408
405
  this._pollId = void 0;
409
406
  }
410
407
  async unexpose(id, validate = true) {
411
- const mod = asModuleInstance(await this.rootModule.resolve(id, {
412
- maxDepth: 10
413
- }));
408
+ const mod = asModuleInstance(await this.rootModule.resolve(id, { maxDepth: 10 }));
414
409
  if (mod) {
415
410
  assertEx3(!validate || this._exposedAddresses.has(mod.address), () => `Address not exposed [${mod.address}][${mod.id}]`);
416
411
  this._exposedAddresses.delete(mod.address);
@@ -420,12 +415,18 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
420
415
  return mod;
421
416
  }
422
417
  // eslint-disable-next-line complexity
423
- callLocalModule = /* @__PURE__ */ __name(async (localModule, query) => {
418
+ callLocalModule = async (localModule, query) => {
424
419
  this._idle = false;
425
420
  this._lastQueryTime = Date.now();
426
421
  const localModuleName = localModule.id;
427
- const queryArchivist = assertEx3(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
428
- const responsesArchivist = assertEx3(await this.responsesArchivist(), () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`);
422
+ const queryArchivist = assertEx3(
423
+ await this.queriesArchivist(),
424
+ () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`
425
+ );
426
+ const responsesArchivist = assertEx3(
427
+ await this.responsesArchivist(),
428
+ () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`
429
+ );
429
430
  const queryDestination = query?.$destination;
430
431
  if (queryDestination && queryDestination?.includes(localModule.address)) {
431
432
  const queryIndex = query.payload_hashes.indexOf(query.query);
@@ -433,10 +434,7 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
433
434
  const querySchema = query.payload_schemas[queryIndex];
434
435
  if (localModule.queries.includes(querySchema)) {
435
436
  const queryPayloads = await queryArchivist.get(query.payload_hashes);
436
- this.params.onQueryFulfillStarted?.({
437
- payloads: queryPayloads,
438
- query
439
- });
437
+ this.params.onQueryFulfillStarted?.({ payloads: queryPayloads, query });
440
438
  const queryPayloadsDict = await PayloadBuilder2.toAllHashMap(queryPayloads);
441
439
  const queryHash = await PayloadBuilder2.dataHash(query);
442
440
  if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {
@@ -452,11 +450,7 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
452
450
  });
453
451
  const [bw, payloads, errors] = result;
454
452
  this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`);
455
- const insertResult = await responsesArchivist.insert([
456
- bw,
457
- ...payloads,
458
- ...errors
459
- ]);
453
+ const insertResult = await responsesArchivist.insert([bw, ...payloads, ...errors]);
460
454
  if (insertResult.length === 0) {
461
455
  this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`);
462
456
  }
@@ -480,19 +474,17 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
480
474
  }
481
475
  }
482
476
  }
483
- }, "callLocalModule");
477
+ };
484
478
  /**
485
- * Finds unprocessed commands addressed to the supplied address
486
- * @param address The address to find commands for
487
- */
488
- findQueriesToAddress = /* @__PURE__ */ __name(async (address) => {
479
+ * Finds unprocessed commands addressed to the supplied address
480
+ * @param address The address to find commands for
481
+ */
482
+ findQueriesToAddress = async (address) => {
489
483
  const queriesDivinerId = assertEx3(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined");
490
484
  const queriesBoundWitnessDiviner = await this.queriesDiviner();
491
485
  if (queriesBoundWitnessDiviner) {
492
486
  const prevState = await this.retrieveState(address);
493
- const destination = [
494
- address
495
- ];
487
+ const destination = [address];
496
488
  const limit = this.perAddressBatchQueryLimit;
497
489
  const divinerQuery = {
498
490
  destination,
@@ -501,9 +493,7 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
501
493
  schema: BoundWitnessDivinerQuerySchema2,
502
494
  cursor: prevState
503
495
  };
504
- const result = await queriesBoundWitnessDiviner.divine([
505
- divinerQuery
506
- ]);
496
+ const result = await queriesBoundWitnessDiviner.divine([divinerQuery]);
507
497
  const queries = result.filter(isQueryBoundWitnessWithStorageMeta);
508
498
  const highestQuerySequence = queries.reduce((acc, query) => acc = query._sequence > acc ? query._sequence : acc, SequenceConstants2.minLocalSequence);
509
499
  const nextState = queries.length > 0 ? highestQuerySequence : SequenceConstants2.minLocalSequence;
@@ -511,71 +501,70 @@ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
511
501
  this.logger?.debug("findQueriesToAddress", address, prevState, nextState);
512
502
  return queries;
513
503
  } else {
514
- this.logger?.warn(`Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper2.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`);
504
+ this.logger?.warn(
505
+ `Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper2.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`
506
+ );
515
507
  }
516
- }, "findQueriesToAddress");
508
+ };
517
509
  /**
518
- * Runs the background divine process on a loop with a delay
519
- * specified by the `config.pollFrequency`
520
- */
510
+ * Runs the background divine process on a loop with a delay
511
+ * specified by the `config.pollFrequency`
512
+ */
521
513
  poll() {
522
- this._pollId = setTimeoutEx2(async () => {
523
- try {
524
- await this.processIncomingQueries();
525
- } catch (e) {
526
- this.logger?.error?.(`Error in main loop: ${e}`);
527
- } finally {
528
- if (this._pollId) clearTimeoutEx2(this._pollId);
529
- this._pollId = void 0;
530
- this.poll();
531
- }
532
- const now = Date.now();
533
- if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
534
- this._idle = true;
535
- }
536
- }, this._idle ? this.idlePollFrequency : this.pollFrequency);
514
+ this._pollId = setTimeoutEx2(
515
+ async () => {
516
+ try {
517
+ await this.processIncomingQueries();
518
+ } catch (e) {
519
+ this.logger?.error?.(`Error in main loop: ${e}`);
520
+ } finally {
521
+ if (this._pollId) clearTimeoutEx2(this._pollId);
522
+ this._pollId = void 0;
523
+ this.poll();
524
+ }
525
+ const now = Date.now();
526
+ if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
527
+ this._idle = true;
528
+ }
529
+ },
530
+ this._idle ? this.idlePollFrequency : this.pollFrequency
531
+ );
537
532
  }
538
533
  /**
539
- * Background process for checking for inbound queries
540
- */
541
- processIncomingQueries = /* @__PURE__ */ __name(async () => {
534
+ * Background process for checking for inbound queries
535
+ */
536
+ processIncomingQueries = async () => {
542
537
  this.logger?.debug("Checking for inbound queries");
543
538
  const localModules = await this.listeningModules();
544
- await Promise.allSettled(localModules.map(async (localModule) => {
545
- try {
546
- const localModuleName = localModule.id;
547
- this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
548
- const queries = await this.findQueriesToAddress(localModule.address) ?? [];
549
- if (queries.length === 0) return;
550
- this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`);
551
- for (const query of queries) {
552
- await this.callLocalModule(localModule, query);
539
+ await Promise.allSettled(
540
+ localModules.map(async (localModule) => {
541
+ try {
542
+ const localModuleName = localModule.id;
543
+ this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
544
+ const queries = await this.findQueriesToAddress(localModule.address) ?? [];
545
+ if (queries.length === 0) return;
546
+ this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`);
547
+ for (const query of queries) {
548
+ await this.callLocalModule(localModule, query);
549
+ }
550
+ } catch (error) {
551
+ this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`);
553
552
  }
554
- } catch (error) {
555
- this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`);
556
- }
557
- }));
558
- }, "processIncomingQueries");
553
+ })
554
+ );
555
+ };
559
556
  };
560
557
 
561
558
  // src/AsyncQueryBus/ModuleHost/ModuleHost.ts
562
559
  var AsyncQueryBusModuleHost = class extends AbstractModuleHost {
563
- static {
564
- __name(this, "AsyncQueryBusModuleHost");
565
- }
566
560
  _busHost;
567
561
  constructor(params) {
568
562
  super(params);
569
563
  }
570
564
  async start() {
571
- const listeningModules = this.params.config.listeningModules ?? (await this.params.mod.resolve("*", {
572
- direction: "down"
573
- })).map((m) => m.address);
565
+ const listeningModules = this.params.config.listeningModules ?? (await this.params.mod.resolve("*", { direction: "down" })).map((m) => m.address);
574
566
  this._busHost = new AsyncQueryBusHost({
575
- config: {
576
- ...this.params.config,
577
- listeningModules
578
- },
567
+ config: { ...this.params.config, listeningModules },
579
568
  logger: this.params.logger,
580
569
  rootModule: this.params.mod
581
570
  });
@@ -594,9 +583,6 @@ import { isAddress } from "@xylabs/hex";
594
583
  import { AbstractModuleProxy } from "@xyo-network/bridge-abstract";
595
584
  import { ResolveHelper as ResolveHelper3 } from "@xyo-network/module-model";
596
585
  var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractModuleProxy {
597
- static {
598
- __name(this, "AsyncQueryBusModuleProxy");
599
- }
600
586
  static createCount = 0;
601
587
  constructor(params) {
602
588
  _AsyncQueryBusModuleProxy.createCount = _AsyncQueryBusModuleProxy.createCount + 1;
@@ -613,10 +599,7 @@ var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractM
613
599
  }
614
600
  async proxyQueryHandler(query, payloads) {
615
601
  if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
616
- forget2(this.storeToArchivists([
617
- query,
618
- ...payloads ?? []
619
- ]));
602
+ forget2(this.storeToArchivists([query, ...payloads ?? []]));
620
603
  }
621
604
  const result = await this.params.busClient.send(this.address, query, payloads);
622
605
  if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
@@ -625,7 +608,9 @@ var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractM
625
608
  return result;
626
609
  }
627
610
  async publicChildren() {
628
- return (await Promise.all(Object.keys(await this.childAddressMap()).filter(exists).map((address) => this.resolve(address)))).filter(exists);
611
+ return (await Promise.all(
612
+ Object.keys(await this.childAddressMap()).filter(exists).map((address) => this.resolve(address))
613
+ )).filter(exists);
629
614
  }
630
615
  async resolve(idOrFilter = "*", options = {}) {
631
616
  const config = {
@@ -676,7 +661,14 @@ import { forget as forget3 } from "@xylabs/forget";
676
661
  import { isAddress as isAddress3 } from "@xylabs/hex";
677
662
  import { toJsonString } from "@xylabs/object";
678
663
  import { AbstractBridge } from "@xyo-network/bridge-abstract";
679
- import { AddressSchema, creatableModule, isAddressModuleFilter, resolveAddressToInstance as resolveAddressToInstance2, resolveAddressToInstanceUp, ResolveHelper as ResolveHelper5 } from "@xyo-network/module-model";
664
+ import {
665
+ AddressSchema,
666
+ creatableModule,
667
+ isAddressModuleFilter,
668
+ resolveAddressToInstance as resolveAddressToInstance2,
669
+ resolveAddressToInstanceUp,
670
+ ResolveHelper as ResolveHelper5
671
+ } from "@xyo-network/module-model";
680
672
  import { asNodeInstance } from "@xyo-network/node-model";
681
673
  import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
682
674
  import { Mutex as Mutex3 } from "async-mutex";
@@ -687,16 +679,15 @@ import { isAddress as isAddress2 } from "@xylabs/hex";
687
679
  import { Account } from "@xyo-network/account";
688
680
  import { AbstractBridgeModuleResolver, wrapModuleWithType } from "@xyo-network/bridge-abstract";
689
681
  import { ConfigSchema } from "@xyo-network/config-payload-plugin";
690
- import { asModuleInstance as asModuleInstance2, ModuleConfigSchema as ModuleConfigSchema2, ResolveHelper as ResolveHelper4 } from "@xyo-network/module-model";
682
+ import {
683
+ asModuleInstance as asModuleInstance2,
684
+ ModuleConfigSchema as ModuleConfigSchema2,
685
+ ResolveHelper as ResolveHelper4
686
+ } from "@xyo-network/module-model";
691
687
  import { Mutex as Mutex2 } from "async-mutex";
692
688
  import { LRUCache as LRUCache3 } from "lru-cache";
693
689
  var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
694
- static {
695
- __name(this, "PubSubBridgeModuleResolver");
696
- }
697
- _resolvedCache = new LRUCache3({
698
- max: 1e3
699
- });
690
+ _resolvedCache = new LRUCache3({ max: 1e3 });
700
691
  _resolvedCacheMutex = new Mutex2();
701
692
  async resolveHandler(id, options) {
702
693
  const parentResult = await super.resolveHandler(id, options);
@@ -711,10 +702,7 @@ var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
711
702
  const instance = await this._resolvedCacheMutex.runExclusive(async () => {
712
703
  const cachedMod = this._resolvedCache.get(firstPart);
713
704
  if (cachedMod) {
714
- const result2 = idParts.length <= 0 ? cachedMod : cachedMod.resolve(remainderParts, {
715
- ...options,
716
- maxDepth: (options?.maxDepth ?? 5) - 1
717
- });
705
+ const result2 = idParts.length <= 0 ? cachedMod : cachedMod.resolve(remainderParts, { ...options, maxDepth: (options?.maxDepth ?? 5) - 1 });
718
706
  return result2;
719
707
  }
720
708
  const account = await Account.random();
@@ -722,9 +710,7 @@ var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
722
710
  account,
723
711
  archiving: this.params.archiving,
724
712
  busClient: this.params.busClient,
725
- config: {
726
- schema: ModuleConfigSchema2
727
- },
713
+ config: { schema: ModuleConfigSchema2 },
728
714
  host: this,
729
715
  moduleAddress: firstPart,
730
716
  onQuerySendFinished: this.params.onQuerySendFinished,
@@ -734,7 +720,10 @@ var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
734
720
  const state = await proxy.state();
735
721
  if (state) {
736
722
  const configSchema = state.find((payload) => payload.schema === ConfigSchema)?.config;
737
- const config = assertEx5(state.find((payload) => payload.schema === configSchema), () => "Unable to locate config");
723
+ const config = assertEx5(
724
+ state.find((payload) => payload.schema === configSchema),
725
+ () => "Unable to locate config"
726
+ );
738
727
  proxy.setConfig(config);
739
728
  }
740
729
  await proxy.start?.();
@@ -744,30 +733,13 @@ var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
744
733
  return wrapped;
745
734
  });
746
735
  const result = remainderParts.length > 0 ? await instance.resolve(remainderParts, options) : instance;
747
- return result ? [
748
- result
749
- ] : [];
736
+ return result ? [result] : [];
750
737
  }
751
738
  };
752
739
 
753
740
  // src/PubSubBridge.ts
754
- function _ts_decorate(decorators, target, key, desc) {
755
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
756
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
757
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
758
- return c > 3 && r && Object.defineProperty(target, key, r), r;
759
- }
760
- __name(_ts_decorate, "_ts_decorate");
761
741
  var moduleName = "PubSubBridge";
762
742
  var PubSubBridge = class extends AbstractBridge {
763
- static {
764
- __name(this, "PubSubBridge");
765
- }
766
- static configSchemas = [
767
- ...super.configSchemas,
768
- PubSubBridgeConfigSchema
769
- ];
770
- static defaultConfigSchema = PubSubBridgeConfigSchema;
771
743
  _configRootAddress = "";
772
744
  _configStateStoreArchivist = "";
773
745
  _configStateStoreBoundWitnessDiviner = "";
@@ -780,24 +752,15 @@ var PubSubBridge = class extends AbstractBridge {
780
752
  get resolver() {
781
753
  this._resolver = this._resolver ?? new PubSubBridgeModuleResolver({
782
754
  additionalSigners: this.additionalSigners,
783
- archiving: {
784
- ...this.archiving,
785
- resolveArchivists: this.resolveArchivingArchivists.bind(this)
786
- },
755
+ archiving: { ...this.archiving, resolveArchivists: this.resolveArchivingArchivists.bind(this) },
787
756
  bridge: this,
788
757
  busClient: assertEx6(this.busClient(), () => "busClient not configured"),
789
- onQuerySendFinished: /* @__PURE__ */ __name((args) => {
790
- forget3(this.emit("querySendFinished", {
791
- mod: this,
792
- ...args
793
- }));
794
- }, "onQuerySendFinished"),
795
- onQuerySendStarted: /* @__PURE__ */ __name((args) => {
796
- forget3(this.emit("querySendStarted", {
797
- mod: this,
798
- ...args
799
- }));
800
- }, "onQuerySendStarted"),
758
+ onQuerySendFinished: (args) => {
759
+ forget3(this.emit("querySendFinished", { mod: this, ...args }));
760
+ },
761
+ onQuerySendStarted: (args) => {
762
+ forget3(this.emit("querySendStarted", { mod: this, ...args }));
763
+ },
801
764
  root: this,
802
765
  wrapperAccount: this.account
803
766
  });
@@ -830,14 +793,8 @@ var PubSubBridge = class extends AbstractBridge {
830
793
  host.expose(mod);
831
794
  const children = maxDepth > 0 ? await mod.publicChildren?.() ?? [] : [];
832
795
  this.logger.log(`childrenToExpose [${mod.id}][${mod.address}]: ${toJsonString(children.map((child) => child.id))}`);
833
- const exposedChildren = (await Promise.all(children.map((child) => this.exposeChild(child, {
834
- maxDepth: maxDepth - 1,
835
- required: false
836
- })))).flat().filter(exists2);
837
- const allExposed = [
838
- mod,
839
- ...exposedChildren
840
- ];
796
+ const exposedChildren = (await Promise.all(children.map((child) => this.exposeChild(child, { maxDepth: maxDepth - 1, required: false })))).flat().filter(exists2);
797
+ const allExposed = [mod, ...exposedChildren];
841
798
  for (const exposedMod of allExposed) this.logger?.log(`exposed: ${exposedMod.address} [${mod.id}]`);
842
799
  return allExposed;
843
800
  }
@@ -855,29 +812,31 @@ var PubSubBridge = class extends AbstractBridge {
855
812
  }
856
813
  exposedHandler() {
857
814
  const exposedSet = this.busHost()?.exposedAddresses;
858
- return exposedSet ? [
859
- ...exposedSet
860
- ] : [];
815
+ return exposedSet ? [...exposedSet] : [];
861
816
  }
862
817
  async getRoots(force) {
863
818
  return await this._discoverRootsMutex.runExclusive(async () => {
864
819
  if (this._roots === void 0 || force) {
865
- const rootAddresses = (await Promise.all((this.config.roots ?? []).map((id) => {
866
- try {
867
- return ResolveHelper5.transformModuleIdentifier(id);
868
- } catch (ex) {
869
- this.logger?.warn("Unable to transform module identifier:", id, ex);
870
- return;
871
- }
872
- }))).filter(exists2);
873
- const rootInstances = (await Promise.all(rootAddresses.map(async (root) => {
874
- try {
875
- return await this.resolver.resolveHandler(root);
876
- } catch (ex) {
877
- this.logger?.warn("Unable to resolve root:", root, ex);
878
- return;
879
- }
880
- }))).flat().filter(exists2);
820
+ const rootAddresses = (await Promise.all(
821
+ (this.config.roots ?? []).map((id) => {
822
+ try {
823
+ return ResolveHelper5.transformModuleIdentifier(id);
824
+ } catch (ex) {
825
+ this.logger?.warn("Unable to transform module identifier:", id, ex);
826
+ return;
827
+ }
828
+ })
829
+ )).filter(exists2);
830
+ const rootInstances = (await Promise.all(
831
+ rootAddresses.map(async (root) => {
832
+ try {
833
+ return await this.resolver.resolveHandler(root);
834
+ } catch (ex) {
835
+ this.logger?.warn("Unable to resolve root:", root, ex);
836
+ return;
837
+ }
838
+ })
839
+ )).flat().filter(exists2);
881
840
  for (const instance of rootInstances) {
882
841
  this.downResolver.add(instance);
883
842
  }
@@ -888,21 +847,10 @@ var PubSubBridge = class extends AbstractBridge {
888
847
  }
889
848
  async resolve(idOrFilter = "*", options = {}) {
890
849
  const roots = this._roots ?? [];
891
- const workingSet = options.direction === "up" ? [
892
- this
893
- ] : [
894
- ...roots,
895
- this
896
- ];
850
+ const workingSet = options.direction === "up" ? [this] : [...roots, this];
897
851
  if (idOrFilter === "*") {
898
852
  const remainingDepth = (options.maxDepth ?? 1) - 1;
899
- return remainingDepth <= 0 ? workingSet : [
900
- ...workingSet,
901
- ...(await Promise.all(roots.map((mod) => mod.resolve("*", {
902
- ...options,
903
- maxDepth: remainingDepth
904
- })))).flat()
905
- ];
853
+ return remainingDepth <= 0 ? workingSet : [...workingSet, ...(await Promise.all(roots.map((mod) => mod.resolve("*", { ...options, maxDepth: remainingDepth })))).flat()];
906
854
  }
907
855
  switch (typeof idOrFilter) {
908
856
  case "string": {
@@ -935,14 +883,8 @@ var PubSubBridge = class extends AbstractBridge {
935
883
  const mod = await host.unexpose(id, required);
936
884
  if (mod) {
937
885
  const children = maxDepth > 0 ? await mod.publicChildren?.() ?? [] : [];
938
- const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, {
939
- maxDepth: maxDepth - 1,
940
- required: false
941
- })))).flat().filter(exists2);
942
- return [
943
- mod,
944
- ...exposedChildren
945
- ];
886
+ const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, { maxDepth: maxDepth - 1, required: false })))).flat().filter(exists2);
887
+ return [mod, ...exposedChildren];
946
888
  }
947
889
  return [];
948
890
  }
@@ -961,27 +903,18 @@ var PubSubBridge = class extends AbstractBridge {
961
903
  this._busHost = new AsyncQueryBusHost({
962
904
  config: this.config.host,
963
905
  logger: this.logger,
964
- onQueryFulfillFinished: /* @__PURE__ */ __name((args) => {
906
+ onQueryFulfillFinished: (args) => {
965
907
  if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
966
908
  forget3(this.storeToArchivists(args.result?.flat() ?? []));
967
909
  }
968
- forget3(this.emit("queryFulfillFinished", {
969
- mod: this,
970
- ...args
971
- }));
972
- }, "onQueryFulfillFinished"),
973
- onQueryFulfillStarted: /* @__PURE__ */ __name((args) => {
910
+ forget3(this.emit("queryFulfillFinished", { mod: this, ...args }));
911
+ },
912
+ onQueryFulfillStarted: (args) => {
974
913
  if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
975
- forget3(this.storeToArchivists([
976
- args.query,
977
- ...args.payloads ?? []
978
- ]));
914
+ forget3(this.storeToArchivists([args.query, ...args.payloads ?? []]));
979
915
  }
980
- forget3(this.emit("queryFulfillStarted", {
981
- mod: this,
982
- ...args
983
- }));
984
- }, "onQueryFulfillStarted"),
916
+ forget3(this.emit("queryFulfillStarted", { mod: this, ...args }));
917
+ },
985
918
  rootModule: this
986
919
  });
987
920
  }
@@ -994,7 +927,9 @@ var PubSubBridge = class extends AbstractBridge {
994
927
  const node = asNodeInstance(instance);
995
928
  if (node) {
996
929
  const state = await node.state();
997
- const children = (state?.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address) ?? []).filter((a) => a !== instance.address);
930
+ const children = (state?.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address) ?? []).filter(
931
+ (a) => a !== instance.address
932
+ );
998
933
  await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
999
934
  }
1000
935
  }
@@ -1007,7 +942,9 @@ var PubSubBridge = class extends AbstractBridge {
1007
942
  return true;
1008
943
  }
1009
944
  };
1010
- PubSubBridge = _ts_decorate([
945
+ __publicField(PubSubBridge, "configSchemas", [...__superGet(PubSubBridge, PubSubBridge, "configSchemas"), PubSubBridgeConfigSchema]);
946
+ __publicField(PubSubBridge, "defaultConfigSchema", PubSubBridgeConfigSchema);
947
+ PubSubBridge = __decorateClass([
1011
948
  creatableModule()
1012
949
  ], PubSubBridge);
1013
950
  export {