@xyo-network/diviner-indexing 2.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +13 -0
  3. package/dist/browser/Config.d.cts +32 -0
  4. package/dist/browser/Config.d.cts.map +1 -0
  5. package/dist/browser/Config.d.mts +32 -0
  6. package/dist/browser/Config.d.mts.map +1 -0
  7. package/dist/browser/Config.d.ts +32 -0
  8. package/dist/browser/Config.d.ts.map +1 -0
  9. package/dist/browser/Diviner.d.cts +71 -0
  10. package/dist/browser/Diviner.d.cts.map +1 -0
  11. package/dist/browser/Diviner.d.mts +71 -0
  12. package/dist/browser/Diviner.d.mts.map +1 -0
  13. package/dist/browser/Diviner.d.ts +71 -0
  14. package/dist/browser/Diviner.d.ts.map +1 -0
  15. package/dist/browser/Labels.d.cts +9 -0
  16. package/dist/browser/Labels.d.cts.map +1 -0
  17. package/dist/browser/Labels.d.mts +9 -0
  18. package/dist/browser/Labels.d.mts.map +1 -0
  19. package/dist/browser/Labels.d.ts +9 -0
  20. package/dist/browser/Labels.d.ts.map +1 -0
  21. package/dist/browser/Params.d.cts +5 -0
  22. package/dist/browser/Params.d.cts.map +1 -0
  23. package/dist/browser/Params.d.mts +5 -0
  24. package/dist/browser/Params.d.mts.map +1 -0
  25. package/dist/browser/Params.d.ts +5 -0
  26. package/dist/browser/Params.d.ts.map +1 -0
  27. package/dist/browser/Schema.d.cts +3 -0
  28. package/dist/browser/Schema.d.cts.map +1 -0
  29. package/dist/browser/Schema.d.mts +3 -0
  30. package/dist/browser/Schema.d.mts.map +1 -0
  31. package/dist/browser/Schema.d.ts +3 -0
  32. package/dist/browser/Schema.d.ts.map +1 -0
  33. package/dist/browser/SearchableStorage.d.cts +10 -0
  34. package/dist/browser/SearchableStorage.d.cts.map +1 -0
  35. package/dist/browser/SearchableStorage.d.mts +10 -0
  36. package/dist/browser/SearchableStorage.d.mts.map +1 -0
  37. package/dist/browser/SearchableStorage.d.ts +10 -0
  38. package/dist/browser/SearchableStorage.d.ts.map +1 -0
  39. package/dist/browser/Stage.d.cts +29 -0
  40. package/dist/browser/Stage.d.cts.map +1 -0
  41. package/dist/browser/Stage.d.mts +29 -0
  42. package/dist/browser/Stage.d.mts.map +1 -0
  43. package/dist/browser/Stage.d.ts +29 -0
  44. package/dist/browser/Stage.d.ts.map +1 -0
  45. package/dist/browser/State.d.cts +5 -0
  46. package/dist/browser/State.d.cts.map +1 -0
  47. package/dist/browser/State.d.mts +5 -0
  48. package/dist/browser/State.d.mts.map +1 -0
  49. package/dist/browser/State.d.ts +5 -0
  50. package/dist/browser/State.d.ts.map +1 -0
  51. package/dist/browser/index.cjs +219 -0
  52. package/dist/browser/index.cjs.map +1 -0
  53. package/dist/browser/index.d.cts +8 -0
  54. package/dist/browser/index.d.cts.map +1 -0
  55. package/dist/browser/index.d.mts +8 -0
  56. package/dist/browser/index.d.mts.map +1 -0
  57. package/dist/browser/index.d.ts +8 -0
  58. package/dist/browser/index.d.ts.map +1 -0
  59. package/dist/browser/index.js +196 -0
  60. package/dist/browser/index.js.map +1 -0
  61. package/dist/node/Config.d.cts +32 -0
  62. package/dist/node/Config.d.cts.map +1 -0
  63. package/dist/node/Config.d.mts +32 -0
  64. package/dist/node/Config.d.mts.map +1 -0
  65. package/dist/node/Config.d.ts +32 -0
  66. package/dist/node/Config.d.ts.map +1 -0
  67. package/dist/node/Diviner.d.cts +71 -0
  68. package/dist/node/Diviner.d.cts.map +1 -0
  69. package/dist/node/Diviner.d.mts +71 -0
  70. package/dist/node/Diviner.d.mts.map +1 -0
  71. package/dist/node/Diviner.d.ts +71 -0
  72. package/dist/node/Diviner.d.ts.map +1 -0
  73. package/dist/node/Labels.d.cts +9 -0
  74. package/dist/node/Labels.d.cts.map +1 -0
  75. package/dist/node/Labels.d.mts +9 -0
  76. package/dist/node/Labels.d.mts.map +1 -0
  77. package/dist/node/Labels.d.ts +9 -0
  78. package/dist/node/Labels.d.ts.map +1 -0
  79. package/dist/node/Params.d.cts +5 -0
  80. package/dist/node/Params.d.cts.map +1 -0
  81. package/dist/node/Params.d.mts +5 -0
  82. package/dist/node/Params.d.mts.map +1 -0
  83. package/dist/node/Params.d.ts +5 -0
  84. package/dist/node/Params.d.ts.map +1 -0
  85. package/dist/node/Schema.d.cts +3 -0
  86. package/dist/node/Schema.d.cts.map +1 -0
  87. package/dist/node/Schema.d.mts +3 -0
  88. package/dist/node/Schema.d.mts.map +1 -0
  89. package/dist/node/Schema.d.ts +3 -0
  90. package/dist/node/Schema.d.ts.map +1 -0
  91. package/dist/node/SearchableStorage.d.cts +10 -0
  92. package/dist/node/SearchableStorage.d.cts.map +1 -0
  93. package/dist/node/SearchableStorage.d.mts +10 -0
  94. package/dist/node/SearchableStorage.d.mts.map +1 -0
  95. package/dist/node/SearchableStorage.d.ts +10 -0
  96. package/dist/node/SearchableStorage.d.ts.map +1 -0
  97. package/dist/node/Stage.d.cts +29 -0
  98. package/dist/node/Stage.d.cts.map +1 -0
  99. package/dist/node/Stage.d.mts +29 -0
  100. package/dist/node/Stage.d.mts.map +1 -0
  101. package/dist/node/Stage.d.ts +29 -0
  102. package/dist/node/Stage.d.ts.map +1 -0
  103. package/dist/node/State.d.cts +5 -0
  104. package/dist/node/State.d.cts.map +1 -0
  105. package/dist/node/State.d.mts +5 -0
  106. package/dist/node/State.d.mts.map +1 -0
  107. package/dist/node/State.d.ts +5 -0
  108. package/dist/node/State.d.ts.map +1 -0
  109. package/dist/node/index.d.cts +8 -0
  110. package/dist/node/index.d.cts.map +1 -0
  111. package/dist/node/index.d.mts +8 -0
  112. package/dist/node/index.d.mts.map +1 -0
  113. package/dist/node/index.d.ts +8 -0
  114. package/dist/node/index.d.ts.map +1 -0
  115. package/dist/node/index.js +234 -0
  116. package/dist/node/index.js.map +1 -0
  117. package/dist/node/index.mjs +204 -0
  118. package/dist/node/index.mjs.map +1 -0
  119. package/package.json +71 -0
  120. package/src/Config.ts +35 -0
  121. package/src/Diviner.ts +228 -0
  122. package/src/Labels.ts +13 -0
  123. package/src/Params.ts +6 -0
  124. package/src/Schema.ts +2 -0
  125. package/src/SearchableStorage.ts +9 -0
  126. package/src/Stage.ts +30 -0
  127. package/src/State.ts +5 -0
  128. package/src/index.ts +7 -0
  129. package/typedoc.json +5 -0
@@ -0,0 +1,204 @@
1
+ // src/Schema.ts
2
+ var IndexingDivinerSchema = "network.xyo.diviner.indexing";
3
+
4
+ // src/Config.ts
5
+ var IndexingDivinerConfigSchema = `${IndexingDivinerSchema}.config`;
6
+
7
+ // src/Diviner.ts
8
+ import { assertEx } from "@xylabs/assert";
9
+ import { AbstractDiviner } from "@xyo-network/abstract-diviner";
10
+ import { ArchivistWrapper } from "@xyo-network/archivist-wrapper";
11
+ import { BoundWitnessBuilder } from "@xyo-network/boundwitness-builder";
12
+ import { isBoundWitness } from "@xyo-network/boundwitness-model";
13
+ import { BoundWitnessDivinerQuerySchema } from "@xyo-network/diviner-boundwitness-model";
14
+ import { asDivinerInstance, DivinerConfigSchema } from "@xyo-network/diviner-model";
15
+ import { DivinerWrapper } from "@xyo-network/diviner-wrapper";
16
+ import { isModuleState, ModuleStateSchema } from "@xyo-network/module-model";
17
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
18
+ var moduleName = "IndexingDiviner";
19
+ var IndexingDiviner = class extends AbstractDiviner {
20
+ static configSchemas = [IndexingDivinerConfigSchema, DivinerConfigSchema];
21
+ _lastState;
22
+ _pollId;
23
+ get payloadDivinerLimit() {
24
+ return this.config.payloadDivinerLimit ?? 1e3;
25
+ }
26
+ get pollFrequency() {
27
+ return this.config.pollFrequency ?? 1e4;
28
+ }
29
+ /**
30
+ * Works via batched iteration of the source archivist to populate the index.
31
+ * @returns A promise that resolves when the background process is complete
32
+ */
33
+ backgroundDivine = async () => {
34
+ const lastState = await this.retrieveState();
35
+ const indexCandidateDiviner = await this.getIndexingDivinerStage("stateToIndexCandidateDiviner");
36
+ const results = lastState ? await indexCandidateDiviner.divine([lastState]) : await indexCandidateDiviner.divine();
37
+ const nextState = results.find(isModuleState);
38
+ const indexCandidates = results.filter((x) => !isModuleState(x));
39
+ const toIndexTransformDiviner = await this.getIndexingDivinerStage("indexCandidateToIndexDiviner");
40
+ const indexes = await toIndexTransformDiviner.divine(indexCandidates);
41
+ const indexArchivist = await this.getArchivistForStore("indexStore");
42
+ await indexArchivist.insert(indexes);
43
+ if (nextState) {
44
+ await this.commitState(nextState);
45
+ }
46
+ };
47
+ /**
48
+ * Commit the internal state of the Diviner process. This is similar
49
+ * to a transaction completion in a database and should only be called
50
+ * when results have been successfully persisted to the appropriate
51
+ * external stores.
52
+ * @param nextState The state to commit
53
+ */
54
+ async commitState(nextState) {
55
+ var _a;
56
+ if (nextState.state.offset === ((_a = this._lastState) == null ? void 0 : _a.state.offset))
57
+ return;
58
+ this._lastState = nextState;
59
+ const archivist = await this.getArchivistForStore("stateStore");
60
+ const [bw] = await new BoundWitnessBuilder().payload(nextState).witness(this.account).build();
61
+ await archivist.insert([bw, nextState]);
62
+ }
63
+ async divineHandler(payloads = []) {
64
+ const indexPayloadDiviner = await this.getPayloadDivinerForStore("indexStore");
65
+ const divinerQueryToIndexQueryDiviner = await this.getIndexingDivinerStage("divinerQueryToIndexQueryDiviner");
66
+ const indexQueryResponseToDivinerQueryResponseDiviner = await this.getIndexingDivinerStage("indexQueryResponseToDivinerQueryResponseDiviner");
67
+ const results = (await Promise.all(
68
+ payloads.map(async (payload) => {
69
+ const indexQuery = await divinerQueryToIndexQueryDiviner.divine([payload]);
70
+ const indexedResults = await indexPayloadDiviner.divine(indexQuery);
71
+ const response = await Promise.all(
72
+ indexedResults.flat().map((indexedResult) => indexQueryResponseToDivinerQueryResponseDiviner.divine([payload, indexedResult]))
73
+ );
74
+ return response.flat();
75
+ })
76
+ )).flat();
77
+ return results;
78
+ }
79
+ /**
80
+ * Retrieves the archivist for the specified store
81
+ * @param store The store to retrieve the archivist for
82
+ * @returns The archivist for the specified store
83
+ */
84
+ async getArchivistForStore(store) {
85
+ var _a, _b;
86
+ const name = assertEx((_b = (_a = this.config) == null ? void 0 : _a[store]) == null ? void 0 : _b.archivist, () => `${moduleName}: Config for ${store}.archivist not specified`);
87
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.archivist`);
88
+ return ArchivistWrapper.wrap(mod, this.account);
89
+ }
90
+ /**
91
+ * Retrieves the BoundWitness Diviner for the specified store
92
+ * @param store The store to retrieve the BoundWitness Diviner for
93
+ * @returns The BoundWitness Diviner for the specified store
94
+ */
95
+ async getBoundWitnessDivinerForStore(store) {
96
+ var _a, _b;
97
+ const name = assertEx((_b = (_a = this.config) == null ? void 0 : _a[store]) == null ? void 0 : _b.boundWitnessDiviner, () => `${moduleName}: Config for ${store}.boundWitnessDiviner not specified`);
98
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.boundWitnessDiviner`);
99
+ return DivinerWrapper.wrap(mod, this.account);
100
+ }
101
+ /**
102
+ * Gets the Diviner for the supplied Indexing Diviner stage
103
+ * @param transform The Indexing Diviner stage
104
+ * @returns The diviner corresponding to the Indexing Diviner stage
105
+ */
106
+ async getIndexingDivinerStage(transform) {
107
+ var _a, _b;
108
+ const nameOrAddress = assertEx(
109
+ (_b = (_a = this.config) == null ? void 0 : _a.indexingDivinerStages) == null ? void 0 : _b[transform],
110
+ () => `${moduleName}: Config for indexingDivinerStages.${transform} not specified`
111
+ );
112
+ const mod = await this.resolve(nameOrAddress);
113
+ return assertEx(asDivinerInstance(mod), () => `${moduleName}: Failed to resolve indexing diviner stage for ${transform}`);
114
+ }
115
+ /**
116
+ * Retrieves the Payload Diviner for the specified store
117
+ * @param store The store to retrieve the Payload Diviner for
118
+ * @returns The Payload Diviner for the specified store
119
+ */
120
+ async getPayloadDivinerForStore(store) {
121
+ var _a, _b;
122
+ const name = assertEx((_b = (_a = this.config) == null ? void 0 : _a[store]) == null ? void 0 : _b.payloadDiviner, () => `${moduleName}: Config for ${store}.payloadDiviner not specified`);
123
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.payloadDiviner`);
124
+ return DivinerWrapper.wrap(mod, this.account);
125
+ }
126
+ /**
127
+ * Retrieves the last state of the Diviner process. Used to recover state after
128
+ * preemptions, reboots, etc.
129
+ */
130
+ async retrieveState() {
131
+ if (this._lastState)
132
+ return this._lastState;
133
+ let hash = "";
134
+ const diviner = await this.getBoundWitnessDivinerForStore("stateStore");
135
+ const query = new PayloadBuilder({ schema: BoundWitnessDivinerQuerySchema }).fields({
136
+ address: this.account.address,
137
+ limit: 1,
138
+ offset: 0,
139
+ order: "desc",
140
+ payload_schemas: [ModuleStateSchema]
141
+ }).build();
142
+ const boundWitnesses = await diviner.divine([query]);
143
+ if (boundWitnesses.length > 0) {
144
+ const boundWitness = boundWitnesses[0];
145
+ if (isBoundWitness(boundWitness)) {
146
+ hash = boundWitness.addresses.map((address, index) => ({ address, index })).filter(({ address }) => address === this.account.address).reduce(
147
+ (prev, curr) => {
148
+ var _a;
149
+ return ((_a = boundWitness.payload_schemas) == null ? void 0 : _a[curr == null ? void 0 : curr.index]) === ModuleStateSchema ? boundWitness.payload_hashes[curr == null ? void 0 : curr.index] : prev;
150
+ },
151
+ ""
152
+ );
153
+ }
154
+ }
155
+ if (hash) {
156
+ const archivist = await this.getArchivistForStore("stateStore");
157
+ const payload = (await archivist.get([hash])).find(isModuleState);
158
+ if (payload) {
159
+ return payload;
160
+ }
161
+ }
162
+ return void 0;
163
+ }
164
+ async startHandler() {
165
+ await super.startHandler();
166
+ this.poll();
167
+ return true;
168
+ }
169
+ async stopHandler(_timeout) {
170
+ if (this._pollId) {
171
+ clearTimeout(this._pollId);
172
+ this._pollId = void 0;
173
+ }
174
+ return await super.stopHandler();
175
+ }
176
+ /**
177
+ * Runs the background divine process on a loop with a delay
178
+ * specified by the `config.pollFrequency`
179
+ */
180
+ poll() {
181
+ this._pollId = setTimeout(async () => {
182
+ try {
183
+ await this.backgroundDivine();
184
+ } catch (e) {
185
+ console.log(e);
186
+ } finally {
187
+ if (this._pollId)
188
+ clearTimeout(this._pollId);
189
+ this._pollId = void 0;
190
+ this.poll();
191
+ }
192
+ }, this.pollFrequency);
193
+ }
194
+ };
195
+
196
+ // src/Stage.ts
197
+ var DivinerStageSchema = "network.xyo.diviner.stage";
198
+ export {
199
+ DivinerStageSchema,
200
+ IndexingDiviner,
201
+ IndexingDivinerConfigSchema,
202
+ IndexingDivinerSchema
203
+ };
204
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/Schema.ts","../../src/Config.ts","../../src/Diviner.ts","../../src/Stage.ts"],"sourcesContent":["export const IndexingDivinerSchema = 'network.xyo.diviner.indexing' as const\nexport type ImageThumbnailDivinerSchema = typeof IndexingDivinerSchema\n","import { DivinerConfig } from '@xyo-network/diviner-model'\n\nimport { IndexingDivinerSchema } from './Schema'\nimport { SearchableStorage } from './SearchableStorage'\nimport { IndexingDivinerStageConfig } from './Stage'\n\nexport const IndexingDivinerConfigSchema = `${IndexingDivinerSchema}.config` as const\nexport type IndexingDivinerConfigSchema = typeof IndexingDivinerConfigSchema\n\nexport type IndexingDivinerConfig = DivinerConfig<{\n /**\n * Where the diviner should store it's index\n */\n indexStore?: SearchableStorage\n /**\n * Config section for individual indexing diviner stages\n */\n indexingDivinerStages: IndexingDivinerStageConfig\n /**\n * The maximum number of payloads to index at a time\n */\n payloadDivinerLimit?: number\n /**\n * How often to poll for new payloads to index\n */\n pollFrequency?: number\n /**\n * The schema for the Diviner config\n */\n schema: IndexingDivinerConfigSchema\n /**\n * Where the diviner should persist its internal state\n */\n stateStore?: SearchableStorage\n}>\n","import { assertEx } from '@xylabs/assert'\nimport { AbstractDiviner } from '@xyo-network/abstract-diviner'\nimport { ArchivistWrapper } from '@xyo-network/archivist-wrapper'\nimport { BoundWitnessBuilder } from '@xyo-network/boundwitness-builder'\nimport { isBoundWitness } from '@xyo-network/boundwitness-model'\nimport { BoundWitnessDivinerQueryPayload, BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'\nimport { asDivinerInstance, DivinerConfigSchema, DivinerModule, DivinerModuleEventData } from '@xyo-network/diviner-model'\nimport { DivinerWrapper } from '@xyo-network/diviner-wrapper'\nimport { isModuleState, ModuleState, ModuleStateSchema } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload } from '@xyo-network/payload-model'\n\nimport { IndexingDivinerConfig, IndexingDivinerConfigSchema } from './Config'\nimport { IndexingDivinerParams } from './Params'\nimport { IndexingDivinerStage } from './Stage'\nimport { IndexingDivinerState } from './State'\n\ntype ConfigStoreKey = 'indexStore' | 'stateStore'\n\ntype ConfigStore = Extract<keyof IndexingDivinerConfig, ConfigStoreKey>\n\nconst moduleName = 'IndexingDiviner'\n\nexport class IndexingDiviner<\n TParams extends IndexingDivinerParams = IndexingDivinerParams,\n TIn extends Payload = Payload,\n TOut extends Payload = Payload,\n TEventData extends DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut> = DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut>,\n> extends AbstractDiviner<TParams, TIn, TOut, TEventData> {\n static override readonly configSchemas = [IndexingDivinerConfigSchema, DivinerConfigSchema]\n\n private _lastState?: ModuleState<IndexingDivinerState>\n private _pollId?: string | number | NodeJS.Timeout\n\n get payloadDivinerLimit() {\n return this.config.payloadDivinerLimit ?? 1_000\n }\n\n get pollFrequency() {\n return this.config.pollFrequency ?? 10_000\n }\n\n /**\n * Works via batched iteration of the source archivist to populate the index.\n * @returns A promise that resolves when the background process is complete\n */\n protected backgroundDivine = async (): Promise<void> => {\n // Load last state\n const lastState = await this.retrieveState()\n // Get next batch of results\n const indexCandidateDiviner = await this.getIndexingDivinerStage('stateToIndexCandidateDiviner')\n const results = lastState ? await indexCandidateDiviner.divine([lastState]) : await indexCandidateDiviner.divine()\n // Filter next state out from results\n const nextState = results.find(isModuleState<IndexingDivinerState>)\n const indexCandidates = results.filter((x) => !isModuleState(x))\n // Transform candidates to indexes\n const toIndexTransformDiviner = await this.getIndexingDivinerStage('indexCandidateToIndexDiviner')\n const indexes = await toIndexTransformDiviner.divine(indexCandidates)\n // Insert index results\n const indexArchivist = await this.getArchivistForStore('indexStore')\n await indexArchivist.insert(indexes)\n // Update state\n if (nextState) {\n await this.commitState(nextState)\n }\n }\n\n /**\n * Commit the internal state of the Diviner 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 nextState The state to commit\n */\n protected async commitState(nextState: ModuleState<IndexingDivinerState>) {\n // Don't commit state if no state has changed\n if (nextState.state.offset === this._lastState?.state.offset) return\n this._lastState = nextState\n const archivist = await this.getArchivistForStore('stateStore')\n const [bw] = await new BoundWitnessBuilder().payload(nextState).witness(this.account).build()\n await archivist.insert([bw, nextState])\n }\n\n protected override async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {\n const indexPayloadDiviner = await this.getPayloadDivinerForStore('indexStore')\n const divinerQueryToIndexQueryDiviner = await this.getIndexingDivinerStage('divinerQueryToIndexQueryDiviner')\n const indexQueryResponseToDivinerQueryResponseDiviner = await this.getIndexingDivinerStage('indexQueryResponseToDivinerQueryResponseDiviner')\n const results = (\n await Promise.all(\n payloads.map(async (payload) => {\n const indexQuery = await divinerQueryToIndexQueryDiviner.divine([payload])\n // Divine the results\n const indexedResults = await indexPayloadDiviner.divine(indexQuery)\n // Transform the results to the response shape\n const response = await Promise.all(\n indexedResults.flat().map((indexedResult) => indexQueryResponseToDivinerQueryResponseDiviner.divine([payload, indexedResult])),\n )\n return response.flat()\n }),\n )\n ).flat()\n // TODO: Infer this type over casting to this type\n return results as TOut[]\n }\n\n /**\n * Retrieves the archivist for the specified store\n * @param store The store to retrieve the archivist for\n * @returns The archivist for the specified store\n */\n protected async getArchivistForStore(store: ConfigStore) {\n const name = assertEx(this.config?.[store]?.archivist, () => `${moduleName}: Config for ${store}.archivist not specified`)\n const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.archivist`)\n return ArchivistWrapper.wrap(mod, this.account)\n }\n\n /**\n * Retrieves the BoundWitness Diviner for the specified store\n * @param store The store to retrieve the BoundWitness Diviner for\n * @returns The BoundWitness Diviner for the specified store\n */\n protected async getBoundWitnessDivinerForStore(store: ConfigStore) {\n const name = assertEx(this.config?.[store]?.boundWitnessDiviner, () => `${moduleName}: Config for ${store}.boundWitnessDiviner not specified`)\n const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.boundWitnessDiviner`)\n return DivinerWrapper.wrap(mod, this.account)\n }\n\n /**\n * Gets the Diviner for the supplied Indexing Diviner stage\n * @param transform The Indexing Diviner stage\n * @returns The diviner corresponding to the Indexing Diviner stage\n */\n protected async getIndexingDivinerStage(transform: IndexingDivinerStage) {\n const nameOrAddress = assertEx(\n this.config?.indexingDivinerStages?.[transform],\n () => `${moduleName}: Config for indexingDivinerStages.${transform} not specified`,\n )\n const mod = await this.resolve(nameOrAddress)\n return assertEx(asDivinerInstance(mod), () => `${moduleName}: Failed to resolve indexing diviner stage for ${transform}`)\n }\n\n /**\n * Retrieves the Payload Diviner for the specified store\n * @param store The store to retrieve the Payload Diviner for\n * @returns The Payload Diviner for the specified store\n */\n protected async getPayloadDivinerForStore(store: ConfigStore) {\n const name = assertEx(this.config?.[store]?.payloadDiviner, () => `${moduleName}: Config for ${store}.payloadDiviner not specified`)\n const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.payloadDiviner`)\n return DivinerWrapper.wrap(mod, this.account)\n }\n\n /**\n * Retrieves the last state of the Diviner process. Used to recover state after\n * preemptions, reboots, etc.\n */\n protected async retrieveState(): Promise<ModuleState<IndexingDivinerState> | undefined> {\n if (this._lastState) return this._lastState\n let hash: string = ''\n const diviner = await this.getBoundWitnessDivinerForStore('stateStore')\n const query = new PayloadBuilder<BoundWitnessDivinerQueryPayload>({ schema: BoundWitnessDivinerQuerySchema })\n .fields({\n address: this.account.address,\n limit: 1,\n offset: 0,\n order: 'desc',\n payload_schemas: [ModuleStateSchema],\n })\n .build()\n const boundWitnesses = await diviner.divine([query])\n if (boundWitnesses.length > 0) {\n const boundWitness = boundWitnesses[0]\n if (isBoundWitness(boundWitness)) {\n // Find the index for this address in the BoundWitness that is a ModuleState\n hash = boundWitness.addresses\n .map((address, index) => ({ address, index }))\n .filter(({ address }) => address === this.account.address)\n .reduce(\n (prev, curr) => (boundWitness.payload_schemas?.[curr?.index] === ModuleStateSchema ? boundWitness.payload_hashes[curr?.index] : prev),\n '',\n )\n }\n }\n\n // If we able to located the last state\n if (hash) {\n // Get last state\n const archivist = await this.getArchivistForStore('stateStore')\n const payload = (await archivist.get([hash])).find(isModuleState<IndexingDivinerState>)\n if (payload) {\n return payload\n }\n }\n return undefined\n }\n\n protected override async startHandler(): Promise<boolean> {\n await super.startHandler()\n this.poll()\n return true\n }\n\n protected override async stopHandler(_timeout?: number | undefined): Promise<boolean> {\n if (this._pollId) {\n clearTimeout(this._pollId)\n this._pollId = undefined\n }\n return await super.stopHandler()\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 = setTimeout(async () => {\n try {\n await this.backgroundDivine()\n } catch (e) {\n console.log(e)\n } finally {\n if (this._pollId) clearTimeout(this._pollId)\n this._pollId = undefined\n this.poll()\n }\n }, this.pollFrequency)\n }\n}\n","export type DivinerStageSchema = 'network.xyo.diviner.stage'\nexport const DivinerStageSchema: DivinerStageSchema = 'network.xyo.diviner.stage'\n\n/**\n * The diviners for each stage of an indexing diviner\n */\nexport type IndexingDivinerStage =\n /**\n * Transforms a diviner query into an index query\n */\n | 'divinerQueryToIndexQueryDiviner'\n /**\n * Transforms the index candidates into indexes\n */\n | 'indexCandidateToIndexDiviner'\n /**\n * Transforms an index query response into a diviner divine query response\n */\n | 'indexQueryResponseToDivinerQueryResponseDiviner'\n /**\n * Uses the current state to determine the next batch of index candidates\n */\n | 'stateToIndexCandidateDiviner'\n\n/**\n * Config section for declaring each indexing diviner stage\n */\nexport type IndexingDivinerStageConfig = {\n [key in IndexingDivinerStage]: string\n}\n"],"mappings":";AAAO,IAAM,wBAAwB;;;ACM9B,IAAM,8BAA8B,GAAG,qBAAqB;;;ACNnE,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAA0C,sCAAsC;AAChF,SAAS,mBAAmB,2BAAkE;AAC9F,SAAS,sBAAsB;AAC/B,SAAS,eAA4B,yBAAyB;AAC9D,SAAS,sBAAsB;AAY/B,IAAM,aAAa;AAEZ,IAAM,kBAAN,cAKG,gBAAgD;AAAA,EACxD,OAAyB,gBAAgB,CAAC,6BAA6B,mBAAmB;AAAA,EAElF;AAAA,EACA;AAAA,EAER,IAAI,sBAAsB;AACxB,WAAO,KAAK,OAAO,uBAAuB;AAAA,EAC5C;AAAA,EAEA,IAAI,gBAAgB;AAClB,WAAO,KAAK,OAAO,iBAAiB;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,mBAAmB,YAA2B;AAEtD,UAAM,YAAY,MAAM,KAAK,cAAc;AAE3C,UAAM,wBAAwB,MAAM,KAAK,wBAAwB,8BAA8B;AAC/F,UAAM,UAAU,YAAY,MAAM,sBAAsB,OAAO,CAAC,SAAS,CAAC,IAAI,MAAM,sBAAsB,OAAO;AAEjH,UAAM,YAAY,QAAQ,KAAK,aAAmC;AAClE,UAAM,kBAAkB,QAAQ,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAE/D,UAAM,0BAA0B,MAAM,KAAK,wBAAwB,8BAA8B;AACjG,UAAM,UAAU,MAAM,wBAAwB,OAAO,eAAe;AAEpE,UAAM,iBAAiB,MAAM,KAAK,qBAAqB,YAAY;AACnE,UAAM,eAAe,OAAO,OAAO;AAEnC,QAAI,WAAW;AACb,YAAM,KAAK,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AAY;AACpC,UAAI;AACF,cAAM,KAAK,iBAAiB;AAAA,MAC9B,SAAS,GAAG;AACV,gBAAQ,IAAI,CAAC;AAAA,MACf,UAAE;AACA,YAAI,KAAK;AAAS,uBAAa,KAAK,OAAO;AAC3C,aAAK,UAAU;AACf,aAAK,KAAK;AAAA,MACZ;AAAA,IACF,GAAG,KAAK,aAAa;AAAA,EACvB;AACF;;;AClOO,IAAM,qBAAyC;","names":[]}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@xyo-network/diviner-indexing",
3
+ "author": {
4
+ "email": "support@xyo.network",
5
+ "name": "XYO Development Team",
6
+ "url": "https://xyo.network"
7
+ },
8
+ "bugs": {
9
+ "email": "support@xyo.network",
10
+ "url": "https://github.com/XYOracleNetwork/sdk-xyo-client-js/issues"
11
+ },
12
+ "dependencies": {
13
+ "@xylabs/assert": "^2.13.3",
14
+ "@xyo-network/abstract-diviner": "~2.79.0",
15
+ "@xyo-network/archivist-wrapper": "~2.79.0",
16
+ "@xyo-network/boundwitness-builder": "~2.79.0",
17
+ "@xyo-network/boundwitness-model": "~2.79.0",
18
+ "@xyo-network/diviner-boundwitness-model": "~2.79.0",
19
+ "@xyo-network/diviner-model": "~2.79.0",
20
+ "@xyo-network/diviner-wrapper": "~2.79.0",
21
+ "@xyo-network/module-model": "~2.79.0",
22
+ "@xyo-network/payload-builder": "~2.79.0",
23
+ "@xyo-network/payload-model": "~2.79.0"
24
+ },
25
+ "devDependencies": {
26
+ "@xylabs/ts-scripts-yarn3": "^3.1.21",
27
+ "@xylabs/tsconfig": "^3.1.21",
28
+ "typescript": "^5.2.2"
29
+ },
30
+ "description": "Primary SDK for using XYO Protocol 2.0",
31
+ "docs": "dist/docs.json",
32
+ "types": "dist/node/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "browser": {
36
+ "require": {
37
+ "types": "./dist/browser/index.d.cts",
38
+ "default": "./dist/browser/index.cjs"
39
+ },
40
+ "import": {
41
+ "types": "./dist/browser/index.d.mts",
42
+ "default": "./dist/browser/index.js"
43
+ }
44
+ },
45
+ "node": {
46
+ "require": {
47
+ "types": "./dist/node/index.d.ts",
48
+ "default": "./dist/node/index.js"
49
+ },
50
+ "import": {
51
+ "types": "./dist/node/index.d.mts",
52
+ "default": "./dist/node/index.mjs"
53
+ }
54
+ }
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ "main": "dist/node/index.js",
59
+ "module": "dist/node/index.mjs",
60
+ "homepage": "https://xyo.network",
61
+ "license": "LGPL-3.0-only",
62
+ "publishConfig": {
63
+ "access": "public"
64
+ },
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "https://github.com/XYOracleNetwork/sdk-xyo-client-js.git"
68
+ },
69
+ "sideEffects": false,
70
+ "version": "2.79.0"
71
+ }
package/src/Config.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { DivinerConfig } from '@xyo-network/diviner-model'
2
+
3
+ import { IndexingDivinerSchema } from './Schema'
4
+ import { SearchableStorage } from './SearchableStorage'
5
+ import { IndexingDivinerStageConfig } from './Stage'
6
+
7
+ export const IndexingDivinerConfigSchema = `${IndexingDivinerSchema}.config` as const
8
+ export type IndexingDivinerConfigSchema = typeof IndexingDivinerConfigSchema
9
+
10
+ export type IndexingDivinerConfig = DivinerConfig<{
11
+ /**
12
+ * Where the diviner should store it's index
13
+ */
14
+ indexStore?: SearchableStorage
15
+ /**
16
+ * Config section for individual indexing diviner stages
17
+ */
18
+ indexingDivinerStages: IndexingDivinerStageConfig
19
+ /**
20
+ * The maximum number of payloads to index at a time
21
+ */
22
+ payloadDivinerLimit?: number
23
+ /**
24
+ * How often to poll for new payloads to index
25
+ */
26
+ pollFrequency?: number
27
+ /**
28
+ * The schema for the Diviner config
29
+ */
30
+ schema: IndexingDivinerConfigSchema
31
+ /**
32
+ * Where the diviner should persist its internal state
33
+ */
34
+ stateStore?: SearchableStorage
35
+ }>
package/src/Diviner.ts ADDED
@@ -0,0 +1,228 @@
1
+ import { assertEx } from '@xylabs/assert'
2
+ import { AbstractDiviner } from '@xyo-network/abstract-diviner'
3
+ import { ArchivistWrapper } from '@xyo-network/archivist-wrapper'
4
+ import { BoundWitnessBuilder } from '@xyo-network/boundwitness-builder'
5
+ import { isBoundWitness } from '@xyo-network/boundwitness-model'
6
+ import { BoundWitnessDivinerQueryPayload, BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'
7
+ import { asDivinerInstance, DivinerConfigSchema, DivinerModule, DivinerModuleEventData } from '@xyo-network/diviner-model'
8
+ import { DivinerWrapper } from '@xyo-network/diviner-wrapper'
9
+ import { isModuleState, ModuleState, ModuleStateSchema } from '@xyo-network/module-model'
10
+ import { PayloadBuilder } from '@xyo-network/payload-builder'
11
+ import { Payload } from '@xyo-network/payload-model'
12
+
13
+ import { IndexingDivinerConfig, IndexingDivinerConfigSchema } from './Config'
14
+ import { IndexingDivinerParams } from './Params'
15
+ import { IndexingDivinerStage } from './Stage'
16
+ import { IndexingDivinerState } from './State'
17
+
18
+ type ConfigStoreKey = 'indexStore' | 'stateStore'
19
+
20
+ type ConfigStore = Extract<keyof IndexingDivinerConfig, ConfigStoreKey>
21
+
22
+ const moduleName = 'IndexingDiviner'
23
+
24
+ export class IndexingDiviner<
25
+ TParams extends IndexingDivinerParams = IndexingDivinerParams,
26
+ TIn extends Payload = Payload,
27
+ TOut extends Payload = Payload,
28
+ TEventData extends DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut> = DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut>,
29
+ > extends AbstractDiviner<TParams, TIn, TOut, TEventData> {
30
+ static override readonly configSchemas = [IndexingDivinerConfigSchema, DivinerConfigSchema]
31
+
32
+ private _lastState?: ModuleState<IndexingDivinerState>
33
+ private _pollId?: string | number | NodeJS.Timeout
34
+
35
+ get payloadDivinerLimit() {
36
+ return this.config.payloadDivinerLimit ?? 1_000
37
+ }
38
+
39
+ get pollFrequency() {
40
+ return this.config.pollFrequency ?? 10_000
41
+ }
42
+
43
+ /**
44
+ * Works via batched iteration of the source archivist to populate the index.
45
+ * @returns A promise that resolves when the background process is complete
46
+ */
47
+ protected backgroundDivine = async (): Promise<void> => {
48
+ // Load last state
49
+ const lastState = await this.retrieveState()
50
+ // Get next batch of results
51
+ const indexCandidateDiviner = await this.getIndexingDivinerStage('stateToIndexCandidateDiviner')
52
+ const results = lastState ? await indexCandidateDiviner.divine([lastState]) : await indexCandidateDiviner.divine()
53
+ // Filter next state out from results
54
+ const nextState = results.find(isModuleState<IndexingDivinerState>)
55
+ const indexCandidates = results.filter((x) => !isModuleState(x))
56
+ // Transform candidates to indexes
57
+ const toIndexTransformDiviner = await this.getIndexingDivinerStage('indexCandidateToIndexDiviner')
58
+ const indexes = await toIndexTransformDiviner.divine(indexCandidates)
59
+ // Insert index results
60
+ const indexArchivist = await this.getArchivistForStore('indexStore')
61
+ await indexArchivist.insert(indexes)
62
+ // Update state
63
+ if (nextState) {
64
+ await this.commitState(nextState)
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Commit the internal state of the Diviner process. This is similar
70
+ * to a transaction completion in a database and should only be called
71
+ * when results have been successfully persisted to the appropriate
72
+ * external stores.
73
+ * @param nextState The state to commit
74
+ */
75
+ protected async commitState(nextState: ModuleState<IndexingDivinerState>) {
76
+ // Don't commit state if no state has changed
77
+ if (nextState.state.offset === this._lastState?.state.offset) return
78
+ this._lastState = nextState
79
+ const archivist = await this.getArchivistForStore('stateStore')
80
+ const [bw] = await new BoundWitnessBuilder().payload(nextState).witness(this.account).build()
81
+ await archivist.insert([bw, nextState])
82
+ }
83
+
84
+ protected override async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {
85
+ const indexPayloadDiviner = await this.getPayloadDivinerForStore('indexStore')
86
+ const divinerQueryToIndexQueryDiviner = await this.getIndexingDivinerStage('divinerQueryToIndexQueryDiviner')
87
+ const indexQueryResponseToDivinerQueryResponseDiviner = await this.getIndexingDivinerStage('indexQueryResponseToDivinerQueryResponseDiviner')
88
+ const results = (
89
+ await Promise.all(
90
+ payloads.map(async (payload) => {
91
+ const indexQuery = await divinerQueryToIndexQueryDiviner.divine([payload])
92
+ // Divine the results
93
+ const indexedResults = await indexPayloadDiviner.divine(indexQuery)
94
+ // Transform the results to the response shape
95
+ const response = await Promise.all(
96
+ indexedResults.flat().map((indexedResult) => indexQueryResponseToDivinerQueryResponseDiviner.divine([payload, indexedResult])),
97
+ )
98
+ return response.flat()
99
+ }),
100
+ )
101
+ ).flat()
102
+ // TODO: Infer this type over casting to this type
103
+ return results as TOut[]
104
+ }
105
+
106
+ /**
107
+ * Retrieves the archivist for the specified store
108
+ * @param store The store to retrieve the archivist for
109
+ * @returns The archivist for the specified store
110
+ */
111
+ protected async getArchivistForStore(store: ConfigStore) {
112
+ const name = assertEx(this.config?.[store]?.archivist, () => `${moduleName}: Config for ${store}.archivist not specified`)
113
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.archivist`)
114
+ return ArchivistWrapper.wrap(mod, this.account)
115
+ }
116
+
117
+ /**
118
+ * Retrieves the BoundWitness Diviner for the specified store
119
+ * @param store The store to retrieve the BoundWitness Diviner for
120
+ * @returns The BoundWitness Diviner for the specified store
121
+ */
122
+ protected async getBoundWitnessDivinerForStore(store: ConfigStore) {
123
+ const name = assertEx(this.config?.[store]?.boundWitnessDiviner, () => `${moduleName}: Config for ${store}.boundWitnessDiviner not specified`)
124
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.boundWitnessDiviner`)
125
+ return DivinerWrapper.wrap(mod, this.account)
126
+ }
127
+
128
+ /**
129
+ * Gets the Diviner for the supplied Indexing Diviner stage
130
+ * @param transform The Indexing Diviner stage
131
+ * @returns The diviner corresponding to the Indexing Diviner stage
132
+ */
133
+ protected async getIndexingDivinerStage(transform: IndexingDivinerStage) {
134
+ const nameOrAddress = assertEx(
135
+ this.config?.indexingDivinerStages?.[transform],
136
+ () => `${moduleName}: Config for indexingDivinerStages.${transform} not specified`,
137
+ )
138
+ const mod = await this.resolve(nameOrAddress)
139
+ return assertEx(asDivinerInstance(mod), () => `${moduleName}: Failed to resolve indexing diviner stage for ${transform}`)
140
+ }
141
+
142
+ /**
143
+ * Retrieves the Payload Diviner for the specified store
144
+ * @param store The store to retrieve the Payload Diviner for
145
+ * @returns The Payload Diviner for the specified store
146
+ */
147
+ protected async getPayloadDivinerForStore(store: ConfigStore) {
148
+ const name = assertEx(this.config?.[store]?.payloadDiviner, () => `${moduleName}: Config for ${store}.payloadDiviner not specified`)
149
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.payloadDiviner`)
150
+ return DivinerWrapper.wrap(mod, this.account)
151
+ }
152
+
153
+ /**
154
+ * Retrieves the last state of the Diviner process. Used to recover state after
155
+ * preemptions, reboots, etc.
156
+ */
157
+ protected async retrieveState(): Promise<ModuleState<IndexingDivinerState> | undefined> {
158
+ if (this._lastState) return this._lastState
159
+ let hash: string = ''
160
+ const diviner = await this.getBoundWitnessDivinerForStore('stateStore')
161
+ const query = new PayloadBuilder<BoundWitnessDivinerQueryPayload>({ schema: BoundWitnessDivinerQuerySchema })
162
+ .fields({
163
+ address: this.account.address,
164
+ limit: 1,
165
+ offset: 0,
166
+ order: 'desc',
167
+ payload_schemas: [ModuleStateSchema],
168
+ })
169
+ .build()
170
+ const boundWitnesses = await diviner.divine([query])
171
+ if (boundWitnesses.length > 0) {
172
+ const boundWitness = boundWitnesses[0]
173
+ if (isBoundWitness(boundWitness)) {
174
+ // Find the index for this address in the BoundWitness that is a ModuleState
175
+ hash = boundWitness.addresses
176
+ .map((address, index) => ({ address, index }))
177
+ .filter(({ address }) => address === this.account.address)
178
+ .reduce(
179
+ (prev, curr) => (boundWitness.payload_schemas?.[curr?.index] === ModuleStateSchema ? boundWitness.payload_hashes[curr?.index] : prev),
180
+ '',
181
+ )
182
+ }
183
+ }
184
+
185
+ // If we able to located the last state
186
+ if (hash) {
187
+ // Get last state
188
+ const archivist = await this.getArchivistForStore('stateStore')
189
+ const payload = (await archivist.get([hash])).find(isModuleState<IndexingDivinerState>)
190
+ if (payload) {
191
+ return payload
192
+ }
193
+ }
194
+ return undefined
195
+ }
196
+
197
+ protected override async startHandler(): Promise<boolean> {
198
+ await super.startHandler()
199
+ this.poll()
200
+ return true
201
+ }
202
+
203
+ protected override async stopHandler(_timeout?: number | undefined): Promise<boolean> {
204
+ if (this._pollId) {
205
+ clearTimeout(this._pollId)
206
+ this._pollId = undefined
207
+ }
208
+ return await super.stopHandler()
209
+ }
210
+
211
+ /**
212
+ * Runs the background divine process on a loop with a delay
213
+ * specified by the `config.pollFrequency`
214
+ */
215
+ private poll() {
216
+ this._pollId = setTimeout(async () => {
217
+ try {
218
+ await this.backgroundDivine()
219
+ } catch (e) {
220
+ console.log(e)
221
+ } finally {
222
+ if (this._pollId) clearTimeout(this._pollId)
223
+ this._pollId = undefined
224
+ this.poll()
225
+ }
226
+ }, this.pollFrequency)
227
+ }
228
+ }
package/src/Labels.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Labels } from '@xyo-network/module-model'
2
+
3
+ import { DivinerStageSchema, IndexingDivinerStage } from './Stage'
4
+
5
+ /**
6
+ * Labels for Indexing Diviner Stage Diviners
7
+ */
8
+ export type IndexingDivinerStageLabels = Labels & {
9
+ /**
10
+ * Labels for the stage of the Indexing Diviner Stage Diviner
11
+ */
12
+ [key in DivinerStageSchema]: IndexingDivinerStage
13
+ }
package/src/Params.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { DivinerParams } from '@xyo-network/diviner-model'
2
+ import { AnyConfigSchema } from '@xyo-network/module-model'
3
+
4
+ import { IndexingDivinerConfig } from './Config'
5
+
6
+ export type IndexingDivinerParams = DivinerParams<AnyConfigSchema<IndexingDivinerConfig>>
package/src/Schema.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const IndexingDivinerSchema = 'network.xyo.diviner.indexing' as const
2
+ export type ImageThumbnailDivinerSchema = typeof IndexingDivinerSchema
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Describes an Archivist/Diviner combination
3
+ * that enables searching signed payloads
4
+ */
5
+ export interface SearchableStorage {
6
+ archivist: string
7
+ boundWitnessDiviner: string
8
+ payloadDiviner: string
9
+ }
package/src/Stage.ts ADDED
@@ -0,0 +1,30 @@
1
+ export type DivinerStageSchema = 'network.xyo.diviner.stage'
2
+ export const DivinerStageSchema: DivinerStageSchema = 'network.xyo.diviner.stage'
3
+
4
+ /**
5
+ * The diviners for each stage of an indexing diviner
6
+ */
7
+ export type IndexingDivinerStage =
8
+ /**
9
+ * Transforms a diviner query into an index query
10
+ */
11
+ | 'divinerQueryToIndexQueryDiviner'
12
+ /**
13
+ * Transforms the index candidates into indexes
14
+ */
15
+ | 'indexCandidateToIndexDiviner'
16
+ /**
17
+ * Transforms an index query response into a diviner divine query response
18
+ */
19
+ | 'indexQueryResponseToDivinerQueryResponseDiviner'
20
+ /**
21
+ * Uses the current state to determine the next batch of index candidates
22
+ */
23
+ | 'stateToIndexCandidateDiviner'
24
+
25
+ /**
26
+ * Config section for declaring each indexing diviner stage
27
+ */
28
+ export type IndexingDivinerStageConfig = {
29
+ [key in IndexingDivinerStage]: string
30
+ }
package/src/State.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { StateDictionary } from '@xyo-network/module-model'
2
+
3
+ export type IndexingDivinerState = StateDictionary & {
4
+ offset: number
5
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './Config'
2
+ export * from './Diviner'
3
+ export * from './Labels'
4
+ export * from './Params'
5
+ export * from './Schema'
6
+ export * from './SearchableStorage'
7
+ export * from './Stage'
package/typedoc.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "$schema": "https://typedoc.org/schema.json",
3
+ "entryPoints": ["src/index.ts"],
4
+ "tsconfig": "./tsconfig.typedoc.json"
5
+ }