@xyo-network/bridge-pub-sub 2.106.0 → 2.107.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.cts +44 -59
  2. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.cts.map +1 -1
  3. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.mts +44 -59
  4. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.mts.map +1 -1
  5. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.ts +44 -59
  6. package/dist/browser/AsyncQueryBus/AsyncQueryBusBase.d.ts.map +1 -1
  7. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.cts +0 -10
  8. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -1
  9. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.mts +0 -10
  10. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -1
  11. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.ts +0 -10
  12. package/dist/browser/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -1
  13. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.cts +16 -27
  14. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -1
  15. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.mts +16 -27
  16. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -1
  17. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.ts +16 -27
  18. package/dist/browser/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -1
  19. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts +0 -2
  20. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts.map +1 -1
  21. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts +0 -2
  22. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts.map +1 -1
  23. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts +0 -2
  24. package/dist/browser/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts.map +1 -1
  25. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.cts +0 -6
  26. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.cts.map +1 -1
  27. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.mts +0 -6
  28. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.mts.map +1 -1
  29. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.ts +0 -6
  30. package/dist/browser/AsyncQueryBus/model/BaseConfig.d.ts.map +1 -1
  31. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.cts +0 -3
  32. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.cts.map +1 -1
  33. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.mts +0 -3
  34. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.mts.map +1 -1
  35. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.ts +0 -3
  36. package/dist/browser/AsyncQueryBus/model/ClientConfig.d.ts.map +1 -1
  37. package/dist/browser/AsyncQueryBus/model/HostConfig.d.cts +0 -13
  38. package/dist/browser/AsyncQueryBus/model/HostConfig.d.cts.map +1 -1
  39. package/dist/browser/AsyncQueryBus/model/HostConfig.d.mts +0 -13
  40. package/dist/browser/AsyncQueryBus/model/HostConfig.d.mts.map +1 -1
  41. package/dist/browser/AsyncQueryBus/model/HostConfig.d.ts +0 -13
  42. package/dist/browser/AsyncQueryBus/model/HostConfig.d.ts.map +1 -1
  43. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.cts +0 -6
  44. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.cts.map +1 -1
  45. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.mts +0 -6
  46. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.mts.map +1 -1
  47. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.ts +0 -6
  48. package/dist/browser/AsyncQueryBus/model/IntersectConfig.d.ts.map +1 -1
  49. package/dist/browser/Config.d.cts +0 -3
  50. package/dist/browser/Config.d.cts.map +1 -1
  51. package/dist/browser/Config.d.mts +0 -3
  52. package/dist/browser/Config.d.mts.map +1 -1
  53. package/dist/browser/Config.d.ts +0 -3
  54. package/dist/browser/Config.d.ts.map +1 -1
  55. package/dist/browser/Params.d.cts +0 -3
  56. package/dist/browser/Params.d.cts.map +1 -1
  57. package/dist/browser/Params.d.mts +0 -3
  58. package/dist/browser/Params.d.mts.map +1 -1
  59. package/dist/browser/Params.d.ts +0 -3
  60. package/dist/browser/Params.d.ts.map +1 -1
  61. package/dist/browser/PubSubBridge.d.cts +0 -2
  62. package/dist/browser/PubSubBridge.d.cts.map +1 -1
  63. package/dist/browser/PubSubBridge.d.mts +0 -2
  64. package/dist/browser/PubSubBridge.d.mts.map +1 -1
  65. package/dist/browser/PubSubBridge.d.ts +0 -2
  66. package/dist/browser/PubSubBridge.d.ts.map +1 -1
  67. package/dist/browser/PubSubBridgeModuleResolver.d.cts +6 -6
  68. package/dist/browser/PubSubBridgeModuleResolver.d.mts +6 -6
  69. package/dist/browser/PubSubBridgeModuleResolver.d.ts +6 -6
  70. package/dist/browser/index.cjs +1 -1055
  71. package/dist/browser/index.cjs.map +1 -1
  72. package/dist/browser/index.js +1 -1034
  73. package/dist/browser/index.js.map +1 -1
  74. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts +44 -59
  75. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts.map +1 -1
  76. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts +44 -59
  77. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts.map +1 -1
  78. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts +44 -59
  79. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts.map +1 -1
  80. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts +0 -10
  81. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -1
  82. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts +0 -10
  83. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -1
  84. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts +0 -10
  85. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -1
  86. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts +16 -27
  87. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -1
  88. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts +16 -27
  89. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -1
  90. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts +16 -27
  91. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -1
  92. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts +0 -2
  93. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts.map +1 -1
  94. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts +0 -2
  95. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts.map +1 -1
  96. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts +0 -2
  97. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts.map +1 -1
  98. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts +0 -6
  99. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts.map +1 -1
  100. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts +0 -6
  101. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts.map +1 -1
  102. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts +0 -6
  103. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts.map +1 -1
  104. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts +0 -3
  105. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts.map +1 -1
  106. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts +0 -3
  107. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts.map +1 -1
  108. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts +0 -3
  109. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts.map +1 -1
  110. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts +0 -13
  111. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts.map +1 -1
  112. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts +0 -13
  113. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts.map +1 -1
  114. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts +0 -13
  115. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts.map +1 -1
  116. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts +0 -6
  117. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts.map +1 -1
  118. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts +0 -6
  119. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts.map +1 -1
  120. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts +0 -6
  121. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts.map +1 -1
  122. package/dist/neutral/Config.d.cts +0 -3
  123. package/dist/neutral/Config.d.cts.map +1 -1
  124. package/dist/neutral/Config.d.mts +0 -3
  125. package/dist/neutral/Config.d.mts.map +1 -1
  126. package/dist/neutral/Config.d.ts +0 -3
  127. package/dist/neutral/Config.d.ts.map +1 -1
  128. package/dist/neutral/Params.d.cts +0 -3
  129. package/dist/neutral/Params.d.cts.map +1 -1
  130. package/dist/neutral/Params.d.mts +0 -3
  131. package/dist/neutral/Params.d.mts.map +1 -1
  132. package/dist/neutral/Params.d.ts +0 -3
  133. package/dist/neutral/Params.d.ts.map +1 -1
  134. package/dist/neutral/PubSubBridge.d.cts +0 -2
  135. package/dist/neutral/PubSubBridge.d.cts.map +1 -1
  136. package/dist/neutral/PubSubBridge.d.mts +0 -2
  137. package/dist/neutral/PubSubBridge.d.mts.map +1 -1
  138. package/dist/neutral/PubSubBridge.d.ts +0 -2
  139. package/dist/neutral/PubSubBridge.d.ts.map +1 -1
  140. package/dist/neutral/PubSubBridgeModuleResolver.d.cts +6 -6
  141. package/dist/neutral/PubSubBridgeModuleResolver.d.mts +6 -6
  142. package/dist/neutral/PubSubBridgeModuleResolver.d.ts +6 -6
  143. package/dist/neutral/index.cjs +1 -1055
  144. package/dist/neutral/index.cjs.map +1 -1
  145. package/dist/neutral/index.js +1 -1034
  146. package/dist/neutral/index.js.map +1 -1
  147. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.cts +44 -59
  148. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.cts.map +1 -1
  149. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.mts +44 -59
  150. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.mts.map +1 -1
  151. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.ts +44 -59
  152. package/dist/node/AsyncQueryBus/AsyncQueryBusBase.d.ts.map +1 -1
  153. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.cts +0 -10
  154. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -1
  155. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.mts +0 -10
  156. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -1
  157. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.ts +0 -10
  158. package/dist/node/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -1
  159. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.cts +16 -27
  160. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -1
  161. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.mts +16 -27
  162. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -1
  163. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.ts +16 -27
  164. package/dist/node/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -1
  165. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts +0 -2
  166. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts.map +1 -1
  167. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts +0 -2
  168. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts.map +1 -1
  169. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts +0 -2
  170. package/dist/node/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts.map +1 -1
  171. package/dist/node/AsyncQueryBus/model/BaseConfig.d.cts +0 -6
  172. package/dist/node/AsyncQueryBus/model/BaseConfig.d.cts.map +1 -1
  173. package/dist/node/AsyncQueryBus/model/BaseConfig.d.mts +0 -6
  174. package/dist/node/AsyncQueryBus/model/BaseConfig.d.mts.map +1 -1
  175. package/dist/node/AsyncQueryBus/model/BaseConfig.d.ts +0 -6
  176. package/dist/node/AsyncQueryBus/model/BaseConfig.d.ts.map +1 -1
  177. package/dist/node/AsyncQueryBus/model/ClientConfig.d.cts +0 -3
  178. package/dist/node/AsyncQueryBus/model/ClientConfig.d.cts.map +1 -1
  179. package/dist/node/AsyncQueryBus/model/ClientConfig.d.mts +0 -3
  180. package/dist/node/AsyncQueryBus/model/ClientConfig.d.mts.map +1 -1
  181. package/dist/node/AsyncQueryBus/model/ClientConfig.d.ts +0 -3
  182. package/dist/node/AsyncQueryBus/model/ClientConfig.d.ts.map +1 -1
  183. package/dist/node/AsyncQueryBus/model/HostConfig.d.cts +0 -13
  184. package/dist/node/AsyncQueryBus/model/HostConfig.d.cts.map +1 -1
  185. package/dist/node/AsyncQueryBus/model/HostConfig.d.mts +0 -13
  186. package/dist/node/AsyncQueryBus/model/HostConfig.d.mts.map +1 -1
  187. package/dist/node/AsyncQueryBus/model/HostConfig.d.ts +0 -13
  188. package/dist/node/AsyncQueryBus/model/HostConfig.d.ts.map +1 -1
  189. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.cts +0 -6
  190. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.cts.map +1 -1
  191. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.mts +0 -6
  192. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.mts.map +1 -1
  193. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.ts +0 -6
  194. package/dist/node/AsyncQueryBus/model/IntersectConfig.d.ts.map +1 -1
  195. package/dist/node/Config.d.cts +0 -3
  196. package/dist/node/Config.d.cts.map +1 -1
  197. package/dist/node/Config.d.mts +0 -3
  198. package/dist/node/Config.d.mts.map +1 -1
  199. package/dist/node/Config.d.ts +0 -3
  200. package/dist/node/Config.d.ts.map +1 -1
  201. package/dist/node/Params.d.cts +0 -3
  202. package/dist/node/Params.d.cts.map +1 -1
  203. package/dist/node/Params.d.mts +0 -3
  204. package/dist/node/Params.d.mts.map +1 -1
  205. package/dist/node/Params.d.ts +0 -3
  206. package/dist/node/Params.d.ts.map +1 -1
  207. package/dist/node/PubSubBridge.d.cts +0 -2
  208. package/dist/node/PubSubBridge.d.cts.map +1 -1
  209. package/dist/node/PubSubBridge.d.mts +0 -2
  210. package/dist/node/PubSubBridge.d.mts.map +1 -1
  211. package/dist/node/PubSubBridge.d.ts +0 -2
  212. package/dist/node/PubSubBridge.d.ts.map +1 -1
  213. package/dist/node/PubSubBridgeModuleResolver.d.cts +6 -6
  214. package/dist/node/PubSubBridgeModuleResolver.d.mts +6 -6
  215. package/dist/node/PubSubBridgeModuleResolver.d.ts +6 -6
  216. package/dist/node/index.cjs +1 -1111
  217. package/dist/node/index.cjs.map +1 -1
  218. package/dist/node/index.js +1 -1077
  219. package/dist/node/index.js.map +1 -1
  220. package/package.json +22 -22
  221. package/src/AsyncQueryBus/AsyncQueryBusHost.ts +1 -1
  222. package/src/PubSubBridge.ts +1 -1
@@ -1,1035 +1,2 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/AbstractModuleHost/AbstractModuleHost.ts
5
- import { Base } from "@xylabs/object";
6
- var AbstractModuleHost = class extends Base {
7
- static {
8
- __name(this, "AbstractModuleHost");
9
- }
10
- };
11
-
12
- // src/AsyncQueryBus/AsyncQueryBusClient.ts
13
- import { assertEx as assertEx2 } from "@xylabs/assert";
14
- import { delay } from "@xylabs/delay";
15
- import { forget } from "@xylabs/forget";
16
- import { clearTimeoutEx, setTimeoutEx } from "@xylabs/timer";
17
- import { isBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
18
- import { BoundWitnessDivinerQuerySchema } from "@xyo-network/diviner-boundwitness-model";
19
- import { PayloadBuilder } from "@xyo-network/payload-builder";
20
- import { LRUCache as LRUCache2 } from "lru-cache";
21
-
22
- // src/AsyncQueryBus/AsyncQueryBusBase.ts
23
- import { assertEx } from "@xylabs/assert";
24
- import { Base as Base2 } from "@xylabs/object";
25
- import { isArchivistInstance } from "@xyo-network/archivist-model";
26
- import { isDivinerInstance } from "@xyo-network/diviner-model";
27
- import { ResolveHelper } from "@xyo-network/module-model";
28
- import { Mutex } from "async-mutex";
29
- import { LRUCache } from "lru-cache";
30
- var POLLING_FREQUENCY_MIN = 100;
31
- var POLLING_FREQUENCY_MAX = 6e4;
32
- var POLLING_FREQUENCY_DEFAULT = 1e3;
33
- var AsyncQueryBusBase = class extends Base2 {
34
- static {
35
- __name(this, "AsyncQueryBusBase");
36
- }
37
- _lastState;
38
- _targetConfigs = {};
39
- _targetQueries = {};
40
- _lastResolveFailure = {};
41
- _queriesArchivist;
42
- _queriesDiviner;
43
- _reResolveDelay = 1e3 * 5;
44
- _resolveMutex = new Mutex();
45
- _responsesArchivist;
46
- _responsesDiviner;
47
- constructor(params) {
48
- super(params);
49
- }
50
- get config() {
51
- return this.params.config;
52
- }
53
- get pollFrequency() {
54
- const frequency = this.config?.pollFrequency ?? POLLING_FREQUENCY_DEFAULT;
55
- if (frequency < POLLING_FREQUENCY_MIN || frequency > POLLING_FREQUENCY_MAX) {
56
- return POLLING_FREQUENCY_DEFAULT;
57
- }
58
- return frequency;
59
- }
60
- get rootModule() {
61
- return this.params.rootModule;
62
- }
63
- /**
64
- * A cache of the last offset of the Diviner process per address
65
- */
66
- get lastState() {
67
- const requiredConfig = {
68
- max: 1e3,
69
- ttl: 0
70
- };
71
- this._lastState = this._lastState ?? new LRUCache(requiredConfig);
72
- return this._lastState;
73
- }
74
- async queriesArchivist() {
75
- return await this._resolveMutex.runExclusive(async () => {
76
- this._queriesArchivist = this._queriesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.queries?.archivist, () => "No queries Archivist defined"), isArchivistInstance);
77
- return this._queriesArchivist;
78
- });
79
- }
80
- async queriesDiviner() {
81
- return await this._resolveMutex.runExclusive(async () => {
82
- this._queriesDiviner = this._queriesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined"), isDivinerInstance);
83
- return this._queriesDiviner;
84
- });
85
- }
86
- async responsesArchivist() {
87
- return await this._resolveMutex.runExclusive(async () => {
88
- this._responsesArchivist = this._responsesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.responses?.archivist, () => "No responses Archivist defined"), isArchivistInstance);
89
- return this._responsesArchivist;
90
- });
91
- }
92
- async responsesDiviner() {
93
- return await this._resolveMutex.runExclusive(async () => {
94
- this._responsesDiviner = this._responsesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => "No responses Diviner defined"), isDivinerInstance);
95
- return this._responsesDiviner;
96
- });
97
- }
98
- /**
99
- * Commit the internal state of the process. This is similar
100
- * to a transaction completion in a database and should only be called
101
- * when results have been successfully persisted to the appropriate
102
- * external stores.
103
- * @param address The module address to commit the state for
104
- * @param nextState The state to commit
105
- */
106
- async commitState(address, nextState) {
107
- await Promise.resolve();
108
- const lastState = this.lastState.get(address);
109
- if (lastState && lastState >= nextState) return;
110
- this.lastState.set(address, nextState);
111
- }
112
- /**
113
- * Retrieves the last state of the process. Used to recover state after
114
- * preemptions, reboots, etc.
115
- */
116
- async retrieveState(address) {
117
- await Promise.resolve();
118
- const state = this.lastState.get(address);
119
- if (state === void 0) {
120
- const newState = Date.now() - 1e3;
121
- this.lastState.set(address, newState);
122
- return newState;
123
- } else {
124
- return state;
125
- }
126
- }
127
- async resolve(id, typeCheck) {
128
- if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {
129
- return;
130
- }
131
- this._lastResolveFailure[id] = Date.now();
132
- const resolved = await ResolveHelper.resolveModuleIdentifier(this.rootModule, id);
133
- if (resolved) {
134
- if (typeCheck(resolved)) {
135
- delete this._lastResolveFailure[id];
136
- return resolved;
137
- } else {
138
- this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${id}][${resolved?.constructor?.name}]: ${resolved.id}`);
139
- }
140
- } else {
141
- this.logger?.debug(`Unable to resolve queriesArchivist [${id}] [${await ResolveHelper.traceModuleIdentifier(this.rootModule, id)}]`);
142
- }
143
- }
144
- };
145
-
146
- // src/AsyncQueryBus/model/QueryStatus.ts
147
- var Pending = "pending";
148
-
149
- // src/AsyncQueryBus/AsyncQueryBusClient.ts
150
- var AsyncQueryBusClient = class extends AsyncQueryBusBase {
151
- static {
152
- __name(this, "AsyncQueryBusClient");
153
- }
154
- _queryCache;
155
- _pollCount = 0;
156
- _pollId;
157
- constructor(params) {
158
- super(params);
159
- }
160
- get queryCacheConfig() {
161
- const queryCacheConfig = this.config?.queryCache === true ? {} : this.config?.queryCache;
162
- return {
163
- max: 100,
164
- ttl: 1e3 * 60,
165
- ...queryCacheConfig
166
- };
167
- }
168
- get started() {
169
- return !!this._pollId;
170
- }
171
- /**
172
- * A cache of queries that have been issued
173
- */
174
- get queryCache() {
175
- const config = this.queryCacheConfig;
176
- const requiredConfig = {
177
- noUpdateTTL: false,
178
- ttlAutopurge: true
179
- };
180
- this._queryCache = this._queryCache ?? new LRUCache2({
181
- ...config,
182
- ...requiredConfig
183
- });
184
- return this._queryCache;
185
- }
186
- listeningAddresses() {
187
- return this._queryCache?.keys();
188
- }
189
- async send(address, query, payloads) {
190
- this.logger?.debug(`Begin issuing query to: ${address}`);
191
- const $meta = {
192
- ...query?.$meta,
193
- destination: [
194
- address
195
- ]
196
- };
197
- const routedQuery = await PayloadBuilder.build({
198
- ...query,
199
- $meta
200
- });
201
- const queryArchivist = assertEx2(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
202
- const routedQueryHash = (
203
- // Trust the signed hash if it's there
204
- routedQuery?.$hash ?? // TODO: What is the right way to find the dataHash
205
- Object.keys(await PayloadBuilder.toDataHashMap([
206
- routedQuery
207
- ]))[0]
208
- );
209
- this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`);
210
- const data = payloads ? [
211
- routedQuery,
212
- ...payloads
213
- ] : [
214
- routedQuery
215
- ];
216
- const insertResult = await queryArchivist.insert?.(data);
217
- this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`);
218
- this.queryCache.set(routedQueryHash, Pending);
219
- if (!insertResult) throw new Error("Unable to issue query to queryArchivist");
220
- const context = new Promise((resolve, reject) => {
221
- this.logger?.debug(`Polling for response to query: ${routedQueryHash}`);
222
- let nextDelay = 100;
223
- const pollForResponse = /* @__PURE__ */ __name(async () => {
224
- try {
225
- this.start();
226
- let response = this.queryCache.get(routedQueryHash);
227
- while (response !== void 0) {
228
- await delay(nextDelay);
229
- response = this.queryCache.get(routedQueryHash);
230
- if (response && response !== Pending) {
231
- this.logger?.log(`Returning response to query: ${routedQueryHash}`);
232
- resolve(response);
233
- return;
234
- }
235
- nextDelay = Math.floor(nextDelay * 1.2);
236
- if (nextDelay > 1e3) nextDelay = 1e3;
237
- }
238
- this.logger?.error("Timeout waiting for query response");
239
- const error = {
240
- message: "Timeout waiting for query response",
241
- query: "network.xyo.boundwitness",
242
- schema: "network.xyo.error.module",
243
- sources: [
244
- routedQueryHash
245
- ]
246
- };
247
- reject(error);
248
- return;
249
- } finally {
250
- this.stop();
251
- }
252
- }, "pollForResponse");
253
- forget(pollForResponse());
254
- });
255
- return context;
256
- }
257
- /**
258
- * Runs the background divine process on a loop with a delay
259
- * specified by the `config.pollFrequency`
260
- */
261
- poll() {
262
- this._pollId = setTimeoutEx(async () => {
263
- try {
264
- await this.processIncomingResponses();
265
- } catch (e) {
266
- this.logger?.error?.(`Error in main loop: ${e}`);
267
- } finally {
268
- if (this._pollId) clearTimeoutEx(this._pollId);
269
- this._pollId = void 0;
270
- this.poll();
271
- }
272
- }, this.pollFrequency);
273
- }
274
- /**
275
- * Background process for processing incoming responses to previously issued queries
276
- */
277
- processIncomingResponses = /* @__PURE__ */ __name(async () => {
278
- const responseArchivist = await this.responsesArchivist();
279
- if (responseArchivist) {
280
- const responseBoundWitnessDiviner = await this.responsesDiviner();
281
- if (responseBoundWitnessDiviner) {
282
- const pendingCommands = [
283
- ...this.queryCache.entries()
284
- ].filter(([_, status]) => status === Pending);
285
- await Promise.allSettled(pendingCommands.map(async ([sourceQuery, status]) => {
286
- if (status === Pending) {
287
- const divinerQuery = {
288
- limit: 1,
289
- order: "desc",
290
- schema: BoundWitnessDivinerQuerySchema,
291
- sourceQuery
292
- };
293
- const result = await responseBoundWitnessDiviner.divine([
294
- divinerQuery
295
- ]);
296
- if (result && result.length > 0) {
297
- const response = result.find(isBoundWitnessWithMeta);
298
- if (response && response?.$meta?.sourceQuery === sourceQuery) {
299
- this.logger?.debug(`Found response to query: ${sourceQuery}`);
300
- const payloads = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : [];
301
- this.queryCache.set(sourceQuery, [
302
- response,
303
- payloads,
304
- []
305
- ]);
306
- }
307
- }
308
- }
309
- }));
310
- }
311
- }
312
- }, "processIncomingResponses");
313
- start() {
314
- if (this._pollCount === 0) {
315
- this.poll();
316
- }
317
- this._pollCount++;
318
- }
319
- stop() {
320
- this._pollCount--;
321
- if (this._pollCount <= 0) {
322
- if (this._pollId) clearTimeoutEx(this._pollId);
323
- this._pollId = void 0;
324
- this._pollCount = 0;
325
- }
326
- }
327
- };
328
-
329
- // src/AsyncQueryBus/AsyncQueryBusHost.ts
330
- import { containsAll } from "@xylabs/array";
331
- import { assertEx as assertEx3 } from "@xylabs/assert";
332
- import { clearTimeoutEx as clearTimeoutEx2, setTimeoutEx as setTimeoutEx2 } from "@xylabs/timer";
333
- import { isQueryBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
334
- import { isBridgeInstance } from "@xyo-network/bridge-model";
335
- import { BoundWitnessDivinerQuerySchema as BoundWitnessDivinerQuerySchema2 } from "@xyo-network/diviner-boundwitness-model";
336
- import { asModuleInstance, ModuleConfigSchema, resolveAddressToInstance, ResolveHelper as ResolveHelper2 } from "@xyo-network/module-model";
337
- import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
338
- var IDLE_POLLING_FREQUENCY_RATIO_MIN = 4;
339
- var IDLE_POLLING_FREQUENCY_RATIO_MAX = 64;
340
- var IDLE_POLLING_FREQUENCY_RATIO_DEFAULT = 16;
341
- var IDLE_THRESHOLD_RATIO_MIN = 4;
342
- var IDLE_THRESHOLD_RATIO_MAX = 64;
343
- var IDLE_THRESHOLD_RATIO_DEFAULT = 16;
344
- var AsyncQueryBusHost = class extends AsyncQueryBusBase {
345
- static {
346
- __name(this, "AsyncQueryBusHost");
347
- }
348
- _exposedAddresses = /* @__PURE__ */ new Set();
349
- _exposeOptions = {};
350
- _idle = false;
351
- _lastQueryTime;
352
- _pollId;
353
- constructor(params) {
354
- super(params);
355
- }
356
- get exposedAddresses() {
357
- return this._exposedAddresses;
358
- }
359
- get idlePollFrequency() {
360
- const frequency = this.config?.idlePollFrequency ?? IDLE_POLLING_FREQUENCY_RATIO_DEFAULT * this.pollFrequency;
361
- if (frequency < this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MIN) {
362
- return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
363
- }
364
- if (frequency > this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MAX) {
365
- return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
366
- }
367
- return frequency;
368
- }
369
- get idleThreshold() {
370
- const threshold = this.config?.idleThreshold ?? IDLE_THRESHOLD_RATIO_DEFAULT * this.idlePollFrequency;
371
- if (threshold < this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MIN) {
372
- return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
373
- }
374
- if (threshold > this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MAX) {
375
- return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
376
- }
377
- return threshold;
378
- }
379
- get perAddressBatchQueryLimit() {
380
- return this.config?.perAddressBatchQueryLimit ?? 10;
381
- }
382
- get started() {
383
- return !!this._pollId;
384
- }
385
- expose(module, options) {
386
- const { failOnAlreadyExposed } = options ?? {};
387
- if (isBridgeInstance(module)) {
388
- this.logger?.warn(`Attempted to expose a BridgeModule [${module.id}] - Not exposing`);
389
- } else {
390
- assertEx3(!failOnAlreadyExposed || !this._exposedAddresses.has(module.address), () => `Address already exposed: ${module.id} [${module.address}]`);
391
- this._exposedAddresses.add(module.address);
392
- this._exposeOptions[module.address] = {
393
- ...options
394
- };
395
- this.logger?.debug(`${module.id} exposed [${module.address}]`);
396
- return module;
397
- }
398
- }
399
- async listeningModules() {
400
- const exposedModules = [
401
- ...this.config?.listeningModules ?? [],
402
- ...this.exposedAddresses.values()
403
- ];
404
- const mods = await Promise.all(exposedModules.map(async (exposedModule) => assertEx3(asModuleInstance(await resolveAddressToInstance(this.rootModule, exposedModule)), () => `Unable to resolve listeningModule [${exposedModule}]`)));
405
- return mods;
406
- }
407
- start() {
408
- if (this.started) {
409
- console.warn("AsyncQueryBus starting when already started");
410
- }
411
- this.poll();
412
- }
413
- stop() {
414
- if (!this.started) {
415
- console.warn("AsyncQueryBus stopping when already stopped");
416
- }
417
- if (this._pollId) clearTimeoutEx2(this._pollId);
418
- this._pollId = void 0;
419
- }
420
- async unexpose(id, validate = true) {
421
- const module = asModuleInstance(await this.rootModule.resolve(id, {
422
- maxDepth: 10
423
- }));
424
- if (module) {
425
- assertEx3(!validate || this._exposedAddresses.has(module.address), () => `Address not exposed [${module.address}][${module.id}]`);
426
- this._exposedAddresses.delete(module.address);
427
- delete this._exposeOptions[module.address];
428
- this.logger?.debug(`${module.address} [${module.id}] unexposed`);
429
- }
430
- return module;
431
- }
432
- // eslint-disable-next-line max-statements
433
- callLocalModule = /* @__PURE__ */ __name(async (localModule, query) => {
434
- this._idle = false;
435
- this._lastQueryTime = Date.now();
436
- const localModuleName = localModule.id;
437
- const queryArchivist = assertEx3(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
438
- const responsesArchivist = assertEx3(await this.responsesArchivist(), () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`);
439
- const queryDestination = query.$meta?.destination;
440
- if (queryDestination && queryDestination?.includes(localModule.address)) {
441
- const queryIndex = query.payload_hashes.indexOf(query.query);
442
- if (queryIndex !== -1) {
443
- const querySchema = query.payload_schemas[queryIndex];
444
- if (localModule.queries.includes(querySchema)) {
445
- const queryPayloads = await queryArchivist.get(query.payload_hashes);
446
- this.params.onQueryFulfillStarted?.({
447
- payloads: queryPayloads,
448
- query
449
- });
450
- const queryPayloadsDict = await PayloadBuilder2.toAllHashMap(queryPayloads);
451
- const queryHash = (await PayloadBuilder2.build(query)).$hash;
452
- if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {
453
- this.logger?.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`);
454
- return;
455
- }
456
- try {
457
- const querySchema2 = queryPayloadsDict[query.query].schema;
458
- this.logger?.debug(`Issuing query ${querySchema2} (${queryHash}) addressed to module: ${localModuleName}`);
459
- const result = await localModule.query(query, queryPayloads, {
460
- allowedQueries: this._exposeOptions[localModule.address]?.allowedQueries,
461
- schema: ModuleConfigSchema
462
- });
463
- const [bw, payloads, errors] = result;
464
- this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`);
465
- const insertResult = await responsesArchivist.insert([
466
- bw,
467
- ...payloads,
468
- ...errors
469
- ]);
470
- if (insertResult.length === 0) {
471
- this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`);
472
- }
473
- if (query?.timestamp) {
474
- await this.commitState(localModule.address, query.timestamp);
475
- }
476
- this.params.onQueryFulfillFinished?.({
477
- payloads: queryPayloads,
478
- query,
479
- result,
480
- status: "success"
481
- });
482
- } catch (error) {
483
- this.params.onQueryFulfillFinished?.({
484
- payloads: queryPayloads,
485
- query,
486
- status: "failure"
487
- });
488
- this.logger?.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
489
- }
490
- }
491
- }
492
- }
493
- }, "callLocalModule");
494
- /**
495
- * Finds unprocessed commands addressed to the supplied address
496
- * @param address The address to find commands for
497
- */
498
- findQueriesToAddress = /* @__PURE__ */ __name(async (address) => {
499
- const queriesDivinerId = assertEx3(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined");
500
- const queriesBoundWitnessDiviner = await this.queriesDiviner();
501
- if (queriesBoundWitnessDiviner) {
502
- const prevState = await this.retrieveState(address);
503
- const destination = [
504
- address
505
- ];
506
- const limit = this.perAddressBatchQueryLimit;
507
- const divinerQuery = {
508
- destination,
509
- limit,
510
- order: "asc",
511
- schema: BoundWitnessDivinerQuerySchema2,
512
- timestamp: prevState + 1
513
- };
514
- const result = await queriesBoundWitnessDiviner.divine([
515
- divinerQuery
516
- ]);
517
- const queries = result.filter(isQueryBoundWitnessWithMeta);
518
- const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? prevState)) + 1 : Date.now();
519
- await this.commitState(address, nextState);
520
- this.logger?.debug("findQueriesToAddress", address, prevState, nextState);
521
- return queries;
522
- } else {
523
- this.logger?.warn(`Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper2.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`);
524
- }
525
- }, "findQueriesToAddress");
526
- /**
527
- * Runs the background divine process on a loop with a delay
528
- * specified by the `config.pollFrequency`
529
- */
530
- poll() {
531
- this._pollId = setTimeoutEx2(async () => {
532
- try {
533
- await this.processIncomingQueries();
534
- } catch (e) {
535
- this.logger?.error?.(`Error in main loop: ${e}`);
536
- } finally {
537
- if (this._pollId) clearTimeoutEx2(this._pollId);
538
- this._pollId = void 0;
539
- this.poll();
540
- }
541
- const now = Date.now();
542
- if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
543
- this._idle = true;
544
- }
545
- }, this._idle ? this.idlePollFrequency : this.pollFrequency);
546
- }
547
- /**
548
- * Background process for checking for inbound queries
549
- */
550
- processIncomingQueries = /* @__PURE__ */ __name(async () => {
551
- this.logger?.debug("Checking for inbound queries");
552
- const localModules = await this.listeningModules();
553
- await Promise.allSettled(localModules.map(async (localModule) => {
554
- try {
555
- const localModuleName = localModule.id;
556
- this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
557
- const queries = await this.findQueriesToAddress(localModule.address) ?? [];
558
- if (queries.length === 0) return;
559
- this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`);
560
- for (const query of queries) {
561
- await this.callLocalModule(localModule, query);
562
- }
563
- } catch (error) {
564
- this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`);
565
- }
566
- }));
567
- }, "processIncomingQueries");
568
- };
569
-
570
- // src/AsyncQueryBus/ModuleHost/ModuleHost.ts
571
- var AsyncQueryBusModuleHost = class extends AbstractModuleHost {
572
- static {
573
- __name(this, "AsyncQueryBusModuleHost");
574
- }
575
- _busHost;
576
- constructor(params) {
577
- super(params);
578
- }
579
- async start() {
580
- const listeningModules = this.params.config.listeningModules ?? (await this.params.module.resolve("*", {
581
- direction: "down"
582
- })).map((m) => m.address);
583
- this._busHost = new AsyncQueryBusHost({
584
- config: {
585
- ...this.params.config,
586
- listeningModules
587
- },
588
- logger: this.params.logger,
589
- rootModule: this.params.module
590
- });
591
- this._busHost?.start();
592
- }
593
- stop() {
594
- this._busHost?.stop();
595
- }
596
- };
597
-
598
- // src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts
599
- import { assertEx as assertEx4 } from "@xylabs/assert";
600
- import { exists } from "@xylabs/exists";
601
- import { forget as forget2 } from "@xylabs/forget";
602
- import { isAddress } from "@xylabs/hex";
603
- import { AbstractModuleProxy } from "@xyo-network/bridge-abstract";
604
- import { ResolveHelper as ResolveHelper3 } from "@xyo-network/module-model";
605
- var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractModuleProxy {
606
- static {
607
- __name(this, "AsyncQueryBusModuleProxy");
608
- }
609
- static createCount = 0;
610
- constructor(params) {
611
- _AsyncQueryBusModuleProxy.createCount = _AsyncQueryBusModuleProxy.createCount + 1;
612
- if (Math.floor(_AsyncQueryBusModuleProxy.createCount / 10) === _AsyncQueryBusModuleProxy.createCount / 10) {
613
- console.log(`AsyncQueryBusModuleProxy.createCount: ${_AsyncQueryBusModuleProxy.createCount}`);
614
- }
615
- super(params);
616
- }
617
- get id() {
618
- return this.address;
619
- }
620
- get modName() {
621
- return void 0;
622
- }
623
- async proxyQueryHandler(query, payloads) {
624
- if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
625
- forget2(this.storeToArchivists([
626
- query,
627
- ...payloads ?? []
628
- ]));
629
- }
630
- const result = await this.params.busClient.send(this.address, query, payloads);
631
- if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
632
- forget2(this.storeToArchivists(result.flat()));
633
- }
634
- return result;
635
- }
636
- async publicChildren() {
637
- return (await Promise.all(Object.values(await this.childAddressMap()).filter(exists).map((address) => this.resolve(address)))).filter(exists);
638
- }
639
- async resolve(idOrFilter = "*", options = {}) {
640
- const config = {
641
- address: this.address,
642
- dead: this.dead,
643
- downResolver: this.downResolver,
644
- logger: this.logger,
645
- module: this,
646
- transformers: this.moduleIdentifierTransformers,
647
- upResolver: this.upResolver
648
- };
649
- if (idOrFilter === "*") {
650
- return await this.publicChildren();
651
- }
652
- switch (typeof idOrFilter) {
653
- case "string": {
654
- const parts = idOrFilter.split(":");
655
- const first = assertEx4(parts.shift(), () => "Missing first");
656
- const remainingPath = parts.join(":");
657
- const address = isAddress(first) ? first : this.childAddressByName(first);
658
- if (!address) return void 0;
659
- const firstInstance = await this.params.host.resolve(address);
660
- return remainingPath ? await firstInstance?.resolve(remainingPath) : firstInstance;
661
- }
662
- case "object": {
663
- return (await ResolveHelper3.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
664
- }
665
- default: {
666
- return (await ResolveHelper3.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
667
- }
668
- }
669
- }
670
- async startHandler() {
671
- return await super.startHandler();
672
- }
673
- };
674
-
675
- // src/Schema.ts
676
- var PubSubBridgeSchema = "network.xyo.bridge.pubsub";
677
-
678
- // src/Config.ts
679
- var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
680
-
681
- // src/PubSubBridge.ts
682
- import { assertEx as assertEx6 } from "@xylabs/assert";
683
- import { exists as exists2 } from "@xylabs/exists";
684
- import { forget as forget3 } from "@xylabs/forget";
685
- import { isAddress as isAddress3 } from "@xylabs/hex";
686
- import { toJsonString } from "@xylabs/object";
687
- import { AbstractBridge } from "@xyo-network/bridge-abstract";
688
- import { AddressSchema, creatableModule, isAddressModuleFilter, resolveAddressToInstance as resolveAddressToInstance2, resolveAddressToInstanceUp, ResolveHelper as ResolveHelper5 } from "@xyo-network/module-model";
689
- import { asNodeInstance } from "@xyo-network/node-model";
690
- import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
691
- import { Mutex as Mutex3 } from "async-mutex";
692
-
693
- // src/PubSubBridgeModuleResolver.ts
694
- import { assertEx as assertEx5 } from "@xylabs/assert";
695
- import { isAddress as isAddress2 } from "@xylabs/hex";
696
- import { Account } from "@xyo-network/account";
697
- import { AbstractBridgeModuleResolver, wrapModuleWithType } from "@xyo-network/bridge-abstract";
698
- import { ConfigSchema } from "@xyo-network/config-payload-plugin";
699
- import { asModuleInstance as asModuleInstance2, ModuleConfigSchema as ModuleConfigSchema2, ResolveHelper as ResolveHelper4 } from "@xyo-network/module-model";
700
- import { Mutex as Mutex2 } from "async-mutex";
701
- import { LRUCache as LRUCache3 } from "lru-cache";
702
- var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
703
- static {
704
- __name(this, "PubSubBridgeModuleResolver");
705
- }
706
- _resolvedCache = new LRUCache3({
707
- max: 1e3
708
- });
709
- _resolvedCacheMutex = new Mutex2();
710
- async resolveHandler(id, options) {
711
- const parentResult = await super.resolveHandler(id, options);
712
- if (parentResult.length > 0) {
713
- return parentResult;
714
- }
715
- const idParts = id.split(":");
716
- const untransformedFirstPart = assertEx5(idParts.shift(), () => "Missing module identifier");
717
- const firstPart = await ResolveHelper4.transformModuleIdentifier(untransformedFirstPart);
718
- assertEx5(isAddress2(firstPart), () => `Invalid module address: ${firstPart}`);
719
- const remainderParts = idParts.join(":");
720
- const instance = await this._resolvedCacheMutex.runExclusive(async () => {
721
- const cachedMod = this._resolvedCache.get(firstPart);
722
- if (cachedMod) {
723
- const result2 = idParts.length <= 0 ? cachedMod : cachedMod.resolve(remainderParts, {
724
- ...options,
725
- maxDepth: (options?.maxDepth ?? 5) - 1
726
- });
727
- return result2;
728
- }
729
- const account = Account.randomSync();
730
- const finalParams = {
731
- account,
732
- archiving: this.params.archiving,
733
- busClient: this.params.busClient,
734
- config: {
735
- schema: ModuleConfigSchema2
736
- },
737
- host: this,
738
- moduleAddress: firstPart,
739
- onQuerySendFinished: this.params.onQuerySendFinished,
740
- onQuerySendStarted: this.params.onQuerySendStarted
741
- };
742
- const proxy = new AsyncQueryBusModuleProxy(finalParams);
743
- const state = await proxy.state();
744
- if (state) {
745
- const configSchema = state.find((payload) => payload.schema === ConfigSchema)?.config;
746
- const config = assertEx5(state.find((payload) => payload.schema === configSchema), () => "Unable to locate config");
747
- proxy.setConfig(config);
748
- }
749
- await proxy.start?.();
750
- const wrapped = wrapModuleWithType(proxy, account);
751
- assertEx5(asModuleInstance2(wrapped, {}), () => `Failed to asModuleInstance [${id}]`);
752
- this._resolvedCache.set(wrapped.address, wrapped);
753
- return wrapped;
754
- });
755
- const result = remainderParts.length > 0 ? await instance.resolve(remainderParts, options) : instance;
756
- return result ? [
757
- result
758
- ] : [];
759
- }
760
- };
761
-
762
- // src/PubSubBridge.ts
763
- function _ts_decorate(decorators, target, key, desc) {
764
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
765
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
766
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
767
- return c > 3 && r && Object.defineProperty(target, key, r), r;
768
- }
769
- __name(_ts_decorate, "_ts_decorate");
770
- var moduleName = "PubSubBridge";
771
- var PubSubBridge = class extends AbstractBridge {
772
- static {
773
- __name(this, "PubSubBridge");
774
- }
775
- static configSchemas = [
776
- ...super.configSchemas,
777
- PubSubBridgeConfigSchema
778
- ];
779
- static defaultConfigSchema = PubSubBridgeConfigSchema;
780
- _configRootAddress = "";
781
- _configStateStoreArchivist = "";
782
- _configStateStoreBoundWitnessDiviner = "";
783
- _exposedAddresses = [];
784
- _lastState;
785
- _busClient;
786
- _busHost;
787
- _discoverRootsMutex = new Mutex3();
788
- _resolver;
789
- get resolver() {
790
- this._resolver = this._resolver ?? new PubSubBridgeModuleResolver({
791
- additionalSigners: this.additionalSigners,
792
- archiving: {
793
- ...this.archiving,
794
- resolveArchivists: this.resolveArchivingArchivists.bind(this)
795
- },
796
- bridge: this,
797
- busClient: assertEx6(this.busClient(), () => "busClient not configured"),
798
- onQuerySendFinished: /* @__PURE__ */ __name((args) => {
799
- forget3(this.emit("querySendFinished", {
800
- module: this,
801
- ...args
802
- }));
803
- }, "onQuerySendFinished"),
804
- onQuerySendStarted: /* @__PURE__ */ __name((args) => {
805
- forget3(this.emit("querySendStarted", {
806
- module: this,
807
- ...args
808
- }));
809
- }, "onQuerySendStarted"),
810
- root: this,
811
- wrapperAccount: this.account
812
- });
813
- return this._resolver;
814
- }
815
- get moduleName() {
816
- return this.modName ?? moduleName;
817
- }
818
- async connect(id, maxDepth = 5) {
819
- const transformedId = assertEx6(await ResolveHelper5.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
820
- const existingInstance = await this.resolve(transformedId);
821
- if (existingInstance) {
822
- return existingInstance.address;
823
- }
824
- const [instance] = await this.resolver.resolveHandler(id);
825
- return await this.connectInstance(instance, maxDepth);
826
- }
827
- async disconnect(id) {
828
- const transformedId = assertEx6(await ResolveHelper5.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
829
- const instance = await this.resolve(transformedId);
830
- if (instance) {
831
- this.downResolver.remove(instance.address);
832
- return instance.address;
833
- }
834
- }
835
- async exposeChild(mod, options) {
836
- const { maxDepth = 5 } = options ?? {};
837
- console.log(`exposeChild: ${mod.address} ${mod?.id} ${maxDepth}`);
838
- const host = assertEx6(this.busHost(), () => "Not configured as a host");
839
- host.expose(mod);
840
- const children = maxDepth > 0 ? await mod.publicChildren?.() ?? [] : [];
841
- this.logger.log(`childrenToExpose [${mod.id}][${mod.address}]: ${toJsonString(children.map((child) => child.id))}`);
842
- const exposedChildren = (await Promise.all(children.map((child) => this.exposeChild(child, {
843
- maxDepth: maxDepth - 1,
844
- required: false
845
- })))).flat().filter(exists2);
846
- const allExposed = [
847
- mod,
848
- ...exposedChildren
849
- ];
850
- for (const exposedMod of allExposed) this.logger?.log(`exposed: ${exposedMod.address} [${mod.id}]`);
851
- return allExposed;
852
- }
853
- async exposeHandler(address, options) {
854
- const { required = true } = options ?? {};
855
- const mod = await resolveAddressToInstanceUp(this, address);
856
- console.log(`exposeHandler: ${address} ${mod?.id}`);
857
- if (required && !mod) {
858
- throw new Error(`Unable to find required module: ${address}`);
859
- }
860
- if (mod) {
861
- return this.exposeChild(mod, options);
862
- }
863
- return [];
864
- }
865
- exposedHandler() {
866
- const exposedSet = this.busHost()?.exposedAddresses;
867
- return exposedSet ? [
868
- ...exposedSet
869
- ] : [];
870
- }
871
- async getRoots(force) {
872
- return await this._discoverRootsMutex.runExclusive(async () => {
873
- if (this._roots === void 0 || force) {
874
- const rootAddresses = (await Promise.all((this.config.roots ?? []).map((id) => {
875
- try {
876
- return ResolveHelper5.transformModuleIdentifier(id);
877
- } catch (ex) {
878
- this.logger?.warn("Unable to transform module identifier:", id, ex);
879
- return;
880
- }
881
- }))).filter(exists2);
882
- const rootInstances = (await Promise.all(rootAddresses.map(async (root) => {
883
- try {
884
- return await this.resolver.resolveHandler(root);
885
- } catch (ex) {
886
- this.logger?.warn("Unable to resolve root:", root, ex);
887
- return;
888
- }
889
- }))).flat().filter(exists2);
890
- for (const instance of rootInstances) {
891
- this.downResolver.add(instance);
892
- }
893
- this._roots = rootInstances;
894
- }
895
- return this._roots;
896
- });
897
- }
898
- // eslint-disable-next-line complexity
899
- async resolve(idOrFilter = "*", options = {}) {
900
- const roots = this._roots ?? [];
901
- const workingSet = options.direction === "up" ? [
902
- this
903
- ] : [
904
- ...roots,
905
- this
906
- ];
907
- if (idOrFilter === "*") {
908
- const remainingDepth = (options.maxDepth ?? 1) - 1;
909
- return remainingDepth <= 0 ? workingSet : [
910
- ...workingSet,
911
- ...(await Promise.all(roots.map((mod) => mod.resolve("*", {
912
- ...options,
913
- maxDepth: remainingDepth
914
- })))).flat()
915
- ];
916
- }
917
- switch (typeof idOrFilter) {
918
- case "string": {
919
- const parts = idOrFilter.split(":");
920
- const first = assertEx6(parts.shift(), () => "Missing first part");
921
- const firstInstance = isAddress3(first) ? await resolveAddressToInstance2(this, first, void 0, [], options.direction) : this._roots?.find((mod) => mod.id === first);
922
- return parts.length === 0 ? firstInstance : firstInstance?.resolve(parts.join(":"), options);
923
- }
924
- case "object": {
925
- const results = [];
926
- if (isAddressModuleFilter(idOrFilter)) {
927
- for (const mod of workingSet) {
928
- if (mod.modName && idOrFilter.address.includes(mod.address)) results.push(mod);
929
- }
930
- }
931
- return results;
932
- }
933
- default: {
934
- return;
935
- }
936
- }
937
- }
938
- async startHandler() {
939
- this.busHost()?.start();
940
- return await super.startHandler();
941
- }
942
- async unexposeHandler(id, options) {
943
- const { maxDepth = 2, required = true } = options ?? {};
944
- const host = assertEx6(this.busHost(), () => "Not configured as a host");
945
- const module = await host.unexpose(id, required);
946
- if (module) {
947
- const children = maxDepth > 0 ? await module.publicChildren?.() ?? [] : [];
948
- const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, {
949
- maxDepth: maxDepth - 1,
950
- required: false
951
- })))).flat().filter(exists2);
952
- return [
953
- module,
954
- ...exposedChildren
955
- ];
956
- }
957
- return [];
958
- }
959
- busClient() {
960
- if (!this._busClient && this.config.client) {
961
- this._busClient = new AsyncQueryBusClient({
962
- config: this.config.client,
963
- logger: this.logger,
964
- rootModule: this
965
- });
966
- }
967
- return this._busClient;
968
- }
969
- busHost() {
970
- if (!this._busHost && this.config.host) {
971
- this._busHost = new AsyncQueryBusHost({
972
- config: this.config.host,
973
- logger: this.logger,
974
- onQueryFulfillFinished: /* @__PURE__ */ __name((args) => {
975
- if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
976
- forget3(this.storeToArchivists(args.result?.flat() ?? []));
977
- }
978
- forget3(this.emit("queryFulfillFinished", {
979
- module: this,
980
- ...args
981
- }));
982
- }, "onQueryFulfillFinished"),
983
- onQueryFulfillStarted: /* @__PURE__ */ __name((args) => {
984
- if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
985
- forget3(this.storeToArchivists([
986
- args.query,
987
- ...args.payloads ?? []
988
- ]));
989
- }
990
- forget3(this.emit("queryFulfillStarted", {
991
- module: this,
992
- ...args
993
- }));
994
- }, "onQueryFulfillStarted"),
995
- rootModule: this
996
- });
997
- }
998
- return this._busHost;
999
- }
1000
- async connectInstance(instance, maxDepth = 5) {
1001
- if (instance) {
1002
- this.downResolver.add(instance);
1003
- if (maxDepth > 0) {
1004
- const node = asNodeInstance(instance);
1005
- if (node) {
1006
- const state = await node.state();
1007
- const children = (state?.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address) ?? []).filter((a) => a !== instance.address);
1008
- await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
1009
- }
1010
- }
1011
- this.logger?.log(`Connect: ${instance.id}`);
1012
- return instance.address;
1013
- }
1014
- }
1015
- stopHandler(_timeout) {
1016
- this.busHost()?.stop();
1017
- return true;
1018
- }
1019
- };
1020
- PubSubBridge = _ts_decorate([
1021
- creatableModule()
1022
- ], PubSubBridge);
1023
- export {
1024
- AbstractModuleHost,
1025
- AsyncQueryBusClient,
1026
- AsyncQueryBusHost,
1027
- AsyncQueryBusModuleHost,
1028
- AsyncQueryBusModuleProxy,
1029
- Pending,
1030
- PubSubBridge,
1031
- PubSubBridgeConfigSchema,
1032
- PubSubBridgeModuleResolver,
1033
- PubSubBridgeSchema
1034
- };
1
+ var V=Object.defineProperty;var l=(d,e)=>V(d,"name",{value:e,configurable:!0});import{Base as Z}from"@xylabs/object";var b=class extends Z{static{l(this,"AbstractModuleHost")}};import{assertEx as oe}from"@xylabs/assert";import{delay as ne}from"@xylabs/delay";import{forget as ae}from"@xylabs/forget";import{clearTimeoutEx as O,setTimeoutEx as le}from"@xylabs/timer";import{isBoundWitnessWithMeta as de}from"@xyo-network/boundwitness-model";import{BoundWitnessDivinerQuerySchema as ce}from"@xyo-network/diviner-boundwitness-model";import{PayloadBuilder as W}from"@xyo-network/payload-builder";import{LRUCache as he}from"lru-cache";import{assertEx as C}from"@xylabs/assert";import{Base as ee}from"@xylabs/object";import{isArchivistInstance as L}from"@xyo-network/archivist-model";import{isDivinerInstance as N}from"@xyo-network/diviner-model";import{ResolveHelper as B}from"@xyo-network/module-model";import{Mutex as se}from"async-mutex";import{LRUCache as te}from"lru-cache";var re=100,ie=6e4,U=1e3,y=class extends ee{static{l(this,"AsyncQueryBusBase")}_lastState;_targetConfigs={};_targetQueries={};_lastResolveFailure={};_queriesArchivist;_queriesDiviner;_reResolveDelay=1e3*5;_resolveMutex=new se;_responsesArchivist;_responsesDiviner;constructor(e){super(e)}get config(){return this.params.config}get pollFrequency(){let e=this.config?.pollFrequency??U;return e<re||e>ie?U:e}get rootModule(){return this.params.rootModule}get lastState(){let e={max:1e3,ttl:0};return this._lastState=this._lastState??new te(e),this._lastState}async queriesArchivist(){return await this._resolveMutex.runExclusive(async()=>(this._queriesArchivist=this._queriesArchivist??await this.resolve(C(this.config?.intersect?.queries?.archivist,()=>"No queries Archivist defined"),L),this._queriesArchivist))}async queriesDiviner(){return await this._resolveMutex.runExclusive(async()=>(this._queriesDiviner=this._queriesDiviner??await this.resolve(C(this.config?.intersect?.queries?.boundWitnessDiviner,()=>"No queries Diviner defined"),N),this._queriesDiviner))}async responsesArchivist(){return await this._resolveMutex.runExclusive(async()=>(this._responsesArchivist=this._responsesArchivist??await this.resolve(C(this.config?.intersect?.responses?.archivist,()=>"No responses Archivist defined"),L),this._responsesArchivist))}async responsesDiviner(){return await this._resolveMutex.runExclusive(async()=>(this._responsesDiviner=this._responsesDiviner??await this.resolve(C(this.config?.intersect?.responses?.boundWitnessDiviner,()=>"No responses Diviner defined"),N),this._responsesDiviner))}async commitState(e,s){await Promise.resolve();let t=this.lastState.get(e);t&&t>=s||this.lastState.set(e,s)}async retrieveState(e){await Promise.resolve();let s=this.lastState.get(e);if(s===void 0){let t=Date.now()-1e3;return this.lastState.set(e,t),t}else return s}async resolve(e,s){if(Date.now()-(this._lastResolveFailure[e]??0)<this._reResolveDelay)return;this._lastResolveFailure[e]=Date.now();let t=await B.resolveModuleIdentifier(this.rootModule,e);if(t){if(s(t))return delete this._lastResolveFailure[e],t;this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${e}][${t?.constructor?.name}]: ${t.id}`)}else this.logger?.debug(`Unable to resolve queriesArchivist [${e}] [${await B.traceModuleIdentifier(this.rootModule,e)}]`)}};var q="pending";var I=class extends y{static{l(this,"AsyncQueryBusClient")}_queryCache;_pollCount=0;_pollId;constructor(e){super(e)}get queryCacheConfig(){let e=this.config?.queryCache===!0?{}:this.config?.queryCache;return{max:100,ttl:1e3*60,...e}}get started(){return!!this._pollId}get queryCache(){let e=this.queryCacheConfig,s={noUpdateTTL:!1,ttlAutopurge:!0};return this._queryCache=this._queryCache??new he({...e,...s}),this._queryCache}listeningAddresses(){return this._queryCache?.keys()}async send(e,s,t){this.logger?.debug(`Begin issuing query to: ${e}`);let r={...s?.$meta,destination:[e]},i=await W.build({...s,$meta:r}),o=oe(await this.queriesArchivist(),()=>`Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`),n=i?.$hash??Object.keys(await W.toDataHashMap([i]))[0];this.logger?.debug(`Issuing query: ${n} to: ${e}`);let a=t?[i,...t]:[i],c=await o.insert?.(a);if(this.logger?.debug(`Issued query: ${n} to: ${e}`),this.queryCache.set(n,q),!c)throw new Error("Unable to issue query to queryArchivist");return new Promise((u,m)=>{this.logger?.debug(`Polling for response to query: ${n}`);let h=100;ae(l(async()=>{try{this.start();let p=this.queryCache.get(n);for(;p!==void 0;){if(await ne(h),p=this.queryCache.get(n),p&&p!==q){this.logger?.log(`Returning response to query: ${n}`),u(p);return}h=Math.floor(h*1.2),h>1e3&&(h=1e3)}this.logger?.error("Timeout waiting for query response"),m({message:"Timeout waiting for query response",query:"network.xyo.boundwitness",schema:"network.xyo.error.module",sources:[n]});return}finally{this.stop()}},"pollForResponse")())})}poll(){this._pollId=le(async()=>{try{await this.processIncomingResponses()}catch(e){this.logger?.error?.(`Error in main loop: ${e}`)}finally{this._pollId&&O(this._pollId),this._pollId=void 0,this.poll()}},this.pollFrequency)}processIncomingResponses=l(async()=>{let e=await this.responsesArchivist();if(e){let s=await this.responsesDiviner();if(s){let t=[...this.queryCache.entries()].filter(([r,i])=>i===q);await Promise.allSettled(t.map(async([r,i])=>{if(i===q){let o={limit:1,order:"desc",schema:ce,sourceQuery:r},n=await s.divine([o]);if(n&&n.length>0){let a=n.find(de);if(a&&a?.$meta?.sourceQuery===r){this.logger?.debug(`Found response to query: ${r}`);let c=a.payload_hashes?.length>0?await e.get(a.payload_hashes):[];this.queryCache.set(r,[a,c,[]])}}}}))}}},"processIncomingResponses");start(){this._pollCount===0&&this.poll(),this._pollCount++}stop(){this._pollCount--,this._pollCount<=0&&(this._pollId&&O(this._pollId),this._pollId=void 0,this._pollCount=0)}};import{containsAll as ue}from"@xylabs/array";import{assertEx as v}from"@xylabs/assert";import{clearTimeoutEx as j,setTimeoutEx as pe}from"@xylabs/timer";import{isQueryBoundWitnessWithMeta as fe}from"@xyo-network/boundwitness-model";import{isBridgeInstance as me}from"@xyo-network/bridge-model";import{BoundWitnessDivinerQuerySchema as ge}from"@xyo-network/diviner-boundwitness-model";import{asModuleInstance as G,ModuleConfigSchema as ye,resolveAddressToInstance as ve,ResolveHelper as _e}from"@xyo-network/module-model";import{PayloadBuilder as Y}from"@xyo-network/payload-builder";var P=4,Q=64,we=16,xe=4,Ae=64,qe=16,_=class extends y{static{l(this,"AsyncQueryBusHost")}_exposedAddresses=new Set;_exposeOptions={};_idle=!1;_lastQueryTime;_pollId;constructor(e){super(e)}get exposedAddresses(){return this._exposedAddresses}get idlePollFrequency(){let e=this.config?.idlePollFrequency??we*this.pollFrequency;return e<this.pollFrequency*P?P*this.pollFrequency:e>this.pollFrequency*Q?Q*this.pollFrequency:e}get idleThreshold(){let e=this.config?.idleThreshold??qe*this.idlePollFrequency;return e<this.idlePollFrequency*xe?P*this.pollFrequency:e>this.idlePollFrequency*Ae?Q*this.pollFrequency:e}get perAddressBatchQueryLimit(){return this.config?.perAddressBatchQueryLimit??10}get started(){return!!this._pollId}expose(e,s){let{failOnAlreadyExposed:t}=s??{};if(me(e))this.logger?.warn(`Attempted to expose a BridgeModule [${e.id}] - Not exposing`);else return v(!t||!this._exposedAddresses.has(e.address),()=>`Address already exposed: ${e.id} [${e.address}]`),this._exposedAddresses.add(e.address),this._exposeOptions[e.address]={...s},this.logger?.debug(`${e.id} exposed [${e.address}]`),e}async listeningModules(){let e=[...this.config?.listeningModules??[],...this.exposedAddresses.values()];return await Promise.all(e.map(async t=>v(G(await ve(this.rootModule,t)),()=>`Unable to resolve listeningModule [${t}]`)))}start(){this.started&&console.warn("AsyncQueryBus starting when already started"),this.poll()}stop(){this.started||console.warn("AsyncQueryBus stopping when already stopped"),this._pollId&&j(this._pollId),this._pollId=void 0}async unexpose(e,s=!0){let t=G(await this.rootModule.resolve(e,{maxDepth:10}));return t&&(v(!s||this._exposedAddresses.has(t.address),()=>`Address not exposed [${t.address}][${t.id}]`),this._exposedAddresses.delete(t.address),delete this._exposeOptions[t.address],this.logger?.debug(`${t.address} [${t.id}] unexposed`)),t}callLocalModule=l(async(e,s)=>{this._idle=!1,this._lastQueryTime=Date.now();let t=e.id,r=v(await this.queriesArchivist(),()=>`Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`),i=v(await this.responsesArchivist(),()=>`Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`),o=s.$meta?.destination;if(o&&o?.includes(e.address)){let n=s.payload_hashes.indexOf(s.query);if(n!==-1){let a=s.payload_schemas[n];if(e.queries.includes(a)){let c=await r.get(s.payload_hashes);this.params.onQueryFulfillStarted?.({payloads:c,query:s});let f=await Y.toAllHashMap(c),u=(await Y.build(s)).$hash;if(!ue(Object.keys(f),s.payload_hashes)){this.logger?.error(`Error processing command ${u} for module ${t}, missing payloads`);return}try{let m=f[s.query].schema;this.logger?.debug(`Issuing query ${m} (${u}) addressed to module: ${t}`);let h=await e.query(s,c,{allowedQueries:this._exposeOptions[e.address]?.allowedQueries,schema:ye}),[g,p,A]=h;this.logger?.debug(`Replying to query ${u} addressed to module: ${t}`),(await i.insert([g,...p,...A])).length===0&&this.logger?.error(`Error replying to query ${u} addressed to module: ${t}`),s?.timestamp&&await this.commitState(e.address,s.timestamp),this.params.onQueryFulfillFinished?.({payloads:c,query:s,result:h,status:"success"})}catch(m){this.params.onQueryFulfillFinished?.({payloads:c,query:s,status:"failure"}),this.logger?.error(`Error processing query ${u} for module ${t}: ${m}`)}}}}},"callLocalModule");findQueriesToAddress=l(async e=>{let s=v(this.config?.intersect?.queries?.boundWitnessDiviner,()=>"No queries Diviner defined"),t=await this.queriesDiviner();if(t){let r=await this.retrieveState(e),i=[e],o=this.perAddressBatchQueryLimit,n={destination:i,limit:o,order:"asc",schema:ge,timestamp:r+1},c=(await t.divine([n])).filter(fe),f=c.length>0?Math.max(...c.map(u=>u.timestamp??r))+1:Date.now();return await this.commitState(e,f),this.logger?.debug("findQueriesToAddress",e,r,f),c}else this.logger?.warn(`Unable to resolve queriesBoundWitnessDiviner [${s}] [${await _e.traceModuleIdentifier(this.rootModule,s)}]`)},"findQueriesToAddress");poll(){this._pollId=pe(async()=>{try{await this.processIncomingQueries()}catch(s){this.logger?.error?.(`Error in main loop: ${s}`)}finally{this._pollId&&j(this._pollId),this._pollId=void 0,this.poll()}let e=Date.now();this.idleThreshold<e-(this._lastQueryTime??e)&&(this._idle=!0)},this._idle?this.idlePollFrequency:this.pollFrequency)}processIncomingQueries=l(async()=>{this.logger?.debug("Checking for inbound queries");let e=await this.listeningModules();await Promise.allSettled(e.map(async s=>{try{let t=s.id;this.logger?.debug(`Checking for inbound queries to ${t} [${s.address}]`);let r=await this.findQueriesToAddress(s.address)??[];if(r.length===0)return;this.logger?.debug(`Found queries addressed to local module: ${t}`);for(let i of r)await this.callLocalModule(s,i)}catch(t){this.logger?.error(`Error processing queries for address ${s.address}: ${t}`)}}))},"processIncomingQueries")};var k=class extends b{static{l(this,"AsyncQueryBusModuleHost")}_busHost;constructor(e){super(e)}async start(){let e=this.params.config.listeningModules??(await this.params.module.resolve("*",{direction:"down"})).map(s=>s.address);this._busHost=new _({config:{...this.params.config,listeningModules:e},logger:this.params.logger,rootModule:this.params.module}),this._busHost?.start()}stop(){this._busHost?.stop()}};import{assertEx as be}from"@xylabs/assert";import{exists as X}from"@xylabs/exists";import{forget as J}from"@xylabs/forget";import{isAddress as Ce}from"@xylabs/hex";import{AbstractModuleProxy as Ie}from"@xyo-network/bridge-abstract";import{ResolveHelper as z}from"@xyo-network/module-model";var $=class d extends Ie{static{l(this,"AsyncQueryBusModuleProxy")}static createCount=0;constructor(e){d.createCount=d.createCount+1,Math.floor(d.createCount/10)===d.createCount/10&&console.log(`AsyncQueryBusModuleProxy.createCount: ${d.createCount}`),super(e)}get id(){return this.address}get modName(){}async proxyQueryHandler(e,s){this.archiving&&this.isAllowedArchivingQuery(e.schema)&&J(this.storeToArchivists([e,...s??[]]));let t=await this.params.busClient.send(this.address,e,s);return this.archiving&&this.isAllowedArchivingQuery(e.schema)&&J(this.storeToArchivists(t.flat())),t}async publicChildren(){return(await Promise.all(Object.values(await this.childAddressMap()).filter(X).map(e=>this.resolve(e)))).filter(X)}async resolve(e="*",s={}){let t={address:this.address,dead:this.dead,downResolver:this.downResolver,logger:this.logger,module:this,transformers:this.moduleIdentifierTransformers,upResolver:this.upResolver};if(e==="*")return await this.publicChildren();switch(typeof e){case"string":{let r=e.split(":"),i=be(r.shift(),()=>"Missing first"),o=r.join(":"),n=Ce(i)?i:this.childAddressByName(i);if(!n)return;let a=await this.params.host.resolve(n);return o?await a?.resolve(o):a}case"object":return(await z.resolve(t,e,s)).filter(r=>r.address!==this.address);default:return(await z.resolve(t,e,s)).filter(r=>r.address!==this.address)}}async startHandler(){return await super.startHandler()}};var K="network.xyo.bridge.pubsub";var F=`${K}.config`;import{assertEx as w}from"@xylabs/assert";import{exists as M}from"@xylabs/exists";import{forget as x}from"@xylabs/forget";import{isAddress as Le}from"@xylabs/hex";import{toJsonString as Ne}from"@xylabs/object";import{AbstractBridge as Be}from"@xyo-network/bridge-abstract";import{AddressSchema as Ue,creatableModule as Oe,isAddressModuleFilter as We,resolveAddressToInstance as je,resolveAddressToInstanceUp as Ge,ResolveHelper as H}from"@xyo-network/module-model";import{asNodeInstance as Ye}from"@xyo-network/node-model";import{isPayloadOfSchemaType as ke}from"@xyo-network/payload-model";import{Mutex as Xe}from"async-mutex";import{assertEx as S}from"@xylabs/assert";import{isAddress as $e}from"@xylabs/hex";import{Account as Se}from"@xyo-network/account";import{AbstractBridgeModuleResolver as De,wrapModuleWithType as Me}from"@xyo-network/bridge-abstract";import{ConfigSchema as Re}from"@xyo-network/config-payload-plugin";import{asModuleInstance as Ee,ModuleConfigSchema as Pe,ResolveHelper as Qe}from"@xyo-network/module-model";import{Mutex as Fe}from"async-mutex";import{LRUCache as He}from"lru-cache";var D=class extends De{static{l(this,"PubSubBridgeModuleResolver")}_resolvedCache=new He({max:1e3});_resolvedCacheMutex=new Fe;async resolveHandler(e,s){let t=await super.resolveHandler(e,s);if(t.length>0)return t;let r=e.split(":"),i=S(r.shift(),()=>"Missing module identifier"),o=await Qe.transformModuleIdentifier(i);S($e(o),()=>`Invalid module address: ${o}`);let n=r.join(":"),a=await this._resolvedCacheMutex.runExclusive(async()=>{let f=this._resolvedCache.get(o);if(f)return r.length<=0?f:f.resolve(n,{...s,maxDepth:(s?.maxDepth??5)-1});let u=Se.randomSync(),m={account:u,archiving:this.params.archiving,busClient:this.params.busClient,config:{schema:Pe},host:this,moduleAddress:o,onQuerySendFinished:this.params.onQuerySendFinished,onQuerySendStarted:this.params.onQuerySendStarted},h=new $(m),g=await h.state();if(g){let A=g.find(E=>E.schema===Re)?.config,T=S(g.find(E=>E.schema===A),()=>"Unable to locate config");h.setConfig(T)}await h.start?.();let p=Me(h,u);return S(Ee(p,{}),()=>`Failed to asModuleInstance [${e}]`),this._resolvedCache.set(p.address,p),p}),c=n.length>0?await a.resolve(n,s):a;return c?[c]:[]}};function Te(d,e,s,t){var r=arguments.length,i=r<3?e:t===null?t=Object.getOwnPropertyDescriptor(e,s):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(d,e,s,t);else for(var n=d.length-1;n>=0;n--)(o=d[n])&&(i=(r<3?o(i):r>3?o(e,s,i):o(e,s))||i);return r>3&&i&&Object.defineProperty(e,s,i),i}l(Te,"_ts_decorate");var Je="PubSubBridge",R=class extends Be{static{l(this,"PubSubBridge")}static configSchemas=[...super.configSchemas,F];static defaultConfigSchema=F;_configRootAddress="";_configStateStoreArchivist="";_configStateStoreBoundWitnessDiviner="";_exposedAddresses=[];_lastState;_busClient;_busHost;_discoverRootsMutex=new Xe;_resolver;get resolver(){return this._resolver=this._resolver??new D({additionalSigners:this.additionalSigners,archiving:{...this.archiving,resolveArchivists:this.resolveArchivingArchivists.bind(this)},bridge:this,busClient:w(this.busClient(),()=>"busClient not configured"),onQuerySendFinished:l(e=>{x(this.emit("querySendFinished",{module:this,...e}))},"onQuerySendFinished"),onQuerySendStarted:l(e=>{x(this.emit("querySendStarted",{module:this,...e}))},"onQuerySendStarted"),root:this,wrapperAccount:this.account}),this._resolver}get moduleName(){return this.modName??Je}async connect(e,s=5){let t=w(await H.transformModuleIdentifier(e),()=>`Unable to transform module identifier: ${e}`),r=await this.resolve(t);if(r)return r.address;let[i]=await this.resolver.resolveHandler(e);return await this.connectInstance(i,s)}async disconnect(e){let s=w(await H.transformModuleIdentifier(e),()=>`Unable to transform module identifier: ${e}`),t=await this.resolve(s);if(t)return this.downResolver.remove(t.address),t.address}async exposeChild(e,s){let{maxDepth:t=5}=s??{};console.log(`exposeChild: ${e.address} ${e?.id} ${t}`),w(this.busHost(),()=>"Not configured as a host").expose(e);let i=t>0?await e.publicChildren?.()??[]:[];this.logger.log(`childrenToExpose [${e.id}][${e.address}]: ${Ne(i.map(a=>a.id))}`);let o=(await Promise.all(i.map(a=>this.exposeChild(a,{maxDepth:t-1,required:!1})))).flat().filter(M),n=[e,...o];for(let a of n)this.logger?.log(`exposed: ${a.address} [${e.id}]`);return n}async exposeHandler(e,s){let{required:t=!0}=s??{},r=await Ge(this,e);if(console.log(`exposeHandler: ${e} ${r?.id}`),t&&!r)throw new Error(`Unable to find required module: ${e}`);return r?this.exposeChild(r,s):[]}exposedHandler(){let e=this.busHost()?.exposedAddresses;return e?[...e]:[]}async getRoots(e){return await this._discoverRootsMutex.runExclusive(async()=>{if(this._roots===void 0||e){let s=(await Promise.all((this.config.roots??[]).map(r=>{try{return H.transformModuleIdentifier(r)}catch(i){this.logger?.warn("Unable to transform module identifier:",r,i);return}}))).filter(M),t=(await Promise.all(s.map(async r=>{try{return await this.resolver.resolveHandler(r)}catch(i){this.logger?.warn("Unable to resolve root:",r,i);return}}))).flat().filter(M);for(let r of t)this.downResolver.add(r);this._roots=t}return this._roots})}async resolve(e="*",s={}){let t=this._roots??[],r=s.direction==="up"?[this]:[...t,this];if(e==="*"){let i=(s.maxDepth??1)-1;return i<=0?r:[...r,...(await Promise.all(t.map(o=>o.resolve("*",{...s,maxDepth:i})))).flat()]}switch(typeof e){case"string":{let i=e.split(":"),o=w(i.shift(),()=>"Missing first part"),n=Le(o)?await je(this,o,void 0,[],s.direction):this._roots?.find(a=>a.id===o);return i.length===0?n:n?.resolve(i.join(":"),s)}case"object":{let i=[];if(We(e))for(let o of r)o.modName&&e.address.includes(o.address)&&i.push(o);return i}default:return}}async startHandler(){return this.busHost()?.start(),await super.startHandler()}async unexposeHandler(e,s){let{maxDepth:t=2,required:r=!0}=s??{},o=await w(this.busHost(),()=>"Not configured as a host").unexpose(e,r);if(o){let n=t>0?await o.publicChildren?.()??[]:[],a=(await Promise.all(n.map(c=>this.unexposeHandler(c.address,{maxDepth:t-1,required:!1})))).flat().filter(M);return[o,...a]}return[]}busClient(){return!this._busClient&&this.config.client&&(this._busClient=new I({config:this.config.client,logger:this.logger,rootModule:this})),this._busClient}busHost(){return!this._busHost&&this.config.host&&(this._busHost=new _({config:this.config.host,logger:this.logger,onQueryFulfillFinished:l(e=>{this.archiving&&this.isAllowedArchivingQuery(e.query.schema)&&x(this.storeToArchivists(e.result?.flat()??[])),x(this.emit("queryFulfillFinished",{module:this,...e}))},"onQueryFulfillFinished"),onQueryFulfillStarted:l(e=>{this.archiving&&this.isAllowedArchivingQuery(e.query.schema)&&x(this.storeToArchivists([e.query,...e.payloads??[]])),x(this.emit("queryFulfillStarted",{module:this,...e}))},"onQueryFulfillStarted"),rootModule:this})),this._busHost}async connectInstance(e,s=5){if(e){if(this.downResolver.add(e),s>0){let t=Ye(e);if(t){let i=((await t.state())?.filter(ke(Ue)).map(o=>o.address)??[]).filter(o=>o!==e.address);await Promise.all(i.map(o=>this.connect(o,s-1)))}}return this.logger?.log(`Connect: ${e.id}`),e.address}}stopHandler(e){return this.busHost()?.stop(),!0}};R=Te([Oe()],R);export{b as AbstractModuleHost,I as AsyncQueryBusClient,_ as AsyncQueryBusHost,k as AsyncQueryBusModuleHost,$ as AsyncQueryBusModuleProxy,q as Pending,R as PubSubBridge,F as PubSubBridgeConfigSchema,D as PubSubBridgeModuleResolver,K as PubSubBridgeSchema};
1035
2
  //# sourceMappingURL=index.js.map