All files / src/StakePool/TypeormStakePoolProvider TypeormStakePoolProvider.ts

88.15% Statements 67/76
57.69% Branches 15/26
100% Functions 11/11
90.27% Lines 65/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 27036x                         36x 36x 36x 36x 36x 36x               36x   36x                                                             36x 1x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x         1x     1x       1x   1x                           5x       5x                                 5x 1x 1x                 1x                                     1x           64x   64x 1x             63x 1x                   62x 62x     62x 62x   62x 62x 4x 4x   4x   14x     4x                 62x   62x 62x   62x 62x   62x                             62x 62x   62x       62x 62x   62x                       62x         2x   2x 2x               2x      
import {
  Cardano,
  FuzzyOptions,
  Paginated,
  ProviderError,
  ProviderFailure,
  QueryStakePoolsArgs,
  StakePoolProvider,
  StakePoolStats
} from '@cardano-sdk/core';
import { DataSource } from 'typeorm';
import { DeepPartial } from '@cardano-sdk/util';
import { InMemoryCache } from '../../InMemoryCache';
import { MissingProgramOption } from '../../Program/errors';
import { PoolDelistedEntity, StakePoolEntity } from '@cardano-sdk/projection-typeorm';
import { PoolModel, PoolStatsModel, mapPoolStats, mapStakePoolsResult } from './mappers';
import { ServiceNames } from '../../Program/programs/types';
import { TypeormProvider, TypeormProviderDependencies } from '../../util';
import {
  computeROS,
  getSortOptions,
  getWhereClauseAndArgs,
  stakePoolSearchSelection,
  stakePoolSearchTotalCount,
  withTextFilter
} from './util';
import Fuse from 'fuse.js';
 
export const DEFAULT_FUZZY_SEARCH_OPTIONS: FuzzyOptions = {
  distance: 255,
  fieldNormWeight: 1,
  ignoreFieldNorm: false,
  ignoreLocation: true,
  location: 0,
  minMatchCharLength: 1,
  threshold: 0.3,
  useExtendedSearch: false,
  weights: { description: 4, homepage: 1, name: 6, poolId: 1, ticker: 10 }
};
 
/** Properties that are need to create TypeormStakePoolProvider */
export interface TypeOrmStakePoolProviderProps {
  /** Options for the fuzzy search on stake pool metadata */
  fuzzyOptions?: FuzzyOptions;
 
  /** Number of epochs over which lastRos is computed */
  lastRosEpochs?: number;
 
  /** Pagination page size limit used for provider methods constraint. */
  paginationPageSizeLimit: number;
 
  /** If `true` allows the override of `fuzzyOptions` through `queryStakePools` call.*/
  overrideFuzzyOptions?: boolean;
}
 
export interface TypeormStakePoolProviderDependencies extends TypeormProviderDependencies {
  cache: InMemoryCache;
}
 
export class TypeormStakePoolProvider extends TypeormProvider implements StakePoolProvider {
  #cache: InMemoryCache;
  #fuzzyOptions: FuzzyOptions;
  #lastRosEpochs: number;
  #paginationPageSizeLimit: number;
  #overrideFuzzyOptions?: boolean;
 
  constructor(config: TypeOrmStakePoolProviderProps, deps: TypeormStakePoolProviderDependencies) {
    const { lastRosEpochs, overrideFuzzyOptions, paginationPageSizeLimit } = config;
 
    super('TypeormStakePoolProvider', deps);
    this.#cache = deps.cache;
    this.#fuzzyOptions = DEFAULT_FUZZY_SEARCH_OPTIONS;
    this.#paginationPageSizeLimit = paginationPageSizeLimit;
    this.#overrideFuzzyOptions = overrideFuzzyOptions;
 
    // Introduced following code repetition as the correct form is source of a circular-deps:check failure.
    // Solving it would require an invasive refactoring action, probably better to defer it.
    // if (!lastRosEpochs) throw new MissingProgramOption(STAKE_POOL_REWARDS, Descriptions.LastRosEpochs);
    Iif (!lastRosEpochs)
      throw new MissingProgramOption(ServiceNames.StakePool, 'Number of epochs over which lastRos is computed');
 
    this.#lastRosEpochs = lastRosEpochs;
  }
 
  async startImpl() {
    await super.startImpl();
 
    await this.withDataSource((dataSource) => this.getFuse(dataSource));
  }
 
  private async getFuse(dataSource: DataSource, fuzzyOptions?: DeepPartial<FuzzyOptions>) {
    const {
      distance,
      fieldNormWeight,
      ignoreFieldNorm,
      ignoreLocation,
      location,
      minMatchCharLength,
      threshold,
      useExtendedSearch,
      weights: { description, homepage, name, poolId, ticker }
    } = this.#overrideFuzzyOptions
      ? { ...this.#fuzzyOptions, ...fuzzyOptions, weights: { ...this.#fuzzyOptions.weights, ...fuzzyOptions?.weights } }
      : this.#fuzzyOptions;
 
    const cacheKey = this.#overrideFuzzyOptions
      ? `fuzzy-index-${JSON.stringify([
          description,
          distance,
          fieldNormWeight,
          homepage,
          ignoreFieldNorm,
          ignoreLocation,
          location,
          minMatchCharLength,
          name,
          threshold,
          ticker,
          useExtendedSearch
        ])}`
      : 'fuzzy-index';
 
    return this.#cache.get(cacheKey, async () => {
      const metadata = await this.#cache.get('all-metadata', async () =>
        dataSource
          .createQueryBuilder()
          .from(StakePoolEntity, 'pool')
          .leftJoinAndSelect('pool.lastRegistration', 'params')
          .leftJoinAndSelect('params.metadata', 'metadata')
          .select(['description', 'homepage', 'name', 'pool.id AS pool_id', 'ticker'])
          .getRawMany<{ description: string; homepage: string; name: string; pool_id: string; ticker: string }>()
      );
 
      const opts = {
        distance,
        fieldNormWeight,
        ignoreFieldNorm,
        ignoreLocation,
        includeScore: true,
        keys: [
          { name: 'description', weight: description },
          { name: 'homepage', weight: homepage },
          { name: 'name', weight: name },
          { name: 'pool_id', weight: poolId },
          { name: 'ticker', weight: ticker }
        ],
        location,
        minMatchCharLength,
        threshold,
        useExtendedSearch
      };
 
      return new Fuse(metadata, opts, Fuse.createIndex(opts.keys, metadata));
    });
  }
 
  // eslint-disable-next-line sonarjs/cognitive-complexity
  public async queryStakePools(options: QueryStakePoolsArgs): Promise<Paginated<Cardano.StakePool>> {
    const { epochRewards, epochsLength, filters, fuzzyOptions, pagination, sort } = options;
 
    if (pagination.limit > this.#paginationPageSizeLimit) {
      throw new ProviderError(
        ProviderFailure.BadRequest,
        undefined,
        `Page size of ${pagination.limit} can not be greater than ${this.#paginationPageSizeLimit}`
      );
    }
 
    if (filters?.identifier && filters.identifier.values.length > this.#paginationPageSizeLimit) {
      throw new ProviderError(
        ProviderFailure.BadRequest,
        undefined,
        `Filter identifiers of ${filters.identifier.values.length} can not be greater than ${
          this.#paginationPageSizeLimit
        }`
      );
    }
 
    // eslint-disable-next-line complexity
    return this.withDataSource(async (dataSource: DataSource) => {
      const queryRunner = dataSource.createQueryRunner();
 
      let rawResult: PoolModel[];
      let sortByScore = false;
      let textFilter = false;
 
      try {
        if (withTextFilter(filters)) {
          sortByScore = sort === undefined;
          textFilter = true;
 
          const values = (await this.getFuse(dataSource, fuzzyOptions))
            .search(filters.text)
            .map(({ item: { pool_id }, score }) => `('${pool_id}',${score})`)
            .join(',');
 
          await queryRunner.query(
            [
              'DROP TABLE IF EXISTS tmp_fuzzy',
              'CREATE TEMPORARY TABLE tmp_fuzzy (pool_id VARCHAR, score NUMERIC) WITHOUT OIDS',
              ...(values === '' ? [] : [`INSERT INTO tmp_fuzzy VALUES ${values}`])
            ].join(';')
          );
        }
 
        this.logger.debug('About to query projected stake pools');
 
        const { clause, args } = getWhereClauseAndArgs(filters, textFilter);
        const { field, order } = getSortOptions(sortByScore, sort);
 
        const queryBuilder1 = dataSource.createQueryBuilder(queryRunner).from(StakePoolEntity, 'pool');
        const queryBuilder2 = textFilter ? queryBuilder1.innerJoin('tmp_fuzzy', 'tmp', 'id = pool_id') : queryBuilder1;
 
        rawResult = await queryBuilder2
          .leftJoinAndSelect('pool.metrics', 'metrics')
          .leftJoinAndSelect('pool.lastRegistration', 'params')
          .leftJoinAndSelect('params.metadata', 'metadata')
          .leftJoin(PoolDelistedEntity, 'delist', 'delist.stakePoolId = pool.id')
          .select(stakePoolSearchSelection)
          .addSelect(stakePoolSearchTotalCount)
          .where(clause, args)
          .andWhere('delist.stakePoolId IS NULL')
          .orderBy(field, order, 'NULLS LAST')
          .addOrderBy('pool.id', 'ASC')
          .offset(pagination.startAt)
          .limit(pagination.limit)
          .getRawMany<PoolModel>();
      } finally {
        try {
          if (textFilter) await queryRunner.query('DROP TABLE IF EXISTS tmp_fuzzy');
        } finally {
          await queryRunner.release();
        }
      }
 
      const result = mapStakePoolsResult(rawResult);
      const requestedNotStdLength = epochsLength !== undefined && epochsLength !== this.#lastRosEpochs;
 
      Iif (epochRewards || requestedNotStdLength) {
        const epochs = epochsLength || this.#lastRosEpochs;
 
        for (const pool of result.pageResults) {
          const { id, metrics } = pool;
          const [ros, history] = await computeROS({ dataSource, epochs, logger: this.logger, stakePool: { id } });
 
          Iif (epochRewards) pool.rewardHistory = history;
          Iif (requestedNotStdLength && metrics) metrics.lastRos = ros;
        }
      }
 
      return result;
    });
  }
 
  public async stakePoolStats(): Promise<StakePoolStats> {
    this.logger.debug('About to query projected pool stats');
 
    const rawResult = await this.withDataSource<PoolStatsModel[]>((dataSource: DataSource) =>
      dataSource
        .createQueryBuilder()
        .addSelect('count(*) as count, pool.status')
        .from(StakePoolEntity, 'pool')
        .groupBy('pool.status')
        .getRawMany()
    );
 
    return { qty: mapPoolStats(rawResult) };
  }
}