-
Notifications
You must be signed in to change notification settings - Fork 0
/
entityHistoryFetcher.ts
192 lines (161 loc) · 5.77 KB
/
entityHistoryFetcher.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { compose } from 'node:stream'
import { StorageEntry, StorageStream, Utils } from '@aleph-indexer/core'
import {
FetchAccountEntitiesByDateRequestArgs,
AccountEntityHistoryFetcherState,
AccountEntityHistoryState,
AddAccountEntityRequestArgs,
DelAccountEntityRequestArgs,
GetAccountEntityStateRequestArgs,
} from './types.js'
import { FetcherMsClient } from '../client.js'
import { PendingAccountStorage } from './dal/account.js'
import { FetcherPool } from './fetcherPool.js'
import { Blockchain, IndexableEntityType } from '../../../types.js'
import { BaseHistoryFetcher } from './baseHistoryFetcher.js'
import {
AccountEntityHistoryDALIndex,
AccountEntityHistoryStorage,
AccountEntityHistoryStorageEntity,
} from './dal/accountEntityHistory.js'
const { StreamBuffer, StreamMap } = Utils
/**
* The main class of the fetcher service.
*/
export abstract class BaseEntityHistoryFetcher<
CU,
HE extends AccountEntityHistoryStorageEntity,
> {
protected pendingAccounts: FetcherPool<string[]>
/**
* Initialize the fetcher service.
* @param blockchainId The blockchain identifier.
* @param fetcherClient The Fetcher ms client.
* @param accountDAL The account job storage.
*/
constructor(
protected type: IndexableEntityType,
protected blockchainId: Blockchain,
protected fetcherClient: FetcherMsClient,
protected accountDAL: PendingAccountStorage,
protected accountEntityHistoryDAL: AccountEntityHistoryStorage<HE>,
protected id = `${blockchainId}:${type}-history-accounts`,
) {
this.pendingAccounts = new FetcherPool({
id,
interval: 0,
concurrency: 1,
dal: this.accountDAL,
getFetcher: ({ id }) => this.getAccountFetcher(id),
// checkComplete: () => false, // @note: Delegated to each baseFetcher
})
}
async start(): Promise<void> {
await this.pendingAccounts.start()
}
async stop(): Promise<void> {
await this.pendingAccounts.stop()
}
/**
* Assigns to a fetcher instance an account owned by the specific program
* and initializes it.
* @param args Account address to asign to the fetcher instance,
*/
async addAccount(args: AddAccountEntityRequestArgs): Promise<void> {
const { account, indexerId } = args
const work = {
id: account,
time: Date.now(),
payload: indexerId ? [indexerId] : [],
}
await this.pendingAccounts.addWork(work)
}
/**
* Stops the fetching process of that instance of the fetcher for that account.
* @param account The account address to stop the fetching process.
*/
async delAccount(args: DelAccountEntityRequestArgs): Promise<void> {
const { account, indexerId } = args
if (!indexerId) return
const work = await this.accountDAL.getFirstValueFromTo([account], [account])
if (!work) return
work.payload = work.payload.filter((id) => id !== indexerId)
await this.pendingAccounts.removeWork(work)
if (work.payload.length > 0) {
await this.pendingAccounts.addWork(work)
}
}
async getState(): Promise<AccountEntityHistoryFetcherState> {
const accountFetchers = await this.pendingAccounts.getCount()
return { accountFetchers }
}
async fetchAccountEntitiesByDate(
args: FetchAccountEntitiesByDateRequestArgs,
): Promise<void | AsyncIterable<string[]>> {
const { account, startDate, endDate, indexerId } = args
const state = await this.getAccountState({
type: this.type,
blockchainId: this.blockchainId,
account,
})
if (!state) return
const { firstTimestamp = Number.MAX_SAFE_INTEGER, lastTimestamp = 0 } =
state
// @todo: make sure that there wont be incomplete ranges on the right
// containing transactions with the same timestamp, in that case we
// are lossing data
const inRange = startDate >= firstTimestamp && endDate <= lastTimestamp
if (!inRange) return
const entitiesQuery = await this.queryEntitiesByDate(args)
return compose(
entitiesQuery,
new StreamMap(({ value }: StorageEntry<string, HE>) => value.id),
new StreamBuffer(1000),
new StreamMap(async (ids: string[]) => {
await this.fetchAccountEntitiesByIdFromDateRange(ids, args)
return ids
}),
)
}
protected async fetchAccountEntitiesByIdFromDateRange(
ids: string[],
byDateArgs: FetchAccountEntitiesByDateRequestArgs,
): Promise<void> {
const { indexerId } = byDateArgs
// @note: Use the client here for load balancing ids through all fetcher instances
await this.fetcherClient
.useBlockchain(this.blockchainId)
.fetchEntitiesById({ type: this.type, ids, indexerId, meta: byDateArgs })
}
protected async getPartialAccountState(
args: GetAccountEntityStateRequestArgs,
): Promise<AccountEntityHistoryState<CU> | undefined> {
const { account } = args
const fetcher = this.getAccountFetcher(args.account)
const fetcherState = await fetcher.getState()
if (!fetcherState) return
const completeHistory = await fetcher.isComplete('backward')
return {
fetcher: this.fetcherClient.getNodeId() || 'unknown',
type: this.type,
blockchain: this.blockchainId,
account,
cursors: fetcherState.cursors,
completeHistory,
}
}
protected queryEntitiesByDate(
args: FetchAccountEntitiesByDateRequestArgs,
): Promise<StorageStream<string, HE>> {
const { account, startDate, endDate } = args
return this.accountEntityHistoryDAL
.useIndex(AccountEntityHistoryDALIndex.AccountTimestampIndex)
.getAllFromTo([account, startDate], [account, endDate], {
reverse: false,
})
}
abstract getAccountState(
args: GetAccountEntityStateRequestArgs,
): Promise<AccountEntityHistoryState<CU> | undefined>
protected abstract getAccountFetcher(account: string): BaseHistoryFetcher<CU>
}