@xyo-network/bridge-pub-sub 2.94.25 → 2.94.27

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 (36) hide show
  1. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -1
  2. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -1
  3. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -1
  4. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -1
  5. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -1
  6. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -1
  7. package/dist/browser/PubSubBridge.d.cts +3 -0
  8. package/dist/browser/PubSubBridge.d.cts.map +1 -1
  9. package/dist/browser/PubSubBridge.d.mts +3 -0
  10. package/dist/browser/PubSubBridge.d.mts.map +1 -1
  11. package/dist/browser/PubSubBridge.d.ts +3 -0
  12. package/dist/browser/PubSubBridge.d.ts.map +1 -1
  13. package/dist/browser/index.cjs +45 -4
  14. package/dist/browser/index.cjs.map +1 -1
  15. package/dist/browser/index.js +45 -4
  16. package/dist/browser/index.js.map +1 -1
  17. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -1
  18. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -1
  19. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -1
  20. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -1
  21. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -1
  22. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -1
  23. package/dist/node/PubSubBridge.d.cts +3 -0
  24. package/dist/node/PubSubBridge.d.cts.map +1 -1
  25. package/dist/node/PubSubBridge.d.mts +3 -0
  26. package/dist/node/PubSubBridge.d.mts.map +1 -1
  27. package/dist/node/PubSubBridge.d.ts +3 -0
  28. package/dist/node/PubSubBridge.d.ts.map +1 -1
  29. package/dist/node/index.cjs +47 -4
  30. package/dist/node/index.cjs.map +1 -1
  31. package/dist/node/index.js +47 -4
  32. package/dist/node/index.js.map +1 -1
  33. package/package.json +20 -18
  34. package/src/AsyncQueryBus/AsyncQueryBusClient.ts +7 -3
  35. package/src/AsyncQueryBus/AsyncQueryBusHost.ts +0 -1
  36. package/src/PubSubBridge.ts +44 -1
@@ -260,19 +260,23 @@ var _AsyncQueryBusClient = class _AsyncQueryBusClient extends AsyncQueryBusBase
260
260
  const context = new Promise((resolve, reject) => {
261
261
  var _a2;
262
262
  (_a2 = this.logger) == null ? void 0 : _a2.debug(`Polling for response to query: ${routedQueryHash}`);
263
+ let nextDelay = 100;
263
264
  const pollForResponse = /* @__PURE__ */ __name(async () => {
264
265
  var _a3, _b2;
265
266
  try {
266
267
  this.start();
267
268
  let response = this.queryCache.get(routedQueryHash);
268
269
  while (response !== void 0) {
269
- await (0, import_delay.delay)(100);
270
+ await (0, import_delay.delay)(nextDelay);
270
271
  response = this.queryCache.get(routedQueryHash);
271
272
  if (response && response !== Pending) {
272
- (_a3 = this.logger) == null ? void 0 : _a3.debug(`Returning response to query: ${routedQueryHash}`);
273
+ (_a3 = this.logger) == null ? void 0 : _a3.log(`Returning response to query: ${routedQueryHash}`);
273
274
  resolve(response);
274
275
  return;
275
276
  }
277
+ nextDelay = Math.floor(nextDelay * 1.2);
278
+ if (nextDelay > 1e3)
279
+ nextDelay = 1e3;
276
280
  }
277
281
  (_b2 = this.logger) == null ? void 0 : _b2.error("Timeout waiting for query response");
278
282
  const error = {
@@ -502,7 +506,6 @@ var _AsyncQueryBusHost = class _AsyncQueryBusHost extends AsyncQueryBusBase {
502
506
  }
503
507
  } catch (error) {
504
508
  (_g = this.logger) == null ? void 0 : _g.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
505
- console.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
506
509
  }
507
510
  }
508
511
  }
@@ -638,8 +641,12 @@ var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
638
641
  // src/PubSubBridge.ts
639
642
  var import_assert5 = require("@xylabs/assert");
640
643
  var import_exists = require("@xylabs/exists");
644
+ var import_object3 = require("@xylabs/object");
641
645
  var import_abstract_bridge3 = require("@xyo-network/abstract-bridge");
646
+ var import_address_payload_plugin = require("@xyo-network/address-payload-plugin");
642
647
  var import_module_model4 = require("@xyo-network/module-model");
648
+ var import_node_model = require("@xyo-network/node-model");
649
+ var import_payload_model = require("@xyo-network/payload-model");
643
650
 
644
651
  // src/PubSubBridgeModuleResolver.ts
645
652
  var import_assert4 = require("@xylabs/assert");
@@ -727,6 +734,21 @@ var _PubSubBridge = class _PubSubBridge extends import_abstract_bridge3.Abstract
727
734
  get roots() {
728
735
  return (0, import_assert5.assertEx)(this.config.roots, () => "roots not configured");
729
736
  }
737
+ async connect(id, maxDepth = 5) {
738
+ const existingInstance = await this.resolve(id);
739
+ if (existingInstance) {
740
+ return existingInstance.address;
741
+ }
742
+ const instance = await this.resolver.resolve(id);
743
+ return await this.connectInstance(instance, maxDepth);
744
+ }
745
+ async disconnect(id) {
746
+ const instance = await this.resolve(id);
747
+ if (instance) {
748
+ this.downResolver.remove(instance.address);
749
+ return instance.address;
750
+ }
751
+ }
730
752
  async discoverRoots() {
731
753
  const rootInstances = (await Promise.all(this.roots.map(async (root) => await this.resolver.resolve(root)))).filter(import_exists.exists);
732
754
  for (const instance of rootInstances) {
@@ -735,7 +757,8 @@ var _PubSubBridge = class _PubSubBridge extends import_abstract_bridge3.Abstract
735
757
  return rootInstances;
736
758
  }
737
759
  async exposeHandler(id, options) {
738
- const { maxDepth = 2, direction = "all", required = true } = options ?? {};
760
+ var _a;
761
+ const { maxDepth = 2, direction = "down", required = true } = options ?? {};
739
762
  const host = (0, import_assert5.assertEx)(this.busHost(), () => "Not configured as a host");
740
763
  const module2 = await host.expose(id, {
741
764
  required
@@ -749,6 +772,10 @@ var _PubSubBridge = class _PubSubBridge extends import_abstract_bridge3.Abstract
749
772
  maxDepth: maxDepth - 1,
750
773
  required: false
751
774
  })))).flat().filter(import_exists.exists);
775
+ (_a = this.logger) == null ? void 0 : _a.log(`exposed: ${(0, import_object3.toJsonString)([
776
+ module2,
777
+ ...exposedChildren
778
+ ].map((m) => `${m.address} [${m.config.name}]`))}`);
752
779
  return [
753
780
  module2,
754
781
  ...exposedChildren
@@ -808,6 +835,22 @@ var _PubSubBridge = class _PubSubBridge extends import_abstract_bridge3.Abstract
808
835
  }
809
836
  return this._busHost;
810
837
  }
838
+ async connectInstance(instance, maxDepth = 5) {
839
+ var _a;
840
+ if (instance) {
841
+ this.downResolver.add(instance);
842
+ if (maxDepth > 0) {
843
+ const node = (0, import_node_model.asNodeInstance)(instance);
844
+ if (node) {
845
+ const state = await node.state();
846
+ const children = ((state == null ? void 0 : state.filter((0, import_payload_model.isPayloadOfSchemaType)(import_address_payload_plugin.AddressSchema)).map((s) => s.address)) ?? []).filter((a) => a !== instance.address);
847
+ await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
848
+ }
849
+ }
850
+ (_a = this.logger) == null ? void 0 : _a.log(`Connect: ${instance.config.name ?? instance.address}`);
851
+ return instance.address;
852
+ }
853
+ }
811
854
  stopHandler(_timeout) {
812
855
  var _a;
813
856
  (_a = this.busHost()) == null ? void 0 : _a.stop();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/AbstractModuleHost/AbstractModuleHost.ts","../../src/AsyncQueryBus/AsyncQueryBusClient.ts","../../src/AsyncQueryBus/AsyncQueryBusBase.ts","../../src/AsyncQueryBus/model/QueryStatus.ts","../../src/AsyncQueryBus/AsyncQueryBusHost.ts","../../src/AsyncQueryBus/ModuleHost/ModuleHost.ts","../../src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts","../../src/Schema.ts","../../src/Config.ts","../../src/PubSubBridge.ts","../../src/PubSubBridgeModuleResolver.ts"],"sourcesContent":["export * from './AbstractModuleHost'\nexport * from './AsyncQueryBus'\nexport * from './Config'\nexport * from './Params'\nexport * from './PubSubBridge'\nexport * from './PubSubBridgeModuleResolver'\nexport * from './Schema'\n","import { Base, BaseParams } from '@xylabs/object'\nimport { Promisable } from '@xylabs/promise'\nimport { ModuleInstance } from '@xyo-network/module-model'\n\nexport type ModuleHostParams<THostedInstance extends ModuleInstance = ModuleInstance> = BaseParams<{\n module: THostedInstance\n}>\n\nexport abstract class AbstractModuleHost<TParams extends ModuleHostParams = ModuleHostParams> extends Base<TParams> {\n abstract start(): Promisable<void>\n abstract stop(): Promisable<void>\n}\n","import { assertEx } from '@xylabs/assert'\nimport { delay } from '@xylabs/delay'\nimport { forget } from '@xylabs/forget'\nimport { Address } from '@xylabs/hex'\nimport { clearTimeoutEx, setTimeoutEx } from '@xylabs/timer'\nimport { isBoundWitnessWithMeta, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { BoundWitnessDivinerQueryPayload, BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'\nimport { CacheConfig, ModuleQueryResult } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { ModuleError, Payload, PayloadWithMeta, WithMeta } from '@xyo-network/payload-model'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusBase } from './AsyncQueryBusBase'\nimport { AsyncQueryBusClientParams, Pending } from './model'\n\nexport class AsyncQueryBusClient<TParams extends AsyncQueryBusClientParams = AsyncQueryBusClientParams> extends AsyncQueryBusBase<TParams> {\n protected _queryCache?: LRUCache<Address, Pending | ModuleQueryResult>\n private _pollCount = 0\n private _pollId?: string\n\n constructor(params: TParams) {\n super(params)\n }\n\n get queryCacheConfig(): LRUCache.Options<Address, Pending | ModuleQueryResult, unknown> {\n const queryCacheConfig: CacheConfig | undefined = this.config?.queryCache === true ? {} : this.config?.queryCache\n return { max: 100, ttl: 1000 * 60, ...queryCacheConfig }\n }\n\n get started() {\n return !!this._pollId\n }\n\n /**\n * A cache of queries that have been issued\n */\n protected get queryCache(): LRUCache<Address, Pending | ModuleQueryResult> {\n const config = this.queryCacheConfig\n const requiredConfig = { noUpdateTTL: false, ttlAutopurge: true }\n this._queryCache = this._queryCache ?? new LRUCache<Address, Pending | ModuleQueryResult>({ ...config, ...requiredConfig })\n return this._queryCache\n }\n\n listeningAddresses() {\n return this._queryCache?.keys()\n }\n\n async send(address: Address, query: QueryBoundWitness, payloads?: Payload[] | undefined): Promise<ModuleQueryResult> {\n //console.log('send')\n this.logger?.debug(`Begin issuing query to: ${address}`)\n const $meta = { ...query?.$meta, destination: [address] }\n const routedQuery = await PayloadBuilder.build({ ...query, $meta })\n //console.log('queryArchivist - calling')\n const queryArchivist = assertEx(\n await this.queriesArchivist(),\n () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n //console.log('queryArchivist')\n\n // TODO: Should we always re-hash to true up timestamps? We can't\n // re-sign correctly so we would lose that information if we did and\n // would also be replying to consumers with a different query hash than\n // they sent us (which might be OK since it reflect the chain of custody)\n // Revisit this once we have proxy module support as they are another\n // intermediary to consider.\n const routedQueryHash =\n // Trust the signed hash if it's there\n (routedQuery as WithMeta<QueryBoundWitness>)?.$hash ??\n // TODO: What is the right way to find the dataHash\n Object.keys(await PayloadBuilder.toDataHashMap([routedQuery]))[0]\n this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`)\n // If there was data associated with the query, add it to the insert\n const data = payloads ? [routedQuery, ...payloads] : [routedQuery]\n const insertResult = await queryArchivist.insert?.(data)\n this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`)\n this.queryCache.set(routedQueryHash, Pending)\n if (!insertResult) throw new Error('Unable to issue query to queryArchivist')\n const context = new Promise<ModuleQueryResult>((resolve, reject) => {\n this.logger?.debug(`Polling for response to query: ${routedQueryHash}`)\n const pollForResponse = async () => {\n try {\n this.start()\n let response = this.queryCache.get(routedQueryHash)\n // Poll for response until cache key expires (response timed out)\n while (response !== undefined) {\n //console.log('polling...')\n // Wait a bit\n await delay(100)\n // Check the status of the response\n response = this.queryCache.get(routedQueryHash)\n // If status is no longer pending that means we received a response\n if (response && response !== Pending) {\n this.logger?.debug(`Returning response to query: ${routedQueryHash}`)\n resolve(response)\n return\n }\n }\n // If we got here waiting for a response timed out\n this.logger?.error('Timeout waiting for query response')\n // Resolve with error to match what a local module would do if it were to error\n // TODO: BW Builder/Sign result as this module?\n const error: ModuleError = {\n message: 'Timeout waiting for query response',\n query: 'network.xyo.boundwitness',\n schema: 'network.xyo.error.module',\n sources: [routedQueryHash],\n }\n reject(error)\n return\n } finally {\n this.stop()\n }\n }\n forget(pollForResponse())\n })\n return context\n }\n\n /**\n * Runs the background divine process on a loop with a delay\n * specified by the `config.pollFrequency`\n */\n private poll() {\n this._pollId = setTimeoutEx(async () => {\n try {\n await this.processIncomingResponses()\n } catch (e) {\n this.logger?.error?.(`Error in main loop: ${e}`)\n } finally {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this.poll()\n }\n }, this.pollFrequencyConfig)\n }\n\n /**\n * Background process for processing incoming responses to previously issued queries\n */\n private processIncomingResponses = async () => {\n const responseArchivist = await this.responsesArchivist()\n if (responseArchivist) {\n const responseBoundWitnessDiviner = await this.responsesDiviner()\n if (responseBoundWitnessDiviner) {\n const pendingCommands = [...this.queryCache.entries()].filter(([_, status]) => status === Pending)\n // TODO: Do in throttled batches\n await Promise.allSettled(\n pendingCommands.map(async ([sourceQuery, status]) => {\n if (status === Pending) {\n const divinerQuery: BoundWitnessDivinerQueryPayload = { schema: BoundWitnessDivinerQuerySchema, sourceQuery }\n const result = await responseBoundWitnessDiviner.divine([divinerQuery])\n if (result && result.length > 0) {\n const response = result.find(isBoundWitnessWithMeta)\n if (response && (response?.$meta as unknown as { sourceQuery: string })?.sourceQuery === sourceQuery) {\n this.logger?.debug(`Found response to query: ${sourceQuery}`)\n // Get any payloads associated with the response\n const payloads: PayloadWithMeta[] = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : []\n this.queryCache.set(sourceQuery, [response, payloads, []])\n }\n }\n }\n }),\n )\n }\n }\n }\n\n private start() {\n if (this._pollCount === 0) {\n this.poll()\n }\n this._pollCount++\n }\n\n private stop() {\n this._pollCount--\n if (this._pollCount <= 0) {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this._pollCount = 0\n }\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { Address } from '@xylabs/hex'\nimport { Base, TypeCheck } from '@xylabs/object'\nimport { ArchivistInstance, isArchivistInstance } from '@xyo-network/archivist-model'\nimport { BoundWitness, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload } from '@xyo-network/diviner-boundwitness-model'\nimport { DivinerInstance, isDivinerInstance } from '@xyo-network/diviner-model'\nimport { ModuleConfig, ModuleIdentifier, ModuleInstance, ResolveHelper } from '@xyo-network/module-model'\nimport { Mutex } from 'async-mutex'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusParams } from './model'\n\nexport class AsyncQueryBusBase<TParams extends AsyncQueryBusParams = AsyncQueryBusParams> extends Base<TParams> {\n protected _lastState?: LRUCache<Address, number>\n protected _targetConfigs: Record<Address, ModuleConfig> = {}\n protected _targetQueries: Record<Address, string[]> = {}\n\n private _lastResolveFailure: Record<ModuleIdentifier, number> = {}\n private _queriesArchivist?: ArchivistInstance\n private _queriesDiviner?: DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, QueryBoundWitness>\n private _reResolveDelay = 1000 * 5 //5 seconds\n private _resolveMutex = new Mutex()\n private _responsesArchivist?: ArchivistInstance\n private _responsesDiviner?: DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, BoundWitness>\n\n constructor(params: TParams) {\n super(params)\n }\n\n get config(): TParams['config'] {\n return this.params.config\n }\n\n get pollFrequencyConfig(): number {\n return this.config?.pollFrequency ?? 1000\n }\n\n get resolver() {\n return this.params.resolver\n }\n\n /**\n * A cache of the last offset of the Diviner process per address\n */\n protected get lastState(): LRUCache<Address, number> {\n const requiredConfig = { max: 1000, ttl: 0 }\n this._lastState = this._lastState ?? new LRUCache<Address, number>(requiredConfig)\n return this._lastState\n }\n\n async queriesArchivist() {\n return await this._resolveMutex.runExclusive(async () => {\n this._queriesArchivist =\n this._queriesArchivist ??\n (await this.resolve(\n assertEx(this.config?.intersect?.queries?.archivist, () => 'No queries Archivist defined'),\n isArchivistInstance,\n ))\n return this._queriesArchivist\n })\n }\n\n async queriesDiviner() {\n return await this._resolveMutex.runExclusive(async () => {\n this._queriesDiviner =\n this._queriesDiviner ??\n ((await this.resolve(\n assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => 'No queries Diviner defined'),\n isDivinerInstance,\n )) as DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, QueryBoundWitness>)\n return this._queriesDiviner\n })\n }\n\n async responsesArchivist() {\n return await this._resolveMutex.runExclusive(async () => {\n this._responsesArchivist =\n this._responsesArchivist ??\n (await this.resolve(\n assertEx(this.config?.intersect?.responses?.archivist, () => 'No responses Archivist defined'),\n isArchivistInstance,\n ))\n return this._responsesArchivist\n })\n }\n\n async responsesDiviner() {\n return await this._resolveMutex.runExclusive(async () => {\n this._responsesDiviner =\n this._responsesDiviner ??\n ((await this.resolve(\n assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => 'No responses Diviner defined'),\n isDivinerInstance,\n )) as DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, BoundWitness>)\n return this._responsesDiviner\n })\n }\n\n /**\n * Commit the internal state of the process. This is similar\n * to a transaction completion in a database and should only be called\n * when results have been successfully persisted to the appropriate\n * external stores.\n * @param address The module address to commit the state for\n * @param nextState The state to commit\n */\n protected async commitState(address: Address, nextState: number) {\n await Promise.resolve()\n // TODO: Offload to Archivist/Diviner instead of in-memory\n const lastState = this.lastState.get(address)\n if (lastState && lastState >= nextState) return\n this.lastState.set(address, nextState)\n }\n\n /**\n * Retrieves the last state of the process. Used to recover state after\n * preemptions, reboots, etc.\n */\n protected async retrieveState(address: Address): Promise<number> {\n await Promise.resolve()\n const state = this.lastState.get(address)\n if (state === undefined) {\n // If this is a boot we can go back a bit in time\n // and begin processing recent commands\n const newState = Date.now() - 1000\n this.lastState.set(address, newState)\n return newState\n } else {\n return state\n }\n }\n\n private async resolve<T extends ModuleInstance>(id: ModuleIdentifier, typeCheck: TypeCheck<T>): Promise<T | undefined> {\n if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {\n return\n }\n this._lastResolveFailure[id] = Date.now()\n const resolved = await ResolveHelper.resolveModuleIdentifier(this.resolver, id)\n if (resolved) {\n if (typeCheck(resolved)) {\n delete this._lastResolveFailure[id]\n return resolved\n } else {\n this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${id}][${resolved?.constructor?.name}]: ${resolved.id}`)\n }\n } else {\n this.logger?.debug(`Unable to resolve queriesArchivist [${id}] [${await ResolveHelper.traceModuleIdentifier(this.resolver, id)}]`)\n }\n }\n}\n","export const Pending = 'pending' as const\nexport type Pending = typeof Pending\n","import { containsAll } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { Address } from '@xylabs/hex'\nimport { clearTimeoutEx, setTimeoutEx } from '@xylabs/timer'\nimport { isQueryBoundWitnessWithMeta, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { isBridgeInstance } from '@xyo-network/bridge-model'\nimport { BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'\nimport { asModuleInstance, ModuleConfigSchema, ModuleIdentifier, ModuleInstance, ResolveHelper } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Schema, WithMeta } from '@xyo-network/payload-model'\n\nimport { AsyncQueryBusBase } from './AsyncQueryBusBase'\nimport { AsyncQueryBusHostParams } from './model'\n\nexport interface ExposeOptions {\n allowedQueries?: Schema[]\n failOnAlreadyExposed?: boolean\n required?: boolean\n}\n\nexport class AsyncQueryBusHost<TParams extends AsyncQueryBusHostParams = AsyncQueryBusHostParams> extends AsyncQueryBusBase<TParams> {\n protected _exposedAddresses = new Set<Address>()\n private _exposeOptions: Record<Address, ExposeOptions> = {}\n private _pollId?: string\n\n constructor(params: TParams) {\n super(params)\n }\n\n get exposedAddresses() {\n return this._exposedAddresses\n }\n\n get perAddressBatchQueryLimit(): number {\n return this.config?.perAddressBatchQueryLimit ?? 10\n }\n\n get started() {\n return !!this._pollId\n }\n\n async expose(id: ModuleIdentifier, options?: ExposeOptions) {\n const { failOnAlreadyExposed, required = true } = options ?? {}\n const module = asModuleInstance(await this.resolver.resolve(id, { maxDepth: 10 }))\n if (!module && required) {\n throw new Error(`Unable to resolve module to expose [${id}]`)\n }\n if (module) {\n if (!required && isBridgeInstance(module)) {\n this.logger?.warn(`Attempted to expose a BridgeModule without required = true [${id}] - Not exposing`)\n } else {\n assertEx(!failOnAlreadyExposed || !this._exposedAddresses.has(module.address), () => `Address already exposed: ${id} [${module.address}]`)\n this._exposedAddresses.add(module.address)\n this._exposeOptions[module.address] = { ...options }\n this.logger?.debug(`${id} exposed [${module.address}]`)\n return module\n }\n }\n }\n\n async listeningModules(): Promise<ModuleInstance[]> {\n const exposedModules = [...(this.config?.listeningModules ?? []), ...this.exposedAddresses.values()]\n const mods = await Promise.all(\n exposedModules.map(async (exposedModule) =>\n assertEx(\n asModuleInstance(await this.resolver.resolve(exposedModule, { maxDepth: 10 })),\n () => `Unable to resolve listeningModule [${exposedModule}]`,\n ),\n ),\n )\n return mods\n }\n\n start() {\n if (this.started) {\n console.warn('AsyncQueryBus starting when already started')\n }\n this.poll()\n }\n\n stop() {\n if (!this.started) {\n console.warn('AsyncQueryBus stopping when already stopped')\n }\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n }\n\n async unexpose(id: ModuleIdentifier, validate = true) {\n const module = asModuleInstance(await this.resolver.resolve(id, { maxDepth: 10 }))\n if (module) {\n assertEx(!validate || this._exposedAddresses.has(module.address), () => `Address not exposed [${module.address}][${module.id}]`)\n this._exposedAddresses.delete(module.address)\n delete this._exposeOptions[module.address]\n this.logger?.debug(`${module.address} [${module.id}] unexposed`)\n }\n return module\n }\n\n protected callLocalModule = async (localModule: ModuleInstance, query: WithMeta<QueryBoundWitness>) => {\n const localModuleName = localModule.config.name ?? localModule.address\n const queryArchivist = assertEx(\n await this.queriesArchivist(),\n () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n const responsesArchivist = assertEx(\n await this.responsesArchivist(),\n () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n const queryDestination = (query.$meta as { destination?: string[] })?.destination\n if (queryDestination && queryDestination?.includes(localModule.address)) {\n // Find the query\n const queryIndex = query.payload_hashes.indexOf(query.query)\n if (queryIndex !== -1) {\n const querySchema = query.payload_schemas[queryIndex]\n // If the destination can process this type of query\n if (localModule.queries.includes(querySchema)) {\n // Get the associated payloads\n const queryPayloads = await queryArchivist.get(query.payload_hashes)\n const queryPayloadsDict = await PayloadBuilder.toAllHashMap(queryPayloads)\n const queryHash = (await PayloadBuilder.build(query)).$hash\n // Check that we have all the arguments for the command\n if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {\n this.logger?.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`)\n return\n }\n try {\n // Issue the query against module\n const querySchema = queryPayloadsDict[query.query].schema\n this.logger?.debug(`Issuing query ${querySchema} (${queryHash}) addressed to module: ${localModuleName}`)\n const response = await localModule.query(query, queryPayloads, {\n allowedQueries: this._exposeOptions[localModule.address]?.allowedQueries,\n schema: ModuleConfigSchema,\n })\n const [bw, payloads, errors] = response\n this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`)\n const insertResult = await responsesArchivist.insert([bw, ...payloads, ...errors])\n // NOTE: If all archivists support the contract that numPayloads inserted === numPayloads returned we can\n // do some deeper assertions here like lenIn === lenOut, but for now this should be good enough since BWs\n // should always be unique causing at least one insertion\n if (insertResult.length === 0) {\n this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`)\n }\n if (query?.timestamp) {\n // TODO: This needs to be thought through as we can't use a distributed timestamp\n // because of collisions. We need to ensure we are using the timestamp of the store\n // so there's no chance of multiple commands at the same time\n await this.commitState(localModule.address, query.timestamp)\n }\n } catch (error) {\n this.logger?.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`)\n console.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`)\n }\n }\n }\n }\n }\n\n /**\n * Finds unprocessed commands addressed to the supplied address\n * @param address The address to find commands for\n */\n protected findQueriesToAddress = async (address: Address) => {\n const queriesDivinerId = assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => 'No queries Diviner defined')\n const queriesBoundWitnessDiviner = await this.queriesDiviner()\n if (queriesBoundWitnessDiviner) {\n // Retrieve last offset from state store\n const timestamp = await this.retrieveState(address)\n const destination = [address]\n const limit = this.perAddressBatchQueryLimit\n // Filter for commands to us by destination address\n const divinerQuery = { destination, limit, schema: BoundWitnessDivinerQuerySchema, sort: 'asc', timestamp }\n const result = await queriesBoundWitnessDiviner.divine([divinerQuery])\n const queries = result.filter(isQueryBoundWitnessWithMeta)\n const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? 0)) + 1 : timestamp\n // TODO: This needs to be thought through as we can't use a distributed timestamp\n // because of collisions. We need to use the timestamp of the store so there's no\n // chance of multiple commands at the same time\n await this.commitState(address, nextState)\n return queries\n } else {\n this.logger?.warn(\n `Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper.traceModuleIdentifier(this.resolver, queriesDivinerId)}]`,\n )\n }\n }\n\n /**\n * Runs the background divine process on a loop with a delay\n * specified by the `config.pollFrequency`\n */\n private poll() {\n this._pollId = setTimeoutEx(async () => {\n try {\n await this.processIncomingQueries()\n } catch (e) {\n this.logger?.error?.(`Error in main loop: ${e}`)\n } finally {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this.poll()\n }\n }, this.pollFrequencyConfig)\n }\n\n /**\n * Background process for checking for inbound queries\n */\n private processIncomingQueries = async () => {\n this.logger?.debug('Checking for inbound queries')\n // Check for any queries that have been issued and have not been responded to\n const localModules = await this.listeningModules()\n\n // TODO: Do in throttled batches\n await Promise.allSettled(\n localModules.map(async (localModule) => {\n try {\n const localModuleName = localModule.config.name ?? localModule.address\n this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`)\n const queries = (await this.findQueriesToAddress(localModule.address)) ?? []\n if (queries.length === 0) return\n this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`)\n for (const query of queries) {\n await this.callLocalModule(localModule, query)\n }\n } catch (error) {\n this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`)\n }\n }),\n )\n }\n}\n","import { AbstractModuleHost, ModuleHostParams } from '../../AbstractModuleHost'\nimport { AsyncQueryBusHost } from '../AsyncQueryBusHost'\nimport { AsyncQueryBusHostConfig } from '../model'\n\nexport type AsyncQueryBusModuleHostParams = ModuleHostParams & {\n config: AsyncQueryBusHostConfig\n}\n\nexport class AsyncQueryBusModuleHost extends AbstractModuleHost<AsyncQueryBusModuleHostParams> {\n private _busHost?: AsyncQueryBusHost\n\n constructor(params: AsyncQueryBusModuleHostParams) {\n super(params)\n }\n\n override async start(): Promise<void> {\n const listeningModules =\n this.params.config.listeningModules ?? (await this.params.module.resolve('*', { direction: 'down' })).map((m) => m.address)\n this._busHost = new AsyncQueryBusHost({\n config: { ...this.params.config, listeningModules },\n logger: this.params.logger,\n resolver: this.params.module,\n })\n this._busHost?.start()\n }\n override stop() {\n this._busHost?.stop()\n }\n}\n","import { AbstractModuleProxy, ModuleProxyParams } from '@xyo-network/abstract-bridge'\nimport { QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { ModuleInstance, ModuleQueryResult } from '@xyo-network/module-model'\nimport { Payload } from '@xyo-network/payload-model'\n\nimport { AsyncQueryBusClient } from '../AsyncQueryBusClient'\n\nexport type AsyncQueryBusModuleProxyParams = ModuleProxyParams & {\n busClient: AsyncQueryBusClient\n}\n\nexport class AsyncQueryBusModuleProxy<\n TWrappedModule extends ModuleInstance = ModuleInstance,\n TParams extends Omit<AsyncQueryBusModuleProxyParams, 'config'> & { config: TWrappedModule['config'] } = Omit<\n AsyncQueryBusModuleProxyParams,\n 'config'\n > & {\n config: TWrappedModule['config']\n },\n >\n extends AbstractModuleProxy<TWrappedModule, TParams>\n implements ModuleInstance<TParams, TWrappedModule['eventData']>\n{\n async proxyQueryHandler<T extends QueryBoundWitness = QueryBoundWitness>(query: T, payloads?: Payload[]): Promise<ModuleQueryResult> {\n return await this.params.busClient.send(this.address, query, payloads)\n }\n\n override async startHandler(): Promise<boolean> {\n return await super.startHandler()\n }\n}\n","export const PubSubBridgeSchema = 'network.xyo.bridge.pubsub'\nexport type PubSubBridgeSchema = typeof PubSubBridgeSchema\n","import { Address } from '@xylabs/hex'\nimport { EmptyObject } from '@xylabs/object'\nimport { BridgeConfig } from '@xyo-network/bridge-model'\n\nimport { AsyncQueryBusClientConfig, AsyncQueryBusHostConfig } from './AsyncQueryBus'\nimport { PubSubBridgeSchema } from './Schema'\n\nexport const PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`\nexport type PubSubBridgeConfigSchema = typeof PubSubBridgeConfigSchema\n\n/**\n * Configuration for the PubSubBridge\n */\nexport type PubSubBridgeConfig<TConfig extends EmptyObject = EmptyObject, TSchema extends string | void = void> = BridgeConfig<\n {\n client?: AsyncQueryBusClientConfig\n host?: AsyncQueryBusHostConfig\n roots?: Address[]\n } & TConfig,\n TSchema extends string ? TSchema : PubSubBridgeConfigSchema\n>\n","import { assertEx } from '@xylabs/assert'\nimport { exists } from '@xylabs/exists'\nimport { Address } from '@xylabs/hex'\nimport { AbstractBridge } from '@xyo-network/abstract-bridge'\nimport { BridgeExposeOptions, BridgeModule, BridgeUnexposeOptions } from '@xyo-network/bridge-model'\nimport { creatableModule, ModuleIdentifier, ModuleInstance, ModuleResolverInstance } from '@xyo-network/module-model'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusClient, AsyncQueryBusHost } from './AsyncQueryBus'\nimport { PubSubBridgeConfigSchema } from './Config'\nimport { PubSubBridgeParams } from './Params'\nimport { PubSubBridgeModuleResolver } from './PubSubBridgeModuleResolver'\n\nconst moduleName = 'PubSubBridge'\n\n@creatableModule()\nexport class PubSubBridge<TParams extends PubSubBridgeParams = PubSubBridgeParams> extends AbstractBridge<TParams> implements BridgeModule<TParams> {\n static override configSchemas = [PubSubBridgeConfigSchema]\n\n protected _configRootAddress: Address = ''\n protected _configStateStoreArchivist: string = ''\n protected _configStateStoreBoundWitnessDiviner: string = ''\n protected _exposedAddresses: Address[] = []\n protected _lastState?: LRUCache<string, number>\n\n private _busClient?: AsyncQueryBusClient\n private _busHost?: AsyncQueryBusHost\n private _resolver?: PubSubBridgeModuleResolver\n\n override get resolver(): ModuleResolverInstance {\n this._resolver =\n this._resolver ??\n new PubSubBridgeModuleResolver({\n bridge: this,\n busClient: assertEx(this.busClient(), () => 'busClient not configured'),\n root: this,\n wrapperAccount: this.account,\n })\n return this._resolver\n }\n\n protected get moduleName() {\n return `${this.config.name ?? moduleName}`\n }\n\n protected get roots() {\n return assertEx(this.config.roots, () => 'roots not configured')\n }\n\n override async discoverRoots(): Promise<ModuleInstance[]> {\n const rootInstances = (await Promise.all(this.roots.map(async (root) => await this.resolver.resolve<ModuleInstance>(root)))).filter(exists)\n for (const instance of rootInstances) {\n this.downResolver.add(instance)\n }\n return rootInstances\n }\n\n async exposeHandler(id: ModuleIdentifier, options?: BridgeExposeOptions | undefined): Promise<ModuleInstance[]> {\n const { maxDepth = 2, direction = 'all', required = true } = options ?? {}\n const host = assertEx(this.busHost(), () => 'Not configured as a host')\n const module = await host.expose(id, { required })\n if (module) {\n const children = maxDepth > 0 ? await module.resolve('*', { direction, maxDepth }) : []\n const exposedChildren = (\n await Promise.all(children.map((child) => this.exposeHandler(child.address, { maxDepth: maxDepth - 1, required: false })))\n )\n .flat()\n .filter(exists)\n return [module, ...exposedChildren]\n }\n return []\n }\n\n exposedHandler(): Address[] {\n const exposedSet = this.busHost()?.exposedAddresses\n return exposedSet ? [...exposedSet] : []\n }\n\n override async startHandler(): Promise<boolean> {\n this.busHost()?.start()\n return await super.startHandler()\n }\n\n async unexposeHandler(id: ModuleIdentifier, options?: BridgeUnexposeOptions | undefined): Promise<ModuleInstance[]> {\n const { maxDepth = 2, direction = 'all', required = true } = options ?? {}\n const host = assertEx(this.busHost(), () => 'Not configured as a host')\n const module = await host.unexpose(id, required)\n if (module) {\n const children = maxDepth > 0 ? await module.resolve('*', { direction, maxDepth }) : []\n const exposedChildren = (\n await Promise.all(children.map((child) => this.unexposeHandler(child.address, { maxDepth: maxDepth - 1, required: false })))\n )\n .flat()\n .filter(exists)\n return [module, ...exposedChildren]\n }\n return []\n }\n\n protected busClient() {\n if (!this._busClient && this.config.client) {\n this._busClient = new AsyncQueryBusClient({\n config: this.config.client,\n logger: this.logger,\n resolver: this,\n })\n }\n return this._busClient\n }\n\n protected busHost() {\n if (!this._busHost && this.config.host) {\n this._busHost = new AsyncQueryBusHost({\n config: this.config.host,\n logger: this.logger,\n resolver: this,\n })\n }\n return this._busHost\n }\n\n protected override stopHandler(_timeout?: number | undefined) {\n this.busHost()?.stop()\n return true\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { Address, isAddress } from '@xylabs/hex'\nimport { AbstractBridgeModuleResolver, BridgeModuleResolverParams, wrapModuleWithType } from '@xyo-network/abstract-bridge'\nimport { Account } from '@xyo-network/account'\nimport { ConfigPayload, ConfigSchema } from '@xyo-network/config-payload-plugin'\nimport { asModuleInstance, ModuleConfig, ModuleConfigSchema, ModuleFilterOptions, ModuleIdentifier, ModuleInstance } from '@xyo-network/module-model'\n\nimport { AsyncQueryBusClient, AsyncQueryBusModuleProxy, AsyncQueryBusModuleProxyParams } from './AsyncQueryBus'\n\nexport interface PubSubBridgeModuleResolverParams extends BridgeModuleResolverParams {\n busClient: AsyncQueryBusClient\n}\n\nexport class PubSubBridgeModuleResolver extends AbstractBridgeModuleResolver<PubSubBridgeModuleResolverParams> {\n override async resolveHandler<T extends ModuleInstance = ModuleInstance>(\n id: ModuleIdentifier,\n options?: ModuleFilterOptions<T>,\n ): Promise<T | T[] | undefined> {\n const parentResult = await super.resolveHandler(id, options)\n if (parentResult) {\n return parentResult\n }\n const idParts = id.split(':')\n const firstPart = idParts.shift()\n assertEx(isAddress(firstPart), () => `Invalid module address: ${firstPart}`)\n const remainderParts = idParts.join(':')\n const account = Account.randomSync()\n const params: AsyncQueryBusModuleProxyParams = {\n account,\n busClient: this.params.busClient,\n config: { schema: ModuleConfigSchema },\n host: this.params.bridge,\n moduleAddress: firstPart as Address,\n }\n const proxy = new AsyncQueryBusModuleProxy<T, AsyncQueryBusModuleProxyParams>(params)\n if (proxy) {\n const state = await proxy.state()\n if (state) {\n const configSchema = (state.find((payload) => payload.schema === ConfigSchema) as ConfigPayload | undefined)?.config\n const config = assertEx(\n state.find((payload) => payload.schema === configSchema),\n () => 'Unable to locate config',\n ) as ModuleConfig\n proxy.setConfig(config)\n }\n }\n await proxy.start?.()\n const wrapped = wrapModuleWithType(proxy, account) as unknown as T\n const as = assertEx(asModuleInstance<T>(wrapped, {}), () => `Failed to asModuleInstance [${id}]`)\n proxy.upResolver.add(as)\n proxy.downResolver.add(as)\n this.add(as)\n return remainderParts.length > 0 ? await proxy.resolve(remainderParts, options) : as\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;ACAA,oBAAiC;AAQ1B,IAAeA,sBAAf,MAAeA,4BAAgFC,mBAAAA;AAGtG;AAHsGA;AAA/F,IAAeD,qBAAf;;;ACRP,IAAAE,i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,WAAO,KAAKF;EACd;EAEmBkD,YAAYC,UAA+B;;AAC5D,eAAKpB,QAAO,MAAZ,mBAAgBqB;AAChB,WAAO;EACT;AACF;AA7G2F3D;AACzF,cADWD,eACK6D,iBAAgB;EAACC;;AAD5B,IAAM9D,eAAN;AAAMA,eAAAA,aAAAA;MADZ+D,sCAAAA;GACY/D,YAAAA;","names":["AbstractModuleHost","Base","import_assert","import_lru_cache","import_object","AsyncQueryBusBase","Base","_lastState","_targetConfigs","_targetQueries","_lastResolveFailure","_queriesArchivist","_queriesDiviner","_reResolveDelay","_resolveMutex","Mutex","_responsesArchivist","_responsesDiviner","constructor","params","config","pollFrequencyConfig","pollFrequency","resolver","lastState","requiredConfig","max","ttl","LRUCache","queriesArchivist","runExclusive","resolve","assertEx","intersect","queries","archivist","isArchivistInstance","queriesDiviner","boundWitnessDiviner","isDivinerInstance","responsesArchivist","responses","responsesDiviner","commitState","address","nextState","Promise","get","set","retrieveState","state","undefined","newState","Date","now","id","typeCheck","resolved","ResolveHelper","resolveModuleIdentifier","logger","warn","name","debug","traceModuleIdentifier","Pending","AsyncQueryBusClient","AsyncQueryBusBase","_queryCache","_pollCount","_pollId","constructor","params","queryCacheConfig","config","queryCache","max","ttl","started","requiredConfig","noUpdateTTL","ttlAutopurge","LRUCache","listeningAddresses","keys","send","address","query","payloads","logger","debug","$meta","destination","routedQuery","PayloadBuilder","build","queryArchivist","assertEx","queriesArchivist","_a","_b","_c","intersect","queries","archivist","routedQueryHash","$hash","Object","toDataHashMap","data","insertResult","insert","set","Pending","Error","context","Promise","resolve","reject","pollForResponse","start","response","get","undefined","delay","error","message","schema","sources","stop","forget","poll","setTimeoutEx","processIncomingResponses","e","clearTimeoutEx","pollFrequencyConfig","responseArchivist","responsesArchivist","responseBoundWitnessDiviner","responsesDiviner","pendingCommands","entries","filter","_","status","allSettled","map","sourceQuery","divinerQuery","BoundWitnessDivinerQuerySchema","result","divine","length","find","isBoundWitnessWithMeta","payload_hashes","import_assert","import_timer","import_boundwitness_model","import_diviner_boundwitness_model","import_module_model","import_payload_builder","AsyncQueryBusHost","AsyncQueryBusBase","_exposedAddresses","Set","_exposeOptions","_pollId","constructor","params","exposedAddresses","perAddressBatchQueryLimit","config","started","expose","id","options","failOnAlreadyExposed","required","module","asModuleInstance","resolver","resolve","maxDepth","Error","isBridgeInstance","logger","warn","assertEx","has","address","add","debug","listeningModules","exposedModules","values","mods","Promise","all","map","exposedModule","start","console","poll","stop","clearTimeoutEx","undefined","unexpose","validate","delete","callLocalModule","localModule","query","localModuleName","name","queryArchivist","queriesArchivist","_a","_b","_c","intersect","queries","archivist","responsesArchivist","queryDestination","$meta","destination","includes","queryIndex","payload_hashes","indexOf","querySchema","payload_schemas","queryPayloads","get","queryPayloadsDict","PayloadBuilder","toAllHashMap","queryHash","build","$hash","containsAll","Object","keys","error","schema","response","allowedQueries","ModuleConfigSchema","bw","payloads","errors","insertResult","insert","length","timestamp","commitState","findQueriesToAddress","queriesDivinerId","boundWitnessDiviner","queriesBoundWitnessDiviner","queriesDiviner","retrieveState","limit","divinerQuery","BoundWitnessDivinerQuerySchema","sort","result","divine","filter","isQueryBoundWitnessWithMeta","nextState","Math","max","c","ResolveHelper","traceModuleIdentifier","setTimeoutEx","processIncomingQueries","e","pollFrequencyConfig","localModules","allSettled","AsyncQueryBusModuleHost","AbstractModuleHost","_busHost","constructor","params","start","listeningModules","config","module","resolve","direction","map","m","address","AsyncQueryBusHost","logger","resolver","stop","AsyncQueryBusModuleProxy","AbstractModuleProxy","proxyQueryHandler","query","payloads","params","busClient","send","address","startHandler","PubSubBridgeSchema","PubSubBridgeConfigSchema","PubSubBridgeSchema","import_assert","import_abstract_bridge","import_module_model","import_assert","import_abstract_bridge","import_module_model","PubSubBridgeModuleResolver","AbstractBridgeModuleResolver","resolveHandler","id","options","parentResult","idParts","split","firstPart","shift","assertEx","isAddress","remainderParts","join","account","Account","randomSync","params","busClient","config","schema","ModuleConfigSchema","host","bridge","moduleAddress","proxy","AsyncQueryBusModuleProxy","state","configSchema","find","payload","ConfigSchema","setConfig","start","wrapped","wrapModuleWithType","as","asModuleInstance","upResolver","add","downResolver","length","resolve","moduleName","PubSubBridge","AbstractBridge","_configRootAddress","_configStateStoreArchivist","_configStateStoreBoundWitnessDiviner","_exposedAddresses","_lastState","_busClient","_busHost","_resolver","resolver","PubSubBridgeModuleResolver","bridge","busClient","assertEx","root","wrapperAccount","account","config","name","roots","discoverRoots","rootInstances","Promise","all","map","resolve","filter","exists","instance","downResolver","add","exposeHandler","id","options","maxDepth","direction","required","host","busHost","module","expose","children","exposedChildren","child","address","flat","exposedHandler","exposedSet","exposedAddresses","startHandler","start","unexposeHandler","unexpose","client","AsyncQueryBusClient","logger","AsyncQueryBusHost","stopHandler","_timeout","stop","configSchemas","PubSubBridgeConfigSchema","creatableModule"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/AbstractModuleHost/AbstractModuleHost.ts","../../src/AsyncQueryBus/AsyncQueryBusClient.ts","../../src/AsyncQueryBus/AsyncQueryBusBase.ts","../../src/AsyncQueryBus/model/QueryStatus.ts","../../src/AsyncQueryBus/AsyncQueryBusHost.ts","../../src/AsyncQueryBus/ModuleHost/ModuleHost.ts","../../src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts","../../src/Schema.ts","../../src/Config.ts","../../src/PubSubBridge.ts","../../src/PubSubBridgeModuleResolver.ts"],"sourcesContent":["export * from './AbstractModuleHost'\nexport * from './AsyncQueryBus'\nexport * from './Config'\nexport * from './Params'\nexport * from './PubSubBridge'\nexport * from './PubSubBridgeModuleResolver'\nexport * from './Schema'\n","import { Base, BaseParams } from '@xylabs/object'\nimport { Promisable } from '@xylabs/promise'\nimport { ModuleInstance } from '@xyo-network/module-model'\n\nexport type ModuleHostParams<THostedInstance extends ModuleInstance = ModuleInstance> = BaseParams<{\n module: THostedInstance\n}>\n\nexport abstract class AbstractModuleHost<TParams extends ModuleHostParams = ModuleHostParams> extends Base<TParams> {\n abstract start(): Promisable<void>\n abstract stop(): Promisable<void>\n}\n","import { assertEx } from '@xylabs/assert'\nimport { delay } from '@xylabs/delay'\nimport { forget } from '@xylabs/forget'\nimport { Address } from '@xylabs/hex'\nimport { clearTimeoutEx, setTimeoutEx } from '@xylabs/timer'\nimport { isBoundWitnessWithMeta, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { BoundWitnessDivinerQueryPayload, BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'\nimport { CacheConfig, ModuleQueryResult } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { ModuleError, Payload, PayloadWithMeta, WithMeta } from '@xyo-network/payload-model'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusBase } from './AsyncQueryBusBase'\nimport { AsyncQueryBusClientParams, Pending } from './model'\n\nexport class AsyncQueryBusClient<TParams extends AsyncQueryBusClientParams = AsyncQueryBusClientParams> extends AsyncQueryBusBase<TParams> {\n protected _queryCache?: LRUCache<Address, Pending | ModuleQueryResult>\n private _pollCount = 0\n private _pollId?: string\n\n constructor(params: TParams) {\n super(params)\n }\n\n get queryCacheConfig(): LRUCache.Options<Address, Pending | ModuleQueryResult, unknown> {\n const queryCacheConfig: CacheConfig | undefined = this.config?.queryCache === true ? {} : this.config?.queryCache\n return { max: 100, ttl: 1000 * 60, ...queryCacheConfig }\n }\n\n get started() {\n return !!this._pollId\n }\n\n /**\n * A cache of queries that have been issued\n */\n protected get queryCache(): LRUCache<Address, Pending | ModuleQueryResult> {\n const config = this.queryCacheConfig\n const requiredConfig = { noUpdateTTL: false, ttlAutopurge: true }\n this._queryCache = this._queryCache ?? new LRUCache<Address, Pending | ModuleQueryResult>({ ...config, ...requiredConfig })\n return this._queryCache\n }\n\n listeningAddresses() {\n return this._queryCache?.keys()\n }\n\n async send(address: Address, query: QueryBoundWitness, payloads?: Payload[] | undefined): Promise<ModuleQueryResult> {\n this.logger?.debug(`Begin issuing query to: ${address}`)\n const $meta = { ...query?.$meta, destination: [address] }\n const routedQuery = await PayloadBuilder.build({ ...query, $meta })\n //console.log('queryArchivist - calling')\n const queryArchivist = assertEx(\n await this.queriesArchivist(),\n () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n //console.log('queryArchivist')\n\n // TODO: Should we always re-hash to true up timestamps? We can't\n // re-sign correctly so we would lose that information if we did and\n // would also be replying to consumers with a different query hash than\n // they sent us (which might be OK since it reflect the chain of custody)\n // Revisit this once we have proxy module support as they are another\n // intermediary to consider.\n const routedQueryHash =\n // Trust the signed hash if it's there\n (routedQuery as WithMeta<QueryBoundWitness>)?.$hash ??\n // TODO: What is the right way to find the dataHash\n Object.keys(await PayloadBuilder.toDataHashMap([routedQuery]))[0]\n this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`)\n // If there was data associated with the query, add it to the insert\n const data = payloads ? [routedQuery, ...payloads] : [routedQuery]\n const insertResult = await queryArchivist.insert?.(data)\n this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`)\n this.queryCache.set(routedQueryHash, Pending)\n if (!insertResult) throw new Error('Unable to issue query to queryArchivist')\n const context = new Promise<ModuleQueryResult>((resolve, reject) => {\n this.logger?.debug(`Polling for response to query: ${routedQueryHash}`)\n let nextDelay = 100\n const pollForResponse = async () => {\n try {\n this.start()\n let response = this.queryCache.get(routedQueryHash)\n // Poll for response until cache key expires (response timed out)\n while (response !== undefined) {\n //console.log('polling...')\n // Wait a bit\n await delay(nextDelay)\n // Check the status of the response\n response = this.queryCache.get(routedQueryHash)\n // If status is no longer pending that means we received a response\n if (response && response !== Pending) {\n this.logger?.log(`Returning response to query: ${routedQueryHash}`)\n resolve(response)\n return\n }\n //back off the polling frequency\n nextDelay = Math.floor(nextDelay * 1.2)\n //cap it at 1000ms\n if (nextDelay > 1000) nextDelay = 1000\n }\n // If we got here waiting for a response timed out\n this.logger?.error('Timeout waiting for query response')\n // Resolve with error to match what a local module would do if it were to error\n // TODO: BW Builder/Sign result as this module?\n const error: ModuleError = {\n message: 'Timeout waiting for query response',\n query: 'network.xyo.boundwitness',\n schema: 'network.xyo.error.module',\n sources: [routedQueryHash],\n }\n reject(error)\n return\n } finally {\n this.stop()\n }\n }\n forget(pollForResponse())\n })\n return context\n }\n\n /**\n * Runs the background divine process on a loop with a delay\n * specified by the `config.pollFrequency`\n */\n private poll() {\n this._pollId = setTimeoutEx(async () => {\n try {\n await this.processIncomingResponses()\n } catch (e) {\n this.logger?.error?.(`Error in main loop: ${e}`)\n } finally {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this.poll()\n }\n }, this.pollFrequencyConfig)\n }\n\n /**\n * Background process for processing incoming responses to previously issued queries\n */\n private processIncomingResponses = async () => {\n const responseArchivist = await this.responsesArchivist()\n if (responseArchivist) {\n const responseBoundWitnessDiviner = await this.responsesDiviner()\n if (responseBoundWitnessDiviner) {\n const pendingCommands = [...this.queryCache.entries()].filter(([_, status]) => status === Pending)\n // TODO: Do in throttled batches\n await Promise.allSettled(\n pendingCommands.map(async ([sourceQuery, status]) => {\n if (status === Pending) {\n const divinerQuery: BoundWitnessDivinerQueryPayload = { schema: BoundWitnessDivinerQuerySchema, sourceQuery }\n const result = await responseBoundWitnessDiviner.divine([divinerQuery])\n if (result && result.length > 0) {\n const response = result.find(isBoundWitnessWithMeta)\n if (response && (response?.$meta as unknown as { sourceQuery: string })?.sourceQuery === sourceQuery) {\n this.logger?.debug(`Found response to query: ${sourceQuery}`)\n // Get any payloads associated with the response\n const payloads: PayloadWithMeta[] = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : []\n this.queryCache.set(sourceQuery, [response, payloads, []])\n }\n }\n }\n }),\n )\n }\n }\n }\n\n private start() {\n if (this._pollCount === 0) {\n this.poll()\n }\n this._pollCount++\n }\n\n private stop() {\n this._pollCount--\n if (this._pollCount <= 0) {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this._pollCount = 0\n }\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { Address } from '@xylabs/hex'\nimport { Base, TypeCheck } from '@xylabs/object'\nimport { ArchivistInstance, isArchivistInstance } from '@xyo-network/archivist-model'\nimport { BoundWitness, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload } from '@xyo-network/diviner-boundwitness-model'\nimport { DivinerInstance, isDivinerInstance } from '@xyo-network/diviner-model'\nimport { ModuleConfig, ModuleIdentifier, ModuleInstance, ResolveHelper } from '@xyo-network/module-model'\nimport { Mutex } from 'async-mutex'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusParams } from './model'\n\nexport class AsyncQueryBusBase<TParams extends AsyncQueryBusParams = AsyncQueryBusParams> extends Base<TParams> {\n protected _lastState?: LRUCache<Address, number>\n protected _targetConfigs: Record<Address, ModuleConfig> = {}\n protected _targetQueries: Record<Address, string[]> = {}\n\n private _lastResolveFailure: Record<ModuleIdentifier, number> = {}\n private _queriesArchivist?: ArchivistInstance\n private _queriesDiviner?: DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, QueryBoundWitness>\n private _reResolveDelay = 1000 * 5 //5 seconds\n private _resolveMutex = new Mutex()\n private _responsesArchivist?: ArchivistInstance\n private _responsesDiviner?: DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, BoundWitness>\n\n constructor(params: TParams) {\n super(params)\n }\n\n get config(): TParams['config'] {\n return this.params.config\n }\n\n get pollFrequencyConfig(): number {\n return this.config?.pollFrequency ?? 1000\n }\n\n get resolver() {\n return this.params.resolver\n }\n\n /**\n * A cache of the last offset of the Diviner process per address\n */\n protected get lastState(): LRUCache<Address, number> {\n const requiredConfig = { max: 1000, ttl: 0 }\n this._lastState = this._lastState ?? new LRUCache<Address, number>(requiredConfig)\n return this._lastState\n }\n\n async queriesArchivist() {\n return await this._resolveMutex.runExclusive(async () => {\n this._queriesArchivist =\n this._queriesArchivist ??\n (await this.resolve(\n assertEx(this.config?.intersect?.queries?.archivist, () => 'No queries Archivist defined'),\n isArchivistInstance,\n ))\n return this._queriesArchivist\n })\n }\n\n async queriesDiviner() {\n return await this._resolveMutex.runExclusive(async () => {\n this._queriesDiviner =\n this._queriesDiviner ??\n ((await this.resolve(\n assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => 'No queries Diviner defined'),\n isDivinerInstance,\n )) as DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, QueryBoundWitness>)\n return this._queriesDiviner\n })\n }\n\n async responsesArchivist() {\n return await this._resolveMutex.runExclusive(async () => {\n this._responsesArchivist =\n this._responsesArchivist ??\n (await this.resolve(\n assertEx(this.config?.intersect?.responses?.archivist, () => 'No responses Archivist defined'),\n isArchivistInstance,\n ))\n return this._responsesArchivist\n })\n }\n\n async responsesDiviner() {\n return await this._resolveMutex.runExclusive(async () => {\n this._responsesDiviner =\n this._responsesDiviner ??\n ((await this.resolve(\n assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => 'No responses Diviner defined'),\n isDivinerInstance,\n )) as DivinerInstance<BoundWitnessDivinerParams, BoundWitnessDivinerQueryPayload, BoundWitness>)\n return this._responsesDiviner\n })\n }\n\n /**\n * Commit the internal state of the process. This is similar\n * to a transaction completion in a database and should only be called\n * when results have been successfully persisted to the appropriate\n * external stores.\n * @param address The module address to commit the state for\n * @param nextState The state to commit\n */\n protected async commitState(address: Address, nextState: number) {\n await Promise.resolve()\n // TODO: Offload to Archivist/Diviner instead of in-memory\n const lastState = this.lastState.get(address)\n if (lastState && lastState >= nextState) return\n this.lastState.set(address, nextState)\n }\n\n /**\n * Retrieves the last state of the process. Used to recover state after\n * preemptions, reboots, etc.\n */\n protected async retrieveState(address: Address): Promise<number> {\n await Promise.resolve()\n const state = this.lastState.get(address)\n if (state === undefined) {\n // If this is a boot we can go back a bit in time\n // and begin processing recent commands\n const newState = Date.now() - 1000\n this.lastState.set(address, newState)\n return newState\n } else {\n return state\n }\n }\n\n private async resolve<T extends ModuleInstance>(id: ModuleIdentifier, typeCheck: TypeCheck<T>): Promise<T | undefined> {\n if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {\n return\n }\n this._lastResolveFailure[id] = Date.now()\n const resolved = await ResolveHelper.resolveModuleIdentifier(this.resolver, id)\n if (resolved) {\n if (typeCheck(resolved)) {\n delete this._lastResolveFailure[id]\n return resolved\n } else {\n this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${id}][${resolved?.constructor?.name}]: ${resolved.id}`)\n }\n } else {\n this.logger?.debug(`Unable to resolve queriesArchivist [${id}] [${await ResolveHelper.traceModuleIdentifier(this.resolver, id)}]`)\n }\n }\n}\n","export const Pending = 'pending' as const\nexport type Pending = typeof Pending\n","import { containsAll } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { Address } from '@xylabs/hex'\nimport { clearTimeoutEx, setTimeoutEx } from '@xylabs/timer'\nimport { isQueryBoundWitnessWithMeta, QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { isBridgeInstance } from '@xyo-network/bridge-model'\nimport { BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'\nimport { asModuleInstance, ModuleConfigSchema, ModuleIdentifier, ModuleInstance, ResolveHelper } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Schema, WithMeta } from '@xyo-network/payload-model'\n\nimport { AsyncQueryBusBase } from './AsyncQueryBusBase'\nimport { AsyncQueryBusHostParams } from './model'\n\nexport interface ExposeOptions {\n allowedQueries?: Schema[]\n failOnAlreadyExposed?: boolean\n required?: boolean\n}\n\nexport class AsyncQueryBusHost<TParams extends AsyncQueryBusHostParams = AsyncQueryBusHostParams> extends AsyncQueryBusBase<TParams> {\n protected _exposedAddresses = new Set<Address>()\n private _exposeOptions: Record<Address, ExposeOptions> = {}\n private _pollId?: string\n\n constructor(params: TParams) {\n super(params)\n }\n\n get exposedAddresses() {\n return this._exposedAddresses\n }\n\n get perAddressBatchQueryLimit(): number {\n return this.config?.perAddressBatchQueryLimit ?? 10\n }\n\n get started() {\n return !!this._pollId\n }\n\n async expose(id: ModuleIdentifier, options?: ExposeOptions) {\n const { failOnAlreadyExposed, required = true } = options ?? {}\n const module = asModuleInstance(await this.resolver.resolve(id, { maxDepth: 10 }))\n if (!module && required) {\n throw new Error(`Unable to resolve module to expose [${id}]`)\n }\n if (module) {\n if (!required && isBridgeInstance(module)) {\n this.logger?.warn(`Attempted to expose a BridgeModule without required = true [${id}] - Not exposing`)\n } else {\n assertEx(!failOnAlreadyExposed || !this._exposedAddresses.has(module.address), () => `Address already exposed: ${id} [${module.address}]`)\n this._exposedAddresses.add(module.address)\n this._exposeOptions[module.address] = { ...options }\n this.logger?.debug(`${id} exposed [${module.address}]`)\n return module\n }\n }\n }\n\n async listeningModules(): Promise<ModuleInstance[]> {\n const exposedModules = [...(this.config?.listeningModules ?? []), ...this.exposedAddresses.values()]\n const mods = await Promise.all(\n exposedModules.map(async (exposedModule) =>\n assertEx(\n asModuleInstance(await this.resolver.resolve(exposedModule, { maxDepth: 10 })),\n () => `Unable to resolve listeningModule [${exposedModule}]`,\n ),\n ),\n )\n return mods\n }\n\n start() {\n if (this.started) {\n console.warn('AsyncQueryBus starting when already started')\n }\n this.poll()\n }\n\n stop() {\n if (!this.started) {\n console.warn('AsyncQueryBus stopping when already stopped')\n }\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n }\n\n async unexpose(id: ModuleIdentifier, validate = true) {\n const module = asModuleInstance(await this.resolver.resolve(id, { maxDepth: 10 }))\n if (module) {\n assertEx(!validate || this._exposedAddresses.has(module.address), () => `Address not exposed [${module.address}][${module.id}]`)\n this._exposedAddresses.delete(module.address)\n delete this._exposeOptions[module.address]\n this.logger?.debug(`${module.address} [${module.id}] unexposed`)\n }\n return module\n }\n\n protected callLocalModule = async (localModule: ModuleInstance, query: WithMeta<QueryBoundWitness>) => {\n const localModuleName = localModule.config.name ?? localModule.address\n const queryArchivist = assertEx(\n await this.queriesArchivist(),\n () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n const responsesArchivist = assertEx(\n await this.responsesArchivist(),\n () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`,\n )\n const queryDestination = (query.$meta as { destination?: string[] })?.destination\n if (queryDestination && queryDestination?.includes(localModule.address)) {\n // Find the query\n const queryIndex = query.payload_hashes.indexOf(query.query)\n if (queryIndex !== -1) {\n const querySchema = query.payload_schemas[queryIndex]\n // If the destination can process this type of query\n if (localModule.queries.includes(querySchema)) {\n // Get the associated payloads\n const queryPayloads = await queryArchivist.get(query.payload_hashes)\n const queryPayloadsDict = await PayloadBuilder.toAllHashMap(queryPayloads)\n const queryHash = (await PayloadBuilder.build(query)).$hash\n // Check that we have all the arguments for the command\n if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {\n this.logger?.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`)\n return\n }\n try {\n // Issue the query against module\n const querySchema = queryPayloadsDict[query.query].schema\n this.logger?.debug(`Issuing query ${querySchema} (${queryHash}) addressed to module: ${localModuleName}`)\n const response = await localModule.query(query, queryPayloads, {\n allowedQueries: this._exposeOptions[localModule.address]?.allowedQueries,\n schema: ModuleConfigSchema,\n })\n const [bw, payloads, errors] = response\n this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`)\n const insertResult = await responsesArchivist.insert([bw, ...payloads, ...errors])\n // NOTE: If all archivists support the contract that numPayloads inserted === numPayloads returned we can\n // do some deeper assertions here like lenIn === lenOut, but for now this should be good enough since BWs\n // should always be unique causing at least one insertion\n if (insertResult.length === 0) {\n this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`)\n }\n if (query?.timestamp) {\n // TODO: This needs to be thought through as we can't use a distributed timestamp\n // because of collisions. We need to ensure we are using the timestamp of the store\n // so there's no chance of multiple commands at the same time\n await this.commitState(localModule.address, query.timestamp)\n }\n } catch (error) {\n this.logger?.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`)\n }\n }\n }\n }\n }\n\n /**\n * Finds unprocessed commands addressed to the supplied address\n * @param address The address to find commands for\n */\n protected findQueriesToAddress = async (address: Address) => {\n const queriesDivinerId = assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => 'No queries Diviner defined')\n const queriesBoundWitnessDiviner = await this.queriesDiviner()\n if (queriesBoundWitnessDiviner) {\n // Retrieve last offset from state store\n const timestamp = await this.retrieveState(address)\n const destination = [address]\n const limit = this.perAddressBatchQueryLimit\n // Filter for commands to us by destination address\n const divinerQuery = { destination, limit, schema: BoundWitnessDivinerQuerySchema, sort: 'asc', timestamp }\n const result = await queriesBoundWitnessDiviner.divine([divinerQuery])\n const queries = result.filter(isQueryBoundWitnessWithMeta)\n const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? 0)) + 1 : timestamp\n // TODO: This needs to be thought through as we can't use a distributed timestamp\n // because of collisions. We need to use the timestamp of the store so there's no\n // chance of multiple commands at the same time\n await this.commitState(address, nextState)\n return queries\n } else {\n this.logger?.warn(\n `Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper.traceModuleIdentifier(this.resolver, queriesDivinerId)}]`,\n )\n }\n }\n\n /**\n * Runs the background divine process on a loop with a delay\n * specified by the `config.pollFrequency`\n */\n private poll() {\n this._pollId = setTimeoutEx(async () => {\n try {\n await this.processIncomingQueries()\n } catch (e) {\n this.logger?.error?.(`Error in main loop: ${e}`)\n } finally {\n if (this._pollId) clearTimeoutEx(this._pollId)\n this._pollId = undefined\n this.poll()\n }\n }, this.pollFrequencyConfig)\n }\n\n /**\n * Background process for checking for inbound queries\n */\n private processIncomingQueries = async () => {\n this.logger?.debug('Checking for inbound queries')\n // Check for any queries that have been issued and have not been responded to\n const localModules = await this.listeningModules()\n\n // TODO: Do in throttled batches\n await Promise.allSettled(\n localModules.map(async (localModule) => {\n try {\n const localModuleName = localModule.config.name ?? localModule.address\n this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`)\n const queries = (await this.findQueriesToAddress(localModule.address)) ?? []\n if (queries.length === 0) return\n this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`)\n for (const query of queries) {\n await this.callLocalModule(localModule, query)\n }\n } catch (error) {\n this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`)\n }\n }),\n )\n }\n}\n","import { AbstractModuleHost, ModuleHostParams } from '../../AbstractModuleHost'\nimport { AsyncQueryBusHost } from '../AsyncQueryBusHost'\nimport { AsyncQueryBusHostConfig } from '../model'\n\nexport type AsyncQueryBusModuleHostParams = ModuleHostParams & {\n config: AsyncQueryBusHostConfig\n}\n\nexport class AsyncQueryBusModuleHost extends AbstractModuleHost<AsyncQueryBusModuleHostParams> {\n private _busHost?: AsyncQueryBusHost\n\n constructor(params: AsyncQueryBusModuleHostParams) {\n super(params)\n }\n\n override async start(): Promise<void> {\n const listeningModules =\n this.params.config.listeningModules ?? (await this.params.module.resolve('*', { direction: 'down' })).map((m) => m.address)\n this._busHost = new AsyncQueryBusHost({\n config: { ...this.params.config, listeningModules },\n logger: this.params.logger,\n resolver: this.params.module,\n })\n this._busHost?.start()\n }\n override stop() {\n this._busHost?.stop()\n }\n}\n","import { AbstractModuleProxy, ModuleProxyParams } from '@xyo-network/abstract-bridge'\nimport { QueryBoundWitness } from '@xyo-network/boundwitness-model'\nimport { ModuleInstance, ModuleQueryResult } from '@xyo-network/module-model'\nimport { Payload } from '@xyo-network/payload-model'\n\nimport { AsyncQueryBusClient } from '../AsyncQueryBusClient'\n\nexport type AsyncQueryBusModuleProxyParams = ModuleProxyParams & {\n busClient: AsyncQueryBusClient\n}\n\nexport class AsyncQueryBusModuleProxy<\n TWrappedModule extends ModuleInstance = ModuleInstance,\n TParams extends Omit<AsyncQueryBusModuleProxyParams, 'config'> & { config: TWrappedModule['config'] } = Omit<\n AsyncQueryBusModuleProxyParams,\n 'config'\n > & {\n config: TWrappedModule['config']\n },\n >\n extends AbstractModuleProxy<TWrappedModule, TParams>\n implements ModuleInstance<TParams, TWrappedModule['eventData']>\n{\n async proxyQueryHandler<T extends QueryBoundWitness = QueryBoundWitness>(query: T, payloads?: Payload[]): Promise<ModuleQueryResult> {\n return await this.params.busClient.send(this.address, query, payloads)\n }\n\n override async startHandler(): Promise<boolean> {\n return await super.startHandler()\n }\n}\n","export const PubSubBridgeSchema = 'network.xyo.bridge.pubsub'\nexport type PubSubBridgeSchema = typeof PubSubBridgeSchema\n","import { Address } from '@xylabs/hex'\nimport { EmptyObject } from '@xylabs/object'\nimport { BridgeConfig } from '@xyo-network/bridge-model'\n\nimport { AsyncQueryBusClientConfig, AsyncQueryBusHostConfig } from './AsyncQueryBus'\nimport { PubSubBridgeSchema } from './Schema'\n\nexport const PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`\nexport type PubSubBridgeConfigSchema = typeof PubSubBridgeConfigSchema\n\n/**\n * Configuration for the PubSubBridge\n */\nexport type PubSubBridgeConfig<TConfig extends EmptyObject = EmptyObject, TSchema extends string | void = void> = BridgeConfig<\n {\n client?: AsyncQueryBusClientConfig\n host?: AsyncQueryBusHostConfig\n roots?: Address[]\n } & TConfig,\n TSchema extends string ? TSchema : PubSubBridgeConfigSchema\n>\n","import { assertEx } from '@xylabs/assert'\nimport { exists } from '@xylabs/exists'\nimport { Address } from '@xylabs/hex'\nimport { toJsonString } from '@xylabs/object'\nimport { AbstractBridge } from '@xyo-network/abstract-bridge'\nimport { AddressPayload, AddressSchema } from '@xyo-network/address-payload-plugin'\nimport { BridgeExposeOptions, BridgeModule, BridgeUnexposeOptions } from '@xyo-network/bridge-model'\nimport { creatableModule, ModuleIdentifier, ModuleInstance, ModuleResolverInstance } from '@xyo-network/module-model'\nimport { asNodeInstance } from '@xyo-network/node-model'\nimport { isPayloadOfSchemaType } from '@xyo-network/payload-model'\nimport { LRUCache } from 'lru-cache'\n\nimport { AsyncQueryBusClient, AsyncQueryBusHost } from './AsyncQueryBus'\nimport { PubSubBridgeConfigSchema } from './Config'\nimport { PubSubBridgeParams } from './Params'\nimport { PubSubBridgeModuleResolver } from './PubSubBridgeModuleResolver'\n\nconst moduleName = 'PubSubBridge'\n\n@creatableModule()\nexport class PubSubBridge<TParams extends PubSubBridgeParams = PubSubBridgeParams> extends AbstractBridge<TParams> implements BridgeModule<TParams> {\n static override configSchemas = [PubSubBridgeConfigSchema]\n\n protected _configRootAddress: Address = ''\n protected _configStateStoreArchivist: string = ''\n protected _configStateStoreBoundWitnessDiviner: string = ''\n protected _exposedAddresses: Address[] = []\n protected _lastState?: LRUCache<string, number>\n\n private _busClient?: AsyncQueryBusClient\n private _busHost?: AsyncQueryBusHost\n private _resolver?: PubSubBridgeModuleResolver\n\n override get resolver(): ModuleResolverInstance {\n this._resolver =\n this._resolver ??\n new PubSubBridgeModuleResolver({\n bridge: this,\n busClient: assertEx(this.busClient(), () => 'busClient not configured'),\n root: this,\n wrapperAccount: this.account,\n })\n return this._resolver\n }\n\n protected get moduleName() {\n return `${this.config.name ?? moduleName}`\n }\n\n protected get roots() {\n return assertEx(this.config.roots, () => 'roots not configured')\n }\n\n async connect(id: ModuleIdentifier, maxDepth = 5): Promise<Address | undefined> {\n //check if already connected\n const existingInstance = await this.resolve<ModuleInstance>(id)\n if (existingInstance) {\n return existingInstance.address\n }\n\n //use the resolver to create the proxy instance\n const instance = await this.resolver.resolve<ModuleInstance>(id)\n return await this.connectInstance(instance, maxDepth)\n }\n\n async disconnect(id: ModuleIdentifier): Promise<Address | undefined> {\n const instance = await this.resolve<ModuleInstance>(id)\n if (instance) {\n this.downResolver.remove(instance.address)\n return instance.address\n }\n }\n\n override async discoverRoots(): Promise<ModuleInstance[]> {\n const rootInstances = (await Promise.all(this.roots.map(async (root) => await this.resolver.resolve<ModuleInstance>(root)))).filter(exists)\n for (const instance of rootInstances) {\n this.downResolver.add(instance)\n }\n return rootInstances\n }\n\n async exposeHandler(id: ModuleIdentifier, options?: BridgeExposeOptions | undefined): Promise<ModuleInstance[]> {\n const { maxDepth = 2, direction = 'down', required = true } = options ?? {}\n const host = assertEx(this.busHost(), () => 'Not configured as a host')\n const module = await host.expose(id, { required })\n if (module) {\n const children = maxDepth > 0 ? await module.resolve('*', { direction, maxDepth }) : []\n const exposedChildren = (\n await Promise.all(children.map((child) => this.exposeHandler(child.address, { maxDepth: maxDepth - 1, required: false })))\n )\n .flat()\n .filter(exists)\n this.logger?.log(`exposed: ${toJsonString([module, ...exposedChildren].map((m) => `${m.address} [${m.config.name}]`))}`)\n return [module, ...exposedChildren]\n }\n return []\n }\n\n exposedHandler(): Address[] {\n const exposedSet = this.busHost()?.exposedAddresses\n return exposedSet ? [...exposedSet] : []\n }\n\n override async startHandler(): Promise<boolean> {\n this.busHost()?.start()\n return await super.startHandler()\n }\n\n async unexposeHandler(id: ModuleIdentifier, options?: BridgeUnexposeOptions | undefined): Promise<ModuleInstance[]> {\n const { maxDepth = 2, direction = 'all', required = true } = options ?? {}\n const host = assertEx(this.busHost(), () => 'Not configured as a host')\n const module = await host.unexpose(id, required)\n if (module) {\n const children = maxDepth > 0 ? await module.resolve('*', { direction, maxDepth }) : []\n const exposedChildren = (\n await Promise.all(children.map((child) => this.unexposeHandler(child.address, { maxDepth: maxDepth - 1, required: false })))\n )\n .flat()\n .filter(exists)\n return [module, ...exposedChildren]\n }\n return []\n }\n\n protected busClient() {\n if (!this._busClient && this.config.client) {\n this._busClient = new AsyncQueryBusClient({\n config: this.config.client,\n logger: this.logger,\n resolver: this,\n })\n }\n return this._busClient\n }\n\n protected busHost() {\n if (!this._busHost && this.config.host) {\n this._busHost = new AsyncQueryBusHost({\n config: this.config.host,\n logger: this.logger,\n resolver: this,\n })\n }\n return this._busHost\n }\n\n protected async connectInstance(instance?: ModuleInstance, maxDepth = 5): Promise<Address | undefined> {\n if (instance) {\n this.downResolver.add(instance)\n if (maxDepth > 0) {\n const node = asNodeInstance(instance)\n if (node) {\n const state = await node.state()\n const children = (state?.filter(isPayloadOfSchemaType<AddressPayload>(AddressSchema)).map((s) => s.address) ?? []).filter(\n (a) => a !== instance.address,\n )\n await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)))\n }\n }\n this.logger?.log(`Connect: ${instance.config.name ?? instance.address}`)\n return instance.address\n }\n }\n\n protected override stopHandler(_timeout?: number | undefined) {\n this.busHost()?.stop()\n return true\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { Address, isAddress } from '@xylabs/hex'\nimport { AbstractBridgeModuleResolver, BridgeModuleResolverParams, wrapModuleWithType } from '@xyo-network/abstract-bridge'\nimport { Account } from '@xyo-network/account'\nimport { ConfigPayload, ConfigSchema } from '@xyo-network/config-payload-plugin'\nimport { asModuleInstance, ModuleConfig, ModuleConfigSchema, ModuleFilterOptions, ModuleIdentifier, ModuleInstance } from '@xyo-network/module-model'\n\nimport { AsyncQueryBusClient, AsyncQueryBusModuleProxy, AsyncQueryBusModuleProxyParams } from './AsyncQueryBus'\n\nexport interface PubSubBridgeModuleResolverParams extends BridgeModuleResolverParams {\n busClient: AsyncQueryBusClient\n}\n\nexport class PubSubBridgeModuleResolver extends AbstractBridgeModuleResolver<PubSubBridgeModuleResolverParams> {\n override async resolveHandler<T extends ModuleInstance = ModuleInstance>(\n id: ModuleIdentifier,\n options?: ModuleFilterOptions<T>,\n ): Promise<T | T[] | undefined> {\n const parentResult = await super.resolveHandler(id, options)\n if (parentResult) {\n return parentResult\n }\n const idParts = id.split(':')\n const firstPart = idParts.shift()\n assertEx(isAddress(firstPart), () => `Invalid module address: ${firstPart}`)\n const remainderParts = idParts.join(':')\n const account = Account.randomSync()\n const params: AsyncQueryBusModuleProxyParams = {\n account,\n busClient: this.params.busClient,\n config: { schema: ModuleConfigSchema },\n host: this.params.bridge,\n moduleAddress: firstPart as Address,\n }\n const proxy = new AsyncQueryBusModuleProxy<T, AsyncQueryBusModuleProxyParams>(params)\n if (proxy) {\n const state = await proxy.state()\n if (state) {\n const configSchema = (state.find((payload) => payload.schema === ConfigSchema) as ConfigPayload | undefined)?.config\n const config = assertEx(\n state.find((payload) => payload.schema === configSchema),\n () => 'Unable to locate config',\n ) as ModuleConfig\n proxy.setConfig(config)\n }\n }\n await proxy.start?.()\n const wrapped = wrapModuleWithType(proxy, account) as unknown as T\n const as = assertEx(asModuleInstance<T>(wrapped, {}), () => `Failed to asModuleInstance [${id}]`)\n proxy.upResolver.add(as)\n proxy.downResolver.add(as)\n this.add(as)\n return remainderParts.length > 0 ? await proxy.resolve(remainderParts, options) : as\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;ACAA,oBAAiC;AAQ1B,IAAeA,sBAAf,MAAeA,4BAAgFC,mBAAAA;AAGtG;AAHsGA;AAA/F,IAAeD,qBAAf;;;ACRP,IAAAE,iBAAyB;AACzB,mBAAsB;AACtB,oBAAuB;AAEvB,mBAA6C;AAC7C,gCAA0D;AAC1D,wCAAgF;AAEhF,6BAA+B;AAE/B,IAAAC,oBAAyB;;;ACVzB,oBAAyB;AAEzB,IAAAC,iBAAgC;AAChC,6BAAuD;AAGvD,2BAAmD;AACnD,0BAA8E;AAC9E,yBAAsB;AACtB,uBAAyB;AAIlB,IAAMC,qBAAN,MAAMA,2BAAqFC,oBAAAA;EACtFC;EACAC,iBAAgD,CAAC;EACjDC,iBAA4C,CAAC;EAE/CC,sBAAwD,CAAC;EACzDC;EACAC;EACAC,kBAAkB,MAAO;EACzBC,gBAAgB,IAAIC,yBAAAA;EACpBC;EACAC;EAERC,YAAYC,QAAiB;AAC3B,UAAMA,MAAAA;EACR;EAEA,IAAIC,SAA4B;AAC9B,WAAO,KAAKD,OAAOC;EACrB;EAEA,IAAIC,sBAA8B;AAlCpC;AAmCI,aAAO,UAAKD,WAAL,mBAAaE,kBAAiB;EACvC;EAEA,IAAIC,WAAW;AACb,WAAO,KAAKJ,OAAOI;EACrB;;;;EAKA,IAAcC,YAAuC;AACnD,UAAMC,iBAAiB;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AAKF;EACd;EAEA,MAAgBoB,gBAAgBD,UAA2BJ,WAAW,GAAiC;;AACrG,QAAII,UAAU;AACZ,WAAKG,aAAaS,IAAIZ,QAAAA;AACtB,UAAIJ,WAAW,GAAG;AAChB,cAAM2C,WAAOC,kCAAexC,QAAAA;AAC5B,YAAIuC,MAAM;AACR,gBAAME,QAAQ,MAAMF,KAAKE,MAAK;AAC9B,gBAAMpB,aAAYoB,+BAAO/B,WAAOgC,4CAAsCC,2CAAAA,GAAgBlC,IAAI,CAACmC,MAAMA,EAAE7C,aAAY,CAAA,GAAIW,OACjH,CAACmC,MAAMA,MAAM7C,SAASD,OAAO;AAE/B,gBAAMQ,QAAQC,IAAIa,SAASZ,IAAI,CAACc,UAAU,KAAK7B,QAAQ6B,OAAO3B,WAAW,CAAA,CAAA,CAAA;QAC3E;MACF;AACA,iBAAK6B,WAAL,mBAAaC,IAAI,YAAY1B,SAAST,OAAOC,QAAQQ,SAASD,OAAO;AACrE,aAAOC,SAASD;IAClB;EACF;EAEmB+C,YAAYC,UAA+B;;AAC5D,eAAK7B,QAAO,MAAZ,mBAAgB8B;AAChB,WAAO;EACT;AACF;AApJ2F1E;AACzF,cADWD,eACK4E,iBAAgB;EAACC;;AAD5B,IAAM7E,eAAN;AAAMA,eAAAA,aAAAA;MADZ8E,sCAAAA;GACY9E,YAAAA;","names":["AbstractModuleHost","Base","import_assert","import_lru_cache","import_object","AsyncQueryBusBase","Base","_lastState","_targetConfigs","_targetQueries","_lastResolveFailure","_queriesArchivist","_queriesDiviner","_reResolveDelay","_resolveMutex","Mutex","_responsesArchivist","_responsesDiviner","constructor","params","config","pollFrequencyConfig","pollFrequency","resolver","lastState","requiredConfig","max","ttl","LRUCache","queriesArchivist","runExclusive","resolve","assertEx","intersect","queries","archivist","isArchivistInstance","queriesDiviner","boundWitnessDiviner","isDivinerInstance","responsesArchivist","responses","responsesDiviner","commitState","address","nextState","Promise","get","set","retrieveState","state","undefined","newState","Date","now","id","typeCheck","resolved","ResolveHelper","resolveModuleIdentifier","logger","warn","name","debug","traceModuleIdentifier","Pending","AsyncQueryBusClient","AsyncQueryBusBase","_queryCache","_pollCount","_pollId","constructor","params","queryCacheConfig","config","queryCache","max","ttl","started","requiredConfig","noUpdateTTL","ttlAutopurge","LRUCache","listeningAddresses","keys","send","address","query","payloads","logger","debug","$meta","destination","routedQuery","PayloadBuilder","build","queryArchivist","assertEx","queriesArchivist","_a","_b","_c","intersect","queries","archivist","routedQueryHash","$hash","Object","toDataHashMap","data","insertResult","insert","set","Pending","Error","context","Promise","resolve","reject","nextDelay","pollForResponse","start","response","get","undefined","delay","log","Math","floor","error","message","schema","sources","stop","forget","poll","setTimeoutEx","processIncomingResponses","e","clearTimeoutEx","pollFrequencyConfig","responseArchivist","responsesArchivist","responseBoundWitnessDiviner","responsesDiviner","pendingCommands","entries","filter","_","status","allSettled","map","sourceQuery","divinerQuery","BoundWitnessDivinerQuerySchema","result","divine","length","find","isBoundWitnessWithMeta","payload_hashes","import_assert","import_timer","import_boundwitness_model","import_diviner_boundwitness_model","import_module_model","import_payload_builder","AsyncQueryBusHost","AsyncQueryBusBase","_exposedAddresses","Set","_exposeOptions","_pollId","constructor","params","exposedAddresses","perAddressBatchQueryLimit","config","started","expose","id","options","failOnAlreadyExposed","required","module","asModuleInstance","resolver","resolve","maxDepth","Error","isBridgeInstance","logger","warn","assertEx","has","address","add","debug","listeningModules","exposedModules","values","mods","Promise","all","map","exposedModule","start","console","poll","stop","clearTimeoutEx","undefined","unexpose","validate","delete","callLocalModule","localModule","query","localModuleName","name","queryArchivist","queriesArchivist","_a","_b","_c","intersect","queries","archivist","responsesArchivist","queryDestination","$meta","destination","includes","queryIndex","payload_hashes","indexOf","querySchema","payload_schemas","queryPayloads","get","queryPayloadsDict","PayloadBuilder","toAllHashMap","queryHash","build","$hash","containsAll","Object","keys","error","schema","response","allowedQueries","ModuleConfigSchema","bw","payloads","errors","insertResult","insert","length","timestamp","commitState","findQueriesToAddress","queriesDivinerId","boundWitnessDiviner","queriesBoundWitnessDiviner","queriesDiviner","retrieveState","limit","divinerQuery","BoundWitnessDivinerQuerySchema","sort","result","divine","filter","isQueryBoundWitnessWithMeta","nextState","Math","max","c","ResolveHelper","traceModuleIdentifier","setTimeoutEx","processIncomingQueries","e","pollFrequencyConfig","localModules","allSettled","AsyncQueryBusModuleHost","AbstractModuleHost","_busHost","constructor","params","start","listeningModules","config","module","resolve","direction","map","m","address","AsyncQueryBusHost","logger","resolver","stop","AsyncQueryBusModuleProxy","AbstractModuleProxy","proxyQueryHandler","query","payloads","params","busClient","send","address","startHandler","PubSubBridgeSchema","PubSubBridgeConfigSchema","PubSubBridgeSchema","import_assert","import_object","import_abstract_bridge","import_module_model","import_assert","import_abstract_bridge","import_module_model","PubSubBridgeModuleResolver","AbstractBridgeModuleResolver","resolveHandler","id","options","parentResult","idParts","split","firstPart","shift","assertEx","isAddress","remainderParts","join","account","Account","randomSync","params","busClient","config","schema","ModuleConfigSchema","host","bridge","moduleAddress","proxy","AsyncQueryBusModuleProxy","state","configSchema","find","payload","ConfigSchema","setConfig","start","wrapped","wrapModuleWithType","as","asModuleInstance","upResolver","add","downResolver","length","resolve","moduleName","PubSubBridge","AbstractBridge","_configRootAddress","_configStateStoreArchivist","_configStateStoreBoundWitnessDiviner","_exposedAddresses","_lastState","_busClient","_busHost","_resolver","resolver","PubSubBridgeModuleResolver","bridge","busClient","assertEx","root","wrapperAccount","account","config","name","roots","connect","id","maxDepth","existingInstance","resolve","address","instance","connectInstance","disconnect","downResolver","remove","discoverRoots","rootInstances","Promise","all","map","filter","exists","add","exposeHandler","options","direction","required","host","busHost","module","expose","children","exposedChildren","child","flat","logger","log","toJsonString","m","exposedHandler","exposedSet","exposedAddresses","startHandler","start","unexposeHandler","unexpose","client","AsyncQueryBusClient","AsyncQueryBusHost","node","asNodeInstance","state","isPayloadOfSchemaType","AddressSchema","s","a","stopHandler","_timeout","stop","configSchemas","PubSubBridgeConfigSchema","creatableModule"]}
@@ -227,19 +227,23 @@ var _AsyncQueryBusClient = class _AsyncQueryBusClient extends AsyncQueryBusBase
227
227
  const context = new Promise((resolve, reject) => {
228
228
  var _a2;
229
229
  (_a2 = this.logger) == null ? void 0 : _a2.debug(`Polling for response to query: ${routedQueryHash}`);
230
+ let nextDelay = 100;
230
231
  const pollForResponse = /* @__PURE__ */ __name(async () => {
231
232
  var _a3, _b2;
232
233
  try {
233
234
  this.start();
234
235
  let response = this.queryCache.get(routedQueryHash);
235
236
  while (response !== void 0) {
236
- await delay(100);
237
+ await delay(nextDelay);
237
238
  response = this.queryCache.get(routedQueryHash);
238
239
  if (response && response !== Pending) {
239
- (_a3 = this.logger) == null ? void 0 : _a3.debug(`Returning response to query: ${routedQueryHash}`);
240
+ (_a3 = this.logger) == null ? void 0 : _a3.log(`Returning response to query: ${routedQueryHash}`);
240
241
  resolve(response);
241
242
  return;
242
243
  }
244
+ nextDelay = Math.floor(nextDelay * 1.2);
245
+ if (nextDelay > 1e3)
246
+ nextDelay = 1e3;
243
247
  }
244
248
  (_b2 = this.logger) == null ? void 0 : _b2.error("Timeout waiting for query response");
245
249
  const error = {
@@ -469,7 +473,6 @@ var _AsyncQueryBusHost = class _AsyncQueryBusHost extends AsyncQueryBusBase {
469
473
  }
470
474
  } catch (error) {
471
475
  (_g = this.logger) == null ? void 0 : _g.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
472
- console.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
473
476
  }
474
477
  }
475
478
  }
@@ -605,8 +608,12 @@ var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
605
608
  // src/PubSubBridge.ts
606
609
  import { assertEx as assertEx5 } from "@xylabs/assert";
607
610
  import { exists } from "@xylabs/exists";
611
+ import { toJsonString } from "@xylabs/object";
608
612
  import { AbstractBridge } from "@xyo-network/abstract-bridge";
613
+ import { AddressSchema } from "@xyo-network/address-payload-plugin";
609
614
  import { creatableModule } from "@xyo-network/module-model";
615
+ import { asNodeInstance } from "@xyo-network/node-model";
616
+ import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
610
617
 
611
618
  // src/PubSubBridgeModuleResolver.ts
612
619
  import { assertEx as assertEx4 } from "@xylabs/assert";
@@ -694,6 +701,21 @@ var _PubSubBridge = class _PubSubBridge extends AbstractBridge {
694
701
  get roots() {
695
702
  return assertEx5(this.config.roots, () => "roots not configured");
696
703
  }
704
+ async connect(id, maxDepth = 5) {
705
+ const existingInstance = await this.resolve(id);
706
+ if (existingInstance) {
707
+ return existingInstance.address;
708
+ }
709
+ const instance = await this.resolver.resolve(id);
710
+ return await this.connectInstance(instance, maxDepth);
711
+ }
712
+ async disconnect(id) {
713
+ const instance = await this.resolve(id);
714
+ if (instance) {
715
+ this.downResolver.remove(instance.address);
716
+ return instance.address;
717
+ }
718
+ }
697
719
  async discoverRoots() {
698
720
  const rootInstances = (await Promise.all(this.roots.map(async (root) => await this.resolver.resolve(root)))).filter(exists);
699
721
  for (const instance of rootInstances) {
@@ -702,7 +724,8 @@ var _PubSubBridge = class _PubSubBridge extends AbstractBridge {
702
724
  return rootInstances;
703
725
  }
704
726
  async exposeHandler(id, options) {
705
- const { maxDepth = 2, direction = "all", required = true } = options ?? {};
727
+ var _a;
728
+ const { maxDepth = 2, direction = "down", required = true } = options ?? {};
706
729
  const host = assertEx5(this.busHost(), () => "Not configured as a host");
707
730
  const module = await host.expose(id, {
708
731
  required
@@ -716,6 +739,10 @@ var _PubSubBridge = class _PubSubBridge extends AbstractBridge {
716
739
  maxDepth: maxDepth - 1,
717
740
  required: false
718
741
  })))).flat().filter(exists);
742
+ (_a = this.logger) == null ? void 0 : _a.log(`exposed: ${toJsonString([
743
+ module,
744
+ ...exposedChildren
745
+ ].map((m) => `${m.address} [${m.config.name}]`))}`);
719
746
  return [
720
747
  module,
721
748
  ...exposedChildren
@@ -775,6 +802,22 @@ var _PubSubBridge = class _PubSubBridge extends AbstractBridge {
775
802
  }
776
803
  return this._busHost;
777
804
  }
805
+ async connectInstance(instance, maxDepth = 5) {
806
+ var _a;
807
+ if (instance) {
808
+ this.downResolver.add(instance);
809
+ if (maxDepth > 0) {
810
+ const node = asNodeInstance(instance);
811
+ if (node) {
812
+ const state = await node.state();
813
+ const children = ((state == null ? void 0 : state.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address)) ?? []).filter((a) => a !== instance.address);
814
+ await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
815
+ }
816
+ }
817
+ (_a = this.logger) == null ? void 0 : _a.log(`Connect: ${instance.config.name ?? instance.address}`);
818
+ return instance.address;
819
+ }
820
+ }
778
821
  stopHandler(_timeout) {
779
822
  var _a;
780
823
  (_a = this.busHost()) == null ? void 0 : _a.stop();