@xyo-network/diviner-indexing-memory 2.79.5

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.
package/src/Diviner.ts ADDED
@@ -0,0 +1,230 @@
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 {
8
+ IndexingDivinerConfig,
9
+ IndexingDivinerConfigSchema,
10
+ IndexingDivinerParams,
11
+ IndexingDivinerStage,
12
+ IndexingDivinerState,
13
+ } from '@xyo-network/diviner-indexing-model'
14
+ import { asDivinerInstance, DivinerConfigSchema, DivinerModule, DivinerModuleEventData } from '@xyo-network/diviner-model'
15
+ import { DivinerWrapper } from '@xyo-network/diviner-wrapper'
16
+ import { isModuleState, ModuleState, ModuleStateSchema } from '@xyo-network/module-model'
17
+ import { PayloadBuilder } from '@xyo-network/payload-builder'
18
+ import { Payload } from '@xyo-network/payload-model'
19
+
20
+ type ConfigStoreKey = 'indexStore' | 'stateStore'
21
+
22
+ type ConfigStore = Extract<keyof IndexingDivinerConfig, ConfigStoreKey>
23
+
24
+ const moduleName = 'IndexingDiviner'
25
+
26
+ export class IndexingDiviner<
27
+ TParams extends IndexingDivinerParams = IndexingDivinerParams,
28
+ TIn extends Payload = Payload,
29
+ TOut extends Payload = Payload,
30
+ TEventData extends DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut> = DivinerModuleEventData<DivinerModule<TParams>, TIn, TOut>,
31
+ > extends AbstractDiviner<TParams, TIn, TOut, TEventData> {
32
+ static override readonly configSchemas = [IndexingDivinerConfigSchema, DivinerConfigSchema]
33
+
34
+ private _lastState?: ModuleState<IndexingDivinerState>
35
+ private _pollId?: string | number | NodeJS.Timeout
36
+
37
+ get payloadDivinerLimit() {
38
+ return this.config.payloadDivinerLimit ?? 1_000
39
+ }
40
+
41
+ get pollFrequency() {
42
+ return this.config.pollFrequency ?? 10_000
43
+ }
44
+
45
+ /**
46
+ * Works via batched iteration of the source archivist to populate the index.
47
+ * @returns A promise that resolves when the background process is complete
48
+ */
49
+ protected backgroundDivine = async (): Promise<void> => {
50
+ // Load last state
51
+ const lastState = await this.retrieveState()
52
+ // Get next batch of results
53
+ const indexCandidateDiviner = await this.getIndexingDivinerStage('stateToIndexCandidateDiviner')
54
+ const results = lastState ? await indexCandidateDiviner.divine([lastState]) : await indexCandidateDiviner.divine()
55
+ // Filter next state out from results
56
+ const nextState = results.find(isModuleState<IndexingDivinerState>)
57
+ const indexCandidates = results.filter((x) => !isModuleState(x))
58
+ // Transform candidates to indexes
59
+ const toIndexTransformDiviner = await this.getIndexingDivinerStage('indexCandidateToIndexDiviner')
60
+ const indexes = await toIndexTransformDiviner.divine(indexCandidates)
61
+ // Insert index results
62
+ const indexArchivist = await this.getArchivistForStore('indexStore')
63
+ await indexArchivist.insert(indexes)
64
+ // Update state
65
+ if (nextState) {
66
+ await this.commitState(nextState)
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Commit the internal state of the Diviner process. This is similar
72
+ * to a transaction completion in a database and should only be called
73
+ * when results have been successfully persisted to the appropriate
74
+ * external stores.
75
+ * @param nextState The state to commit
76
+ */
77
+ protected async commitState(nextState: ModuleState<IndexingDivinerState>) {
78
+ // Don't commit state if no state has changed
79
+ if (nextState.state.offset === this._lastState?.state.offset) return
80
+ this._lastState = nextState
81
+ const archivist = await this.getArchivistForStore('stateStore')
82
+ const [bw] = await new BoundWitnessBuilder().payload(nextState).witness(this.account).build()
83
+ await archivist.insert([bw, nextState])
84
+ }
85
+
86
+ protected override async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {
87
+ const indexPayloadDiviner = await this.getPayloadDivinerForStore('indexStore')
88
+ const divinerQueryToIndexQueryDiviner = await this.getIndexingDivinerStage('divinerQueryToIndexQueryDiviner')
89
+ const indexQueryResponseToDivinerQueryResponseDiviner = await this.getIndexingDivinerStage('indexQueryResponseToDivinerQueryResponseDiviner')
90
+ const results = (
91
+ await Promise.all(
92
+ payloads.map(async (payload) => {
93
+ const indexQuery = await divinerQueryToIndexQueryDiviner.divine([payload])
94
+ // Divine the results
95
+ const indexedResults = await indexPayloadDiviner.divine(indexQuery)
96
+ // Transform the results to the response shape
97
+ const response = await Promise.all(
98
+ indexedResults.flat().map((indexedResult) => indexQueryResponseToDivinerQueryResponseDiviner.divine([payload, indexedResult])),
99
+ )
100
+ return response.flat()
101
+ }),
102
+ )
103
+ ).flat()
104
+ // TODO: Infer this type over casting to this type
105
+ return results as TOut[]
106
+ }
107
+
108
+ /**
109
+ * Retrieves the archivist for the specified store
110
+ * @param store The store to retrieve the archivist for
111
+ * @returns The archivist for the specified store
112
+ */
113
+ protected async getArchivistForStore(store: ConfigStore) {
114
+ const name = assertEx(this.config?.[store]?.archivist, () => `${moduleName}: Config for ${store}.archivist not specified`)
115
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.archivist`)
116
+ return ArchivistWrapper.wrap(mod, this.account)
117
+ }
118
+
119
+ /**
120
+ * Retrieves the BoundWitness Diviner for the specified store
121
+ * @param store The store to retrieve the BoundWitness Diviner for
122
+ * @returns The BoundWitness Diviner for the specified store
123
+ */
124
+ protected async getBoundWitnessDivinerForStore(store: ConfigStore) {
125
+ const name = assertEx(this.config?.[store]?.boundWitnessDiviner, () => `${moduleName}: Config for ${store}.boundWitnessDiviner not specified`)
126
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.boundWitnessDiviner`)
127
+ return DivinerWrapper.wrap(mod, this.account)
128
+ }
129
+
130
+ /**
131
+ * Gets the Diviner for the supplied Indexing Diviner stage
132
+ * @param transform The Indexing Diviner stage
133
+ * @returns The diviner corresponding to the Indexing Diviner stage
134
+ */
135
+ protected async getIndexingDivinerStage(transform: IndexingDivinerStage) {
136
+ const nameOrAddress = assertEx(
137
+ this.config?.indexingDivinerStages?.[transform],
138
+ () => `${moduleName}: Config for indexingDivinerStages.${transform} not specified`,
139
+ )
140
+ const mod = await this.resolve(nameOrAddress)
141
+ return assertEx(asDivinerInstance(mod), () => `${moduleName}: Failed to resolve indexing diviner stage for ${transform}`)
142
+ }
143
+
144
+ /**
145
+ * Retrieves the Payload Diviner for the specified store
146
+ * @param store The store to retrieve the Payload Diviner for
147
+ * @returns The Payload Diviner for the specified store
148
+ */
149
+ protected async getPayloadDivinerForStore(store: ConfigStore) {
150
+ const name = assertEx(this.config?.[store]?.payloadDiviner, () => `${moduleName}: Config for ${store}.payloadDiviner not specified`)
151
+ const mod = assertEx(await this.resolve(name), () => `${moduleName}: Failed to resolve ${store}.payloadDiviner`)
152
+ return DivinerWrapper.wrap(mod, this.account)
153
+ }
154
+
155
+ /**
156
+ * Retrieves the last state of the Diviner process. Used to recover state after
157
+ * preemptions, reboots, etc.
158
+ */
159
+ protected async retrieveState(): Promise<ModuleState<IndexingDivinerState> | undefined> {
160
+ if (this._lastState) return this._lastState
161
+ let hash: string = ''
162
+ const diviner = await this.getBoundWitnessDivinerForStore('stateStore')
163
+ const query = new PayloadBuilder<BoundWitnessDivinerQueryPayload>({ schema: BoundWitnessDivinerQuerySchema })
164
+ .fields({
165
+ address: this.account.address,
166
+ limit: 1,
167
+ offset: 0,
168
+ order: 'desc',
169
+ payload_schemas: [ModuleStateSchema],
170
+ })
171
+ .build()
172
+ const boundWitnesses = await diviner.divine([query])
173
+ if (boundWitnesses.length > 0) {
174
+ const boundWitness = boundWitnesses[0]
175
+ if (isBoundWitness(boundWitness)) {
176
+ // Find the index for this address in the BoundWitness that is a ModuleState
177
+ hash = boundWitness.addresses
178
+ .map((address, index) => ({ address, index }))
179
+ .filter(({ address }) => address === this.account.address)
180
+ .reduce(
181
+ (prev, curr) => (boundWitness.payload_schemas?.[curr?.index] === ModuleStateSchema ? boundWitness.payload_hashes[curr?.index] : prev),
182
+ '',
183
+ )
184
+ }
185
+ }
186
+
187
+ // If we able to located the last state
188
+ if (hash) {
189
+ // Get last state
190
+ const archivist = await this.getArchivistForStore('stateStore')
191
+ const payload = (await archivist.get([hash])).find(isModuleState<IndexingDivinerState>)
192
+ if (payload) {
193
+ return payload
194
+ }
195
+ }
196
+ return undefined
197
+ }
198
+
199
+ protected override async startHandler(): Promise<boolean> {
200
+ await super.startHandler()
201
+ this.poll()
202
+ return true
203
+ }
204
+
205
+ protected override async stopHandler(_timeout?: number | undefined): Promise<boolean> {
206
+ if (this._pollId) {
207
+ clearTimeout(this._pollId)
208
+ this._pollId = undefined
209
+ }
210
+ return await super.stopHandler()
211
+ }
212
+
213
+ /**
214
+ * Runs the background divine process on a loop with a delay
215
+ * specified by the `config.pollFrequency`
216
+ */
217
+ private poll() {
218
+ this._pollId = setTimeout(async () => {
219
+ try {
220
+ await this.backgroundDivine()
221
+ } catch (e) {
222
+ console.log(e)
223
+ } finally {
224
+ if (this._pollId) clearTimeout(this._pollId)
225
+ this._pollId = undefined
226
+ this.poll()
227
+ }
228
+ }, this.pollFrequency)
229
+ }
230
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './Diviner'
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
+ }