-
Notifications
You must be signed in to change notification settings - Fork 54
/
DbSyncStakePool.ts
214 lines (190 loc) · 8.68 KB
/
DbSyncStakePool.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/* eslint-disable max-len */
/* eslint-disable max-params */
import {
Cardano,
StakePoolProvider,
StakePoolQueryOptions,
StakePoolSearchResults,
StakePoolStats
} from '@cardano-sdk/core';
import { CommonPoolInfo, OrderedResult, PoolAPY, PoolData, PoolMetrics, PoolSortType, PoolUpdate } from './types';
import { DbSyncEpochPollService } from '../../util';
import { DbSyncProvider } from '../../DbSyncProvider';
import { IDS_NAMESPACE, StakePoolsSubQuery, getStakePoolSortType, queryCacheKey } from './util';
import { InMemoryCache, UNLIMITED_CACHE_TTL } from '../../InMemoryCache';
import { Logger } from 'ts-log';
import { Pool } from 'pg';
import { StakePoolBuilder } from './StakePoolBuilder';
import { isNotNil } from '@cardano-sdk/util';
import { toStakePoolResults } from './mappers';
export interface StakePoolProviderDependencies {
db: Pool;
logger: Logger;
cache: InMemoryCache;
epochPollService: DbSyncEpochPollService;
}
export class DbSyncStakePoolProvider extends DbSyncProvider implements StakePoolProvider {
#builder: StakePoolBuilder;
#logger: Logger;
#cache: InMemoryCache;
#epochPollService: DbSyncEpochPollService;
constructor({ db, cache, logger, epochPollService }: StakePoolProviderDependencies) {
super(db);
this.#logger = logger;
this.#cache = cache;
this.#epochPollService = epochPollService;
this.#builder = new StakePoolBuilder(db, logger);
}
private getQueryBySortType(
sortType: PoolSortType,
queryArgs: { hashesIds: number[]; updatesIds: number[]; totalAdaAmount: string }
) {
const { hashesIds, updatesIds, totalAdaAmount } = queryArgs;
// Identify which query to use to order and paginate the result
// Should be the only one to get the sort options, rest should be ordered by their own defaults
switch (sortType) {
// Add more cases as more sort types are supported
case 'metrics':
return (options?: StakePoolQueryOptions) => this.#builder.queryPoolMetrics(hashesIds, totalAdaAmount, options);
case 'apy':
return (options?: StakePoolQueryOptions) => this.#builder.queryPoolAPY(hashesIds, options);
case 'data':
default:
return (options?: StakePoolQueryOptions) => this.#builder.queryPoolData(updatesIds, options);
}
}
private async getPoolsDataOrdered(
poolUpdates: PoolUpdate[],
totalAdaAmount: string,
options?: StakePoolQueryOptions
) {
const hashesIds = poolUpdates.map(({ id }) => id);
const updatesIds = poolUpdates.map(({ updateId }) => updateId);
this.#logger.debug(`${hashesIds.length} pools found`);
const sortType = options?.sort?.field ? getStakePoolSortType(options.sort.field) : 'data';
const orderedResult = await this.getQueryBySortType(sortType, { hashesIds, totalAdaAmount, updatesIds })(options);
const orderedResultHashIds = (orderedResult as CommonPoolInfo[]).map(({ hashId }) => hashId);
const orderedResultUpdateIds = poolUpdates
.filter(({ id }) => orderedResultHashIds.includes(id))
.map(({ updateId }) => updateId);
let poolDatas: PoolData[] = [];
if (sortType !== 'data') {
// If queryPoolData is not the one used to sort there could be more stake pools that should be fetched
// but might not appear in the orderByQuery result
this.#logger.debug('About to query stake pools data');
poolDatas = await this.#builder.queryPoolData(orderedResultUpdateIds);
// If not reached, try to fill the pagination limit using pool data default order
if (options?.pagination?.limit && orderedResult.length < options.pagination.limit) {
const restOfPoolUpdateIds = updatesIds.filter((updateId) => !orderedResultUpdateIds.includes(updateId));
this.#logger.debug('About to query rest of stake pools data');
const restOfPoolData = await this.#builder.queryPoolData(restOfPoolUpdateIds, {
pagination: { limit: options.pagination.limit - orderedResult.length, startAt: 0 }
});
poolDatas.push(...restOfPoolData);
orderedResultUpdateIds.push(...restOfPoolData.map(({ updateId }) => updateId));
orderedResultHashIds.push(...restOfPoolData.map(({ hashId }) => hashId));
}
} else {
poolDatas = orderedResult as PoolData[];
}
return { hashesIds, orderedResult, orderedResultHashIds, orderedResultUpdateIds, poolDatas, sortType };
}
private cacheStakePools(itemsToCache: { [hashId: number]: Cardano.StakePool }) {
for (const [hashId, pool] of Object.entries(itemsToCache))
this.#cache.set(`${IDS_NAMESPACE}/${hashId}`, pool, UNLIMITED_CACHE_TTL);
}
private async queryExtraPoolsData(
idsToFetch: PoolUpdate[],
sortType: PoolSortType,
totalAdaAmount: string,
orderedResult: OrderedResult,
hashesIds: number[],
options?: StakePoolQueryOptions
) {
this.#logger.debug('About to query stake pool extra information');
const orderedResultHashIds = idsToFetch.map(({ id }) => id);
const orderedResultUpdateIds = idsToFetch.map(({ updateId }) => updateId);
return await Promise.all([
// TODO: it would be easier and make the code cleaner if all queries had the same id as argument
// (either hash or update id)
this.#builder.queryPoolRelays(orderedResultUpdateIds),
this.#builder.queryPoolOwners(orderedResultUpdateIds),
this.#builder.queryRegistrations(orderedResultHashIds),
this.#builder.queryRetirements(orderedResultHashIds),
this.#builder.queryPoolRewards(orderedResultHashIds, options?.rewardsHistoryLimit),
sortType === 'metrics'
? (orderedResult as PoolMetrics[])
: this.#builder.queryPoolMetrics(orderedResultHashIds, totalAdaAmount),
sortType === 'apy'
? (orderedResult as PoolAPY[])
: this.#builder.queryPoolAPY(hashesIds, { rewardsHistoryLimit: options?.rewardsHistoryLimit })
]);
}
public async queryStakePools(options?: StakePoolQueryOptions): Promise<StakePoolSearchResults> {
const { params, query } =
options?.filters?._condition === 'or'
? this.#builder.buildOrQuery(options?.filters)
: this.#builder.buildAndQuery(options?.filters);
// Get pool updates/hashes
const poolUpdates = await this.#cache.get(queryCacheKey(StakePoolsSubQuery.POOL_HASHES, options), () =>
this.#builder.queryPoolHashes(query, params)
);
// Get pool total amount of ada
const totalAdaAmount = await this.#cache.get(queryCacheKey(StakePoolsSubQuery.TOTAL_ADA_AMOUNT), () =>
this.#builder.getTotalAmountOfAda()
);
// Get pool total stake pools count
const totalCount = await this.#builder.queryTotalCount(query, params);
// Get last epoch no
const lastEpoch = await this.#builder.getLastEpoch();
// Get stake pools data
const { orderedResultHashIds, orderedResultUpdateIds, orderedResult, poolDatas, hashesIds, sortType } =
await this.#cache.get(queryCacheKey(StakePoolsSubQuery.POOLS_DATA_ORDERED, options), () =>
this.getPoolsDataOrdered(poolUpdates, totalAdaAmount, options)
);
// Create lookup table with pool ids: (hashId:updateId)
const hashIdsMap = Object.fromEntries(
orderedResultHashIds.map((hashId, idx) => [hashId, orderedResultUpdateIds[idx]])
);
// Create a lookup table with cached pools: (hashId:Cardano.StakePool)
const fromCache = Object.fromEntries(
orderedResultHashIds.map((hashId) => [
hashId,
this.#cache.getVal<Cardano.StakePool>(`${IDS_NAMESPACE}/${hashId}`)
])
);
// Compute ids to fetch from db
const idsToFetch = Object.entries(fromCache)
.filter(([_, pool]) => pool === undefined)
.map(([hashId, _]) => ({ id: Number(hashId), updateId: hashIdsMap[hashId] }));
// Get stake pools extra information
const [poolRelays, poolOwners, poolRegistrations, poolRetirements, poolRewards, poolMetrics, poolAPYs] =
await this.queryExtraPoolsData(idsToFetch, sortType, totalAdaAmount, orderedResult, hashesIds, options);
const { results, poolsToCache } = toStakePoolResults(orderedResultHashIds, fromCache, {
lastEpoch,
poolAPYs,
poolDatas,
poolMetrics,
poolOwners,
poolRegistrations,
poolRelays,
poolRetirements,
poolRewards: poolRewards.filter(isNotNil),
totalCount
});
// Cache stake pools core objects
this.cacheStakePools(poolsToCache);
return results;
}
public async stakePoolStats(): Promise<StakePoolStats> {
this.#logger.debug('About to query pool stats');
return await this.#cache.get(queryCacheKey(StakePoolsSubQuery.STATS), () => this.#builder.queryPoolStats());
}
async start(): Promise<void> {
this.#epochPollService.start();
}
async close(): Promise<void> {
this.#cache.shutdown();
this.#epochPollService.shutdown();
}
}