All files / src/Projection prepareTypeormProjection.ts

99.12% Statements 113/114
83.87% Branches 26/31
100% Functions 19/19
99.05% Lines 105/106

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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 40935x                                                                                             35x 35x 35x 35x 35x     35x 35x 35x 35x 35x 35x 35x 35x 35x 35x             35x       35x         6x 6x       6x     6x     6x 6x     6x                                         35x                                                       35x                           35x                                       35x         35x                                   35x                                   35x 14x 14x   14x 72x   46x 70x 58x 58x 58x       14x   14x     35x                       35x                         35x                           35x                           35x         31x 31x 20x 20x 20x 9x 19x         35x 65x 65x 34x 34x 34x 23x 33x         35x             24x 24x 18x 18x 18x 12x 15x     18x 18x 12x 12x     18x 18x 18x 32x         35x 72x 535x 72x                       35x       6x 6x 6x   6x   6x 7x 9x     6x 6x 6x 6x 6x 103x 18x     6x   34x 20x 18x 12x             14x     4x          
import {
  AddressEntity,
  AssetEntity,
  BlockDataEntity,
  BlockEntity,
  CurrentPoolMetricsEntity,
  DataSourceExtensions,
  GovernanceActionEntity,
  HandleEntity,
  HandleMetadataEntity,
  NftMetadataEntity,
  OutputEntity,
  PoolDelistedEntity,
  PoolMetadataEntity,
  PoolRegistrationEntity,
  PoolRetirementEntity,
  PoolRewardsEntity,
  StakeKeyRegistrationEntity,
  StakePoolEntity,
  TokensEntity,
  createStorePoolMetricsUpdateJob,
  createStoreStakePoolMetadataJob,
  storeAddresses,
  storeAssets,
  storeBlock,
  storeGovernanceAction,
  storeHandleMetadata,
  storeHandles,
  storeNftMetadata,
  storeStakeKeyRegistrations,
  storeStakePoolRewardsJob,
  storeStakePools,
  storeUtxo,
  willStoreAddresses,
  willStoreAssets,
  willStoreBlockData,
  willStoreGovernanceAction,
  willStoreHandleMetadata,
  willStoreHandles,
  willStoreNftMetadata,
  willStoreStakeKeyRegistrations,
  willStoreStakePoolMetadataJob,
  willStoreStakePoolRewardsJob,
  willStoreStakePools,
  willStoreUtxo
} from '@cardano-sdk/projection-typeorm';
import { Cardano } from '@cardano-sdk/core';
import { ChainSyncEventType, Mappers as Mapper, ProjectionEvent } from '@cardano-sdk/projection';
import { ObservableType, passthrough } from '@cardano-sdk/util-rxjs';
import { POOLS_METRICS_INTERVAL_DEFAULT, POOLS_METRICS_OUTDATED_INTERVAL_DEFAULT } from '../Program/programs/types';
import { Sorter } from '@hapi/topo';
import { WithLogger, isNotNil } from '@cardano-sdk/util';
 
/** Used as mount segments, so must be URL-friendly */
export enum ProjectionName {
  Address = 'address',
  Asset = 'asset',
  Handle = 'handle',
  ProtocolParameters = 'protocol-parameters',
  StakePool = 'stake-pool',
  StakePoolMetadataJob = 'stake-pool-metadata-job',
  StakePoolMetricsJob = 'stake-pool-metrics-job',
  StakePoolRewardsJob = 'stake-pool-rewards-job',
  UTXO = 'utxo'
}
 
export interface ProjectionOptions {
  handlePolicyIds?: Cardano.PolicyId[];
}
 
const requiredExtensions = (projectionNames: ProjectionName[]): DataSourceExtensions => ({
  pgBoss: projectionNames.includes(ProjectionName.StakePoolMetadataJob)
});
 
const createMapperOperators = (
  projectionNames: ProjectionName[],
  { handlePolicyIds }: ProjectionOptions,
  { logger }: WithLogger
) => {
  const applyUtxoAndMintFilters = handlePolicyIds && !projectionNames.includes(ProjectionName.UTXO);
  const filterUtxo = applyUtxoAndMintFilters
    ? Mapper.filterProducedUtxoByAssetPolicyId({ policyIds: handlePolicyIds })
    : passthrough();
  const filterProducedUtxoByAssetsPresence =
    projectionNames.includes(ProjectionName.Asset) && !projectionNames.includes(ProjectionName.UTXO)
      ? Mapper.filterProducedUtxoByAssetsPresence()
      : passthrough();
  const filterMint = applyUtxoAndMintFilters
    ? Mapper.filterMintByPolicyIds({ policyIds: handlePolicyIds })
    : passthrough();
  const withHandles = handlePolicyIds ? Mapper.withHandles({ policyIds: handlePolicyIds }, logger) : passthrough();
  const withHandleMetadata = handlePolicyIds
    ? Mapper.withHandleMetadata({ policyIds: handlePolicyIds }, logger)
    : passthrough();
  return {
    filterMint,
    filterProducedUtxoByAssetsPresence,
    filterUtxo,
    withAddresses: Mapper.withAddresses(),
    withCIP67: Mapper.withCIP67(),
    withCertificates: Mapper.withCertificates(),
    withGovernanceActions: Mapper.withGovernanceActions(),
    withHandleMetadata,
    withHandles,
    withMint: Mapper.withMint(),
    withNftMetadata: Mapper.withNftMetadata({ logger }),
    withStakeKeyRegistrations: Mapper.withStakeKeyRegistrations(),
    withStakePools: Mapper.withStakePools(),
    withUtxo: Mapper.withUtxo()
  };
};
type MapperOperators = ReturnType<typeof createMapperOperators>;
type MapperName = keyof MapperOperators;
type MapperOperator = MapperOperators[MapperName];
 
export const storeOperators = {
  storeAddresses: storeAddresses(),
  storeAssets: storeAssets(),
  storeBlock: storeBlock(),
  storeGovernanceAction: storeGovernanceAction(),
  storeHandleMetadata: storeHandleMetadata(),
  storeHandles: storeHandles(),
  storeNftMetadata: storeNftMetadata(),
  storePoolMetricsUpdateJob: createStorePoolMetricsUpdateJob(
    POOLS_METRICS_INTERVAL_DEFAULT,
    POOLS_METRICS_OUTDATED_INTERVAL_DEFAULT
  )(),
  storeStakeKeyRegistrations: storeStakeKeyRegistrations(),
  storeStakePoolMetadataJob: createStoreStakePoolMetadataJob()(),
  storeStakePoolRewardsJob: storeStakePoolRewardsJob(),
  storeStakePools: storeStakePools(),
  storeUtxo: storeUtxo()
};
type StoreOperators = typeof storeOperators;
type StoreName = keyof StoreOperators;
type StoreOperator = StoreOperators[StoreName];
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type InferArg0<F extends Function> = F extends (arg0: infer Args) => any ? Args : never;
type WillStore = {
  [k in keyof StoreOperators]: (args: ObservableType<InferArg0<StoreOperators[k]>>) => boolean;
};
 
const willStore: Partial<WillStore> = {
  storeAddresses: willStoreAddresses,
  storeAssets: willStoreAssets,
  storeGovernanceAction: willStoreGovernanceAction,
  storeHandleMetadata: willStoreHandleMetadata,
  storeHandles: willStoreHandles,
  storeNftMetadata: willStoreNftMetadata,
  storeStakeKeyRegistrations: willStoreStakeKeyRegistrations,
  storeStakePoolMetadataJob: willStoreStakePoolMetadataJob,
  storeStakePoolRewardsJob: willStoreStakePoolRewardsJob,
  storeStakePools: willStoreStakePools,
  storeUtxo: willStoreUtxo
};
 
const entities = {
  address: AddressEntity,
  asset: AssetEntity,
  block: BlockEntity,
  blockData: BlockDataEntity,
  currentPoolMetrics: CurrentPoolMetricsEntity,
  governanceAction: GovernanceActionEntity,
  handle: HandleEntity,
  handleMetadata: HandleMetadataEntity,
  nftMetadata: NftMetadataEntity,
  output: OutputEntity,
  poolDelisted: PoolDelistedEntity,
  poolMetadata: PoolMetadataEntity,
  poolRegistration: PoolRegistrationEntity,
  poolRetirement: PoolRetirementEntity,
  poolRewards: PoolRewardsEntity,
  stakeKeyRegistration: StakeKeyRegistrationEntity,
  stakePool: StakePoolEntity,
  tokens: TokensEntity
};
export const allEntities = Object.values(entities);
type Entities = typeof entities;
type EntityName = keyof Entities;
type Entity = Entities[EntityName];
 
const storeEntities: Partial<Record<StoreName, EntityName[]>> = {
  storeAddresses: ['address'],
  storeAssets: ['asset'],
  storeBlock: ['block', 'blockData'],
  storeGovernanceAction: ['governanceAction'],
  storeHandleMetadata: ['handleMetadata', 'output'],
  storeHandles: ['handle', 'asset', 'tokens', 'output'],
  storeNftMetadata: ['asset'],
  storePoolMetricsUpdateJob: ['stakePool', 'currentPoolMetrics', 'poolMetadata'],
  storeStakeKeyRegistrations: ['block', 'stakeKeyRegistration'],
  // 'stake-pool' projection requires it, but `storeStakePools` does not.
  // at the time of writing there was no way to specify a direct projection->entity dependency.
  storeStakePoolMetadataJob: ['stakePool', 'currentPoolMetrics', 'poolMetadata'],
  storeStakePoolRewardsJob: ['poolRewards', 'stakePool'],
  storeStakePools: ['stakePool', 'currentPoolMetrics', 'poolMetadata', 'poolDelisted'],
  storeUtxo: ['tokens', 'output']
};
 
const entityInterDependencies: Partial<Record<EntityName, EntityName[]>> = {
  address: ['stakeKeyRegistration'],
  asset: ['block', 'nftMetadata'],
  blockData: ['block'],
  currentPoolMetrics: ['stakePool'],
  governanceAction: ['block'],
  handle: ['asset'],
  handleMetadata: ['output'],
  output: ['block', 'tokens'],
  poolDelisted: ['stakePool'],
  poolMetadata: ['stakePool'],
  poolRegistration: ['block'],
  poolRetirement: ['block'],
  stakeKeyRegistration: ['block'],
  stakePool: ['block', 'poolRegistration', 'poolRetirement'],
  tokens: ['asset']
};
 
export const getEntities = (entityNames: EntityName[]): Entity[] => {
  const resolvedNames: EntityName[] = [];
  const resultEntities: Entity[] = [];
 
  const scanDependencies = (names: EntityName[] | undefined) => {
    if (!names) return;
 
    for (const name of names)
      if (!resolvedNames.includes(name)) {
        resolvedNames.push(name);
        resultEntities.push(entities[name]);
        scanDependencies(entityInterDependencies[name]);
      }
  };
 
  scanDependencies(entityNames);
 
  return resultEntities;
};
 
const mapperInterDependencies: Partial<Record<MapperName, MapperName[]>> = {
  filterMint: ['withMint'],
  filterUtxo: ['withUtxo'],
  withAddresses: ['withUtxo', 'filterUtxo'],
  withCIP67: ['withUtxo', 'filterUtxo', 'withMint', 'filterMint'],
  withHandleMetadata: ['withNftMetadata', 'withCIP67'],
  withHandles: ['withMint', 'filterMint', 'withUtxo', 'filterUtxo', 'withCIP67'],
  withNftMetadata: ['withCIP67', 'withMint', 'filterMint'],
  withStakeKeyRegistrations: ['withCertificates'],
  withStakePools: ['withCertificates']
};
 
const storeMapperDependencies: Partial<Record<StoreName, MapperName[]>> = {
  storeAddresses: ['withAddresses'],
  storeAssets: ['withMint'],
  storeGovernanceAction: ['withGovernanceActions'],
  storeHandleMetadata: ['withHandleMetadata'],
  storeHandles: ['withHandles'],
  storeNftMetadata: ['withNftMetadata'],
  storeStakeKeyRegistrations: ['withStakeKeyRegistrations'],
  storeStakePoolMetadataJob: ['withStakePools'],
  storeStakePools: ['withStakePools'],
  storeUtxo: ['withUtxo']
};
 
const storeInterDependencies: Partial<Record<StoreName, StoreName[]>> = {
  storeAddresses: ['storeBlock', 'storeStakeKeyRegistrations'],
  storeAssets: ['storeBlock'],
  storeGovernanceAction: ['storeBlock'],
  storeHandleMetadata: ['storeUtxo'],
  storeHandles: ['storeUtxo', 'storeAddresses', 'storeHandleMetadata'],
  storeNftMetadata: ['storeAssets'],
  storePoolMetricsUpdateJob: ['storeBlock'],
  storeStakePoolMetadataJob: ['storeBlock'],
  storeStakePoolRewardsJob: ['storeBlock'],
  storeStakePools: ['storeBlock'],
  storeUtxo: ['storeBlock', 'storeAssets']
};
 
const projectionStoreDependencies: Record<ProjectionName, StoreName[]> = {
  address: ['storeAddresses'],
  asset: ['storeAssets', 'storeNftMetadata'],
  // TODO: remove storeNftMetadata when TypeormAssetProvider tests
  // are updated to use 'asset' database instead of a handle database
  handle: ['storeHandles', 'storeHandleMetadata', 'storeNftMetadata'],
  'protocol-parameters': ['storeGovernanceAction'],
  'stake-pool': ['storeStakePools'],
  'stake-pool-metadata-job': ['storeStakePoolMetadataJob'],
  'stake-pool-metrics-job': ['storePoolMetricsUpdateJob'],
  'stake-pool-rewards-job': ['storeStakePoolRewardsJob'],
  utxo: ['storeUtxo']
};
 
const registerMapper = (
  mapperOperators: MapperOperators,
  mapperName: MapperName,
  mapperSorter: Sorter<MapperOperator>
): void => {
  const mapperOperator = mapperOperators[mapperName];
  if (mapperSorter.nodes.includes(mapperOperator)) return;
  const dependencyMappers = mapperInterDependencies[mapperName];
  mapperSorter.add(mapperOperator, { after: dependencyMappers, group: mapperName });
  if (dependencyMappers) {
    for (const dependencyMapperName of dependencyMappers) {
      registerMapper(mapperOperators, dependencyMapperName, mapperSorter);
    }
  }
};
 
const registerEntity = (entityName: EntityName, entitySorter: Sorter<Entity>): void => {
  const entity = entities[entityName];
  if (entitySorter.nodes.includes(entity)) return;
  const dependencyEntities = entityInterDependencies[entityName];
  entitySorter.add(entity, { after: dependencyEntities, group: entityName });
  if (dependencyEntities) {
    for (const dependencyEntityName of dependencyEntities) {
      registerEntity(dependencyEntityName, entitySorter);
    }
  }
};
 
const registerStore = (
  mapperOperators: MapperOperators,
  storeName: StoreName,
  mapperSorter: Sorter<MapperOperator>,
  storeSorter: Sorter<StoreOperator>,
  entitySorter: Sorter<Entity>
): void => {
  const storeOperator = storeOperators[storeName];
  if (storeSorter.nodes.includes(storeOperator)) return;
  const dependencyStores = storeInterDependencies[storeName];
  storeSorter.add(storeOperator, { after: dependencyStores, group: storeName });
  if (dependencyStores) {
    for (const dependencyStoreName of dependencyStores) {
      registerStore(mapperOperators, dependencyStoreName, mapperSorter, storeSorter, entitySorter);
    }
  }
  const mapperDependencies = storeMapperDependencies[storeName];
  if (mapperDependencies) {
    for (const mapperName of mapperDependencies) {
      registerMapper(mapperOperators, mapperName, mapperSorter);
    }
  }
  const entityDependencies = storeEntities[storeName];
  if (entityDependencies) {
    for (const entityName of entityDependencies) {
      registerEntity(entityName, entitySorter);
    }
  }
};
 
const keyOf = <T extends {}>(obj: T, value: unknown): keyof T | null => {
  for (const [key, keyValue] of Object.entries(obj)) {
    if (value === keyValue) {
      return key as keyof T;
    }
  }
  return null;
};
 
export interface PrepareTypeormProjectionProps {
  projections: ProjectionName[];
  options?: ProjectionOptions;
}
 
/** Selects a required set of entities, mappers and store operators based on 'projections' and presence of 'buffer': */
export const prepareTypeormProjection = (
  { projections, options = {} }: PrepareTypeormProjectionProps,
  dependencies: WithLogger
) => {
  const mapperSorter = new Sorter<MapperOperator>();
  const storeSorter = new Sorter<StoreOperator>();
  const entitySorter = new Sorter<Entity>();
 
  const mapperOperators = createMapperOperators(projections, options, dependencies);
 
  for (const projection of projections) {
    for (const storeName of projectionStoreDependencies[projection]) {
      registerStore(mapperOperators, storeName, mapperSorter, storeSorter, entitySorter);
    }
  }
  const selectedEntities = entitySorter.nodes;
  const selectedMappers = mapperSorter.nodes;
  const selectedStores = storeSorter.nodes;
  const extensions = requiredExtensions(projections);
  const willStoreCheckers = selectedStores
    .map((store) => Object.entries(storeOperators).find(([_, operator]) => store === operator)!)
    .map(([storeName]) => willStore[storeName as keyof StoreOperators])
    .filter(isNotNil);
 
  return {
    __debug: {
      entities: selectedEntities.map((Entity) => keyOf(entities, Entity)),
      mappers: selectedMappers.map((mapper) => keyOf(mapperOperators, mapper)),
      stores: selectedStores.map((store) => keyOf(storeOperators, store)),
      willStoreCheckers: willStoreCheckers.map((checker) => checker.name)
    },
    entities: selectedEntities,
    extensions,
    mappers: selectedMappers,
    stores: selectedStores,
    willStore: <T extends ProjectionEvent>(evt: T) =>
      evt.eventType === ChainSyncEventType.RollBackward ||
      willStoreBlockData(evt) ||
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      willStoreCheckers.some((check) => check(evt as any))
  };
};
 
export type PreparedProjection = ReturnType<typeof prepareTypeormProjection>;